{"text": "function c = mrdivide(a,b)\n% MRDIVIDE implements a/b, where either a or b is an adiff object.\n% It is mapped to a./b where possible (i.e. when b has length 1), and\n% yields an error otherwise.\n\nif prod(size(b))==1\n   c = times(a,1./b);\nelse\n   error('Cannot use / for adiff objects when denominator is nonscalar');\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Utilities/Differentiation/Automatic/@adiff/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2499951077019508}}
{"text": "function state = initstate(nvars,options,n,itr)\n% Initialize swarm condition. Called by PSO.\n\n% Initial particle velocities\nstate.Velocities = zeros(n,nvars) ;\n\n% Initialize particle positions\nstate.Population = ...\n    repmat(options.PopInitRange(1,:),n,1).*ones(n,nvars) + ...\n    repmat((options.PopInitRange(2,:) - options.PopInitRange(1,:)),n,1) ...\n    .*rand(n,nvars) ;\n\n% Initialize the global and local fitness to the worst possible\nstate.fGlobalBest = ones(itr,1)*inf; % Global best fitness score\nstate.fLocalBests = ones(n,1)*inf ; % Individual best fitness score\n\n% Initialize global and local best positions\nstate.xGlobalBest = ones(1,nvars)*inf ;\nstate.xLocalBests = ones(n,nvars)*inf ;", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/psopt/private/initstate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24999510770195077}}
{"text": "function [bndinfo, pbim, gconf, bndinfo_all] =  processIm2Occlusion(im, varargin)\n\n%% Set parameters\n\n%% Read image\n\nif max(size(im))>640\n  fprintf('Warning, this image is pretty big...\\n');\n  %im = imresize(im, 640/max(size(im)), 'bilinear');\nend\n\n%% Get occlusion info\n[bndinfo, pbim, gconf, bndinfo_all] = im2boundariesTopLevel(im);\ngconf = single(gconf);\npbim = single(pbim);\n\n%save(outname, 'bndinfo', 'pbim', 'gconf', 'bndinfo_all');\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/processFunctions/processIm2Occlusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24999510770195077}}
{"text": "classdef Violin < handle\n    % Violin creates violin plots for some data\n    %   A violin plot is an easy to read substitute for a box plot\n    %   that replaces the box shape with a kernel density estimate of\n    %   the data, and optionally overlays the data points itself.\n    %   It is also possible to provide two sets of data which are supposed\n    %   to be compared by plotting each column of the two datasets together\n    %   on each side of the violin.\n    %\n    %   Additional constructor parameters include the width of the\n    %   plot, the bandwidth of the kernel density estimation, the\n    %   X-axis position of the violin plot, and the categories.\n    %\n    %   Use <a href=\"matlab:help('violinplot')\">violinplot</a> for a\n    %   <a href=\"matlab:help('boxplot')\">boxplot</a>-like wrapper for\n    %   interactive plotting.\n    %\n    %   See for more information on Violin Plots:\n    %   J. L. Hintze and R. D. Nelson, \"Violin plots: a box\n    %   plot-density trace synergism,\" The American Statistician, vol.\n    %   52, no. 2, pp. 181-184, 1998.\n    %\n    % Violin Properties:\n    %    ViolinColor    - Fill color of the violin area and data points.\n    %                     Can be either a matrix nx3 or an array of up to two\n    %                     cells containing nx3 matrices.\n    %                     Defaults to the next default color cycle.\n    %    ViolinAlpha    - Transparency of the violin area and data points.\n    %                     Can be either a single scalar value or an array of\n    %                     up to two cells containing scalar values.\n    %                     Defaults to 0.3.\n    %    EdgeColor      - Color of the violin area outline.\n    %                     Defaults to [0.5 0.5 0.5]\n    %    BoxColor       - Color of the box, whiskers, and the outlines of\n    %                     the median point and the notch indicators.\n    %                     Defaults to [0.5 0.5 0.5]\n    %    MedianColor    - Fill color of the median and notch indicators.\n    %                     Defaults to [1 1 1]\n    %    ShowData       - Whether to show data points.\n    %                     Defaults to true\n    %    ShowNotches    - Whether to show notch indicators.\n    %                     Defaults to false\n    %    ShowMean       - Whether to show mean indicator.\n    %                     Defaults to false\n    %    ShowBox        - Whether to show the box.\n    %                     Defaults to true\n    %    ShowMedian     - Whether to show the median indicator.\n    %                     Defaults to true\n    %    ShowWhiskers   - Whether to show the whiskers\n    %                     Defaults to true\n    %    HalfViolin     - Whether to do a half violin(left, right side) or\n    %                     full. Defaults to full.\n    %    QuartileStyle - Option on how to display quartiles, with a\n    %                     boxplot, shadow or none. Defaults to boxplot.\n    %    DataStyle      - Defines the style to show the data points. Opts: \n    %                     'scatter', 'histogram' or 'none'. Default is 'scatter'.\n    %\n    %\n    % Violin Children:\n    %    ScatterPlot    - <a href=\"matlab:help('scatter')\">scatter</a> plot of the data points\n    %    ScatterPlot2   - <a href=\"matlab:help('scatter')\">scatter</a> second plot of the data points\n    %    ViolinPlot     - <a href=\"matlab:help('fill')\">fill</a> plot of the kernel density estimate\n    %    ViolinPlot2    - <a href=\"matlab:help('fill')\">fill</a> second plot of the kernel density estimate\n    %    BoxPlot        - <a href=\"matlab:help('fill')\">fill</a> plot of the box between the quartiles\n    %    WhiskerPlot    - line <a href=\"matlab:help('plot')\">plot</a> between the whisker ends\n    %    MedianPlot     - <a href=\"matlab:help('scatter')\">scatter</a> plot of the median (one point)\n    %    NotchPlots     - <a href=\"matlab:help('scatter')\">scatter</a> plots for the notch indicators\n    %    MeanPlot       - line <a href=\"matlab:help('plot')\">plot</a> at mean value\n    \n    \n    % Copyright (c) 2016, Bastian Bechtold\n    % This code is released under the terms of the BSD 3-clause license\n    \n    properties (Access=public)\n        ScatterPlot     % scatter plot of the data points\n        ScatterPlot2    % comparison scatter plot of the data points\n        ViolinPlot      % fill plot of the kernel density estimate\n        ViolinPlot2     % comparison fill plot of the kernel density estimate\n        BoxPlot         % fill plot of the box between the quartiles\n        WhiskerPlot     % line plot between the whisker ends\n        MedianPlot      % scatter plot of the median (one point)\n        NotchPlots      % scatter plots for the notch indicators\n        MeanPlot        % line plot of the mean (horizontal line)\n        HistogramPlot   % histogram of the data\n        ViolinPlotQ     % fill plot of the Quartiles as shadow\n    end\n    \n    properties (Dependent=true)\n        ViolinColor         % fill color of the violin area and data points\n        ViolinAlpha         % transparency of the violin area and data points\n        MarkerSize          % marker size for the data dots\n        MedianMarkerSize    % marker size for the median dot\n        LineWidth           % linewidth of the median plot\n        EdgeColor           % color of the violin area outline\n        BoxColor            % color of box, whiskers, and median/notch edges\n        BoxWidth            % width of box between the quartiles in axis space (default 10% of Violin plot width, 0.03)\n        MedianColor         % fill color of median and notches\n        ShowData            % whether to show data points\n        ShowNotches         % whether to show notch indicators\n        ShowMean            % whether to show mean indicator\n        ShowBox             % whether to show the box\n        ShowMedian          % whether to show the median line\n        ShowWhiskers        % whether to show the whiskers\n        HalfViolin          % whether to do a half violin(left, right side) or full\n    end\n    \n    methods\n        function obj = Violin(data, pos, varargin)\n            %Violin plots a violin plot of some data at pos\n            %   VIOLIN(DATA, POS) plots a violin at x-position POS for\n            %   a vector of DATA points.\n            %\n            %   VIOLIN(..., 'PARAM1', val1, 'PARAM2', val2, ...)\n            %   specifies optional name/value pairs:\n            %     'Width'        Width of the violin in axis space.\n            %                    Defaults to 0.3\n            %     'Bandwidth'    Bandwidth of the kernel density\n            %                    estimate. Should be between 10% and\n            %                    40% of the data range.\n            %     'ViolinColor'  Fill color of the violin area\n            %                    and data points.Can be either a matrix\n            %                    nx3 or an array of up to two cells\n            %                    containing nx3 matrices.\n            %     'ViolinAlpha'  Transparency of the violin area and data\n            %                    points. Can be either a single scalar\n            %                    value or an array of up to two cells\n            %                    containing scalar values. Defaults to 0.3.\n            %     'MarkerSize'   Size of the data points, if shown.\n            %                    Defaults to 24\n            % 'MedianMarkerSize' Size of the median indicator, if shown.\n            %                    Defaults to 36\n            %     'EdgeColor'    Color of the violin area outline.\n            %                    Defaults to [0.5 0.5 0.5]\n            %     'BoxColor'     Color of the box, whiskers, and the\n            %                    outlines of the median point and the\n            %                    notch indicators. Defaults to\n            %                    [0.5 0.5 0.5]\n            %     'MedianColor'  Fill color of the median and notch\n            %                    indicators. Defaults to [1 1 1]\n            %     'ShowData'     Whether to show data points.\n            %                    Defaults to true\n            %     'ShowNotches'  Whether to show notch indicators.\n            %                    Defaults to false\n            %     'ShowMean'     Whether to show mean indicator.\n            %                    Defaults to false\n            %     'ShowBox'      Whether to show the box\n            %                    Defaults to true\n            %     'ShowMedian'   Whether to show the median line\n            %                    Defaults to true\n            %     'ShowWhiskers' Whether to show the whiskers\n            %                    Defaults to true\n            %     'HalfViolin'   Whether to do a half violin(left, right side) or\n            %                    full. Defaults to full.\n            %   'QuartileStyle'  Option on how to display quartiles, with a\n            %                    boxplot or as a shadow. Defaults to boxplot.\n            %     'DataStyle'    Defines the style to show the data points. Opts:\n            %                   'scatter', 'histogram' or 'none'. Default is 'Scatter'.\n            \n            st = dbstack; % get the calling function for reporting errors\n            namefun = st.name;\n            args = obj.checkInputs(data, pos, varargin{:});\n            \n            if length(data)==1\n                data2 = [];\n                data = data{1};\n                \n            else\n                data2 = data{2};\n                data = data{1};\n            end\n            \n            if isempty(args.ViolinColor)\n                Release= strsplit(version('-release'), {'a','b'}); %Check release\n                if str2num(Release{1})> 2019 || strcmp(version('-release'), '2019b')  \n                     C = colororder;\n                else\n                     C = lines;\n                end\n                \n                if pos > length(C)\n                    C = lines;\n                end\n                args.ViolinColor = {repmat(C,ceil(size(data,2)/length(C)),1)};\n            end\n            \n            data = data(not(isnan(data)));\n            data2 = data2(not(isnan(data2)));\n            if numel(data) == 1\n                obj.MedianPlot = scatter(pos, data, 'filled');\n                obj.MedianColor = args.MedianColor;\n                obj.MedianPlot.MarkerEdgeColor = args.EdgeColor;\n                return\n            end\n            \n            hold('on');\n            \n\n            %% Calculate kernel density estimation for the violin\n            [density, value, width] = obj.calcKernelDensity(data, args.Bandwidth, args.Width);\n            \n            % also calculate the kernel density of the comparison data if\n            % provided\n            if ~isempty(data2)\n                [densityC, valueC, widthC] = obj.calcKernelDensity(data2, args.Bandwidth, args.Width);\n            end\n            \n            %% Plot the data points within the violin area\n            if length(density) > 1\n                [~, unique_idx] = unique(value);\n                jitterstrength = interp1(value(unique_idx), density(unique_idx)*width, data, 'linear','extrap');               \n            else % all data is identical:\n                jitterstrength = density*width;\n            end\n            if isempty(data2) % if no comparison data\n                jitter = 2*(rand(size(data))-0.5); % both sides\n            else\n                jitter = rand(size(data)); % only right side\n            end\n            switch args.HalfViolin % this is more modular\n                case 'left'\n                    jitter = -1*(rand(size(data))); %left\n                case 'right'\n                    jitter = 1*(rand(size(data))); %right\n                case 'full'\n                    jitter = 2*(rand(size(data))-0.5);\n            end\n            % Make scatter plot\n            switch args.DataStyle\n                case 'scatter'\n                    if ~isempty(data2)\n                        jitter = 1*(rand(size(data))); %right\n                        obj.ScatterPlot = ...\n                            scatter(pos + jitter.*jitterstrength, data, args.MarkerSize, 'filled');\n                        % plot the data points within the violin area\n                        if length(densityC) > 1\n                            jitterstrength = interp1(valueC, densityC*widthC, data2);\n                        else % all data is identical:\n                            jitterstrength = densityC*widthC;\n                        end\n                        jitter = -1*rand(size(data2));% left\n                        obj.ScatterPlot2 = ...\n                            scatter(pos + jitter.*jitterstrength, data2, args.MarkerSize, 'filled');         \n                    else \n                        obj.ScatterPlot = ...\n                            scatter(pos + jitter.*jitterstrength, data, args.MarkerSize, 'filled');\n\n                    end\n                case 'histogram'\n                    [counts,edges] = histcounts(data, size(unique(data),1));\n                    switch args.HalfViolin\n                        case 'right'\n                            obj.HistogramPlot= plot([pos-((counts')/max(counts))*max(jitterstrength)*2, pos*ones(size(counts,2),1)]',...\n                                [edges(1:end-1)+max(diff(edges))/2; edges(1:end-1)+max(diff(edges))/2],'-','LineWidth',1, 'Color', 'k');\n                        case 'left'\n                            obj.HistogramPlot= plot([pos*ones(size(counts,2),1), pos+((counts')/max(counts))*max(jitterstrength)*2]',...\n                                [edges(1:end-1)+max(diff(edges))/2; edges(1:end-1)+max(diff(edges))/2],'-','LineWidth',1, 'Color', 'k');\n                        otherwise\n                            fprintf([namefun, ' No histogram/bar plot option available for full violins, as it would look overcrowded.\\n'])\n                    end\n                case 'none'\n            end\n                \n            %% Plot the violin\n            halfViol= ones(1, size(density,2));\n            if isempty(data2) % if no comparison data\n                switch args.HalfViolin\n                    case 'right'\n                        obj.ViolinPlot =  ... % plot color will be overwritten later\n                            fill([pos+density*width halfViol*pos], ...\n                            [value value(end:-1:1)], [1 1 1]);\n                    case 'left'\n                        obj.ViolinPlot =  ... % plot color will be overwritten later\n                            fill([halfViol*pos pos-density(end:-1:1)*width], ...\n                            [value value(end:-1:1)], [1 1 1]);\n                    case 'full'\n                        obj.ViolinPlot =  ... % plot color will be overwritten later\n                            fill([pos+density*width pos-density(end:-1:1)*width], ...\n                            [value value(end:-1:1)], [1 1 1]);\n                end\n            else\n                % plot right half of the violin\n                obj.ViolinPlot =  ...\n                    fill([pos+density*width pos-density(1)*width], ...\n                    [value value(1)], [1 1 1]);\n                % plot left half of the violin\n                obj.ViolinPlot2 =  ...\n                    fill([pos-densityC(end)*widthC pos-densityC(end:-1:1)*widthC], ...\n                    [valueC(end) valueC(end:-1:1)], [1 1 1]);\n            end\n                \n            %% Plot the quartiles within the violin\n            quartiles = quantile(data, [0.25, 0.5, 0.75]);\n            flat= [halfViol*pos halfViol*pos];\n            switch args.QuartileStyle\n                case 'shadow'\n                    switch args.HalfViolin\n                        case 'right'\n                            w = [pos+density*width halfViol*pos];\n                            h= [value value(end:-1:1)];\n                        case 'left'\n                            w = [halfViol*pos pos-density(end:-1:1)*width];\n                            h= [value value(end:-1:1)];\n                        case 'full'\n                            w = [pos+density*width pos-density(end:-1:1)*width];\n                            h= [value value(end:-1:1)];\n                    end\n                    w(h<quartiles(1))=flat(h<quartiles(1));\n                    w(h>quartiles(3))=flat((h>quartiles(3)));\n                    obj.ViolinPlotQ =  ... % plot color will be overwritten later\n                        fill(w, ...\n                        h, [1 1 1]);\n                case 'boxplot'\n                    obj.BoxPlot = ... % plot color will be overwritten later\n                        fill(pos+[-1,1,1,-1]*args.BoxWidth, ...\n                        [quartiles(1) quartiles(1) quartiles(3) quartiles(3)], ...\n                        [1 1 1]);\n                case 'none'\n            end\n                \n            %% Plot the data mean\n            meanValue = mean(data);\n            if length(density) > 1\n                [~, unique_idx] = unique(value);\n                meanDensityWidth = interp1(value(unique_idx), density(unique_idx), meanValue, 'linear','extrap')*width;\n            else % all data is identical:\n                meanDensityWidth = density*width;\n            end\n            if meanDensityWidth<args.BoxWidth/2\n                meanDensityWidth=args.BoxWidth/2;\n            end\n            switch args.HalfViolin\n                case 'right'\n                    obj.MeanPlot = plot(pos+[0,1].*meanDensityWidth, ...\n                        [meanValue, meanValue]);\n                case 'left'\n                    obj.MeanPlot = plot(pos+[-1,0].*meanDensityWidth, ...\n                        [meanValue, meanValue]);\n                case 'full'\n                    obj.MeanPlot = plot(pos+[-1,1].*meanDensityWidth, ...\n                        [meanValue, meanValue]);\n            end\n            obj.MeanPlot.LineWidth = 1;\n                \n            %% Plot the median, notch, and whiskers\n            IQR = quartiles(3) - quartiles(1);\n            lowhisker = quartiles(1) - 1.5*IQR;\n            lowhisker = max(lowhisker, min(data(data > lowhisker)));\n            hiwhisker = quartiles(3) + 1.5*IQR;\n            hiwhisker = min(hiwhisker, max(data(data < hiwhisker)));\n            if ~isempty(lowhisker) && ~isempty(hiwhisker)\n                obj.WhiskerPlot = plot([pos pos], [lowhisker hiwhisker]);\n            end\n                \n            % Median\n            obj.MedianPlot = scatter(pos, quartiles(2), args.MedianMarkerSize, [1 1 1], 'filled');\n                \n            % Notches\n            obj.NotchPlots = ...\n                scatter(pos, quartiles(2)-1.57*IQR/sqrt(length(data)), ...\n                [], [1 1 1], 'filled', '^');\n            obj.NotchPlots(2) = ...\n                scatter(pos, quartiles(2)+1.57*IQR/sqrt(length(data)), ...\n                [], [1 1 1], 'filled', 'v');\n                \n            %% Set graphical preferences\n            obj.EdgeColor = args.EdgeColor;\n            obj.MedianPlot.LineWidth = args.LineWidth;\n            obj.BoxColor = args.BoxColor;\n            obj.BoxWidth = args.BoxWidth;\n            obj.MedianColor = args.MedianColor;\n            obj.ShowData = args.ShowData;\n            obj.ShowNotches = args.ShowNotches;\n            obj.ShowMean = args.ShowMean;\n            obj.ShowBox = args.ShowBox;\n            obj.ShowMedian = args.ShowMedian;\n            obj.ShowWhiskers = args.ShowWhiskers;\n                \n            if not(isempty(args.ViolinColor))\n                if size(args.ViolinColor{1},1) > 1\n                    ViolinColor{1} = args.ViolinColor{1}(pos,:);\n                else\n                    ViolinColor{1} = args.ViolinColor{1};\n                end\n                if length(args.ViolinColor)==2\n                    if size(args.ViolinColor{2},1) > 1\n                        ViolinColor{2} = args.ViolinColor{2}(pos,:);\n                    else\n                        ViolinColor{2} = args.ViolinColor{2};\n                    end\n                else\n                    ViolinColor{2} = ViolinColor{1};\n                end\n            else\n                % defaults\n                if args.scpltBool\n                    ViolinColor{1} = obj.ScatterPlot.CData;\n                else\n                    ViolinColor{1} = [0 0 0];\n                end\n                ViolinColor{2} = [0 0 0];\n            end\n            obj.ViolinColor = ViolinColor;\n                \n                \n            if not(isempty(args.ViolinAlpha))\n                if length(args.ViolinAlpha{1})>1\n                    error('Only scalar values are accepted for the alpha color channel');\n                else\n                    ViolinAlpha{1} = args.ViolinAlpha{1};\n                end\n                if length(args.ViolinAlpha)==2\n                    if length(args.ViolinAlpha{2})>1\n                        error('Only scalar values are accepted for the alpha color channel');\n                    else\n                        ViolinAlpha{2} = args.ViolinAlpha{2};\n                    end\n                else\n                    ViolinAlpha{2} = ViolinAlpha{1}/2;  % default unless specified\n                end\n            else\n                % default\n                ViolinAlpha = {1,1};\n            end\n            obj.ViolinAlpha = ViolinAlpha;\n                \n                \n        end\n            \n        %% SET METHODS\n        function set.EdgeColor(obj, color)\n            if ~isempty(obj.ViolinPlot)\n                obj.ViolinPlot.EdgeColor = color;\n                obj.ViolinPlotQ.EdgeColor = color;\n                if ~isempty(obj.ViolinPlot2)\n                    obj.ViolinPlot2.EdgeColor = color;\n                end\n            end\n        end\n            \n        function color = get.EdgeColor(obj)\n            if ~isempty(obj.ViolinPlot)\n                color = obj.ViolinPlot.EdgeColor;\n            end\n        end\n            \n            \n        function set.MedianColor(obj, color)\n            obj.MedianPlot.MarkerFaceColor = color;\n            if ~isempty(obj.NotchPlots)\n                obj.NotchPlots(1).MarkerFaceColor = color;\n                obj.NotchPlots(2).MarkerFaceColor = color;\n            end\n        end\n            \n        function color = get.MedianColor(obj)\n            color = obj.MedianPlot.MarkerFaceColor;\n        end\n            \n            \n        function set.BoxColor(obj, color)\n            if ~isempty(obj.BoxPlot)\n                obj.BoxPlot.FaceColor = color;\n                obj.BoxPlot.EdgeColor = color;\n                obj.WhiskerPlot.Color = color;\n                obj.MedianPlot.MarkerEdgeColor = color;\n                obj.NotchPlots(1).MarkerFaceColor = color;\n                obj.NotchPlots(2).MarkerFaceColor = color;\n            elseif  ~isempty(obj.ViolinPlotQ)\n                obj.WhiskerPlot.Color = color;\n                obj.MedianPlot.MarkerEdgeColor = color;\n                obj.NotchPlots(1).MarkerFaceColor = color;\n                obj.NotchPlots(2).MarkerFaceColor = color;\n            end\n        end\n            \n        function color = get.BoxColor(obj)\n            if ~isempty(obj.BoxPlot)\n                color = obj.BoxPlot.FaceColor;\n            end\n        end\n            \n            \n        function set.BoxWidth(obj,width)\n            if ~isempty(obj.BoxPlot)\n                pos=mean(obj.BoxPlot.XData);\n                obj.BoxPlot.XData=pos+[-1,1,1,-1]*width;\n            end\n        end\n            \n        function width = get.BoxWidth(obj)\n            width=max(obj.BoxPlot.XData)-min(obj.BoxPlot.XData);\n        end\n            \n            \n        function set.ViolinColor(obj, color)\n            obj.ViolinPlot.FaceColor = color{1};\n            obj.ScatterPlot.MarkerFaceColor = color{1};\n            obj.MeanPlot.Color = color{1};\n            if ~isempty(obj.ViolinPlot2)\n                obj.ViolinPlot2.FaceColor = color{2};\n                obj.ScatterPlot2.MarkerFaceColor = color{2};\n            end\n            if  ~isempty(obj.ViolinPlotQ)\n                obj.ViolinPlotQ.FaceColor = color{1};\n            end\n            for idx = 1: size(obj.HistogramPlot,1)\n                obj.HistogramPlot(idx).Color = color{1};\n            end\n        end\n                \n        function color = get.ViolinColor(obj)\n            color{1} = obj.ViolinPlot.FaceColor;\n            if ~isempty(obj.ViolinPlot2)\n                color{2} = obj.ViolinPlot2.FaceColor;\n            end\n        end\n                \n                \n        function set.ViolinAlpha(obj, alpha)\n            obj.ViolinPlotQ.FaceAlpha = .65;\n            obj.ViolinPlot.FaceAlpha = alpha{1};\n            obj.ScatterPlot.MarkerFaceAlpha = 1;\n            if ~isempty(obj.ViolinPlot2)\n                obj.ViolinPlot2.FaceAlpha = alpha{2};\n                obj.ScatterPlot2.MarkerFaceAlpha = 1;\n            end\n        end\n                \n        function alpha = get.ViolinAlpha(obj)\n            alpha{1} = obj.ViolinPlot.FaceAlpha;\n            if ~isempty(obj.ViolinPlot2)\n                alpha{2} = obj.ViolinPlot2.FaceAlpha;\n            end\n        end\n                \n                \n        function set.ShowData(obj, yesno)\n            if yesno\n                obj.ScatterPlot.Visible = 'on';\n                for idx = 1: size(obj.HistogramPlot,1)\n                    obj.HistogramPlot(idx).Visible = 'on';\n                end\n            else\n                obj.ScatterPlot.Visible = 'off';\n                for idx = 1: size(obj.HistogramPlot,1)\n                    obj.HistogramPlot(idx).Visible = 'off';\n                end\n            end\n            if ~isempty(obj.ScatterPlot2)\n                obj.ScatterPlot2.Visible = obj.ScatterPlot.Visible;\n            end\n            \n        end\n                \n        function yesno = get.ShowData(obj)\n            if ~isempty(obj.ScatterPlot)\n                yesno = strcmp(obj.ScatterPlot.Visible, 'on');\n            end\n        end\n                \n                \n        function set.ShowNotches(obj, yesno)\n            if ~isempty(obj.NotchPlots)\n                if yesno\n                    obj.NotchPlots(1).Visible = 'on';\n                    obj.NotchPlots(2).Visible = 'on';\n                else\n                    obj.NotchPlots(1).Visible = 'off';\n                    obj.NotchPlots(2).Visible = 'off';\n                end\n            end\n        end\n                \n        function yesno = get.ShowNotches(obj)\n            if ~isempty(obj.NotchPlots)\n                yesno = strcmp(obj.NotchPlots(1).Visible, 'on');\n            end\n        end\n                \n                \n        function set.ShowMean(obj, yesno)\n            if ~isempty(obj.MeanPlot)\n                if yesno\n                    obj.MeanPlot.Visible = 'on';\n                else\n                    obj.MeanPlot.Visible = 'off';\n                end\n            end\n        end\n                \n        function yesno = get.ShowMean(obj)\n            if ~isempty(obj.BoxPlot)\n                yesno = strcmp(obj.BoxPlot.Visible, 'on');\n            end\n        end\n                \n                \n        function set.ShowBox(obj, yesno)\n            if ~isempty(obj.BoxPlot)\n                if yesno\n                    obj.BoxPlot.Visible = 'on';\n                else\n                    obj.BoxPlot.Visible = 'off';\n                end\n            end\n        end\n                \n        function yesno = get.ShowBox(obj)\n            if ~isempty(obj.BoxPlot)\n                yesno = strcmp(obj.BoxPlot.Visible, 'on');\n            end\n        end\n                \n                \n        function set.ShowMedian(obj, yesno)\n            if ~isempty(obj.MedianPlot)\n                if yesno\n                    obj.MedianPlot.Visible = 'on';\n                else\n                    obj.MedianPlot.Visible = 'off';\n                end\n            end\n        end\n                \n        function yesno = get.ShowMedian(obj)\n            if ~isempty(obj.MedianPlot)\n                yesno = strcmp(obj.MedianPlot.Visible, 'on');\n            end\n        end\n                \n                \n        function set.ShowWhiskers(obj, yesno)\n            if ~isempty(obj.WhiskerPlot)\n                if yesno\n                    obj.WhiskerPlot.Visible = 'on';\n                else\n                    obj.WhiskerPlot.Visible = 'off';\n                end\n            end\n        end\n                \n        function yesno = get.ShowWhiskers(obj)\n            if ~isempty(obj.WhiskerPlot)\n                yesno = strcmp(obj.WhiskerPlot.Visible, 'on');\n            end\n        end\n                \n    end\n            \n    methods (Access=private)\n        function results = checkInputs(~, data, pos, varargin)\n            isscalarnumber = @(x) (isnumeric(x) & isscalar(x));\n            p = inputParser();\n            p.addRequired('Data', @(x)isnumeric(vertcat(x{:})));\n            p.addRequired('Pos', isscalarnumber);\n            p.addParameter('Width', 0.3, isscalarnumber);\n            p.addParameter('Bandwidth', [], isscalarnumber);\n            iscolor = @(x) (isnumeric(x) & size(x,2) == 3);\n            p.addParameter('ViolinColor', [], @(x)iscolor(vertcat(x{:})));\n            p.addParameter('MarkerSize', 24, @isnumeric);\n            p.addParameter('MedianMarkerSize', 36, @isnumeric);\n            p.addParameter('LineWidth', 0.75, @isnumeric);\n            p.addParameter('BoxColor', [0.5 0.5 0.5], iscolor);\n            p.addParameter('BoxWidth', 0.01, isscalarnumber);\n            p.addParameter('EdgeColor', [0.5 0.5 0.5], iscolor);\n            p.addParameter('MedianColor', [1 1 1], iscolor);\n            p.addParameter('ViolinAlpha', {0.3,0.15}, @(x)isnumeric(vertcat(x{:})));\n            isscalarlogical = @(x) (islogical(x) & isscalar(x));\n            p.addParameter('ShowData', true, isscalarlogical);\n            p.addParameter('ShowNotches', false, isscalarlogical);\n            p.addParameter('ShowMean', false, isscalarlogical);\n            p.addParameter('ShowBox', true, isscalarlogical);\n            p.addParameter('ShowMedian', true, isscalarlogical);\n            p.addParameter('ShowWhiskers', true, isscalarlogical);\n            validSides={'full', 'right', 'left'};\n            checkSide = @(x) any(validatestring(x, validSides));\n            p.addParameter('HalfViolin', 'full', checkSide);\n            validQuartileStyles={'boxplot', 'shadow', 'none'};\n            checkQuartile = @(x)any(validatestring(x, validQuartileStyles));\n            p.addParameter('QuartileStyle', 'boxplot', checkQuartile);\n            validDataStyles = {'scatter', 'histogram', 'none'};\n            checkStyle = @(x)any(validatestring(x, validDataStyles));\n            p.addParameter('DataStyle', 'scatter', checkStyle);\n            \n            p.parse(data, pos, varargin{:});\n            results = p.Results;\n        end\n    end\n        \n    methods (Static)\n        function [density, value, width] = calcKernelDensity(data, bandwidth, width)\n            if isempty(data)\n                error('Empty input data');\n            end\n            [density, value] = ksdensity(data, 'bandwidth', bandwidth);\n            density = density(value >= min(data) & value <= max(data));\n            value = value(value >= min(data) & value <= max(data));\n            value(1) = min(data);\n            value(end) = max(data);\n            value = [value(1)*(1-1E-5), value, value(end)*(1+1E-5)];\n            density = [0, density, 0];\n            \n            % all data is identical\n            if min(data) == max(data)\n                density = 1;\n                value= mean(value);\n            end\n            \n            width = width/max(density);\n        end\n    end\nend\n\n", "meta": {"author": "bastibe", "repo": "Violinplot-Matlab", "sha": "c1545d484b390020c395d11b8174fe44a62d852a", "save_path": "github-repos/MATLAB/bastibe-Violinplot-Matlab", "path": "github-repos/MATLAB/bastibe-Violinplot-Matlab/Violinplot-Matlab-c1545d484b390020c395d11b8174fe44a62d852a/Violin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.24998474183179775}}
{"text": "function valstr = m2json(val)\n    if isstruct(val)\n        valstr = struct2json(val);\n    elseif iscell(val)\n        valstr = cell2json(val);\n    elseif isa(val, 'numeric')\n        sz = size(val);\n        if length(find(sz>1))>1 % 2D or higher array\n            valstr = '';\n            for i = 1:sz(1)\n                valsubstr = [sprintf('%.15g, ', val(i,:))];\n                valsubstr = valsubstr(1:(end-2));\n                valstr = [valstr ', [' valsubstr ']'];\n            end\n            valstr = valstr(3:end); % trail leading commas\n        else\n            valstr = [sprintf('%.15g, ', val)];\n            valstr = valstr(1:(end-2));\n        end\n        if length(val)>1\n            valstr = ['[' valstr ']'];\n        elseif length(val) == 0\n            valstr = '[]';\n        end\n        valstr = strrep(valstr, 'Inf', 'null');\n        valstr = strrep(valstr, 'NaN', 'null');\n    elseif ischar(val)\n        if size(val, 1) > 1\n            valstr = cell2json(cellstr(val));\n        else\n            val = checkescape(val); %add escape characters\n            valstr = ['\"' val '\"'];\n        end\n    elseif islogical(val)\n        if val\n            valstr = 'true';\n        else\n            valstr = 'false';\n        end\n    else\n        valstr = ''; % wtf is it?\n    end\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/thirdParty/plotly-graphing-library-for-matlab-master/plotly/plotly_aux/m2json.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2499389747764833}}
{"text": "function [img1_2,img1_4,img1_8,img2_2,img2_4,img2_8,img2mask_2,img2mask_4,img2mask_8]=GPReduceAll(img1,img2,img2mask,levels,displayflag)\n%\n% [img1_2,img1_4,img1_8,img2_2,img2_4,img2_8]=GPReduceAll(img1,img2,levels)\n%\n\nglobal Gimg1 Gimg2 Gimg2mask Gimg1_2 Gimg1_4 Gimg1_8 Gimg2_2 Gimg2_4 Gimg2_8 Gimg2mask_2 Gimg2mask_4 Gimg2mask_8;\n\nif ~isequal(img1,Gimg1) || isempty(Gimg1_2)\n\tdisp('Down sampling image #1 for step 2...');\n% \tif( size(img1,3) > size(img2,3) & size(img2,3)==16 )\n% \t\tGimg1_2 = GPReduce2(img1,16,displayflag);\n% \telse\n\t\tGimg1_2 = GPReduce(img1,displayflag);\n% \tend\nend\n\nif ~isequal(img2,Gimg2) || isempty(Gimg2_2)\n\tdisp('Down sampling image #2 for step 2...');\n\tGimg2_2 = GPReduce(img2,displayflag);\nend\n\nif ~isequal(img2mask,Gimg2mask) || isempty(Gimg2mask_2)\n\tif isempty(img2mask)\n\t\tGimg2mask_2 = [];\n\telse\n\t\tdisp('Down sampling image #2 mask for step 2...');\n\t\tGimg2mask_2 = GPReduce(img2mask,displayflag);\n\tend\nend\n\nif levels > 2\n\tif ~isequal(img1,Gimg1) || isempty(Gimg1_4)\n\t\tdisp('Down sampling image #1 for step 3...');\n% \t\tif( size(img1,3) > size(img2,3) & size(img2,3)==16 )\n% \t\t\tGimg1_4 = GPReduce2(Gimg1_2,8,displayflag);\n% \t\telse\n\t\t\tGimg1_4 = GPReduce(Gimg1_2,displayflag);\n% \t\tend\n\tend\n\n\tif ~isequal(img2,Gimg2) || isempty(Gimg2_4)\n\t\tdisp('Down sampling image #2 for step 3...');\n\t\tGimg2_4 = GPReduce(Gimg2_2,displayflag);\n\tend\n\n\tif ~isequal(img2mask,Gimg2mask) || isempty(Gimg2mask_4)\n\t\tif isempty(img2mask)\n\t\t\tGimg2mask_4 = [];\n\t\telse\n\t\t\tdisp('Down sampling image #2 mask for step 3...');\n\t\t\tGimg2mask_4 = GPReduce(Gimg2mask_2,displayflag);\n\t\tend\n\tend\nend\n\nif levels > 3\n\tif ~isequal(img1,Gimg1) || isempty(Gimg1_8)\n\t\tdisp('Down sampling image #1 for step 4...');\n% \t\tif( size(img1,3) > size(img2,3) & size(img2,3)==16 )\n% \t\t\tGimg1_8 = GPReduce2(Gimg1_4,4,displayflag);\n% \t\telse\n\t\t\tGimg1_8 = GPReduce(Gimg1_4,displayflag);\n% \t\tend\n\tend\n\n\tif ~isequal(img2,Gimg2) || isempty(Gimg2_8)\n\t\tdisp('Down sampling image #2 for step 4...');\n\t\tGimg2_8 = GPReduce(Gimg2_4,displayflag);\n\tend\n\n\tif ~isequal(img2mask,Gimg2mask) || isempty(Gimg2mask_8)\n\t\tif isempty(img2mask)\n\t\t\tGimg2mask_8 = [];\n\t\telse\n\t\t\tdisp('Down sampling image #2 mask for step 4...');\n\t\t\tGimg2mask_8 = GPReduce(Gimg2mask_4,displayflag);\n\t\tend\n\tend\nend\n\nGimg1 = img1;\nGimg2 = img2;\nGimg2mask = img2mask;\n\nimg1_2 = Gimg1_2;\nimg1_4 = Gimg1_4;\nimg1_8 = Gimg1_8;\nimg2_2 = Gimg2_2;\nimg2_4 = Gimg2_4;\nimg2_8 = Gimg2_8;\nimg2mask_2 = Gimg2mask_2;\nimg2mask_4 = Gimg2mask_4;\nimg2mask_8 = Gimg2mask_8;\n\nclear global Gimg1 Gimg2 Gimg2mask Gimg1_2 Gimg1_4 Gimg1_8 Gimg2_2 Gimg2_4 Gimg2_8 Gimg2mask_2 Gimg2mask_4 Gimg2mask_8;\n\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/OpticalFlow/GPReduceAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2499389747764833}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [vertices, faces] = readSTL(filename)\n\n[fs, vs, cout] = stlreadASCII(filename);\n\n[v,I,J] = unique(vs,'rows');\n\nvertices = vs(sort(I),:);\nfaces = zeros(size(fs));\nfor i = 1:size(fs,2)\n    vf = vs(fs(:,i), :);\n    [tf, lc] = ismember(vf,vertices, 'rows');\n    faces(:,i) = lc;\nend\n\nfaces = unique(faces,'rows');\ndif1 = faces(:,1)-faces(:,2); dif2=faces(:,2)-faces(:,3); dif3=faces(:,3)-faces(:,1);\nindDif1 = find(dif1 == 0);\nindDif2 = find(dif2 == 0);\nindDif3 = find(dif3 == 0);\nindDif = union(indDif1, indDif2, indDif3);\n\nufIDX = setdiff([1:size(faces,1)], indDif);\nfaces = faces(ufIDX,:);\n\nreturn;", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/readSTL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993408376257822}}
{"text": "addpath(genpath('D:\\GitHub\\KiloSort2')) % path to kilosort folder\naddpath('D:\\GitHub\\npy-matlab')\n\npathToYourConfigFile = 'D:\\GitHub\\KiloSort2\\configFiles'; % take from Github folder and put it somewhere else (together with the master_file)\nrun(fullfile(pathToYourConfigFile, 'configFile384.m'))\n\nops.chanMap  = 'D:\\GitHub\\KiloSort2\\configFiles\\neuropixPhase3B2_kilosortChanMap.mat';\n\n% common options for every probe\nops.NchanTOT    = 384;% total number of channels in your recording\nops.trange      =[0 Inf];% TIME RANGE IN SECONDS TO PROCESS\n\n% find the binary file in this folder\nrootZ = 'H:\\DATA\\Spikes\\Allen\\recording1';\nfs = [dir(fullfile(rootZ, '*.dat')) dir(fullfile(rootZ, '*.bin'))];\nfname = fs(1).name;\nops.fbinary     = fullfile(rootZ,  fname);\n\n% path to whitened, filtered proc file (on a fast SSD)\nrootH = 'H:\\DATA\\Spikes\\temp\\';\nops.fproc       = fullfile(rootH, 'temp_wh.dat'); % proc file on a fast SSD\n\n\n% preprocess data to create temp_wh.dat\nrez = preprocessDataSub(ops);\n\n%%\n% pre-clustering to re-order batches by depth\n% rez = clusterSingleBatches(rez);\nclusterSingleBatches2;\n\n%%\n% main optimization\nrez = learnAndSolve8(rez);\n\n% this does splits\nrez    = splitAllClusters(rez);\n\n% this saves to Phy\nrezToPhy(rez, rootZ);\n\nfname = fullfile(rootZ, 'rez.mat');\nsave(fname, 'rez', '-v7.3');\n\n\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/temp/masterFwBwAllen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2499306480324303}}
{"text": "function volCoords = functional2volXformCoords(inplane, gray, preserveExactValues)\n% Return coords from Volume view that correspond to coords in\n% mrVista functional inplane coords\n%\n%  volCoords = functional2volXformCoords(inplane, gray, preserveExactValues)\n%\n% We first get a 3xn matrix of functional view coordinates, then find the\n% corresponding inplane anatomical coordinates, and finally find the\n% corresponding volume  coordinates. We use this transform when\n% we want to convert functional data (e.g., a parameter map, coranal, or\n% time series) from the volume view to the inplane view.\n%\n% INPUTS\n%   inplane: mrVista view structure (must be an inplane view)\n%   gray: mrVista view structure (must be a gray view)\n%   preserveExactValues: boolean. If false, return integer coordinates. If\n%                   true, return the calculated (non-integer values). If\n%                   non-integer values are returned, then the parent\n%                   function will have to deal with these, e.g., via\n%                   interpolation.\n% OUTPUTS\n%   volCoords: 3xn matrix of coordinates in Volume space\n%                   corresponding to 3xn matrix of inplane functional  coords\n%\n% Example:\n%   volCoords = ip2volXformCoords(inplane, gray)\n%\n%\n% CO & JW 2016.01.14\n\n% Don't do this unless inplane is really an inplane and volume is really a volume\nif ~strcmp(viewGet(inplane, 'viewType'),'Inplane')\n    myErrorDlg('ip2volParMap can only be used to transform from inplane to volume/gray.');\nend\nif ~strcmp(viewGet(gray, 'viewType'),'Volume') &&~strcmp(viewGet(gray, 'viewType'),'Gray')\n    myErrorDlg('ip2volParMap can only be used to transform from inplane to volume/gray.');\nend\n\n\n% check inputs\nif ~exist('preserveExactValues', 'var'), preserveExactValues = false; end\n\n% we need mrSESSION for the alignment matrix\nmrGlobals;\n\n% The gray coords are the integer-valued (y,x,z) volume \n% coordinates that correspond to the inplanes.  Convert to\n% homogeneous form by adding a row of ones.\npreserveCoords = true;\nfunctionalCoords  = ip2functionalCoords(inplane,    viewGet(inplane, 'coords'), ...\n    [], preserveCoords, preserveExactValues);\nnVoxels = size(functionalCoords, 2);\nfunctionalCoords  = double([functionalCoords; ones(1,nVoxels)]);\n\n% inplane2VolXform is the 4x4 homogeneous transform matrix that\n% takes inplane (y',x',z',1) coordinates into Volume (y,x,z,1)\n% coordinates.\ninplane2VolXform = sessionGet(mrSESSION,'alignment');\n\n% We don't care about the last coordinate in (y,x,z,1), so we\n% toss the fourth row of Xform.  Then our outputs will be (y,x,z).\n% \ninplane2VolXform = inplane2VolXform(1:3,:);\n\n% Transform coord positions to the volume.  Hence, grayCoords\n% contains the volume position of each of the inplane  voxels.  These\n% will generally not fall on integer-valued coordinates, rather they will\n% fall between voxels.  Other functions that rely on the output of this\n% function will require interpolation to get the data at these\n% between-voxel positions.\n% \nvolCoords = inplane2VolXform*functionalCoords; \n\n% % Convert coords from inplane anatomical space to inplane functional space.\n% % We do this because the anatomical inplane is often higher resolution than\n% % the functional data.  We preserve the number of coords so that the number\n% % of output functional voxels is identical to the number of gray or volume\n% % voxels. If requested, we preserve the exact (non-integer) values, which\n% % means that the functional coordinates will lie in locations between the\n% % actual functional data points.\n% preserveCoords = true;\n% volCoords   = ip2functionalCoords(inplane, ipAnatomicalCoords, ...\n%     [], preserveCoords, preserveExactValues);\n\n% Some confusion about zeros in the output coordinates. It seems best to\n% leave the calculations as they are unless there is a problem that someone\n% understands. See below.\n\n% HH, 6/16/2012: If we use the code below, we elimintate some voxels\n% and then nVoxels is different from the size of ipCoords, leading to a\n% mismatch in the size of the expected time series (tSeries) and the\n% size of interpolated tSeries, causing an error in  the line,\n%  tSeries(frame,:) = interp3(subData, ...\n%                                   ipFuncCoords(2,:), ...\n%                                   ipFuncCoords(1,:), ...\n%                                   ipFuncCoords(3,:), ...\n%                                   method);\n%\n% Hence we comment out the lines below. Leaving in the values with 0\n% did not produce an error, at least for the function we tested it on,\n% ip2volTSeries.\n% \n% % ras 12/20/04:\n% % occasionally the xformed grayCoords will include a 0\n% % coordinate. While it seems this should not happen,\n% % I'm applying this band-aid for the time being:\n% [badRows badCols] = find(ipFuncCoords==0); %#ok<ASGLU>\n% goodCols = setdiff(1:nVoxels, badCols);\n% ipFuncCoords = ipFuncCoords(:,goodCols);\n% if length(badCols)>1\n%     fprintf('%i voxels mapped to slice 0...\\n',length(badCols));\n% end\n\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/XformView/functional2volXformCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24993063721810604}}
{"text": "function k = kernDiagGradX(kern, x)\n\n% KERNDIAGGRADX Compute the gradient of the  kernel wrt X.\n% FORMAT\n% DESC computes the gradient of the diagonal of the kernel matrix\n% with respect to the elements of the design matrix given in X.\n% ARG kern : the kernel structure for which gradients are being computed.\n% ARG X : the input data in the form of a design matrix.\n% RETURN gX : the gradients of the diagonal with respect to each\n% element of X. The returned matrix has the same dimensions as X.\n%\n% SEEALSO : kernDiagGradX, kernGradX\n\n% KERN\n\nfhandle = str2func([kern.type 'KernDiagGradX']);\nk = fhandle(kern, x);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/kernDiagGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.24986272117420635}}
{"text": "function lfmVisualise(model, visualiseFunction, visualiseModify, varargin)\n\n% LFMVISUALISE Visualise the outputs in a latent force model\n% FORMAT\n% DESC visualises a latent force model with two latent forces as inputs\n% ARG model :  the model to visualise.\n% ARG visualiseFunction : the function that draws the visualisation (in\n% data space) when the graphs are first drawn.\n% ARG visualiseModify : the function that modifies the visualisation as\n% you create the latent function.\n% ARG arg1, arg2, arg3, ... : various additional arguments to be passed to the\n% visualisation commands.\n%\n%\n% COPYRIGHT : Mauricio Alvarez and Neil D. Lawrence, 2008\n\n% MLTOOLS\n\nglobal visualiseInfo\nkernType = model.kernType(1:3);\nif ~strcmpi(kernType, 'lfm')\n  error('This function is only implemented for \"LFM\" kernels');\nelse\n  if length(varargin)~=4,\n    error('Include the skeleton, the initial position and two posteriors for the outputs')\n  end     \nend\nrange = 1.1*max(max(abs([varargin{3}{1} varargin{3}{2}])));\nfigure(1)\nset(gcf, 'Position', [19 202 582 527]);\nclf\n% Create a black panel as background\nf1 = linspace(-range, range, 200);\nf2 = linspace(-range, range, 200);\nax = axes('position', [0.15 0.15 0.75 0.75]);\nf1Lim = [min(f1) max(f1)];\nf2Lim = [min(f2) max(f2)];\nset(ax, 'xLim', f1Lim);\nset(ax, 'yLim', f2Lim);\nset(ax, 'fontname', 'arial');\nset(ax, 'fontsize', 15);\nset(ax, 'TickLength', [0 0]);\n\nplot(varargin{3}{1}, varargin{3}{2}, 'b.', 'markersize', 20, 'LineWidth', 2)\nhold on\nplot(varargin{4}{1}, varargin{4}{2}, 'r.', 'markersize', 20, 'LineWidth', 2)\nfor i = 2:length(varargin{3}{1})\n  arrow([varargin{3}{1}(i-1) varargin{3}{1}(i)], ...\n        [varargin{3}{2}(i-1) varargin{3}{2}(i)], [], 'b', 2);\nend\nfor i = 2:length(varargin{4}{1})\n  arrow([varargin{4}{1}(i-1) varargin{4}{1}(i)], ...\n        [varargin{4}{2}(i-1) varargin{4}{2}(i)], [], 'r', 2);\nend\na = text(varargin{3}{1}(1), varargin{3}{2}(1), ' Motion 18');\nset(a, 'horizontalalignment', 'left', 'color', [0 0 1], 'fontsize', 16) \na = text(varargin{4}{1}(1), varargin{4}{2}(1), 'Motion 19 ');\nset(a, 'horizontalalignment', 'right', 'color', [1 0 0], 'fontsize', 16) \nxlabel('f_1(t)')\nylabel('f_2(t)')\ntitle('Latent Forces')\ngrid on\nhold off\n%\nvisualiseInfo.plotAxes = ax; \n\nif verLessThan('matlab', 'R2014a')\n  visualiseInfo.latentHandle = line(varargin{3}{1}(1), varargin{3}{2}(1), ...\n                                    'markersize', 20, ...\n                                    'color', [0.5 0.5 0.5], 'marker', ...\n                                    '.', 'visible', ...\n                                    'on', 'erasemode', 'xor');\nelse\n  visualiseInfo.latentHandle = line(varargin{3}{1}(1), varargin{3}{2}(1), ...\n                                    'markersize', 20, ...\n                                    'color', [0.5 0.5 0.5], 'marker', ...\n                                    '.', 'visible', ...\n                                    'on');\nend\nvisualiseInfo.latentLine = [];\nvisualiseInfo.clicked = 0;\nvisualiseInfo.digitAxes = [];\nvisualiseInfo.digitIndex = [];\n\n% visualiseInfo.dynamicsSlider = ...\n%     uicontrol('Style', 'slider', ...\n%               'String', 'Time', ...\n%               'sliderStep', [0.01, 0.1], ...\n%               'units', 'normalized', ...\n%               'position', [0 0.95 1 0.05], ...\n%               'callback', 'lfmClassVisualise(''dynamicsSliderChange'')');\n\n% set(visualiseInfo.dynamicsSlider, 'visible', 'off');\nset(gcf, 'WindowButtonMotionFcn', 'lfmClassVisualise(''move'')')\nset(gcf, 'WindowButtonDownFcn', 'lfmClassVisualise(''click'')')\n\nvisualiseInfo.timer.series = 0;\nvisualiseInfo.timer.stepTime = 0.03;\n\n%figure(2)\n%set(gcf,'Position',[418 332 445 395]);\n%clf\n%subplot(2,1,1);\n%visualiseInfo.f1.handle = plot(0,1.5, 'LineWidth', 2);\n%title('f_1(t)','FontSize', 15, 'FontName', 'arial')\n%set(gca, 'yLim', [-range range]);\n%set(gca, 'fontname', 'arial');\n%set(gca, 'fontsize', 15);\nvisualiseInfo.f1.series = 0;\n%subplot(2,1,2);\n%visualiseInfo.f2.handle = plot(0,1.5,'LineWidth', 2);\n%title('f_2(t)','FontSize', 15, 'FontName', 'arial')\n%set(gca, 'yLim', [-range range]);\n%set(gca, 'fontname', 'arial');\n%set(gca, 'fontsize', 15);\nvisualiseInfo.f2.series = 0;\n\nfigure(2)\nset(gcf,'Position',[635 201 582 527]);\nclf\nvisualiseInfo.visualiseFunction = str2func(visualiseFunction);\nvisHandle = visualiseInfo.visualiseFunction(varargin{1:2});\n%set(gca, 'xlim', [-8  18], ...\n%         'ylim', [-2 15], ...\n%         'zlim', [0 35]);\nset(gca, 'xlim', [-20 10], ...\n         'ylim', [-20 20], ...\n         'zlim', [0 32]);\ntitle('Synthetic Motion', 'FontSize', 15);\n     \n% Pass the data to visualiseInfo\nvisualiseInfo.model = model;\nvisualiseInfo.varargin = varargin;\nvisualiseInfo.visualiseModify = str2func(visualiseModify);\nvisualiseInfo.visHandle = visHandle;\n\n% figure(4)\n% clf\n% set(gcf,'Position',[418 30 445 395]);\n% visualiseInfo.fPos = plot(0,1.5,'LineWidth', 2);\n% %set(gca, 'xLim', [-2*range 2*range]);\n% %set(gca, 'yLim', [-2*range 2*range]);\n% xlabel('f_1(t)')\n% ylabel('f_2(t)')\n% set(gca, 'fontname', 'arial');\n% set(gca, 'fontsize', 15);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/lfmVisualise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2498627139022121}}
{"text": "function p = extractBounds(p)\nif ~isempty(p.F_struc)\n    [lb,ub,used_rows_eq,used_rows_lp] = find_lp_bounds(p.F_struc,p.K);\n    if ~isempty(used_rows_lp)\n        used_rows_lp = used_rows_lp(~any((p.F_struc(p.K.f + used_rows_lp,1+p.nonlinear)),2));\n        if ~isempty(used_rows_lp)\n            lower_defined = find(~isinf(lb));\n            if ~isempty(lower_defined)\n                p.lb(lower_defined) = max(p.lb(lower_defined),lb(lower_defined));\n            end\n            upper_defined = find(~isinf(ub));\n            if ~isempty(upper_defined)\n                p.ub(upper_defined) = min(p.ub(upper_defined),ub(upper_defined));\n            end\n            p.F_struc(p.K.f + used_rows_lp,:)=[];\n            p.K.l = p.K.l - length(used_rows_lp);\n        end\n    end    \n    if ~isempty(used_rows_eq)\n        used_rows_eq = used_rows_eq(~any(full(p.F_struc(used_rows_eq,1+p.nonlinear)),2));\n        if ~isempty(used_rows_eq)\n            lower_defined = find(~isinf(lb));\n            if ~isempty(lower_defined)\n                p.lb(lower_defined) = max(p.lb(lower_defined),lb(lower_defined));\n            end\n            upper_defined = find(~isinf(ub));\n            if ~isempty(upper_defined)\n                p.ub(upper_defined) = min(p.ub(upper_defined),ub(upper_defined));\n            end\n            p.F_struc(used_rows_eq,:)=[];\n            p.K.f = p.K.f - length(used_rows_eq);\n        end\n    end\nend\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/extractBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24981693395037463}}
{"text": "function Y=repmat(varargin)\n%REPMAT (overloaded)\n\ntry\n  X = varargin{1};\n  Y = X;\n  Y.basis = [];\n  n = Y.dim(1);\n  m = Y.dim(2);\n  for i = 1:length(Y.lmi_variables)+1\n    temp = repmatfixed(reshape(X.basis(:,i),n,m),varargin{2:end});\n    Y.basis(:,i) = temp(:);\n  end\n  Y.dim(1) = size(temp,1);\n  Y.dim(2) = size(temp,2);\n  % Reset info about conic terms\n  Y.conicinfo = [0 0];\ncatch\n  error(lasterr)\nend\n\n\n\nfunction B = repmatfixed(A,M,N)\n\nif nargin < 2\n    error('MATLAB:repmat:NotEnoughInputs', 'Requires at least 2 inputs.')\nend\n\nif nargin == 2\n    if isscalar(M)\n        siz = [M M];\n    else\n        siz = M;\n    end\nelse\n    siz = [M N];\nend\n\nif isscalar(A)\n    nelems = prod(siz);\n    if nelems>0\n        % Since B doesn't exist, the first statement creates a B with\n        % the right size and type.  Then use scalar expansion to\n        % fill the array. Finally reshape to the specified size.\n        B = spalloc(nelems,1,nnz(A));\n        B(nelems) = A;\n        if ~isequal(B(1), B(nelems)) | ~(isnumeric(A) | islogical(A))\n            % if B(1) is the same as B(nelems), then the default value filled in for\n            % B(1:end-1) is already A, so we don't need to waste time redoing\n            % this operation. (This optimizes the case that A is a scalar zero of\n            % some class.)\n            B(:) = A;\n        end\n        B = reshape(B,siz);\n    else\n        B = A(ones(siz));\n    end\nelseif ndims(A) == 2 & numel(siz) == 2\n    [m,n] = size(A);\n    \n    if (m == 1 & siz(2) == 1)\n        B = A(ones(siz(1), 1), :);\n    elseif (n == 1 & siz(1) == 1)\n        B = A(:, ones(siz(2), 1));\n    else\n        mind = (1:m)';\n        nind = (1:n)';\n        mind = mind(:,ones(1,siz(1)));\n        nind = nind(:,ones(1,siz(2)));\n        B = A(mind,nind);\n    end\nelse\n    Asiz = size(A);\n    Asiz = [Asiz ones(1,length(siz)-length(Asiz))];\n    siz = [siz ones(1,length(Asiz)-length(siz))];\n    for i=length(Asiz):-1:1\n        ind = (1:Asiz(i))';\n        subs{i} = ind(:,ones(1,siz(i)));\n    end\n    B = A(subs{:});\nend\n\nfunction a = isscalar(b)\n[n,m] = size(b);\na = (n*m == 1);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/repmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2497560182328059}}
{"text": "% DEMCLASSIFICATIONSVARGPLVM2\n% COPYRIGHT Andreas C. Damianou, 2012\n% SEEALSO: demClassificationSvargplvm, demClassificationSvargplvm3,  demClassificationSvargplvm4\n% VARGPLVM\n\n% Like demClassificationSvargplvm but we train\n% with RANDOM subsets of the training data and in the end we take the mean.\n\n% Fix seeds\n\nif ~exist('onlyTest'), onlyTest = false; end\nif ~exist('doPredictions'),    doPredictions = false; end\nif ~exist('testDataPerClass'), testDataPerClass = -1; end %%% All data\nif ~exist('printPlots'), printPlots = true; end\n\ndataPerClass = -1; %%%% ALL data\n\naddpath(genpath('../../bc-vargplvm/matlab'));\naddpath(genpath('../../vargplvm/matlab'));\n\n% This script initialises the options structure 'globalOpt'.\nsvargplvm_init;\n\nif onlyTest\n    load(['demOilSvargplvm' num2str(experimentNo)]);\n    globalOpt = model.globalOpt;\nend\n\n\nglobalOpt.dataSetNames = {'oilData', 'oilLabels'};\nglobalOpt.dataSetName = 'oil';\nglobalOpt.dataToKeep = -1; %%\n\n\nif exist('timeStamps')\n    [globalOpt, YtrAll] = bc_loadData(globalOpt, timeStamps);\nelse\n    [globalOpt, YtrAll] = bc_loadData(globalOpt);\nend\nYall{1} = YtrAll.Y;\nlblsTrain = YtrAll.lbls;\nlabelsTrain = transformLabels(lblsTrain);\n% ---- We want labels with -1 and 1, not 0 and 1 (anti-correlation)\nYtrAll.lbls(YtrAll.lbls == 0) = -1;\nYall{2} = YtrAll.lbls;\n\n\n\nglobalOptTest = globalOpt;\nglobalOptTest.dataPerClass = testDataPerClass;\nglobalOptTest.dataSetName = 'oilTest';\nif exist('timeStamps')\n    [globalOptTest, YtsAll] = bc_loadData(globalOptTest, timeStamps);\nelse\n    [globalOptTest, YtsAll] = bc_loadData(globalOptTest);\nend\nlblsTest = YtsAll.lbls;\nlabelsTest = transformLabels(lblsTest);\nYts{1} = YtsAll.Y;\nYtsAll.lbls(YtsAll.lbls == 0) = -1;\nYts{2} = YtsAll.lbls;\n\n\nif isfield(globalOpt, 'normaliseData') && globalOpt.normaliseData\n    Yall{1} = utils_normaliseData(Yall{1});\n    Yts{1} = utils_normaliseData(Yts{1});\nend\n\n\n%%%%%%%%%%\nindTemp = randperm(size(Yall{1},1));\nindTrial = indTemp(1:dataToKeep);\nYall{1} = Yall{1}(indTrial,:);\nYall{2} = Yall{2}(indTrial,:);\nlblsTrain = lblsTrain(indTrial,:);\nlabelsTrain = labelsTrain(indTrial);\n%%%%%%%%%%%\n\n\n\nif onlyTest\n    model = svargplvmRestorePrunedModel(model, Yall);\nend\n\nnumberOfDatasets = length(Yall);\n\n% globalOpt.baseKern = {'rbfardjit', 'linard2'};\n\n%globalOpt.baseKern = {'rbfardjit', 'rbfardjit'};\n\nglobalOpt.indPoints = min(globalOpt.indPoints, size(Yall{1},1));\n\n\n%-- Load datasets\nfor i=1:numberOfDatasets\n    Y = Yall{i};\n    dims{i} = size(Y,2);\n    N{i} = size(Y,1);\n    indTr = globalOpt.indTr;\n    if indTr == -1\n        indTr = 1:N{i};\n    end\n    if ~exist('Yts')\n        indTs = setdiff(1:size(Y,1), indTr);\n        Yts{i} = Y(indTs,:);\n    end\n    Ytr{i} = Y(indTr,:);\n    \n    t{i} = linspace(0, 2*pi, size(Y, 1)+1)'; t{i} = t{i}(1:end-1, 1);\n    timeStampsTraining{i} = t{i}(indTr,1); %timeStampsTest = t(indTs,1);\nend\n\nfor i=2:numberOfDatasets\n    if N{i} ~= N{i-1}\n        error('The number of observations in each dataset must be the same!');\n    end\nend\n\n%%\nif ~onlyTest\n    % Free up some memory\n    clear('Y')\n    \n    options = svargplvmOptions(Ytr, globalOpt, labelsTrain);\n    \n    \n    \n    if ~isempty(globalOpt.dynamicsConstrainType)\n        for i=1:numberOfDatasets\n            % Set up dynamcis (i.e. back-constraints) model\n            optionsDyn{i}.type = 'vargpTime';\n            optionsDyn{i}.inverseWidth=30;\n            %   optionsDyn.vardistCovars = vardistCovarsMult;\n            optionsDyn{i}.initX = globalOpt.initX;\n            optionsDyn{i}.constrainType = globalOpt.dynamicsConstrainType;\n            \n            if exist('timeStampsTraining')\n                optionsDyn{i}.t = timeStampsTraining;\n            end\n            if exist('labelsTrain') && ~isempty(labelsTrain)\n                optionsDyn{i}.labels = labelsTrain;\n            end\n        end\n    else\n        optionsDyn= [];\n    end\n    \n    \n    \n    \n    model = svargplvmModelCreate(Ytr, globalOpt, options, optionsDyn);\n    if exist('diaryFile')\n        model.diaryFile = diaryFile;\n    end\n    \n    model.globalOpt = globalOpt;\n    model.options = options;\n    \n    \n    \n    %-- Define what level of parallelism to use (w.r.t submodels or/and w.r.t\n    % datapoints).\n    %{\nfprintf('# Parallel computations w.r.t the submodels!\\n');\nmodel.parallel = 1;\nmodel = svargplvmPropagateField(model,'parallel', 1);\n%\nfprintf('# Parallel computations w.r.t the datapoints!\\n');\nmodel.vardist.parallel = 1;\nfor i=1:model.numModels\n    model.comp{i}.vardist.parallel = 1;\nend\n    %}\n    \n            %%%% TEMP\n    if exist('whiteVar')\n        fprintf('aaa\\n\\n\\n')\n        model.dynamics.kern.comp{2}.variance = whiteVar;\n    end\n    %%%%\n    \n    \n    % Force kernel computations\n    params = svargplvmExtractParam(model);\n    model = svargplvmExpandParam(model, params);\n    \n\n    \n    %%\n    fprintf('# Median of vardist. covars: %d \\n',median(median(model.vardist.covars)));\n    fprintf('# Min of vardist. covars: %d \\n',min(min(model.vardist.covars)));\n    fprintf('# Max of vardist. covars: %d \\n',max(max(model.vardist.covars)));\n    \n    \n    \n    model = svargplvmOptimiseModel(model);\n    \n    svargplvmShowScales(model)\n    figure\nend\n\n%%\n    capName = model.globalOpt.dataSetName;\n    capName(1) = upper(capName(1));\n    errors = fgplvmNearestNeighbour(model.comp{1}, lblsTrain);\n    model2 = vargplvmReduceModel(model.comp{1}, 2);\n    errors2 = fgplvmNearestNeighbour(model2, lblsTrain);\n    fprintf('# Visualisation errors in all dims/in 2D:  %d / %d\\n', errors, errors2)\n    if printPlots    \n        vargplvmPrintPlot(model2, lblsTrain, [capName 'Vargplvm'], model.globalOpt.experimentNo);\n               \n        %%\n        % For 3D plots:\n        % labels = model.options{1}.labels; dims = [1 3 5];\n        % plot3k({model.X(:,dims(1)) model.X(:,dims(2)) model.X(:,dims(3))}, 'ColorData', labels, 'Marker', {'x',6});\n    end\n\n%%\nobsMod = 1; % one of the involved sub-models (the one for which we have the data)\ninfMod = setdiff(1:2, obsMod);\n\nsharedDims = svargplvmFindSharedDims(model);\n\n%---------------------------- PREDICTIONS ---------------\nif ~doPredictions\n    return\nend\n\n\n%%\n\nif ~exist('testOnTraining')\n    testOnTraining=0;\nend\n\n\n%--------------------%\nsvargplvmPredictions %---- Script returning: ZpredMuAll and mini(the indices for NN)\n%--------------------%\n\n\n%--- For classification we are interested in labels\nZpredMuAll(ZpredMuAll > 0) = 1;\nZpredMuAll(ZpredMuAll < 0) = -1;\nNNpred = Ytr{infMod}(mini,:);\nrealLabels = lblsTest(testInd,:);\n\n% Find the error in the labels ------------\n[labelErrors, labelSharingErrors, wrongIndices] = findLabelErrors(realLabels, ZpredMuAll);\n[labelErrorsNN, void, wrongIndicesNN] = findLabelErrors(realLabels,NNpred);\n\nfprintf('# Gplvm label errors: %d\\n', labelErrors);\nfprintf('# Gplvm label sharing errors: %d\\n', labelSharingErrors);\nfprintf('# NN label errors:    %d\\n', labelErrorsNN);\n\n\n% Confusion matrix\ncmat_a = confMatrix( XpredAll, model.X, labelsTrain, labelsTest, 1);\ncmat_rel = cmat_a ./ repmat(sum(cmat_a, 2), 1, length(unique(labelsTrain)));\ncmat_rel\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/demos/demClassificationSvargplvm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24972472098527979}}
{"text": "% overlay_conc\n%\n% callback on mouse down event on spm_image figure\n% should display concentration maps on mri\n%\n% INPUTS:\n% in: CSI object\n% met: metabolite array\n% X: (1,2) vector with the first and last index of x coordinates\n% Y: (1,2) vector with the first and last of y coordinates\n\nfunction overlayConcMapOverMRI\n    %call global variable from spm\n    global st;\n    %default value of 1 for coilNum\n    spmFigure = st.fig;\n\n    [metabolitePlot, xIndexBounds, yIndexBounds, voxels] = getCurrentUserDataValues(spmFigure);\n\n    if(isempty(metabolitePlot))\n        return\n    end\n    % cursorPosition in the dimensions (l-r,a-p,s-i)\n    cursorPosition = st.centre;\n    %dimension size of the MRI\n    dimensionSize = st.vols{1}.dim;\n    %resolution of MRI (in mm)(not used, might be useful)\n    resolution = (st.bb(2,:) - st.bb(1,:) + 1)/dimensionSize(:)';\n\n    [sagital_voxels, coronal_voxels, transverse_voxels] = findIntersectingVoxels(voxels, cursorPosition);\n\n    %3D bounding box of the MRI scan in mm. ie the coordinates where the MRI is\n    %plotted onto.\n    mriBoundingBox = st.bb;\n\n    deleteCurrentConcentrationMap(st);\n    %(needs to be modified if 3D MRSI is to be done)\n    voxelIntersectionPositions = {};\n    counter = 1;\n    metabolitesToPlotVectorized = zeros(1, numel(transverse_voxels));\n    for i = 1:numel(transverse_voxels)\n        xIndex = transverse_voxels(i).fid_aIndex(1) - xIndexBounds(1) + 1;\n        yIndex = transverse_voxels(i).fid_aIndex(2) - yIndexBounds(1) + 1;\n        if (xIndex > 0 && yIndex > 0 && xIndex <= size(metabolitePlot, 1) && yIndex <= size(metabolitePlot, 2))\n            transverseIntersection = transverse_voxels(i).findIntersection('axial', cursorPosition(3));\n            voxelIntersectionPositions{counter} = transverseIntersection(1:2, :) - mriBoundingBox(1,1:2)';\n            metabolitesToPlotVectorized(counter) = metabolitePlot(xIndex, yIndex);\n            counter = counter + 1;\n        end\n    end\n\n    \n    for i = 1:length(voxelIntersectionPositions)\n        currentCoordiante = voxelIntersectionPositions{i};\n        patch(st.vols{1}.ax{4}.ax, currentCoordiante(1, :), ...\n            currentCoordiante(2, :), metabolitesToPlotVectorized(i), ...\n            'Tag', 'trans_plot');\n    end\n    %PLOTTING IN THE SAGITAL PLANE\n    plotVoxelsOnMRIPlane(st.vols{1}.ax{3}.ax, sagital_voxels, 'sagital', cursorPosition);\n\n    %PLOTTING ON THE CORONAL PLANE\n    plotVoxelsOnMRIPlane(st.vols{1}.ax{2}.ax, coronal_voxels, 'coronal', cursorPosition);\nend\n\nfunction [metabolitePlot, xIndexBounds, yIndexBounds, voxels] = getCurrentUserDataValues(spmFigure)\n    figureUserData = spmFigure.UserData;\n    metabolitePlot = figureUserData.metabolitePlot;\n    xIndexBounds = figureUserData.xIndexBounds;\n    yIndexBounds = figureUserData.yIndexBounds;\n    voxels = figureUserData.voxels;\nend\n\nfunction deleteCurrentConcentrationMap(st)\n    concentrationMap = findobj(st.vols{1}.ax{4}.ax,'Tag','trans_plot');\n    delete(concentrationMap);\nend\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/MRSI/callbacks/overlayConcMapOverMRI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24971927847325134}}
{"text": "function RRest(period)\n% RRest runs RR algorithms on ECG and PPG signals using each possible\n% combination of options, as specified in \"setup_universal_params.m\".\n%\n%               RRest('mimic')\n%\n%\tInputs:\n%\t\tdata            data files should be stored in the specified format\n%                       in the directory specified in\n%                       \"setup_universal_params.m\". Data can be downloaded\n%                       using the \"\n%       period          this string specifies the dataset to be analysed.\n%                       Only the 'mimic' dataset has been used with this\n%                       version of the toolbox.\n%\n%\tOutputs:\n%       for each subject, N, the following files are made:\n%           N_int_respSigs      intermediate respiratory signals,\n%           N_respSigs          final respiratory signals\n%           N_rrEsts            RR estimates\n%           N_rrRef             Reference RR values\n%           N_sqi               Signal Quality Index values\n%       for the entire dataset, the following files are made:\n%           alg_names           Names of RR algorithms tested\n%           win_data            Data for every algorithm tested, every\n%                               window, and every subject.\n%\n%   Context:    This is the main file used to run the algorithms. It calls\n%               lots of other functions, contained in separate files.\n%           \n%   Further Information:\n%       This version of the RRest is provided to facilitate reproduction of\n%       the analysis performed in:\n%           Charlton P.H. et al., \"Waveform Analysis to Estimate\n%           Respiratory Rate\" [In Press]\n%       Further information on this study can be obtained at:\n%           http://peterhcharlton.github.io/RRest/waveform_analysis.html\n%       In addition, further information on RRest, including future\n%       versions, can be obtained at:\n%           http://peterhcharlton.github.io/RRest\n%\n%   Comments, Questions, Criticisms, Feedback, Contributions:\n%       See: http://peterhcharlton.github.io/RRest/contributions.html\n%\n%   Version:\n%       v.1 - published on 23rd Feb 2016 by Peter Charlton\n%\n%   Licence:\n%       please see the accompanying file named \"LICENSE\"\n%\n\n%% Setup Universal Parameters\n% The universal parameters are used throughout the algorithms\nup = setup_universal_params(period);\n\nif up.analysis.run_analysis\n    \n    %% Estimate RRs from ECG and PPG\n    % Carry out processing for each stage of the algorithms\n    for key_comp_no = 1 : length(up.al.key_components)\n        feval(up.al.key_components{key_comp_no}, up);\n    end\n    \n    %% Conduct Signal Quality Assessment of Signals\n    % Each window of ECG and PPG is quality assessed\n    calculate_sqi(up);\n    \n    %% Estimate Reference RRs\n    estimate_ref_rr(up);\n    \nend\n\n%% Statistical Analysis\ncalc_stats(up);\ncreate_table_of_algorithms(up);\n\nend", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v1.0/Algorithms/RRest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.24971927279901593}}
{"text": "function [outdata,outstate] = asr_process(data,srate,state,windowlen,lookahead,stepsize,maxdims,chunklen,usegpu)\n% Processing function for the Artifact Subspace Reconstruction (ASR) method.\n% [Data,State] = asr_process(Data,SamplingRate,State,WindowLength,LookAhead,StepSize,MaxDimensions,ChunkLength,UseGPU)\n%\n% This function is used to clean multi-channel signal using the ASR method. The required inputs are \n% the data matrix, the sampling rate of the data, and the filter state (as initialized by\n% asr_calibrate). If the data is used on successive chunks of data, the output state of the previous \n% call to asr_process should be passed in.\n%\n% In:\n%   Data : Chunk of data to process [#channels x #samples]. This is a chunk of data, assumed to be\n%          a continuation of the data that was passed in during the last call to asr_process (if\n%          any). The data should be *zero-mean* (e.g., high-pass filtered the same way as for\n%          asr_calibrate).\n%   \n%   SamplingRate : sampling rate of the data in Hz (e.g., 250.0)\n%\n%   State : initial filter state (determined by asr_calibrate or from previous call to asr_process)\n%\n%   WindowLength : Length of the statistcs window, in seconds (e.g., 0.5). This should not be much\n%                  longer than the time scale over which artifacts persist, but the number of samples \n%                  in the window should not be smaller than 1.5x the number of channels. Default: 0.5\n%\n%   LookAhead : Amount of look-ahead that the algorithm should use. Since the processing is causal,\n%               the output signal will be delayed by this amount. This value is in seconds and should\n%               be between 0 (no lookahead) and WindowLength/2 (optimal lookahead). The recommended\n%               value is WindowLength/2. Default: WindowLength/2\n%\n%   StepSize : The statistics will be updated every this many samples. The larger this is, the faster \n%              the algorithm will be. The value must not be larger than WindowLength*SamplingRate.\n%              The minimum value is 1 (update for every sample) while a good value is 1/3 of a second.\n%              Note that an update is always performed also on the first and last sample of the data\n%              chunk. Default: 32\n%\n%   MaxDimensions : Maximum dimensionality of artifacts to remove. Up to this many dimensions (or up \n%                   to this fraction of dimensions) can be removed for a given data segment. If the\n%                   algorithm needs to tolerate extreme artifacts a higher value than the default\n%                   may be used (the maximum fraction is 1.0). Default 0.66\n%\n%   ChunkLength : The length of the chunks to process, in samples. Larger chunks require more\n%                 memory. Default: 50000\n%\n%   UseGPU : Whether to run on the GPU. This makes sense for offline processing if you have a a card\n%            with enough memory and good double-precision performance (e.g., NVIDIA GTX Titan or\n%            K20). Note that for this to work you need to have the Parallel Computing toolbox.\n%            Default: false\n%\n% Out:\n%   Data : cleaned data chunk (same length as input but delayed by LookAhead samples)\n%\n%   State : final filter state (can be passed in for subsequent calls)\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2012-08-31\n\n% UC Copyright Notice\n% This software is Copyright (C) 2013 The Regents of the University of California. All Rights Reserved.\n% \n% Permission to copy, modify, and distribute this software and its documentation for educational,\n% research and non-profit purposes, without fee, and without a written agreement is hereby granted,\n% provided that the above copyright notice, this paragraph and the following three paragraphs appear\n% in all copies.\n% \n% Permission to make commercial use of this software may be obtained by contacting:\n% Technology Transfer Office\n% 9500 Gilman Drive, Mail Code 0910\n% University of California\n% La Jolla, CA 92093-0910\n% (858) 534-5815\n% invent@ucsd.edu \n% \n% This software program and documentation are copyrighted by The Regents of the University of\n% California. The software program and documentation are supplied \"as is\", without any accompanying\n% services from The Regents. The Regents does not warrant that the operation of the program will be\n% uninterrupted or error-free. The end-user understands that the program was developed for research\n% purposes and is advised not to rely exclusively on the program for any reason.\n% \n% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n% SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF\n% THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,\n% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n% PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n% CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR\n% MODIFICATIONS.\n\nif nargin < 4 || isempty(windowlen) \n    windowlen = 0.5; end\nwindowlen = max(windowlen,1.5*size(data,1)/srate);\nif nargin < 5 || isempty(lookahead)\n    lookahead = windowlen/2; end\nif nargin < 6 || isempty(stepsize)\n    stepsize = 32; end\nif nargin < 7 || isempty(maxdims)\n    maxdims = 0.66; end\nif nargin < 9 || isempty(usegpu)\n    usegpu = false; end\nif nargin < 8 || isempty(chunklen)\n    chunklen = 50000; end\nif maxdims < 1\n    maxdims = round(size(data,1)*maxdims); end\nif isempty(data)\n    outdata = data; outstate = state; return; end\n\n[C,S] = size(data);\nN = round(windowlen*srate);\nP = round(lookahead*srate);\n[T,M,A,B] = deal(state.T,state.M,state.A,state.B);\n\n% initialize prior filter state by extrapolating available data into the past (if necessary)\nif isempty(state.carry)\n    state.carry = repmat(2*data(:,1),1,P) - data(:,1+mod(((P+1):-1:2)-1,S)); end\n\ndata = [state.carry data];\ndata(~isfinite(data(:))) = 0;\n\n% split up the total sample range into k chunks\nsplits = ceil(S/chunklen);\nif splits > 1\n    fprintf('Now cleaning data in %i blocks',splits); end\n\nfor i=1:splits\n    range = 1+floor((i-1)*S/splits) : min(S,floor(i*S/splits));\n    if ~isempty(range)\n        % get spectrally shaped data X for statistics computation (range shifted by lookahead)        \n        X = double(data(:,range+P));\n        if isempty(state.SOS)\n            [X,state.iir] = filter(B,A,double(X),state.iir,2);\n        else\n            for s = 1:size(state.SOS,1)\n                [X,state.Zi{s}] = filter(state.SOS(s,1:3),state.SOS(s,4:6),double(X),state.Zi{s},2); end\n            X = X*state.G;        \n        end\n        \n        % move it to the GPU if applicable\n        if usegpu && length(range) > 1000\n            try X = gpuArray(X); catch,end; end\n        % compute running mean covariance (assuming a zero-mean signal)\n        [Xcov,state.cov] = moving_average(N,reshape(bsxfun(@times,reshape(X,1,C,[]),reshape(X,C,1,[])),C*C,[]),state.cov);\n        % extract the subset of time points at which we intend to update\n        update_at = min(stepsize:stepsize:(size(Xcov,2)+stepsize-1),size(Xcov,2));\n        % if there is no previous R (from the end of the last chunk), we estimate it right at the first sample\n        if isempty(state.last_R)\n            update_at = [1 update_at];  %#ok<AGROW>\n            state.last_R = eye(C);\n        end\n        Xcov = reshape(Xcov(:,update_at),C,C,[]);\n        if usegpu\n            Xcov = gather(Xcov); end\n        % do the reconstruction in intervals of length stepsize (or shorter if at the end of a chunk)\n        last_n = 0;\n        for j=1:length(update_at)\n            % do a PCA to find potential artifact components\n            [V,D] = eig(Xcov(:,:,j));\n            [D,order] = sort(reshape(diag(D),1,C)); V = V(:,order);\n            % determine which components to keep (variance below directional threshold or not admissible for rejection)\n            keep = D<sum((T*V).^2) | (1:C)<(C-maxdims);\n            trivial = all(keep);\n            % update the reconstruction matrix R (reconstruct artifact components using the mixing matrix)\n            if ~trivial\n                R = real(M*pinv(bsxfun(@times,keep',V'*M))*V');\n            else\n                R = eye(C);\n            end\n            % apply the reconstruction to intermediate samples (using raised-cosine blending)\n            n = update_at(j);\n            if ~trivial || ~state.last_trivial\n                subrange = range((last_n+1):n);\n                blend = (1-cos(pi*(1:(n-last_n))/(n-last_n)))/2;\n                data(:,subrange) = bsxfun(@times,blend,R*data(:,subrange)) + bsxfun(@times,1-blend,state.last_R*data(:,subrange));\n            end\n            [last_n,state.last_R,state.last_trivial] = deal(n,R,trivial);\n        end\n    end\n    if splits > 1\n        fprintf('.'); end\nend\nif splits > 1\n    fprintf('\\n'); end\n\n% carry the look-ahead portion of the data over to the state (for successive calls)\nstate.carry = [state.carry data(:,(end-P+1):end)];\nstate.carry = state.carry(:,(end-P+1):end);\n\n% finalize outputs\noutdata = data(:,1:(end-P));\nif usegpu\n    state.iir = gather(state.iir);\n    state.cov = gather(state.cov);\nend\noutstate = state;\n\n\n\nfunction [X,Zf] = moving_average(N,X,Zi)\n% Run a moving-average filter along the second dimension of the data.\n% [X,Zf] = moving_average(N,X,Zi)\n%\n% In:\n%   N : filter length in samples\n%   X : data matrix [#Channels x #Samples]\n%   Zi : initial filter conditions (default: [])\n%\n% Out:\n%   X : the filtered data\n%   Zf : final filter conditions\n%\n%                           Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                           2012-01-10\n\nif nargin <= 2 || isempty(Zi)\n    Zi = zeros(size(X,1),N); end\n\n% pre-pend initial state & get dimensions\nY = [Zi X]; M = size(Y,2);\n% get alternating index vector (for additions & subtractions)\nI = [1:M-N; 1+N:M];\n% get sign vector (also alternating, and includes the scaling)\nS = [-ones(1,M-N); ones(1,M-N)]/N;\n% run moving average\nX = cumsum(bsxfun(@times,Y(:,I(:)),S(:)'),2);\n% read out result\nX = X(:,2:2:end);\n\nif nargout > 1\n    Zf = [-(X(:,end)*N-Y(:,end-N+1)) Y(:,end-N+2:end)]; end\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/methods/asr_process.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.24971780291512713}}
{"text": "function [sensor, crash] = checkCrash(car, obstacle_polygon, obstacle_circle)\n    \n    %% ----- Initialization\n\n    A = get(car(1),'Vertices');     %Get vertices of the vehicle\n    dist_crash = 1.5;               %Sensor distance (1.5 = 15cm) for crash\n    obs_crash = false;              %Obstacle crash\n    sens_crash = false;             %Crash sensor values are below 1.5.\n    status = true;                  %Help variable\n\n    %% ----- Check collision between the vehicle and obstacles\n    \n    n_polygons = length(obstacle_polygon);\n    n_circles = length(obstacle_circle);\n    for i = 1:n_polygons\n\n        B = get(obstacle_polygon(i),'Vertices');\n\n        obs_crash = obstacleCrash(A, B, 'polygon');\n\n        if(obs_crash)\n            status = false;\n            break;\n        end\n\n    end\n\n    if(status)\n\n        for i = 1:n_circles\n\n            C = get(obstacle_circle(i),'Vertices');\n\n            obs_crash = obstacleCrash(A, C, 'circle');\n\n            if(obs_crash)\n                break;\n            end\n        end\n    end\n\n    %% ----- Check collision with sensors\n    \n    n_sensors = length(car(2:end));\n    sensor = zeros(1, n_sensors);\n    \n    % Loop through the sensors\n    for i = 1:n_sensors\n        \n        % Get vertices of the sensors\n        D = get(car(i+1),'Vertices');\n        sensor_temp = 0;\n        \n        % For each sensor, check collision with all the obstacles\n        for j = 1:n_circles\n            \n            C = get(obstacle_circle(j), 'Vertices');\n            \n            % Store all the sensor values in a vector\n            [sensor_temp(j), crash] = sensorValues(D, C, 'circle', dist_crash);\n            \n            % Check collision\n            if(crash)\n                sens_crash = true;\n                break;\n            end\n        end\n\n        if( ~sens_crash )\n\n            for k = (j+1):(j + n_polygons)\n\n                B = get(obstacle_polygon(k-j), 'Vertices');\n\n                [sensor_temp(k), crash] = sensorValues(D, B, 'polygon', dist_crash);\n\n                if(crash)\n                    \n                    sens_crash = true;\n                end\n            end\n        end\n        \n        % store the lowest sensor value\n        sensor(i) = min(sensor_temp);\n\n    end\n\n    %sensor = round(10.*sensor);\n    sensor = 10.*sensor;                % Scale the sensor values with 10\n    crash = [obs_crash, sens_crash];    % Store the results in a vector\nend", "meta": {"author": "kennydl", "repo": "Reinforcment-Learning-With-Q-Learning", "sha": "d9aff50bfaa57bedd59134e3eeab029ba4e42c8c", "save_path": "github-repos/MATLAB/kennydl-Reinforcment-Learning-With-Q-Learning", "path": "github-repos/MATLAB/kennydl-Reinforcment-Learning-With-Q-Learning/Reinforcment-Learning-With-Q-Learning-d9aff50bfaa57bedd59134e3eeab029ba4e42c8c/Matlab/checkCrash.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2496189179892427}}
{"text": "%% Example\n% An example script, it is used to show how to use the arcs\n% functions of the KUKA iiwa matlab toolbox\n% First run the following script in Matlab\n% Then start the client on the KUKA iiwa controller\n\n% Mohammad SAFEEA, 24th of April 2018\n\nclose all,clear all;clc;\nwarning('off');\nip='172.31.1.147'; % The IP of the controller\n% start a connection with the server\nglobal t_Kuka;\nt_Kuka=net_establishConnection( ip );\n\nif ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')\n  warning('Connection could not be establised, script aborted');\n  return;\nelse\n\n\n      %% Go to initial configuration\n      relVel=0.25; % over ride relative joint velocities\n      \n      pos={0, -pi / 180 * 10, 0, -pi / 180 * 100, pi / 180 * 90,pi / 180 * 90, 0};   % initial cofiguration\n\n      movePTPJointSpace( t_Kuka , pos, relVel); % go to home position\n      %% Move in an arc, the orientation of EEF changes while performing the motion,\n      % The function utilized (movePTPCirc1OrintationInter)\n      % f2 is the final frame, at which the arc motion ends\n      % f1 is an intermidiate frame, through wich the robot passes while\n      % performing the motion.\n      \n      f1=getEEFPos( t_Kuka );\n      f2=f1;\n      r=75;\n      f1{2}=f1{2}+r;\n      f1{3}=f1{3}-r;\n      f1{6}=f1{6}+pi/8;\n      \n      f2{3}=f2{3}-2*r;\n      f2{6}=f2{6}+pi/2;\n      \n      vel=150; % linear velocity of end-effector mm/sec\n      movePTPCirc1OrintationInter( t_Kuka , f1,f2, vel)\n      \n          %% Move robot in joint space to some initial configuration\npinit={0,pi*20/180,0,-pi*70/180,0,pi*90/180,0}; % joint angles of initial confuguration\nrelVel=0.15; % the relative velocity\nmovePTPJointSpace( t_Kuka , pinit, relVel); % point to point motion in joint space\n\n%% Move EEF -100 mm in Z direction\ndeltaX=0.0;deltaY=0;deltaZ=-100.; % relative displacemnets of end-effector\nPos{1}=deltaX;\nPos{2}=deltaY;\nPos{3}=deltaZ;\nmovePTPLineEefRelBase( t_Kuka , Pos, vel);\n\n%% Store the current position in the memory\nCen=getEEFPos(t_Kuka); % Concider the current position as the center of the arcs\n\n%% Move EEF 50mm in X direction\ndeltaX=100;deltaY=0;deltaZ=0.;\nPos{1}=deltaX;\nPos{2}=deltaY;\nPos{3}=deltaZ;\nmovePTPLineEefRelBase( t_Kuka , Pos, vel);\n%% Store the current position in the memory\ncircle_Starting_Point=getEEFPos( t_Kuka ); % Consider the current point as circle starting point\n\n%% Move in an arc, the arc is drawn on an incliend plane\n% using the function ((movePTPArc_AC))\ntheta=pi/2; % the angle subtended by the arc at the center ((c))\nk=[1;1;1]; % normal vector of the plane, on which the circle is drawn\nc=[Cen{1};Cen{2};Cen{3}]; % the center of the arc\nvel=100; % the motion velocity mm/sec\nmovePTPArc_AC(t_Kuka,theta,c,k,vel)\n      \n%% Go back to ((circle_Starting_Point)) coordinates\nvel=150;\nmovePTPLineEEF( t_Kuka , circle_Starting_Point, vel);\n%% Move in an arc, the arc is drawn in XY plane\n% using the function ((movePTPArcXY_AC))\ntheta=1.98*pi; % the angle subtended by the arc at the center ((c))\nc=[Cen{1};Cen{2}]; % the XY coordinate of the center of the arc\nvel=150; % the motion velocity mm/sec\nmovePTPArcXY_AC(t_Kuka,theta,c,vel)\n\n      %% turn off the server\n       net_turnOffServer( t_Kuka );\n\n\n       fclose(t_Kuka);\nend\n\nwarning('on');", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/OtherFlavours/RKST/Matlab_server/Tutorial_circles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24956931871832203}}
{"text": "function [avg_runtime, plug_events] = get_average_runtime_from_plug_data(appliance_name, training_days, setup)\n\n    appliance_id = getApplianceID(appliance_name);\n    global caching;\n    if caching == 1\n        if exist('cache_plugs_training.mat') == 2\n            load('cache_plugs_training');\n        else\n            appliance_consumption_training = read_plug_data(setup.dataset, setup.household, appliance_id, training_days, setup.granularity);\n            save('cache_plugs_training', 'appliance_consumption_training');\n        end\n    else\n        appliance_consumption_training = read_plug_data(setup.dataset, setup.household, appliance_id, training_days, setup.granularity);\n    end\n\n    if strcmp(appliance_name, 'TV') == 1 ...\n            || strcmp(appliance_name, 'Stereo') == 1 ...\n            || strcmp(appliance_name, 'Fridge') == 1 ...\n            || strcmp(appliance_name, 'Freezer') == 1\n\n        on_events = [];\n        off_events = [];\n        cons = appliance_consumption_training;\n        for i = 1:length(cons)-1\n            % on events\n            if cons(i) < 20 && cons(i+1) >= 20\n                on_events = [on_events; i, i+1, 1, 1];\n            elseif cons(i) >= 20 && cons(i+1) < 20\n                if length(on_events) == 0\n                    continue;\n                end\n                off_events = [off_events; i, i+1, -1, 1];\n            end\n        end\n        \n        if length(off_events) > length(on_events)\n            off_events(end) = [];\n        end\n        \n        avg_runtime = mean(off_events(:,1) - on_events(:,1));\n        plug_events = {off_events, on_events};\n        \n    else\n        error('Not implemented for appliance %s', appliance_name);\n    end\nend", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/framework/get_average_runtime_from_plug_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24956931203338628}}
{"text": "% snirfDownsample()\n%\n% A utility that let's you pick fNIRS files in a file dialog box that\n% are then decimated to the specified frequency using a low pass filter as\n% implemented by the matlab 'downsample' command.\n%\n% Note that original copies of the fNIRS files are not preserved. It is\n% advised that you create a back up of your fNIRS files in case you want to\n% recover the higher sample rate date.\n% Modified from resample code\n% Fixed the problem with edges\n% Fixed the problem with s vector - Meryem Oct 2016\n% Add code to allow non-integer downsampling factor - Meryem Oct 2018\n% Code refined for Homer3 and fNIRS files\n\n% Homer3 Note\n% Downsample tool does not work for a flat file structure\n\nfunction snirfDownsample()\n\nglobal maingui;\nif isempty(maingui)\n    [files, pathnm] = uigetfile( '*.snirf', 'Pick the .snirf file', 'multiselect','on');\nelse\n    fpath = [maingui.dataTree.currElem.path maingui.dataTree.currElem.name];\n    [files, pathnm] = uigetfile( '*.snirf', 'Pick files to downsample', fpath, 'multiselect','on');\nend\n\nif ~iscell(files)\n    if files==0\n        return;\n    end\nend\n\n[~,name,~] = fileparts(files); \n\nfsn = inputdlg( 'Decrease the sampling rate of a sequence by a factor of', 'Downsample SNIRF files', 1 );\nif isempty(fsn)\n    return\nend\nfsn = str2num(fsn{1});\n\nwd = cd;\ncd(pathnm)\n\nif ~iscell(files)\n    foo{1} = files;\n    files = foo;\nend\n\nfor iFile = 1:length(files)\n    snirfData = SnirfClass(files{iFile});\n%     varLst = whos();\n    \n%     fs = 1/(snirfData.data.time(2)-snirfData.data.time(1));\n    \n    if floor(fsn) == fsn % integer check\n      \n        snirfData.data.dataTimeSeries = downsample(snirfData.data.dataTimeSeries,fsn);\n        if ~isempty(snirfData.aux)\n            for iAux = 1:length(snirfData.aux)\n                snirfData.aux(iAux).dataTimeSeries = downsample(snirfData.aux(iAux).dataTimeSeries,fsn);\n                snirfData.aux(iAux).time = downsample(snirfData.aux(iAux).time,fsn);\n            end\n        end\n        snirfData.data.time = downsample(snirfData.data.time,fsn);\n%         s_sampled = zeros(size(snirfData.data.time,1),length(snirfData.aux));\n%         for j=1:size(snirfData.stim,2)\n%             lst_1 = snirfData.stim(j).data(:,3) == 1;\n% %             lst_1 = round(lst_1/fsn);\n%             s_sampled(lst_1,j) = 1;\n%             lst_2 = snirfData.stim(j).data(:,3) == -1;\n% %             lst_2 = round(lst_2/fsn);\n%             s_sampled(lst_2,j) = -1;\n%             snirfData.stim(j).data = s_sampled(:,j);\n%         end\n    else  % if downsample factor is not an integer (first upsample then downsample)\n        t_new = linspace(1, size(snirfData.data.dataTimeSeries,1), 10*size(snirfData.data.dataTimeSeries,1));\n        snirfData.data.dataTimeSeries = interp1(snirfData.data.dataTimeSeries, t_new);\n        snirfData.data.dataTimeSeries = downsample(snirfData.data.dataTimeSeries,round(fsn*10));\n        \n        if ~isempty(snirfData.aux)\n            for iAux = 1:length(snirfData.aux)\n                snirfData.aux(iAux).dataTimeSeries = interp1(snirfData.aux(iAux).dataTimeSeries,t_new);\n                snirfData.aux(iAux).dataTimeSeries = downsample(snirfData.aux(iAux).dataTimeSeries,round(fsn*10))';\n                snirfData.aux(iAux).time = interp1(snirfData.aux(iAux).time,t_new);\n                snirfData.aux(iAux).time = downsample(snirfData.aux(iAux).time,round(fsn*10))';\n            end\n        end\n        \n        snirfData.data.time = interp1(snirfData.data.time, t_new);\n        snirfData.data.time = downsample(snirfData.data.time,round(fsn*10))';\n        \n%         s_sampled = zeros(size(snirfData.data.time,1),length(snirfData.aux));\n%         for j=1:size(snirfData.stim,2)\n%             lst_1 = snirfData.stim(j).data(:,3) == 1;\n% %             lst_1 = round(lst_1/fsn);\n%             s_sampled(lst_1,j) = 1;\n%             lst_2 = snirfData.stim(j).data(:,3) == -1;\n% %             lst_2 = round(lst_2/fsn);\n%             s_sampled(lst_2,j) = -1;\n%             snirfData.stim(j).data = s_sampled(:,j);\n%         end\n    \n    end\n    \n    snirfName = sprintf([name '_downsample_' num2str(fsn) '.snirf']);\n    snirfData.Save(snirfName);\n    msgbox(['File created with name' snirfName]);\nend\n\nnew_name = [files{1} '.orig'];\nmovefile (files{1}, new_name);\n    \ncd(wd);\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/Utils/snirfDownsample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2494948882183962}}
{"text": "function [mask,xmesh_new,ymesh_new] = dicomrt_trimZ(slice,voiref,inpmatrix,dose_xmesh,dose_ymesh,voi,voiselect)\n% dicomrt_trimZ(slice,voiref,inpmatrix,dose_xmesh,dose_ymesh,voi,voiselect)\n%\n% Trim a matrix to min and max boundaries in the selected voi along X and Y.\n% \n% slice is the number of the section (relative to voiref) to be trimmed.\n%   Slice is used to locate the matrix along Z and to match matrix with the corresponding contour in voiselect.\n% inpmatrix is a 2D matrix.\n% dose_xmesh, dose_ymesh, are the coordinates of the center of the pixel for eval and ref.\n% voi and voiselect are the vois' cell array and the # of the voi to be used for the gamma calculation respectively.\n%   They have to be specified together. Both matrices will be masked and reduced in size accordingly with the selected\n%   voi's dimensions. \n%\n% NOTE: Use dicomrt_mask if you want to zeroes all the voxel data outside the voi of interest, without altering the \n%       dimensions of the dose matrix.\n%       This function leave unchanged matrix values outside the voi of interest: no mask is performed.\n%       This functions changes the X, and Y dimensions of the input matrix to fit as close as possible \n%       to the max and min contour position in x and y direction.\n%\n% Example:\n% \n% [trimdose,new_xmesh,new_ymesh]=dicomrt_trimZ(15,1,dose(:,:,15),dose_xmesh,dose_ymesh,VOI,4);\n%\n% calculates the position of the maximum and minimum contour for VOI number 4 in x and y and cut from \"dose\" all\n% the voxels positioned outside these boundaries. Returns the new matrix in trimdose, and the new xmesh, ymesh\n% in new_xmesh and new_ymesh. Here slice number 15 is defined in voiref 1. \n%\n% See also dicomrt_loadmcdose, dicomrt_dosediff\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check case and set-up some parameters and variables\n[matrix_temp,type,label,PatientPosition]=dicomrt_checkinput(inpmatrix,1);\nmatrix=dicomrt_varfilter(matrix_temp);\n[voi_temp,type,label]=dicomrt_checkinput(voi);\nvoi=dicomrt_varfilter(voi_temp);\n\n[locate_voi_min_x,locate_voi_max_x,locate_voi_min_y,locate_voi_max_y] = ...\n    dicomrt_voiboundariesZ(slice,voiref,dose_xmesh,dose_ymesh,voi_temp,voiselect,PatientPosition);\n\nmask=matrix(locate_voi_min_y:locate_voi_max_y,locate_voi_min_x:locate_voi_max_x);\n\nxmesh_new=dose_xmesh(locate_voi_min_x:locate_voi_max_x);\nymesh_new=dose_ymesh(locate_voi_min_y:locate_voi_max_y);\n\n% Restore original variable format\n[mask]=dicomrt_restorevarformat(matrix_temp,mask);\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/system/dicomrt_trimZ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24949487542490745}}
{"text": "function plot_his_map(groundTruthFile, expMapFile)\n%     NeuroSLAM System Copyright (C) 2018-2019 \n%     NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n%     Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n%     The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n%     The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n%     Reference:\n%     Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n%     \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n    % load ground truth data\n    [frameId, gt_x, gt_y, gt_z, gt_rx, gt_ry, gt_rz] = load_ground_truth_data(groundTruthFile);\n\n    % load experience map data\n    [expId, exp_x, exp_y, exp_z, exp_yaw, exp_pitch] = load_exp_map_data(expMapFile); \n\n    hold on\n    plot3(exp_x*1*(100), exp_y*100, exp_z*(-200), '.b');\n    plot3((gt_x - gt_x(1))*100, (gt_y - gt_y(1))*100, (gt_z - gt_z(1))*(100), '.r');            \n    hold off;\n    % grid on\n    view(3)\n    xl = xlabel('exp-x');\n    yl = ylabel('exp-y');\n    zlabel('exp-z');\n    set(xl,'Rotation',15);\n    set(yl,'Rotation',-30);\n    title('3D Experience Map');\n    %                     legend('Result','Truth' ,'1');\n    % axis([-10 20 -10 20 -10 20]);\n    %                     axis equal                    \n    % axis on\n    rotate3d on\n\nend\n", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/05_tookit/plot_history_data/plot_his_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24949487542490742}}
{"text": "%%generate data config\nparam.split_data_num=1;\nparam.file_path_cam1=fullfile(fileparts(pwd),'prid_2011','multi_shot','cam_a');\nparam.file_path_cam2=fullfile(fileparts(pwd),'prid_2011','multi_shot','cam_b');\nparam.save_traindata_filename='train_data_Prid';\nparam.save_testdata_filename='test_data_Prid';\n%% generate ten split train/test data\nfor split_num_start=1:param.split_data_num\n    if ~exist(strcat(param.save_traindata_filename,num2str(split_num_start)),'file')\n        mkdir(strcat(param.save_traindata_filename,num2str(split_num_start)));\n    end\n    if ~exist(strcat(param.save_testdata_filename,num2str(split_num_start)),'file')\n        mkdir(strcat(param.save_testdata_filename,num2str(split_num_start)));\n    end\n    subdir_cam1=dir(param.file_path_cam1);\n    subdir_cam2=dir(param.file_path_cam2);\n    %% select images >27 frame\n    person_file_cam1=[];\n    person_file_cam2=[];\n    for i=3:202\n        image_path_a=fullfile(param.file_path_cam1,subdir_cam1(i).name,'/');\n        image_list_a=dir(image_path_a);\n        len=length(image_list_a);\n        if len<29\n            continue;\n        else\n            person_file_cam1=[person_file_cam1;i-2];        \n        end\n    end\n    for i=3:202\n        image_path_b=fullfile(param.file_path_cam2,subdir_cam2(i).name,'/');\n        image_list_b=dir(image_path_b);\n        len=length(image_list_b);\n        if len<29 \n            continue;\n        else\n            person_file_cam2=[person_file_cam2;i-2];\n        end\n    end\n    %%\n    person_num=intersect(person_file_cam1,person_file_cam2);\n    select_list_len=size(person_num,1);\n    train_data_select=randperm(select_list_len,select_list_len/2);\n    train_data_index=person_num(train_data_select);\n    test_data_index=setdiff(person_num,train_data_index);\n    %generate train data\n    train_data_cam1=[];\n    label_train_cam1=[];\n    train_image_name_cam1={};\n    train_data_cam2=[];\n    label_train_cam2=[];\n    train_image_name_cam2={};\n    for i=1:(length(train_data_index))\n        fprintf('process train data:%d/%d\\n',i,(length(train_data_index)));\n        index=train_data_index(i);\n        image_path_cam1=fullfile(param.file_path_cam1,subdir_cam1(index+2).name,'/');\n        image_list_cam1=dir(image_path_cam1);\n        for j=3:length(image_list_cam1);\n            image_name=strcat(image_path_cam1,image_list_cam1(j).name);\n            image_data=imread(image_name);\n            train_data_cam1=[train_data_cam1;reshape(image_data,1,64*128*3)];\n            label_train_cam1=[label_train_cam1;i];\n            train_image_name_cam1=[train_image_name_cam1,image_name];\n        end\n        image_path_cam2=fullfile(param.file_path_cam2,subdir_cam2(index+2).name,'/');\n        image_list_cam2=dir(image_path_cam2);\n        for j=3:length(image_list_cam2);\n            image_name=strcat(image_path_cam2,image_list_cam2(j).name);\n            image_data=imread(image_name);\n            train_data_cam2=[train_data_cam2;reshape(image_data,1,64*128*3)];\n            label_train_cam2=[label_train_cam2;i];\n            train_image_name_cam2=[train_image_name_cam2,image_name];\n        end\n    end\n    save(strcat(param.save_traindata_filename,num2str(split_num_start),'/train_data.mat'),'train_data_cam1','train_data_cam2','label_train_cam1','label_train_cam2','train_image_name_cam1','train_image_name_cam2');\n    %% generate test data\n    test_data_cam1=[];\n    label_test_cam1=[];\n    test_image_name_cam1={};\n    test_data_cam2=[];\n    label_test_cam2=[];\n    test_image_name_cam2={};\n    for i=1:(length(test_data_index))\n        fprintf('process test data:%d/%d\\n',i,(length(test_data_index)));\n        index=test_data_index(i);\n        image_path_cam1=fullfile(param.file_path_cam1,subdir_cam1(index+2).name,'/');\n        image_list_cam1=dir(image_path_cam1);\n        for j=3:length(image_list_cam1);\n            image_name=strcat(image_path_cam1,image_list_cam1(j).name);\n            image_data=imread(image_name);\n            test_data_cam1=[test_data_cam1;reshape(image_data,1,64*128*3)];\n            label_test_cam1=[label_test_cam1;i+89];\n            test_image_name_cam1=[test_image_name_cam1,image_name];\n        end\n        image_path_cam2=fullfile(param.file_path_cam2,subdir_cam2(index+2).name,'/');\n        image_list_cam2=dir(image_path_cam2);\n        for j=3:length(image_list_cam2);\n            image_name=strcat(image_path_cam2,image_list_cam2(j).name);\n            image_data=imread(image_name);\n            test_data_cam2=[test_data_cam2;reshape(image_data,1,64*128*3)];\n            label_test_cam2=[label_test_cam2;i+89];\n            test_image_name_cam2=[test_image_name_cam2,image_name];\n        end\n    end\n    save(strcat(param.save_testdata_filename,num2str(split_num_start),'/test_data.mat'),'test_data_cam1','test_data_cam2','label_test_cam1','label_test_cam2','test_image_name_cam1','test_image_name_cam2');\nend", "meta": {"author": "liuyuisanai", "repo": "Quality-Aware-Network", "sha": "c1b3dadf5503938782f3c9b4560ec425a597dddb", "save_path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network", "path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network/Quality-Aware-Network-c1b3dadf5503938782f3c9b4560ec425a597dddb/generate_data/generate_prid2011_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24934540126481736}}
{"text": "function varargout = process_pac_dynamic_sur2( varargin )\n% PROCESS_PAC_DYNAMIC: Compute the Time resolved Phase-Amplitude Coupling\n%\n% DOCUMENTATION\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Soheila Samiee, Francois Tadel 2013\n% \n% Updates:\n%   - 1.0.4:  Soheila\n%   - 2.0.0: Soheila, based on dpac v.1.1.3 and surrogate 3, June 2016\n%   - 2.1:   SS, Based on dpac v2.1.0, Nov. 2016\n%   - 3.1:   SS, block resampling (N = 2)\n%   - 3.3:   SS, number of blocks for resampling could be more than 2 \n%            (default =5 ), May 2017\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'Surrogate tPAC - block resampling - version: 3.4';\n    sProcess.FileTag     = '';\n%     sProcess.Category    = 'Custom';\n%     sProcess.SubGroup    = 'dPAC analysis';\n    sProcess.Category    = 'Custom';\n    sProcess.SubGroup    = {'Frequency','Time-resolved Phase-Amplitude Coupling'};\n    sProcess.Index       = 660;\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'raw',      'data',     'results',  'matrix'};\n    sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq', 'timefreq'};\n    sProcess.nInputs     = 1;\n    sProcess.nMinFiles   = 1;\n\n    % === TIME WINDOW\n    sProcess.options.timewindow.Comment = 'Time:';\n    sProcess.options.timewindow.Type    = 'timewindow';\n    sProcess.options.timewindow.Value   = [];\n    % === NESTING FREQ\n    sProcess.options.nesting.Comment = 'Frequency for phase band (low):';\n    sProcess.options.nesting.Type    = 'range';\n    sProcess.options.nesting.Value   = {[8, 12], 'Hz', 2};\n    % === NESTED FREQ\n    sProcess.options.nested.Comment = 'Frequency for amplitude band (high):';\n    sProcess.options.nested.Type    = 'range';\n    sProcess.options.nested.Value   = {[40, 150], 'Hz', 2};\n        % Band for fa\n%     sProcess.options.label_fa.Comment = 'F_A frequency band:';\n%     sProcess.options.label_fa.Type    = 'label';\n    sProcess.options.fa_type.Comment = {'   Single band', ...\n                                        '   More than one center frequencies (default: 20)' };\n    sProcess.options.fa_type.Type    = 'radio';\n    sProcess.options.fa_type.Value   = 1;\n    \n    % === WINDOW LENGTH\n    sProcess.options.winLen.Comment = 'Length of sliding time window:';\n    sProcess.options.winLen.Type    = 'value';\n    sProcess.options.winLen.Value   = {1.10, 'S', 2};\n    \n    % === NUMBER OF SURROGATE DATASETS\n    sProcess.options.Nsurrogate.Comment    = 'Number of surrogate datasets: ';\n    sProcess.options.Nsurrogate.Type       = 'value';\n    sProcess.options.Nsurrogate.Value      = {100, '', 0};\n    \n    \n    % === SOURCES\n    sProcess.options.label5.Comment = '<U><B>Sensors/sources to be investigated :</B></U>';\n    sProcess.options.label5.Type    = 'label';\n    \n    % === CLUSTERS\n    sProcess.options.clusters.Comment = '';\n    sProcess.options.clusters.Type    = 'scout_confirm';\n    sProcess.options.clusters.Value   = {};\n    sProcess.options.clusters.InputTypes = {'results'};\n    \n    % === SENSOR SELECTION\n    sProcess.options.target_data.Comment    = 'Sensor types or names (empty=all): ';\n    sProcess.options.target_data.Type       = 'text';\n    sProcess.options.target_data.Value      = 'MEG, EEG';\n    sProcess.options.target_data.InputTypes = {'data', 'raw'};\n    % === SOURCE INDICES\n    sProcess.options.target_res.Comment    = 'Source indices (empty=all): ';\n    sProcess.options.target_res.Type       = 'text';\n    sProcess.options.target_res.Value      = '';\n    sProcess.options.target_res.InputTypes = {'results'};\n    sProcess.options.label6.Comment = '(The indices will only be considered if the scouts are not selected)';\n    sProcess.options.label6.Type    = 'label'; \n\n    % === ROW NAMES\n    sProcess.options.target_tf.Comment    = 'Row names or indices (empty=all): ';\n    sProcess.options.target_tf.Type       = 'text';\n    sProcess.options.target_tf.Value      = '';\n    sProcess.options.target_tf.InputTypes = {'timefreq', 'matrix'};\n\n    % === LOOP METHOD\n    sProcess.options.label1.Comment = '<U><B>Processing options [expert only]:</B></U>';\n    sProcess.options.label1.Type    = 'label';\n    % === MAX_BLOCK_SIZE\n    sProcess.options.max_block_size.Comment = 'Number of signals to process at once: ';\n    sProcess.options.max_block_size.Type    = 'value';\n    sProcess.options.max_block_size.Value   = {20, ' ', 0};\n\n    % sProcess.options.filter_sensor.InputTypes = {'results'};\n    % === AVERAGE OUTPUT FILES\n    sProcess.options.label2.Comment = '<U><B>Output options:</B></U>';\n    sProcess.options.label2.Type    = 'label';\n    sProcess.options.avgoutput.Comment = 'Save average PAC across trials';\n    sProcess.options.avgoutput.Type    = 'checkbox';\n    sProcess.options.avgoutput.Value   = 1;\n%     % === SAVE PAC MAPS\n%     sProcess.options.savefull.Comment = 'Save the full PAC maps';\n%     sProcess.options.savefull.Type    = 'checkbox';\n%     sProcess.options.savefull.Value   = 1;\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n    Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputsA) %#ok<DEFNU>\ntic\n    % Get options\n    if isfield(sProcess.options, 'timewindow') && isfield(sProcess.options.timewindow, 'Value') && iscell(sProcess.options.timewindow.Value) && ~isempty(sProcess.options.timewindow.Value)\n        OPTIONS.TimeWindow = sProcess.options.timewindow.Value{1};\n    else\n        OPTIONS.TimeWindow = [];\n    end\n    OPTIONS.FunctionVersion = sProcess.Comment;\n    \n    % Clusters\n    if isfield(sProcess.options, 'clusters') && ~isempty(sProcess.options.clusters) && ~isempty(sProcess.options.clusters.Value)\n        OPTIONS.Clusters = sProcess.options.clusters.Value;\n    else\n        OPTIONS.Clusters = [];\n    end\n    OPTIONS.BandNesting = sProcess.options.nesting.Value{1};\n    OPTIONS.BandNested  = sProcess.options.nested.Value{1};\n    OPTIONS.WinLen      = sProcess.options.winLen.Value{1};\n    % Get target\n    if  ~isempty(OPTIONS.Clusters)         % extract cluster\n        OPTIONS.Target = OPTIONS.Clusters;        \n    elseif ismember(sInputsA(1).FileType, {'data','raw'}) && isfield(sProcess.options, 'target_data') && ~isempty(sProcess.options.target_data.Value)\n        OPTIONS.Target = sProcess.options.target_data.Value;\n    elseif strcmpi(sInputsA(1).FileType, 'results') && isfield(sProcess.options, 'target_res') && ~isempty(sProcess.options.target_res.Value)\n        OPTIONS.Target = sProcess.options.target_res.Value;\n    elseif ismember(sInputsA(1).FileType, {'timefreq', 'matrix'}) && isfield(sProcess.options, 'target_tf') && ~isempty(sProcess.options.target_tf.Value)\n        OPTIONS.Target = sProcess.options.target_tf.Value;\n    else\n        OPTIONS.Target = [];\n    end\n    % All other options\n    OPTIONS.MaxSignals   = sProcess.options.max_block_size.Value{1};\n    if (strcmp(sInputsA(1).FileType,'data') && isempty(sProcess.options.target_data.Value)) || ...\n            (strcmp(sInputsA(1).FileType,'results') && isempty(sProcess.options.target_res.Value))\n        OPTIONS.isFullMaps   = 1; \n    else\n        OPTIONS.isFullMaps   = 0; \n    end\n    OPTIONS.isAvgOutput  = sProcess.options.avgoutput.Value;\n    if (length(sInputsA) == 1)\n        OPTIONS.isAvgOutput = 0;\n    end\n    OPTIONS.HighFreqs    = sProcess.options.fa_type.Value;\n    OPTIONS.Nsur = sProcess.options.Nsurrogate.Value{1};\n\n    % ===== INITIALIZE =====\n    % Initialize output variables\n    OutputFiles = {};\n    sPAC_avg = [];\n    nAvg = 0;\n    % Initialize progress bar\n    if bst_progress('isVisible')\n        startValue = bst_progress('get');\n    else\n        startValue = 0;\n    end\n    % Options for LoadInputFile()\n    if strcmpi(sInputsA(1).FileType, 'results')\n        LoadOptions.LoadFull = 0;  % Load kernel-based results as kernel+data\n    else\n        LoadOptions.LoadFull = 1;  % Load the full file\n    end\n    LoadOptions.IgnoreBad   = 1;  % From raw files: ignore the bad segments\n    LoadOptions.ProcessName = func2str(sProcess.Function);\n    LoadOptions.TargetFunc = 'all';\n    % Start the matlabpool for parallel processing in bst_pac\n    \n    % Loop over input files\n    for iFile = 1:length(sInputsA)\n\n        % ===== LOAD SIGNALS =====\n        bst_progress('text', sprintf('PAC: Loading input file (%d/%d)...', iFile, length(sInputsA)));\n        bst_progress('set', round(startValue + (iFile-1) / length(sInputsA) * 100));\n        \n        % Load input signals \n        [sInput, nSignals, iRows] = bst_process('LoadInputFile', sInputsA(iFile).FileName, OPTIONS.Target, OPTIONS.TimeWindow, LoadOptions);\n        if isempty(sInput) || isempty(sInput.Data)\n            return;\n        end\n        \n        \n        % Get sampling frequency\n        sRate = 1 / (sInput.Time(2) - sInput.Time(1));\n        % Check the nested frequencies\n        if (OPTIONS.BandNested(2) > sRate/3)\n            % Warning\n            strMsg = sprintf('Higher nesting frequency is too high (%d Hz) compared with sampling frequency (%d Hz): Limiting to %d Hz', round(OPTIONS.BandNested(2)), round(sRate), round(sRate/3));\n            disp([10 'process_pac> ' strMsg]);\n            bst_report('Warning', sProcess, [], strMsg);\n            % Fix higher frequencyy\n            OPTIONS.BandNested(2) = sRate/3;\n        end\n        % Check the extent of bandNested band\n        if (OPTIONS.BandNested(2) <= OPTIONS.BandNested(1))\n            bst_report('Error', sProcess, [], sprintf('Invalid frequency range: %d-%d Hz', round(OPTIONS.BandNested(1)), round(OPTIONS.BandNested(2))));\n            continue;\n        end\n\n        % ===== COMPUTE PAC MEASURE =====\n        % Number of blocks of signals\n        MAX_BLOCK_SIZE = OPTIONS.MaxSignals;\n        nBlocks = ceil(nSignals / MAX_BLOCK_SIZE);\n        sPAC = [];\n        % Display processing time\n        disp(sprintf('Processing %d blocks of %d signals each.', nBlocks, MAX_BLOCK_SIZE));\n        % Process each block of signals\n        for iBlock = 1:nBlocks\n%             tic\n            bst_progress('text', sprintf('PAC: File %d/%d - Block %d/%d', iFile, length(sInputsA), iBlock, nBlocks));\n            bst_progress('set', round(startValue + (iFile-1)/length(sInputsA)*100 + iBlock/nBlocks*100));    \n            \n            % Indices of the signals\n            iSignals = (iBlock-1)*MAX_BLOCK_SIZE+1 : min(iBlock*MAX_BLOCK_SIZE, nSignals);\n            \n            % Get signals to process\n            if ~isempty(sInput.ImagingKernel)\n                Fblock = sInput.ImagingKernel(iSignals,:) * sInput.Data;\n            else\n                Fblock = sInput.Data(iSignals,:);\n            end\n           \n            % Defining the options\n            PACoptions.doInterpolation = 1;%0               % Applying interpolation in frequency and time domain\n            PACoptions.logCenters = 0; %1                   % Choose the center frequencies for f_A with log space in faBand\n            PACoptions.overlap = 0.5;                       % Time window over lap (0<= value <1)\n            if OPTIONS.HighFreqs ==1\n                PACoptions.nHighFreqs = 1;                  % Number of high frequency centers\n                PACoptions.doInterpolation = 0;\n            else\n                PACoptions.nHighFreqs = 20; %4               % Number of high frequency centers\n            end\n            PACoptions.nSur = OPTIONS.Nsur;\n            OPTIONS.PACoptions = PACoptions;\n            \n            % Estimating DPAC\n            sPACblock = Compute(Fblock, sRate,  OPTIONS.BandNested, OPTIONS.BandNesting, OPTIONS.WinLen, PACoptions);\n            \n            % Check for errors\n            if isempty(sPACblock)\n                return;\n            end\n            % Initialize output structure\n            nTime = length(sPACblock.TimeOut);\n            if isempty(sPAC)\n                sPAC.ValPAC      = [];\n                sPAC.NestingFreq = [];\n                sPAC.NestedFreq  = [];\n                sPAC.PhasePAC    = [];\n                sPAC.DynamicPAC     = zeros(nSignals, nTime, length(sPACblock.HighFreqs), OPTIONS.Nsur);\n                sPAC.DynamicNesting = zeros(nSignals, nTime, length(sPACblock.HighFreqs), OPTIONS.Nsur);\n                sPAC.DynamicPhase   = zeros(nSignals, nTime, length(sPACblock.HighFreqs), OPTIONS.Nsur);                \n                sPAC.HighFreqs = sPACblock.HighFreqs;\n                \n                meanInputTime  = OPTIONS.TimeWindow(1)+(sPACblock.TimeOut(end)+OPTIONS.WinLen/2)/2;\n                meanOutputTime = (sPACblock.TimeOut(1)+sPACblock.TimeOut(end))/2;\n                sPAC.TimeOut   = sPACblock.TimeOut + (meanInputTime - meanOutputTime);\n            end\n            % Copy block results to output structure\n            sPAC.DynamicPAC(iSignals,:,:,:)     = permute(sPACblock.DynamicPAC,[3,2,1,4]);\n            sPAC.DynamicNesting(iSignals,:,:,:) = permute(sPACblock.DynamicNesting,[3,2,1,4]);\n            sPAC.DynamicPhase(iSignals,:,:,:)   = permute(sPACblock.DynamicPhase,[3,2,1,4]);\n        end\n                \n        % ===== APPLY SOURCE ORIENTATION =====\n        if strcmpi(sInput.DataType, 'results') && (sInput.nComponents > 1)\n            % Number of values per vertex\n            switch (sInput.nComponents)\n                case 2\n                    sPAC.ValPAC         = (sPAC.ValPAC(1:2:end,:,:)           + sPAC.ValPAC(2:2:end,:,:))           / 2;\n                    sPAC.NestingFreq    = (sPAC.NestingFreq(1:2:end,:,:)      + sPAC.NestingFreq(2:2:end,:,:))      / 2;\n                    sPAC.NestedFreq     = (sPAC.NestedFreq(1:2:end,:,:)       + sPAC.NestedFreq(2:2:end,:,:))       / 2;\n                    sPAC.PhasePAC       = (sPAC.PhasePAC(1:2:end,:,:)         + sPAC.PhasePAC(2:2:end,:,:))         / 2;\n                    sPAC.DynamicPAC     = (sPAC.DynamicPAC(1:2:end,:,:,:)     + sPAC.DynamicPAC(2:2:end,:,:,:))     / 2;\n                    sPAC.DynamicNesting = (sPAC.DynamicNesting(1:2:end,:,:,:) + sPAC.DynamicNesting(2:2:end,:,:,:)) / 2;\n                    sInput.RowNames     = sInput.RowNames(1:2:end);\n                    sPAC.DynamicPhase   = (sPAC.DynamicPhase(1:2:end,:,:,:)   + sPAC.DynamicPhase(2:2:end,:,:,:))   / 2;\n                    \n                case 3\n                    sPAC.ValPAC         = (sPAC.ValPAC(1:3:end,:,:)           + sPAC.ValPAC(2:3:end,:,:)           + sPAC.ValPAC(3:3:end,:,:))           / 3;\n                    sPAC.NestingFreq    = (sPAC.NestingFreq(1:3:end,:,:)      + sPAC.NestingFreq(2:3:end,:,:)      + sPAC.NestingFreq(3:3:end,:,:))      / 3;\n                    sPAC.NestedFreq     = (sPAC.NestedFreq(1:3:end,:,:)       + sPAC.NestedFreq(2:3:end,:,:)       + sPAC.NestedFreq(3:3:end,:,:))       / 3;\n                    sPAC.PhasePAC       = (sPAC.PhasePAC(1:3:end,:,:)         + sPAC.PhasePAC(2:3:end,:,:)         + sPAC.PhasePAC(3:3:end,:,:))         / 3;\n                    sPAC.DynamicPAC     = (sPAC.DynamicPAC(1:3:end,:,:,:)     + sPAC.DynamicPAC(2:3:end,:,:,:)     + sPAC.DynamicPAC(3:3:end,:,:,:))     / 3;\n                    sPAC.DynamicNesting = (sPAC.DynamicNesting(1:3:end,:,:,:) + sPAC.DynamicNesting(2:3:end,:,:,:) + sPAC.DynamicNesting(3:3:end,:,:,:)) / 3;\n                    sInput.RowNames     = sInput.RowNames(1:3:end);\n                    sPAC.DynamicPhase   = (sPAC.DynamicPhase(1:3:end,:,:,:)   + sPAC.DynamicPhase(2:3:end,:,:,:)   + sPAC.DynamicPhase(3:3:end,:,:,:))   / 3;\n                    \n            end\n        end\n\n        % ===== SAVE FILE =====\n        % Detect incomplete lists of sources\n        isIncompleteResult = strcmpi(sInput.DataType, 'results') && (length(sInput.RowNames) * sInput.nComponents < nSignals);\n        % Comment\n        Comment = 'Sur. DynamicPAC';\n        if iscell(sInput.RowNames)\n            % Find the scout name\n            scoutName = sInput.RowNames{1};\n            k = strfind(scoutName,'.');               \n            if isempty(k)\n                Comment = [Comment, ': ' scoutName];      \n            else\n                Comment = [Comment, ': ' scoutName(1:k-1)];\n            end\n           \n        elseif (length(sInput.RowNames) == 1)\n            Comment = [Comment, ': #', num2str(sInput.RowNames(1))];\n        elseif isIncompleteResult\n            Comment = [Comment, ': ', num2str(length(sInput.RowNames)), ' sources'];\n        end\n        \n        if OPTIONS.isFullMaps\n            Comment = [Comment, ' (Full)'];\n        end\n        % Output data type: if there are not all the sources, switch the datatype to \"scout\"\n        if isIncompleteResult\n            sInput.DataType = 'scout';\n            % Convert source indices to strings\n            if ~iscell(sInput.RowNames)\n                sInput.RowNames = cellfun(@num2str, num2cell(sInput.RowNames), 'UniformOutput', 0);\n            end\n        end\n        % Save each as an independent file\n        if ~OPTIONS.isAvgOutput\n            nAvg = 1;\n            OutputFiles{end+1} = SaveFile(sPAC, sInput.iStudy, sInputsA(iFile).FileName, sInput, Comment, nAvg, OPTIONS);\n        else\n            % Compute online average of the connectivity matrices\n            if isempty(sPAC_avg)\n                sPAC_avg.ValPAC      = sPAC.ValPAC       ./ length(sInputsA);\n                sPAC_avg.NestingFreq = sPAC.NestingFreq  ./ length(sInputsA);\n                sPAC_avg.NestedFreq  = sPAC.NestedFreq   ./ length(sInputsA);\n                sPAC_avg.PhasePAC(:,:,:,nAvg+1)       =  sPAC.PhasePAC;\n                sPAC_avg.DynamicPAC(:,:,:,nAvg+1)     =  sPAC.DynamicPAC;\n                sPAC_avg.DynamicNesting(:,:,:,nAvg+1) =  sPAC.DynamicNesting;\n                sPAC_avg.DynamicPhase(:,:,:,nAvg+1)   =  sPAC.DynamicPhase;\n                \n                sPAC_avg.TimeOut     = sPAC.TimeOut;\n                sPAC_avg.HighFreqs   = sPAC.HighFreqs;\n            else\n                sPAC_avg.ValPAC      = sPAC_avg.ValPAC      + sPAC.ValPAC      ./ length(sInputsA);\n                sPAC_avg.NestingFreq = sPAC_avg.NestingFreq + sPAC.NestingFreq ./ length(sInputsA);\n                sPAC_avg.NestedFreq  = sPAC_avg.NestedFreq  + sPAC.NestedFreq  ./ length(sInputsA);\n                sPAC_avg.PhasePAC(:,:,:,nAvg+1)       =  sPAC.PhasePAC;\n                sPAC_avg.DynamicPAC(:,:,:,nAvg+1)     =  sPAC.DynamicPAC;\n                sPAC_avg.DynamicPhase(:,:,:,nAvg+1)   =  sPAC.DynamicPhase;\n                sPAC_avg.DynamicNesting(:,:,:,nAvg+1) =  sPAC.DynamicNesting;                 \n            end\n            nAvg = nAvg + 1;\n        end\n    end\n    \n    % ===== SAVE AVERAGE =====\n    if OPTIONS.isAvgOutput\n        % Output study, in case of average\n        [tmp, iOutputStudy] = bst_process('GetOutputStudy', sProcess, sInputsA);\n        % Save file\n        OutputFiles{1} = SaveFile(sPAC_avg, iOutputStudy, [], sInput, Comment, nAvg, OPTIONS);\n    end\nend\n\n\n%% ========================================================================\n%  ===== SUPPORT FUNCTIONS ================================================\n%  ========================================================================\n\n%% ===== SAVE FILE =====\nfunction NewFile = SaveFile(sPAC, iOuptutStudy, DataFile, sInput, Comment, nAvg, OPTIONS)\n    % ===== PREPARE OUTPUT STRUCTURE =====\n    % Create file structure\n    FileMat = db_template('timefreqmat');\n    FileMat.TF        = sPAC.ValPAC;\n    FileMat.Comment   = Comment;\n    FileMat.Method    = 'dpac';\n    FileMat.Measure   = 'maxpac';\n    FileMat.DataFile  = file_win2unix(DataFile);\n    FileMat.nAvg      = nAvg;\n    FileMat.Freqs     = 0;\n    % All the PAC fields\n    FileMat.sPAC = rmfield(sPAC, 'ValPAC');\n    % Time vector\n    FileMat.Time = sPAC.TimeOut;\n\n    % Output data type and Row names\n    if isempty(OPTIONS.Target)\n        FileMat.DataType = sInput.DataType;\n        FileMat.RowNames = sInput.RowNames; \n    elseif strcmpi(sInput.DataType, 'results') && ~isempty(OPTIONS.Target)\n        FileMat.DataType = 'matrix';\n        if isnumeric(sInput.RowNames)\n        \tFileMat.RowNames = cellfun(@num2str, num2cell(sInput.RowNames), 'UniformOutput', 0);\n        else\n            FileMat.RowNames = sInput.RowNames;\n        end\n    else\n        FileMat.DataType = sInput.DataType;\n        FileMat.RowNames = sInput.RowNames;\n    end\n    % Atlas \n    if ~isempty(sInput.Atlas)\n        FileMat.Atlas = sInput.Atlas;\n    end\n    if ~isempty(sInput.SurfaceFile)\n        FileMat.SurfaceFile = sInput.SurfaceFile;\n    end\n    % History: Computation\n    FileMat = bst_history('add', FileMat, 'compute', 'PAC measure (see the field \"Options\" for input parameters)');\n    % Save options in the file\n    FileMat.Options = OPTIONS;\n    \n    % ===== SAVE FILE =====\n    % Get output study\n    sOutputStudy = bst_get('Study', iOuptutStudy);\n    % File tag\n%     if OPTIONS.isFullMaps\n        fileTag = 'timefreq_dpac_fullmaps';\n%     else\n%         fileTag = 'timefreq_dpac';\n%     end\n    % Output filename\n    NewFile = bst_process('GetNewFilename', bst_fileparts(sOutputStudy.FileName), fileTag);\n    % Save file\n    bst_save(NewFile, FileMat, 'v6');\n    % Add file to database structure\n    db_add_data(iOuptutStudy, NewFile, FileMat);\n    toc\nend\n\n\n\n\n% ===== COMPUTE PAC MEASURE =====\nfunction sPAC = Compute(Xinput, sRate, faBand, fpBand, winLen, Options)\n% USAGE:\n%   sPAC = dPACestimate(Xinput, sRate, faBand, fpBand, winLen, PLvector)\n%\n% INPUTS:\n%    - Xinput:        [nChannels,nTime] signal to process\n%    - sRate:         Sampling frequency (Hz)\n%    - faBand:        Nested Band: Minimum and maximum frequency for extraction of frequency for amplitude\n%    - fpBand:        Nesting Band: Minimum and maximum frequency for extraction of frequency for phase (Hz)\n%    - winLen:        Length of each time window for coupling estimation(S) (default: 1 Sec)\n%    - isFullMaps:    If 1, save the full directPAC maps\n%\n% OUTPUTS:   sPAC structure [for each signal]\n%    - TimeOut:        Output time vector (Sec)\n%    - HighFreqs:       Frequency for amplitude vector\n%    - ValPAC:         [nChannels, nTimeOut] Maximum PAC strength in each  time point\n%    - NestedFreq:     [nChannels, nTimeOut] Fnested corresponding to maximum synchronization index in each time point\n%    - NestingFreq:    [nChannels, nTimeOut] Fnesting corresponding to maximum synchronization index in each time point\n%    - phasePAC:       [nChannels, nTimeOut] Phase corresponding to maximum synchronization index in each time point\n%    - DynamicNesting: [nNestedCenters,nTimeOut,nChannels] Estimated nesting frequency for all times, channels and nested intervals\n%    - DynamicPAC:     [nNestedCenters,nTimeOut,nChannels] full array of PAC\n%\n% DESCRIPTION:\n%   Estimation of Phase Amplitude Coupling (PAC) with DPAC method.\n%\n% Author:  Soheila Samiee, 2013\n%\n\nif (nargin < 4) || isempty(fpBand)\n    fpBand = [4, 8];\nend\nif (nargin < 5) || isempty(winLen)\n    winLen = 1;           \nend\nif ~isfield(Options, 'overlap')\n    Options.overlap = 0.5;\nend\n\n\nif fpBand(2)>faBand(1)\n    fpBand(2) = faBand(1)/2;\n    error_msg = ['Maximum of Fp should be less than half of the minimum of Fa!' 10 10 ...\n        'max{Fp} modified to ', num2str(fpBand(2))];\n    bst_report('Error', sProcess, [], error_msg);\n    disp(['Warning: ' error_msg]);    \nend\n\nif winLen < 2*1/fpBand(1)        \n    error_msg = ['Window length is short for extracting this minimum fp!' 10 ...\n        'Either increase window length to: ',num2str(2*1/fpBand(1)), ' or increase minimum fp to; ', num2str(2/winLen)];\n    bst_report('Error', sProcess, [], error_msg);\n    disp(['Warning: ' error_msg]); \n    winLen = 2*1/fpBand(1);\nend\n\n\n% ===== SETTING THE PARAMETERS =====\ntStep = winLen*(1-Options.overlap);     % Time step for sliding window on time (Sec) (Overlap: 50%)\nmargin = 2;%1                       % Margin (in time) for filtering (Sec) --- default: 2sec -> changed to 1 sec in May12,2016\nhilMar = 1/5;                       % Percentage of margin for Hilber transform\nnTS = size(Xinput,2);               % Number of temporal samples of data\nbandNestingLen= max(3,1/(winLen+margin));% Length of band nesting -- considering the resolution in FFT domain with available window length\nisMirror = 0;                       % Mirroring the data in filtering\nisRelax  = 1;                       % Attenuation of the filter in the stopband (1 => 40 dB, 0 => 60 dB)\nminExtracFreq = max(1/winLen, fpBand(1));  % minimum frequency that could be extracted as nestingFreq\nsProcess = 'Process_pac_dynamic_sur2';\n\n% Mode = Options.Mode;                % Mode of estimating the coupling (line or map)\ndoInterpolation = Options.doInterpolation;  % Applying interpolation in frequency and time domain\nlogCenters = Options.logCenters;    % Choose the center frequencies for f_A with log space in faBand\nnHighFreqs = Options.nHighFreqs;    % Number of high frequency centers\n% Mode = 'map';                       % Mode of estimating the coupling (line or map)\n% doInterpolation = 1;                % Applying interpolation in frequency and time domain\n% logCenters = 0; %0                  % Choose the center frequencies for f_A with log space in faBand\n% nHighFreqs = 20;%4;                 % Number of high frequency centers\nmissedPcount = 0;                   % Number of intervals that do not have peak in their F_A envelope PSD \nmirrorEffectSample = 40;            % Number of samples that can be affected due to mirroring effect\n\nN = 5; % Number of blocks for shuffling\n\n% ==== ADDING MARGING TO THE DATA => AVOID EDGE ARTIFACT (FILTERS AND HILBERT TRANSFORM) ====\nnMargin = fix(margin*sRate);\nnHilMar = fix(nMargin*hilMar);\n\nif (nTS/sRate < 2*winLen)\n    error_msg = 'Data length should be at least twice of window length';\n    bst_report('Error', 'process_pac_dynamic', [], error_msg);\n    disp(['Error: ' error_msg]);\n    sPAC = [];\n    return\n% elseif (nTS < nMargin)\n%     tmp = repmat([Xinput(:,end-1:-1:2),Xinput],1,ceil(nMargin/nTS));    \n%     Xinput = [tmp(:,end-nMargin+1-size(Xinput,2):end-size(Xinput,2)), Xinput, tmp(:,1:nMargin)];\n%     clear tmp\n% else\n%     Xinput = [Xinput(:,nMargin+1:-1:2), Xinput, Xinput(:,end-1:-1:end-nMargin)];\nend\n\n% Zero-padding signal for the margin\nXinput = [zeros(size(Xinput,1),nMargin), Xinput, zeros(size(Xinput,1),nMargin)];\n\n\n\n% ==== SETTING THE PARAMETERS OF THE FILTERS ====\nif nHighFreqs > 1 %strcmp(Mode,'map')\n%     Fconst = (faBand(end)-faBand(1))/nHighFreqs;                     % Frequency distant between successive fAs\n    if logCenters\n        nestedCenters = logspace(log10(faBand(1)),log10(faBand(end)),nHighFreqs);\n    else\n        nestedCenters = linspace(faBand(1),faBand(end),nHighFreqs);\n    end\n    Fstep = diff(nestedCenters)/2;  % the range of frequency around each nested center\n    Fstep = [Fstep(1),Fstep,Fstep(end)];\n    Fstep = max(Fstep, fpBand(2)/2);  % Minimum band width is defined to cover the whole interval between consecutive centre frequencies and at the same time consider all coupled frequencies to it in the range of interest.        \nelse\n    nestedCenters = mean(faBand);\n    Fstep    = abs(faBand-nestedCenters);\nend\n\nfArolloff = [];\nfProlloff = [];%1          % roll off frequency for filtering\nsPAC.HighFreqs = nestedCenters;\nnFa = length(nestedCenters);\nnSources = size(Xinput,1);\nisources = 1:nSources;\nnTime = fix((nTS-fix(winLen*sRate))/fix(tStep*sRate))+1;\nTimeOut = winLen/2 : tStep : winLen/2+(nTime-1)*tStep;        % Sec\nnSur = Options.nSur;                % Number of surrogate itterations\nPAC = zeros(nFa,nTime,nSources,nSur);               % PAC measure\nnestingFreq = zeros(nFa,nTime,nSources,nSur);\nDynamicPhase= zeros(nFa,nTime,nSources);               % PAC measure\n\n\n% ===== MAIN LOOP ON FA ===== %\n% Filtering in Fa band before cutting into smaller time windows\n% (=> Higherfrequency resolution + faster process)\n\nfor ifreq=1:nFa\n    % fA band\n    bandNested = [nestedCenters(ifreq)-Fstep(ifreq),nestedCenters(ifreq)+Fstep(ifreq+1)];\n    \n    % Filtering in fA band\n    Xnested = bst_bandpass_hfilter(Xinput, sRate,bandNested(1), bandNested(2), isMirror, isRelax, fArolloff);    % Filtering\n    Xnested = Xnested(:,nMargin-nHilMar+1:end-nMargin+nHilMar);               % Removing part of the margin\n    \n    % Hilbert transform\n    Z = hilbert(Xnested')';\n    \n    % Phase and envelope detection\n    nestedEnv_total = abs(Z);             % Envelope of nested frequency rhythms\n    nestedEnv_total = nestedEnv_total(:,nHilMar:end-nHilMar);              % Removing the margin\n    \n    % Loop on Time\n    for iTime=1:nTime\n        X = Xinput(:, (iTime-1)*fix(tStep*sRate)+[1:fix((2*margin+winLen)*sRate)]);\n        nestedEnv = nestedEnv_total(:, (iTime-1)*fix(tStep*sRate)+[1:fix(winLen*sRate)]);\n        \n        % Time vector and number of samples\n        nSample = size(nestedEnv,2);\n        nFreq = 2^ceil(log2(nSample)+1);\n        \n        % Extraction of nesting frequency\n        Ffft = abs(fft(nestedEnv-repmat(mean(nestedEnv,2),1,nSample),nFreq,2)).^2/nSample;\n        freq = linspace(0,sRate,nFreq);\n        x1 = X(:,nMargin+1:nMargin+fix(winLen*sRate));\n        FfftSig = abs(fft(x1-repmat(mean(x1,2),1,nSample),nFreq,2)).^2/nSample;\n        %%%\n        \n        % Finding the corresponding frequency component\n        ind = bst_closest([minExtracFreq, fpBand(2)], freq);\n        if freq(ind(1))<(minExtracFreq-diff(freq(1:2)))\n            ind(1) = ind(1)+1;\n        end\n        if ind(2)>fpBand(2)\n            ind(2) = ind(2)-1;\n        end\n        \n                % Add previous and next point to the interval to give the algorithm \n        % to find the local peaks even if they are in the first and last \n        % point of interst in the spectrum\n        if ind(1)>1\n            ind(1) = ind(1)-1;\n        end\n        ind(2) = ind(2)+1;\n        \n        if freq(ind(1))<(minExtracFreq-diff(freq(1:2)))\n            ind(1) = ind(1)+1;\n        end\n        \n        indm = zeros(nSources,1);\n        for iSource=1:nSources\n                        \n            % Extracting the peak from envelope's PSD and then confirming\n            % with a peak on the original signal\n            [pks_env,locs_env] = findpeaks(Ffft(iSource,ind(1):ind(2)),'SORTSTR','descend');\n            [pks_orig, locs_orig] = findpeaks(FfftSig(iSource,ind(1):ind(2)),'SORTSTR','descend');  % To check if a peak close to the coupled fp is available in the original signal\n%             clear pks_env pks_orig\n            \n            % Ignore small peaks\n            pks_orig = pks_orig/max(pks_orig);\n            locs_orig = locs_orig(pks_orig>0.1);\n\n            % Confirming the peak\n            max_dist = max(1.5/winLen,1.5);     % maximum acceptable distance between peaks in evelope and the original signal's PSD\n            count = 1;\n            check_pks = 1;\n            fp_loc = [];\n            while check_pks && count<=length(locs_env)\n                index = bst_closest(freq(locs_env(count)), freq(locs_orig));\n                if abs(freq(locs_orig(index))-freq(locs_env(count)))<=max_dist\n                    fp_loc = locs_env(count);\n                    check_pks = 0;\n                else\n                    count = count+1;\n                end\n            end\n            % If peak is not approved or no peak\n            if isempty(fp_loc)\n                fp_loc = 0;    % arbitrary value for fp  ==> will set the pac value to zero\n                missedPcount = missedPcount +1;\n            end\n            \n            indm(iSource) = fp_loc(1);\n            clear pks_env locs_env\n        end\n        \n        nestingFreq(ifreq,iTime,isources) = freq(ind(1)+indm-1);\n        bandNesting = [max([squeeze(nestingFreq(ifreq,iTime,isources))-bandNestingLen/2,zeros(size(nestingFreq,3),1)],[],2),...\n            squeeze(nestingFreq(ifreq,iTime,isources))+bandNestingLen/2];\n        bandNesting(bandNesting<.15)=.15;\n\n% Filtering in fP band\n        if length(unique(bandNesting(:,1)))==1 && length(unique(bandNesting(:,2)))==1\n            Xnesting = bst_bandpass_hfilter(X, sRate,bandNesting(1,1), bandNesting(1,2), isMirror, isRelax, fProlloff);    % Filtering\n        else\n            Xnesting = zeros(size(X));\n            for i=1:length(isources)\n                Xnesting(i,:) = bst_bandpass_hfilter(X(i,:), sRate, bandNesting(i,1), bandNesting(i,2),isMirror, isRelax, fProlloff);    % Filtering\n            end\n        end        \n        Xnesting = Xnesting(:,nMargin-nHilMar+1:fix((margin+winLen)*sRate)+nHilMar);              % Removing part of the margin        \n        % Hilbert transform\n        Z = hilbert(Xnesting')';        \n        % Phase detection\n        nestingPh = angle(Z-repmat(mean(Z,2),1,size(Z,2)));    % Phase of nesting frequency        \n        nestingPh = nestingPh(:,nHilMar:fix(winLen*sRate)+nHilMar-1);              % Removing the margin\n        \n        \n        for ii=1:length(isources)           \n            iphase = find(diff(sign(nestingPh(ii,:) - nestingPh(ii,1)))==-2 | ...\n                sign(nestingPh(ii,2:end)-nestingPh(ii,1))==0 | ...\n                -(diff(sign(nestingPh(ii,:) - nestingPh(ii,1)))-1).*diff(nestingPh(ii,:)-nestingPh(ii,1)) >6 )-1;\n            if isempty(iphase)\n                iphase = length(nestingPh(ii,:));\n            end\n            amplitude = nestedEnv(ii,1:max(iphase));\n            phase = nestingPh(ii,1:max(iphase));\n            \n            % Block resampling N=2\n            numpoints=length(amplitude); %% number of sample points in raw signal\n\n            if N==2\n                minskip=numpoints/4; %% time lag must be at least this big\n                maxskip=numpoints-numpoints/4; %% time lag must be smaller than this\n                skip = ceil(minskip + (maxskip-minskip-1)*rand(2*nSur,1));\n                skip(skip>maxskip)=[];\n                skip(skip<minskip)=[];\n                skip=skip(1:nSur,1);\n                \n                \n                for iSur=1:nSur\n                    surrogate_amplitude=[amplitude(skip(iSur):end) amplitude(1:skip(iSur)-1)];\n                    PAC(ifreq,iTime,isources(ii),iSur) = sum(surrogate_amplitude.*exp(1i*phase),2)./max(iphase)./sqrt(mean(amplitude.^2,2));\n                    DynamicPhase(ifreq,iTime,isources(ii),iSur) = angle(PAC(ifreq,iTime,isources(ii)));\n                    \n                    if indm(ii)==0 % Fp not confirmed and arbitrary value for fp\n                        PAC(ifreq,iTime,isources(ii),iSur) = 0;\n                    end\n                end\n                \n            elseif N>2 & N<numpoints/20\n                % Block resampling N>2\n%                 N = 10;\n                numpoints=length(amplitude); %% number of sample points in raw signal\n                block_len = fix(numpoints/N);\n                remaining = numpoints - block_len*N;\n                blocked_amp = reshape(amplitude(1:end-remaining),[block_len,N]);\n                \n                for iSur=1:nSur\n                    order = randperm(N);\n                    blocked_amp = blocked_amp(:,order);\n                    surrogate_amplitude = [blocked_amp(:)', amplitude(end-remaining+1:end)];\n                    PAC(ifreq,iTime,isources(ii),iSur) = sum(surrogate_amplitude.*exp(1i*phase),2)./max(iphase)./sqrt(mean(amplitude.^2,2));\n                    DynamicPhase(ifreq,iTime,isources(ii),iSur) = angle(PAC(ifreq,iTime,isources(ii)));\n                    \n                    if indm(ii)==0 % Fp not confirmed and arbitrary value for fp\n                        PAC(ifreq,iTime,isources(ii),iSur) = 0;\n                    end\n                end\n                \n            else\n                warning('Number of blocks should be at least 2, and less than 5% of data points')\n            end\n        end\n    end\n      disp(['iFreq: ', num2str(ifreq),' / ',num2str(nFa)]);\nend\n\n\n\n% ===== EXTRACTING THE PAC RELATED VALUES ===== %\n[PACmax,maxInd] = max(abs(PAC),[],1); \n% Fnested  = squeeze(nestedCenters(maxInd))';\n% Sind     = repmat((1:nSources), nTime, 1);           % Source indices\n% Tind     = repmat((1:nTime)', 1, nSources);              % Time indices\n% linInd   = sub2ind(size(PAC),maxInd(:),Tind(:),Sind(:));\n% Fnesting = reshape(nestingFreq(linInd),nTime,nSources)';\n% phase    = reshape(angle(PAC(linInd)),nTime,nSources)'/pi*180;\n% PACmax   = squeeze(PACmax)';\n\n% ===== Interpolation in time domain for smoothing the results ==== %\nif doInterpolation\n    % Interpolation of PAC\n    if nSources>1       \n        [X,Y,Z,W] = ndgrid(nestedCenters,TimeOut,[1:nSources], 1:nSur);\n        ny = linspace(TimeOut(1), TimeOut(end), 2*length(TimeOut)-1);\n        if logCenters\n            nx = logspace(log10(nestedCenters(1)), log10(nestedCenters(end)), 2*nFa-1);\n        else\n            nx = linspace(nestedCenters(1), nestedCenters(end), 2*nFa-1);\n        end\n        [nX,nY,nZ,nW] = ndgrid(nx,ny,[1:nSources], 1:nSur);\n        PAC = interpn(X,Y,Z,W,abs(PAC),nX,nY,nZ,nW,'linear',0);\n        % make the notations similar\n        tmp = nx; nx = ny;ny = tmp; clear tmp;\n        \n    else        \n        [X,Y,Z] = meshgrid(TimeOut,nestedCenters,[1:nSur]);\n        nx = linspace(TimeOut(1), TimeOut(end), 2*nTime-1);\n        if logCenters\n            ny = logspace(log10(nestedCenters(1)), log10(nestedCenters(end)), 2*nFa-1);\n        else\n            ny = linspace(nestedCenters(1), nestedCenters(end), 2*nFa-1);\n        end\n        [nX,nY,nZ] = meshgrid(nx,ny,[1:nSur]);\n        PAC = interp3(X,Y,Z,abs(squeeze(PAC)),nX,nY,nZ,'linear',0);\n        PAC = permute(PAC,[1,2,4,3]);    \n    end\n    TimeOut = nx;\n    sPAC.HighFreqs = ny;\n    clear nx nX nY nZ X Y Z\n       \n    % nestingFreq\n    tmp = zeros(nFa*2-1, nTime, nSources, nSur);\n    tmp(1:2:end,:,:,:) = nestingFreq;\n    tmp(2:2:end,:,:,:) = nestingFreq(1:end-1,:,:,:);\n    tmp2 = zeros(nFa*2-1, nTime*2-1, nSources, nSur);\n    tmp2(:,1:2:end,:,:) = tmp;\n    tmp2(:,2:2:end,:,:) = tmp(:,1:end-1,:,:);\n    nestingFreq = tmp2; \n    \n    \n    tmp = zeros(nFa*2-1, nTime, nSources, nSur);\n    tmp(1:2:end,:,:,:) = DynamicPhase;\n    tmp(2:2:end,:,:,:) = DynamicPhase(1:end-1,:,:,:);\n    tmp2 = zeros(nFa*2-1, nTime*2-1, nSources, nSur);\n    tmp2(:,1:2:end,:,:) = tmp;\n    tmp2(:,2:2:end,:,:) = tmp(:,1:end-1,:,:);\n    DynamicPhase = tmp2; \n    clear tmp tmp2\n    \nend\n\nFnesting = [];\nFnested = [];\nphase = [];\n\nif missedPcount>0\ndisp(['Missed Peaks:',num2str(missedPcount),'/',num2str(nFa*nTime*nSources)])\nend\n\n% ===== OUTPUTS ===== %\nif nTime >1\n    sPAC.ValPAC = PACmax;\n    sPAC.NestingFreq = Fnesting;\n    sPAC.NestedFreq  = Fnested;\n    sPAC.PhasePAC = phase;\n    sPAC.TimeOut  = TimeOut;\n    sPAC.DynamicPAC(:,:,1:nSources,:) = abs(PAC);\n    sPAC.DynamicNesting(:,:,1:nSources,:)  = nestingFreq;\n    sPAC.DynamicPhase(:,:,1:nSources,:)  = DynamicPhase;\n\n        % == Generating two time points for Brainstorm structure ==\nelse        \n    sPAC.ValPAC = [PACmax(:), PACmax(:)];\n    sPAC.NestingFreq = [Fnesting(:), Fnesting(:)];\n    sPAC.NestedFreq  = [Fnested(:), Fnested(:)];\n    sPAC.PhasePAC = [phase(:), phase(:)];\n    sPAC.TimeOut  = [TimeOut, TimeOut+0.001];\n    sPAC.DynamicPAC(:,1:2,1:nSources,:) = repmat(abs(PAC),[1,2,1]);\n    sPAC.DynamicNesting(:,1:2,1:nSources,:)  = repmat(abs(nestingFreq),[1,2,1]);\n    sPAC.DynamicPhase(:,1:2,1:nSources,:)  = repmat(abs(DynamicPhase),[1,2,1]);\nend\n\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_pac_dynamic_sur2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2492538145729629}}
{"text": "function [A, b, C, d, results] = inflate_region(obstacles, A_bounds, b_bounds, start, varargin)\nimport iris.*;\n\np = inputParser();\np.addOptional('require_containment', false, @isscalar);\np.addOptional('error_on_infeasible_start', false, @isscalar);\np.addOptional('termination_threshold', 2e-2, @(x) x > 0);\np.addOptional('iter_limit', 100, @isnumeric);\np.parse(varargin{:});\noptions = p.Results;\n\nif exist('+iris/inflate_regionmex', 'file')\n  if ~iscell(obstacles)\n    obs_cell = cell(1, size(obstacles, 3));\n    for j = 1:size(obstacles, 3)\n      obs_cell{j} = obstacles(:,:,j);\n    end\n    obstacles = obs_cell;\n\n    % Note: could replace this with the following, but mat2cell is 100 times slower than the for loop\n    % obstacles = mat2cell(obstacles, size(obstacles, 1), size(obstacles, 2), ones(1, size(obstacles, 3)));\n  end\n\n  if nargout > 4\n    [A, b, C, d, p_history, e_history] = inflate_regionmex(obstacles, A_bounds, b_bounds, start, options);\n    results = inflation_results();\n    results.start = start;\n    results.obstacles = obstacles;\n    results.n_obs = numel(obstacles);\n    results.e_history = e_history;\n    results.p_history = p_history;\n  else\n    [A, b, C, d] = inflate_regionmex(obstacles, A_bounds, b_bounds, start, options);\n  end\nelse\n  if iscell(obstacles)\n    padded = pad_obstacle_points(obstacles);\n    obstacle_pts = cell2mat(reshape(padded, size(padded, 1), [], length(obstacles)));\n  else\n    obstacle_pts = obstacles;\n  end\n  [A, b, C, d, results] = inflate_region_fallback(obstacle_pts, A_bounds, b_bounds, start, options);\n  results.obstacles = obstacles;\n  if ~iscell(results.obstacles)\n    results.obstacles = mat2cell(results.obstacles, size(results.obstacles, 1), size(results.obstacles, 2), ones(1, size(results.obstacles, 3)));\n  end\nend\n", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/inflate_region.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2492538075504536}}
{"text": "function cv2tifs(y,f)\n%CV2TIFS Decodes a TIFS2CV compressed image sequence.\n%   Y = CV2TIFS(Y,F) decodes compressed sequence Y (a structure\n%   generated by TIFS2CV) and creates a multiframe TIFF file F.\n%\n%   See also TIFS2CV.\n%\n%   Copyright 2002-2020 Gatesmark\n%\n%   This function, and other functions in the DIPUM Toolbox, are based \n%   on the theoretical and practical foundations established in the \n%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n%   Press, 2020.\n%\n%   Book website: http://www.imageprocessingplace.com\n%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\n% Get the number of frames, block size, and reconstruction quality.\nfcnt = double(y.frames);\nm = double(y.blksz);\nq = double(y.quality);\n\n% Reconstruct the first image in the sequence and store.\nif q == 0\n    r = double(huff2mat(y.video(1)));\nelse\n    r = double(jpeg2im(y.video(1)));\nend\nimwrite(uint8(r),f,'Compression','none','WriteMode','overwrite');\n\n% Get the frame size and motion vectors.\nfsz = size(r);\nmvsz = [fsz/m 2 fcnt];\nmv = int16(huff2mat(y.motion));\nmv = reshape(mv,mvsz);\n\n% For frames except the first, get a motion conpensated prediction\n% residual and add to the proper reference subimages.\nfor i = 2:fcnt\n    if q == 0\n        pe = double(huff2mat(y.video(i)));\n    else\n        pe = double(jpeg2im(y.video(i)) - 255);\n    end\n    peC = im2col(pe,[m m],'distinct');\n    \n    for col = 1:size(peC,2)\n        u = 1 + mod(m * (col - 1),fsz(1));\n        v = 1 + m * floor((col - 1) * m / fsz(1));\n        rx = u - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), ...\n           1, i);\n        ry = v - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), ...\n           2, i);\n        \n        subimage = r(rx:rx + m - 1,ry:ry + m - 1);\n        peC(:,col) = subimage(:) - peC(:,col);\n    end\n\n    r = col2im(double(uint16(peC)),[m m],fsz,'distinct');\n    imwrite(uint8(r),f,'Compression','none', ...\n        'WriteMode','append');\nend\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/cv2tifs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24925380755045354}}
{"text": "function view = getFlatCoords(view)\n%\n% view = getFlatCoords(view)\n%\n% view: must be a flat view\n%\n% Loads gLocs2d and gLocs3d coordinates.  Keeps only those voxels\n% that correspond to the inplane coordinates.  Sets FLAT\n% fields: coordsRight, coordsLeft, grayCoordsRight,\n% grayCoordsLeft.\n%\n% djh, 7/98\n%\n% djh, 8/4/99.  Use intersectCols instead of intersecting the indices.\n% djh, 8/18/99.  loadGLocs now returns curvature.\n\nif ~strcmp(view.viewType,'Flat')\n    myErrorDlg('function getFlatCoords only for Flat view.');\nend\n\npathStr=fullfile(viewDir(view),'coords');\n\nif ~check4File(pathStr)\n    imSize=[0,0];\n    waitHandle = mrvWaitbar(0,'Computing flat coordinates.  Please wait...');\n    for h = 1:2\n        mrvWaitbar((h-1)/2)\n        \n        % Load gLocs2d and gLocs3d\n        %\n        if h==1\n            [gLocs2d,gLocs3d,curvature,leftPath] = loadGLocs('left');\n        else\n            [gLocs2d,gLocs3d,curvature,rightPath] = loadGLocs('right');\n        end\n        \n        if isempty(gLocs2d) | isempty(gLocs3d)\n            coords{h} = [];\n            grayCoords{h} = [];\n        else\n            % Compute imSize\n            %\n            imSize = max(imSize,(max(gLocs2d,[],2) - min(gLocs2d,[],2) + 1)');\n            imSize = round(imSize);\n            \n            % Find gray nodes that are both in the inplanes and included\n            % in the unfold.\n            % gray.coords are the gray coords that lie in the inplanes.\n            % gLocs3d are the gray coords in the unfold.\n            hiddenGray = initHiddenGray;\n            [grayCoordsTmp,gLocsIndices,coordsIndices] = ...                \n                intersectCols(gLocs3d,hiddenGray.coords);\n            grayCoords{h} = grayCoordsTmp;\n            \n            % Flat locations corresponding to those voxels\n            % \n            coords{h} = gLocs2d(:,gLocsIndices);\n            \n            % Warning if there are any NaNs in the coords.\n            NaNs = find(isnan(coords{h}(1,:)) | isnan(coords{h}(2,:)));\n            if ~isempty(NaNs)\n                myWarnDlg(['You have ',int2str(length(NaNs)),' NaNs in your flat coords.  ',...\n                        'Those gray matter nodes will not be rendered in the FLAT view.']);\n            end\n        end\n    end\n    close(waitHandle)\n    \n    % Save to file\n    %\n    save(pathStr,'coords','grayCoords','imSize','leftPath','rightPath');\nend\n\n% Load Flat/coords and fill the fields\n% \nload(pathStr);\nview.coords = coords;\nview.grayCoords = grayCoords;\nview.leftPath = leftPath;\nview.rightPath = rightPath;\nview.ui.imSize = imSize;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/XformView/getFlatCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2492538005279442}}
{"text": "function [source] = ft_source2full(source)\n\n% FT_SOURCE2FULL recreates the grid locations outside the brain in the source \n% reconstruction, so that the source volume again describes the full grid.\n% This undoes the memory savings that can be achieved using FT_SOURCE2SPARSE\n% and makes it possible again to plot  the source volume and save it to an\n% external file.\n%\n% Use as\n%   [source] = ft_source2full(source)\n%\n% See also FT_SOURCE2SPARSE\n\n% Copyright (C) 2004, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nft_defaults\n\nif ~isfield(source, 'inside')  || ...\n   ~isfield(source, 'outside') || ...\n   ~isfield(source, 'dim')\n  ft_error('one of the required fields is missing in the source structure');\nend\n\nif ~isfield(source, 'pos') && (~isfield(source, 'xgrid') || ~isfield(source, 'ygrid') || ...\n                               ~isfield(source, 'zgrid'))\n  ft_error('the input data needs at least a ''pos'' field, or ''x/y/zgrid''');\nend\n\nif isfield(source, 'xgrid'),\n  xgrid = source.xgrid;\n  ygrid = source.ygrid;\n  zgrid = source.zgrid;\n  sparsepos = source.pos;\n  \n  % recreate the positions of the dipole grid\n  [X, Y, Z] = ndgrid(xgrid, ygrid, zgrid);\n  pos = [X(:) Y(:) Z(:)];\nelse\n  %FIXME this assumes that the voxel data are ordered as if in a regularly spaced 3D grid,\n  %but with only the inside voxels present\n  ft_warning('assuming the voxel data to be ordered as if in a regularly spaced 3D grid');\n  xgrid = 1:source.dim(1);\n  ygrid = 1:source.dim(2);\n  zgrid = 1:source.dim(3);\n\n  %establish a homogeneous transformation matrix from voxels to headspace based on the sparse positions\n  sparsepos = source.pos;\n  ok  = 0;\n  cnt = 0;\n  while ok==0,\n    cnt  = cnt+1;\n    dpos = sparsepos - sparsepos(cnt*ones(size(sparsepos,1),1),:);\n    [srt, indx] = sort(sum(dpos.^2,2));\n    srt    = dpos(indx,:);\n    tmpsrt = abs(srt(2:7,:));\n    csrt   = tmpsrt*tmpsrt';\n    sel    = find(sum(csrt==0)>=2);\n    if numel(sel)>=3, \n      ok = 1;\n    end\n  end  \n  tmppos  = sparsepos(indx([1 sel(:)'+1]),:);\n  tmpdpos = dpos(indx([1 sel(:)'+1]),:);\n \n  % FIXME the following is a bit experimental and not fully tested yet it works in general case rotation\n  M         = pinv(tmpdpos(2:4,:));\n  \n  % get rotation such that maxima are on diagonal and positive\n  m(1) = find(M(1,:)==max(abs(M(1,:))));\n  m(2) = find(M(2,:)==max(abs(M(2,:))));\n  m(3) = find(M(3,:)==max(abs(M(3,:))));\n  [srt, indx] = sort(m);\n  M    = M(indx,:);\n  M    = M*diag(sign(diag(M)));\n  sparsepos = sparsepos*M;\n  \n  % translation\n  T         = -min(sparsepos,[],1)+1;\n  sparsepos = sparsepos + T(ones(size(sparsepos,1),1), :);  \n\n  % recreate the positions of the dipole grid\n  [X, Y, Z] = ndgrid(xgrid, ygrid, zgrid);\n  pos = [X(:) Y(:) Z(:)];\n  pos = ft_warp_apply(inv([M T(:);0 0 0 1]), pos);\nend\n\nNsparse = length(source.inside);\nsiz     = source.dim;\nNfull   = prod(siz);\n\n% determine the size that each slice takes in memory\nsx = 1;\nsy = siz(1);\nsz = siz(1) * siz(2);\n\nif isfield(source, 'inside') && isfield(source, 'outside') && size(source.pos,1)==Nfull\n  % it contains all source positions\n  inside = source.inside;\n  outside = source.outside;\nelse\n  % it only contains the inside source positions, which are all inside the brain\n  % reconstruct the original inside and outside grid locations\n  inside = zeros(Nsparse,1);\n  for i=1:Nsparse\n    fx = find(xgrid==sparsepos(i,1));\n    fy = find(ygrid==sparsepos(i,2));\n    fz = find(zgrid==sparsepos(i,3));\n      inside(i) = (fx-1)*sx + (fy-1)*sy + (fz-1)*sz + 1;\n  end\n  outside = setdiff([1:Nfull]', inside);\nend\n\nfprintf('total number of dipoles        : %d\\n', length(inside)+length(outside));\nfprintf('number of dipoles inside  brain: %d\\n', length(inside));\nfprintf('number of dipoles outside brain: %d\\n', length(outside));\n\n% determine whether the source is old or new style\nfnames = fieldnames(source);\nif any(~cellfun('isempty', strfind(fnames, 'dimord'))),\n  stype = 'new';\nelse\n  stype = 'old';\nend\n\nif strcmp(stype, 'old')\n  % original code\n  % first do the non-trial fields\n  source.dim = [1 length(inside) 1]; %to fool parameterselection\n  [param]    = parameterselection('all', source);\n  trlparam   = strmatch('trial', param);\n  sel        = setdiff(1:length(param), trlparam);\n  ind=find(ismember(param,'inside')); % find the index of 'inside' field\n  % because its position varies with isfield('plvspctrm') vs. 'cohspctrm'\n  param      = param(sel(ind));\n  \n  for j = 1:length(param)\n    dat = getsubfield(source, param{j});\n    if islogical(dat)\n      tmp         = false(1,Nfull); \n      tmp(inside) = dat;\n    elseif iscell(dat)\n      tmp          = cell(1,Nfull);\n      tmp(inside)  = dat;\n      %tmp(outside) = nan;\n    else\n      tmp         = nan(1,Nfull);\n      tmp(inside) = dat;   \n    end\n    source = setsubfield(source, param{j}, tmp);\n  end\n  \n  % then do the trial fields\n  if     isfield(source, 'trial' )\n    for j = 1:length(source.trial)\n      tmpsource     = source.trial(j);\n      tmpsource.dim = source.dim; % to fool parameterselection\n      tmpparam      = parameterselection('all', tmpsource);\n      for k = 1:length(tmpparam)\n        dat = getsubfield(tmpsource, tmpparam{k});\n        if islogical(dat)\n          tmp         = false(1,Nfull); \n          tmp(inside) = dat;\n        elseif iscell(dat)\n          tmp          = cell(1,Nfull);\n          tmp(inside)  = dat;\n          %tmp(outside) = nan;\n        else\n          tmp         = nan(1,Nfull);\n          tmp(inside) = dat;   \n        end\n        tmpsource = setsubfield(tmpsource, tmpparam{k}, tmp);\n      end\n      tmpsource       = rmfield(tmpsource, 'dim');\n      source.trial(j) = tmpsource;\n    end   \n  elseif isfield(source, 'trialA')\n    for j = 1:length(source.trialA)\n      tmpsource     = source.trialA(j);\n      tmpsource.dim = source.dim; % to fool parameterselection\n      tmpparam      = parameterselection('all', tmpsource);\n      for k = 1:length(tmpparam)\n        dat = getsubfield(tmpsource, tmpparam{k});\n        if islogical(dat)\n          tmp         = false(1,Nfull); \n          tmp(inside) = dat;\n        elseif iscell(dat)\n          tmp          = cell(1,Nfull);\n          tmp(inside)  = dat;\n          %tmp(outside) = nan;\n        else\n          tmp         = nan(1,Nfull);\n          tmp(inside) = dat;   \n        end\n        tmpsource = setsubfield(tmpsource, tmpparam{k}, tmp);\n      end\n      tmpsource        = rmfield(tmpsource, 'dim');\n      source.trialA(j) = tmpsource;   \n    end\n  elseif isfield(source, 'trialB')\n    for j = 1:length(source.trialB)\n      tmpsource     = source.trialB(j);\n      tmpsource.dim = source.dim; % to fool parameterselection\n      tmpparam      = parameterselection('all', tmpsource);\n      for k = 1:length(tmpparam)\n        dat = getsubfield(tmpsource, tmpparam{k});\n        if islogical(dat)\n          tmp         = false(1,Nfull); \n          tmp(inside) = dat;\n        elseif iscell(dat)\n          tmp          = cell(1,Nfull);\n          tmp(inside)  = dat;\n          %tmp(outside) = nan;\n        else\n          tmp         = nan(1,Nfull);\n          tmp(inside) = dat;   \n        end\n        tmpsource = setsubfield(tmpsource, tmpparam{k}, tmp);\n      end\n      tmpsource        = rmfield(tmpsource, 'dim');\n      source.trialB(j) = tmpsource;   \n    end\n  end\n  \n  % and finally do the coherence-like matrices (size Nvox X Nvox)\n  fn = fieldnames(source);\n  for i=1:length(fn)\n    d = getfield(source, fn{i});\n    m = size(d, 1);\n    n = size(d, 2);\n    if m==Nsparse && n==Nsparse\n      tmp = nan(Nfull,Nfull);\n      tmp(inside,inside) = d;\n      source = setfield(source, fn{i}, tmp);\n    end\n  end\n  \n  % update the inside and outside definitions\n  source.inside  = inside;\n  source.outside = outside;\n  source.pos     = pos;\n  source.dim     = siz;\nelseif strcmp(stype, 'new')\n  % new style conversion\n  fn = fieldnames(source);\n  for i=1:numel(fn)\n    if any(size(source.(fn{i}))==Nsparse)\n      if iscell(source.(fn{i}))\n        indx = find(size(source.(fn{i}))==Nsparse);\n        if all(indx==1)\n          tmp            = cell(Nfull,1);\n          tmp(inside,1)  = source.(fn{i});\n          source.(fn{i}) = tmp;\n        elseif all(indx==2)\n          tmp            = cell(1,Nfull);\n          tmp(1,inside)  = source.(fn{i});\n          source.(fn{i}) = tmp;\n        else\n          ft_warning('sparse to full conversion failed for field %s\\n', fn{i});\n        end\n      else\n        indx = find(size(source.(fn{i}))==Nsparse);\n        if all(indx==1)\n          tmpsiz = [size(source.(fn{i})) 1];\n          tmp    = nan([Nfull tmpsiz(2:end)]);\n          tmp(inside,:,:,:,:) = source.(fn{i});\n        elseif all(indx==2)\n          tmpsiz = [size(source.(fn{i})) 1];\n          tmp    = nan([tmpsiz(1) Nfull tmpsiz(3:end)]);\n          tmp(:,inside,:,:,:) = source.(fn{i});\n        elseif all(indx==[1 2])\n          % bivariate matrix\n          tmpsiz = [size(source.(fn{i})) 1];\n          tmp    = nan([Nfull Nfull tmpsiz(3:end)]);\n          tmp(inside,inside,:,:,:) = source.(fn{i});\n        else\n          ft_warning('sparse to full conversion failed for field %s\\n', fn{i});\n        end\n      end\n      % nothing to do\n    end\n  end\n  \n  % update the inside and outside definitions and pos\n  source.inside  = inside;\n  source.outside = outside;\n  source.pos     = pos;\n\nend\ncfg = [];\n% add version information to the configuration\ntry\n  % get the full name of the function\n  cfg.version.name = mfilename('fullpath');\ncatch\n  % required for compatibility with MATLAB versions prior to release 13 (6.5)\n  [st, i] = dbstack;\n  cfg.version.name = st(i);\nend\ncfg.version.id = '$Id$';\n% remember the configuration details of the input data\ntry, cfg.previous = source.cfg; end\n% remember the exact configuration details in the output \nsource.cfg = cfg;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/utilities/ft_source2full.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2490362921401594}}
{"text": "function rs = spec(s)\n\n%tstoolbox/@signal/spec\n%   Syntax:\n%     * rs = spec(s)\n%\n%   compute power spectrum for real valued scalar signals. Multivariate\n%   signals are accepted but may produce unwanted results as only the\n%   spectrum of the first column is returned.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,1);\n\nc = spec(s.core); \t% call real working routine for parent core object\nrs = signal(c, s);\t% special constructor calling syntax for working routines\n   \na = getaxis(s, 1); \nrs = setaxis(rs, 1, achse(unit(a)^(-1),0, samplerate(a)/dlens(s,1)));\nrs = addhistory(rs, 'Calculated spectrum (spec)');\nrs = setyunit(rs, yunit(s)^2);\nrs = addcommandlines(rs, 's = spec(s');\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@signal/spec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2490259750136175}}
{"text": "function beamlet = createIMBeamlet(doseV, indV, beamNum, fullLength)\n%\"createIMBeamlet\"\n%   Take a vector of dose values and a vector of indices into the scan\n%   array and build an IM.beamlets element.  \n%\n%JRA 9/20/04\n%\n%Usage:\n%   function beamlet = createIMBeamlet(doseV, indV, beamNum, fullLength)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n%Initialize the beamlet.\n% IM = initIMRTProblem;\n% beamlet = IM.beamlets;\nbeamlet = initBeamlet;\nbeamlet(1).format  = 'uint8';\nbeamlet(1).beamNum = beamNum;\nbeamlet(1).fullLength = fullLength;\n\nif isempty(indV) || isempty(doseV)    \n%     disp(['Warning: a pencil beam in beam ' num2str(beamNum) ' does not contribute any dose to this structure.'])\n    return;\nend\n\nind2V = find(doseV);\n\nif isempty(ind2V)\n    valsV = [];   \n    maxVal = 0;\n    smallVals = logical([]);\nelse\n\tvalsV = doseV(ind2V);\n\t\n\tmaxVal = max(valsV(:));\n\t\n\t%Bool vector to note low values, helps avoid uint8 roundoff error.\n\tsmallVals = valsV < (maxVal/(2^8 - 1));\n\t\n\t%Store non small values as normal uint8s.\n\tvalsV(~smallVals) = (valsV(~smallVals)/maxVal) * (2^8 - 1);  \n\t\n\t%Store small values as uint8s with another factor of 256.        \n\tvalsV(smallVals) = valsV(smallVals)/(maxVal)*(2^8 - 1)*(2^8 - 1);    \nend\n\n%Save vector to ID low values when builidng inflM later.\n%Uses a logical packer to decrease size by about 8.\n\nbeamlet(1).lowDosePoints = packLogicals(smallVals);        \nbeamlet(1).influence = uint8(valsV);\nbeamlet(1).indexV = uint32(indV(ind2V));\nbeamlet(1).maxInfluenceVal = maxVal;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/createIMBeamlet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361748}}
{"text": "function mask_normalize()\n    global config mem;\n    curr_layer_idx = config.misc.current_layer - 1;\n    mem.activations{curr_layer_idx} = mem.activations{curr_layer_idx} ./ mem.mask_activations{curr_layer_idx};\nend\n\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/layers/mask_normalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.24896579559260792}}
{"text": "function output = callsdpagmp(interfacedata)\n\n% CALLSDPAGMP.m Call SDPA-GMP from YALMIP\n% ----------------------------------------------------------------------- %\n%        Author:    Giovanni Fantuzzi\n%                   Department of Aeronautics\n%                   Imperial College London\n%       Created:    23/08/2016\n%\n%     Copyright (C) 2016  Giovanni Fantuzzi\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ----------------------------------------------------------------------- %\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc       = interfacedata.c;\nK       = interfacedata.K;\nx0      = interfacedata.x0;\nub      = interfacedata.ub;\nlb      = interfacedata.lb;\n\n% Bounded variables converted to constraints\nif ~isempty(ub)\n    [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\n% Convert from internal (sedumi) format\n[mDIM,nBLOCK,bLOCKsTRUCT,c,F] = sedumi2sdpa(F_struc,c,K);\n\nif options.verbose==0\n    options.sdpa_gmp.print = 'no';\nelse\n    options.sdpa_gmp.print = 'display';\nend\n\nif options.savedebug\n    ops = options.sdpa_gmp;\n    save sdpa_gmpdebug mDIM nBLOCK bLOCKsTRUCT c F ops\nend\n\nif options.showprogress\n    showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CALL SDPA-GMP\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsolvertime = tic;\n[objVal,x,X,Y,INFO] = sdpagmp(mDIM,nBLOCK,bLOCKsTRUCT,c,F,[],[],[],options.sdpa_gmp);\nsolvertime = toc(solvertime);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% From here onwards, like in YALMIP native callsdpa\n% Create variables in YALMIP internal format\nPrimal = x;\n\nDual = [];\nfor i = 1:length(Y)\n    Dual = [Dual;Y{i}(:)];\nend\n\nSlack = [];\nif options.saveduals\n    for i = 1:length(X)\n        Slack = [Slack;X{i}(:)];\n    end\nend\n\nswitch (INFO.phasevalue)\n    case 'pdOPT'\n        problem = 0;\n    case {'noINFO','pFEAS','dFEAS'}\n        problem = 3;\n    case {'pdFEAS'}\n        problem = 4;\n    case 'pFEAS_dINF'\n        problem = 2;\n    case 'pINF_dFEAS'\n        problem = 1;\n    case 'pUNBD'\n        problem = 2;\n    case 'dUNBD'\n        problem = 1;\n    case 'pdINF'\n        problem = 12;\n    otherwise\n        problem = -1;\nend\ninfostr = yalmiperror(problem,interfacedata.solver.tag);\n\nif options.savesolveroutput\n    solveroutput.objVal = objVal;\n    solveroutput.x = x;\n    solveroutput.X = X;\n    solveroutput.Y = Y;\n    solveroutput.INFO = INFO;\nelse\n    solveroutput = [];\nend\n\nif options.savesolverinput\n    solverinput.mDIM = mDIM;\n    solverinput.nBLOCK=nBLOCK;\n    solverinput.bLOCKsTRUCT=bLOCKsTRUCT;\n    solverinput.c=c;\n    solverinput.F=F;\nelse\n    solverinput = [];\nend\n\n% Standard interface\noutput = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/callsdpagmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24896579559260792}}
{"text": "% pop_apcluster() - Clusters STUDY ICs using Affinity Product method. \n%                   In this method, IC measures, except equiv. dipoles, (ERP, ERSP...)  \n%                   are compared for each IC pair and their dissimilarity is multiplied\n%                   together to form a combined pairwise dissimilarity matrix. This matrix\n%                   is then normalized, weighted and added to the normalized and weighted \n%                   IC equiv. dipole distance matrix. The final dissimilarity matrix is\n%                   then clustered using affinity clustering  method. \n%                   You can control the effect of equiv. dipole distances in\n%                   the clustering by setting the 'Relative dipole weight'\n%                   parameter in the pop-uo GUI. For example, by setting\n%                   this value to 0.8, the final dissimilarity matrix will consist of 80% \n%                   distance dissimilarity and 20% of other measures combined together.\n%                   Please note that the number of returned clusters may slighty \n%                   differ from the number requested in the GUI.\n%                  \n%\n% Usage:\n%     >> STUDY = pop_apcluster(STUDY, ALLEEG) % popup window\n%\n% See also:  std_apcluster(), std_apreclust(), , pop_apreclust(), apclusterK()\n% \n% Author: Nima Bigdely-Shamlo, SCCN/INC/UCSD, 2009\n\nfunction [STUDY ALLEEG command] = pop_apcluster(STUDY, ALLEEG)\n% command is used for keeping a history.\n% disable measure checkboxes which are not present (calculated) in\n% pre-clustering.\n\n% ERP\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'erpCorr')\n    erpEnable = 'on';\nelse\n    erpEnable = 'off';\nend;\nerpChecked = strcmp(erpEnable, 'on'); % only check items if they are enabled.\n\n% ERSP\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'erspCorr')\n    erspEnable = 'on';\nelse\n    erspEnable = 'off';\nend;\nerspChecked = strcmp(erspEnable, 'on'); % only check items if they are enabled.\n\n% ITC\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'itcCorr')\n    itcEnable = 'on';\nelse\n    itcEnable = 'off';\nend;\nitcChecked = strcmp(itcEnable, 'on'); % only check items if they are enabled.\n\n% dipole\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'compDistance')\n    dipoleEnable = 'on';\nelse\n    dipoleEnable = 'off';\nend;\ndipoleChecked = strcmp(dipoleEnable, 'on'); % only check items if they are enabled.\n\n\n% spectra\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'specCorr')\n    specEnable = 'on';\nelse\n    specEnable = 'off';\nend;\nspecChecked = strcmp(specEnable, 'on'); % only check items if they are enabled.\n\n\n% scalp map\nif isfield(STUDY.preclust,'similarity') && isfield(STUDY.preclust.similarity,'mapCorr')\n    scalpEnable = 'on';\nelse\n    scalpEnable = 'off';\nend;\n\n% popup GUI\n\nreturnedFromGui = inputgui( 'geometry', { [1 0.5]  [1 0.5] 1 1 [1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1] 1 [3 1.5]}, ...\n    'geomvert', [], 'uilist', { ...\n    { 'style', 'text', 'string', 'Number of clusters to compute:'}, ...\n    { 'style', 'edit', 'string', '10' 'tag' 'numberOfClusters' } , ...\n       { 'style', 'text', 'string', 'Relative dipole weight (between 0 and 1):'}, ...\n    { 'style', 'edit', 'string', '0.8' 'tag' 'numberOfClusters' } , ...\n        { 'style', 'text', 'string', [ 'Select measuretures to be used in the clustering:' ] }, {}, ...\n    {},{ 'Style', 'checkbox', 'string' 'Dipole' 'tag' 'scale' 'value' 1} , {}, ...\n    {},{ 'Style', 'checkbox', 'string' 'ERP' 'tag' 'scale' 'value' erpChecked 'enable' erpEnable}, {},...\n    {},{ 'Style', 'checkbox', 'string' 'ERSP' 'tag' 'scale' 'value' erspChecked 'enable' erspEnable}, {},...\n    {},{ 'Style', 'checkbox', 'string' 'ITC' 'tag' 'scale' 'value' itcChecked 'enable' itcEnable}, {},...\n    {},{ 'Style', 'checkbox', 'string' 'Spectra' 'tag' 'scale' 'value' specChecked 'enable' specEnable}, {}, ...\n    {}, { 'Style', 'checkbox', 'string' 'Scalp map' 'tag' 'scale' 'value' 0 'enable' scalpEnable}, {},...\n    {}, { 'Style', 'checkbox', 'string' 'Separate outliers (enter std.)' 'tag' 'scale' 'value' 1}, { 'style', 'edit', 'string', '3' 'tag' 'outlierSTD' }, ...\n\n    }, 'helpcom','pophelp(''pop_mpcluster'');', 'title', 'Affinity Product clustering -- pop_apcluster()');\n\n\n\nif isempty(returnedFromGui) % an empty returnedFromGui means the Cancel button has been pressed so nothing should be done.\n    command = '';\n    return; % Cancel button is pressed, so do nothing.\nelse\n    \n    % analysze answers returned from the GUI\n    numberOfClusters = str2num(returnedFromGui{1});\n    methodParameter = str2num(returnedFromGui{2});\n    \n    answers = cell2mat(returnedFromGui(3:end-1));\n    measureNamesInGUIorder = {'dipole', 'erp', 'ersp', 'itc', 'spec', 'map'};\n    measuresToUseInClustering = measureNamesInGUIorder(find(answers(1:end-1))); %#ok<FNDSB>\n    \n    if answers(end) % checkbox for outlier\n        outlierSTD = str2num(returnedFromGui{end});\n    else\n        outlierSTD = Inf;\n    end;\n    \n    STUDY = std_apcluster(STUDY, ALLEEG, numberOfClusters, outlierSTD, measuresToUseInClustering, methodParameter);\n    \n    % prepare 'command' variable for placing both in eeglab histry (accessible with eegh() ) and also\n    % adding to  STUDY.history\n    \n    measuresInOneString = [];\n    for i=1:length(measuresToUseInClustering)\n        if i>1\n            measuresInOneString = [measuresInOneString ' , ' '''' measuresToUseInClustering{i} ''''];\n        else\n            measuresInOneString = ['''' measuresToUseInClustering{1} ''''];\n        end;\n    end;\n    \n    % pop up the cluster edit and visualization .\n    [STUDY commandFromPop_clustedit] = pop_clustedit(STUDY, ALLEEG); \n    \n    command = ['STUDY = std_apcluster(STUDY, ALLEEG, ' num2str(numberOfClusters) ', ' num2str(outlierSTD) ', {' measuresInOneString '} , ' num2str(methodParameter) ');'];\n    command = [command '\\n' commandFromPop_clustedit];     % add the command from pop_clustedit() to the history too.\n    STUDY.history =  sprintf('%s\\n%s',  STUDY.history, command);\n        \nend;", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ap_clustering/pop_apcluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24880839323793746}}
{"text": "function [p params] = glm_getHrfParams(params, select);\n%\n% subParams = glm_getHrfParams(params, [select=0]);\n%\n% If you're using a pre-defined HRF for GLM analyses,\n% such as 'boynton', 'spm', or 'dale&buckner', return those\n% arguments which should be called for those canned function.\n% These arguments are kept in a params.glmHRF_params field.\n% If this field isn't found, or isn't the right size, ask\n% the user to specify these, with appropriate defaults.\n% Will also return the params struct with the glmHRF_params field\n% set properly.\n%\n% If the select flag is passed in as 1, will put up a dialog for the \n% user to specify the parameters. Otherwise, will set to reasonable\n% defaults.\n%\n% ras, 01/2007.\n\n% EDIT HISTORY:\n% ras, 02/2007 -- added select flag, GUI dialogs.\n% DY, 02/20/2007 -- removed checks for number of parameters such that\n% whenever select ~=1, the parameters are automatically set to the\n% defaults, even if there do appear to be the right number of parameters\n% (since odd bugs can result if there are the right number of parameters,\n% but the values are off). \n% ras, 02/21/2007 -- Davie, I get your point that there is this possibility;\n% however, since this function is used to retrieve stored values, your\n% change would cause only the defaults to ever be used (see glm_hrf). It\n% may be possible to change the way this function is called, but this would\n% require additional logic (since you also need a check that the right\n% number of HRF params are specified at HRF creation); and the possibility\n% you're concerned about could only occur if you manually muck with the\n% parameters -- none of the accessor functions can set the wrong # of\n% params. So, I'm reverting for now, and we'll see if we need to do more.\n\np = [];\n\nif ~exist('select', 'var') | isempty(select), select = 0;   end\n\n% this is only needed for predefined HRF options\nif ~ismember(params.glmHRF, [2 3 4]), return; end\n\n% init params field\nif ~isfield(params, 'glmHRF_params')\n    params.glmHRF_params = [];\nend\n\n% get params\nswitch params.glmHRF\n    case 2,     % boynton\n        if select==1\n            params.glmHRF_params = boyntonHIRF_dialog;\n        elseif length(params.glmHRF_params) ~= 3 % wrong size\n            % [n tau delta]\n            params.glmHRF_params = [3 1.08 2.05];\n        end\n\n    case 3,     % spm\n        if select==1\n            params.glmHRF_params = spmHRF_dialog;\n            %\tp(1) - delay of response (relative to onset)\t   6\n            %\tp(2) - delay of undershoot (relative to onset)    16\n            %\tp(3) - dispersion of response\t\t\t   1\n            %\tp(4) - dispersion of undershoot\t\t\t   1\n            %\tp(5) - ratio of response to undershoot\t\t   6\n            %\tp(6) - onset (seconds)\t\t\t\t   0\n            %\tp(7) - length of kernel (seconds)\t\t  32\n\t\telseif length(params.glmHRF_params) ~= 6 % wrong size\n            maxT = max(params.timeWindow);\n            params.glmHRF_params = [6 16 1 1 6 0 maxT];\n        end\n\n    case 4,     % dale & buckner\n        if select==1\n            params.glmHRF_params = daleBucknerHIRF_dialog;\n            % [delta tau]\n%             params.glmHRF_params = [2.25 1.25]; % more event-friendly\n        elseif length(params.glmHRF_params) ~= 2 % wrong size\n            params.glmHRF_params = [1.25 2.5]; % vals used in er_runSelxavgBlock (old code)\n        end\nend\n\np = params.glmHRF_params;\n\nreturn\n% /----------------------------------------------------------------/ %\n\n\n\n% /----------------------------------------------------------------/ %\nfunction p = boyntonHIRF_dialog;\n% dialog to set [n tau delta] for boyntonHIRF function.\ndlg(1).fieldName = 'eqn';\ndlg(1).style = 'text';\ndlg(1).string = 'HRF equation:';\ndlg(1).value = 'h(t) = [(t/tau) ^ (n-1) * exp(-t/tau)] / [tau(n-1)!]';\n\ndlg(2).fieldName = 'n';\ndlg(2).style = 'edit';\ndlg(2).string = 'n (integer):';\ndlg(2).value = '3';\n\ndlg(3).fieldName = 'tau';\ndlg(3).style = 'edit';\ndlg(3).string = 'tau (decay), secs:';\ndlg(3).value = '1.08';\n\ndlg(4).fieldName = 'delta';\ndlg(4).style = 'edit';\ndlg(4).string = 'delay (delta), secs:';\ndlg(4).value = '2.05';\n\nresp = generalDialog(dlg, 'Boynton HRF');\nif isempty(resp)\n    error('User canceled.')\nend\n    \np = [str2num(resp.n) str2num(resp.tau) str2num(resp.delta)];\nreturn\n% /----------------------------------------------------------------/ %\n\n\n\n% /----------------------------------------------------------------/ %\nfunction p = spmHRF_dialog;\n% dialog to set the params for spm_hrf:\n%\tp(1) - delay of response (relative to onset)\t   6\n%\tp(2) - delay of undershoot (relative to onset)    16\n%\tp(3) - dispersion of response\t\t\t   1\n%\tp(4) - dispersion of undershoot\t\t\t   1\n%\tp(5) - ratio of response to undershoot\t\t   6\n%\tp(6) - onset (seconds)\t\t\t\t   0\n%\tp(7) - length of kernel (seconds)\t\t  32\ndlg(1).fieldName = 'responseDelay';\ndlg(end).style = 'edit';\ndlg(end).string = 'delay of response (relative to onset)';\ndlg(end).value = '6';\n\ndlg(end+1).fieldName = 'undershootDelay';\ndlg(end).style = 'edit';\ndlg(end).string = 'delay of undershoot (relative to onset)';\ndlg(end).value = '16';\n\ndlg(end+1).fieldName = 'responseDispersion';\ndlg(end).style = 'edit';\ndlg(end).string = 'dispersion of response';\ndlg(end).value = '1';\n\ndlg(end+1).fieldName = 'undershootDispersion';\ndlg(end).style = 'edit';\ndlg(end).string = 'dispersion of response';\ndlg(end).value = '1';\n\ndlg(end+1).fieldName = 'ratio';\ndlg(end).style = 'edit';\ndlg(end).string = 'ratio of response to undershoot';\ndlg(end).value = '6';\n\ndlg(end+1).fieldName = 'onset';\ndlg(end).style = 'edit';\ndlg(end).string = 'onset (seconds)';\ndlg(end).value = '0';\n\ndlg(end+1).fieldName = 'kernelLength';\ndlg(end).style = 'edit';\ndlg(end).string = 'length of kernel (seconds)';\ndlg(end).value = '32';\n\nresp = generalDialog(dlg, 'SPM HRF');\nif isempty(resp)\n    error('User canceled.')\nend\n    \np = [str2num(resp.responseDelay) str2num(resp.undershootDelay) ...\n     str2num(resp.responseDispersion) str2num(resp.undershootDispersion) ...\n     str2num(resp.ratio) str2num(resp.onset) str2num(resp.kernelLength)];\n\nreturn\n% /----------------------------------------------------------------/ %\n\n\n\n% /----------------------------------------------------------------/ %\nfunction p = daleBucknerHIRF_dialog;\n% dialog to set [delta tau] for fmri_hemodyn function.\ndlg(1).fieldName = 'eqn';\ndlg(1).style = 'text';\ndlg(1).string = 'HRF equation:';\ndlg(1).value = {'h(t>delta)  = ((t-delta)/tau)^2 * exp(-(t-delta)/tau)'; ...\n                 'h(t<=delta) = 0;'};\n\ndlg(2).fieldName = 'delta';\ndlg(2).style = 'edit';\ndlg(2).string = 'delay (delta), secs:';\ndlg(2).value = '1.25';\n\ndlg(3).fieldName = 'tau';\ndlg(3).style = 'edit';\ndlg(3).string = 'tau (decay), secs:';\ndlg(3).value = '2.5';\n\n\nresp = generalDialog(dlg, 'Dale & Buckner HRF');\nif isempty(resp)\n    error('User canceled.')\nend\n    \np = [str2num(resp.delta) str2num(resp.tau)];\n\nreturn\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/GLM/glm_getHrfParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2487681072013796}}
{"text": "function [sampled_graphs, accept_ratio, num_edges] = learn_struct_mcmc(data, ns, varargin)\n% LEARN_STRUCT_MCMC  Monte Carlo Markov Chain search over DAGs assuming fully observed data\n% [sampled_graphs, accept_ratio, num_edges] = learn_struct_mcmc(data, ns, ...)\n% \n% data(i,m) is the value of node i in case m.\n% ns(i) is the number of discrete values node i can take on.\n%\n% sampled_graphs{m} is the m'th sampled graph.\n% accept_ratio(t) = acceptance ratio at iteration t\n% num_edges(t) = number of edges in model at iteration t\n%\n% The following optional arguments can be specified in the form of name/value pairs:\n% [default value in brackets]\n%\n% scoring_fn - 'bayesian' or 'bic' [ 'bayesian' ]\n%              Currently, only networks with all tabular nodes support Bayesian scoring.\n% type       - type{i} is the type of CPD to use for node i, where the type is a string\n%              of the form 'tabular', 'noisy_or', 'gaussian', etc. [ all cells contain 'tabular' ]\n% params     - params{i} contains optional arguments passed to the CPD constructor for node i,\n%              or [] if none.  [ all cells contain {'prior', 1}, meaning use uniform Dirichlet priors ]\n% discrete   - the list of discrete nodes [ 1:N ]\n% clamped    - clamped(i,m) = 1 if node i is clamped in case m [ zeros(N, ncases) ]\n% nsamples   - number of samples to draw from the chain after burn-in [ 100*N ]\n% burnin     - number of steps to take before drawing samples [ 5*N ]\n% init_dag   - starting point for the search [ zeros(N,N) ]\n%\n% e.g., samples = my_learn_struct_mcmc(data, ns, 'nsamples', 1000);\n%\n% \n% Modified by Mingyi Wang  (mingyiwang@hotmail.com) Sep 18, 2006 (based on Sonia Leach (SML)'s version ( 2/4/02, 9/5/03))\n%\n% Some bugs in update_ancestor_matrix() were fixed. This function can call mk_nbrs_of_digraph properly\n% \n\n[n ncases] = size(data);\n\n% set default params\ntype = cell(1,n);\nparams = cell(1,n);\nfor i=1:n\n type{i} = 'tabular';\n %params{i} = { 'prior', 1};\n params{i} = { 'prior_type', 'dirichlet', 'dirichlet_weight', 1 };\nend\nscoring_fn = 'bayesian';\ndiscrete = 1:n;\nclamped = zeros(n, ncases);\nnsamples = 100*n;\nburnin = 5*n;\ndag = zeros(n);\n\nargs = varargin;\nnargs = length(args);\nfor i=1:2:nargs\n switch args{i},\n  case 'nsamples',   nsamples = args{i+1};\n  case 'burnin',     burnin = args{i+1};\n  case 'init_dag',   dag = args{i+1};\n  case 'scoring_fn', scoring_fn = args{i+1};\n  case 'type',       type = args{i+1}; \n  case 'discrete',   discrete = args{i+1}; \n  case 'clamped',    clamped = args{i+1}; \n  case 'gconstraint', gconstraint=args{i+1};  %Added by mingyi\n  case 'params',     if isempty(args{i+1}), params = cell(1,n); else params = args{i+1};  end\n    \n end\nend\n\n% We implement the fast acyclicity check described by P. Giudici and R. Castelo,\n% \"Improving MCMC model search for data mining\", submitted to J. Machine Learning, 2001.\n\n% SML: also keep descendant matrix C\nuse_giudici = 1;\n%use_giudici = 0; %Revised by MIngyi\nif use_giudici\n [nbrs, ops, nodes, A] = mk_nbrs_of_digraph(dag);  \nelse\n [nbrs, ops, nodes] = mk_nbrs_of_dag(dag);    \n A = [];\nend\n\nnum_accepts = 1;\nnum_rejects = 1;\nT = burnin + nsamples;\naccept_ratio = zeros(1, T);\nnum_edges = zeros(1, T);\nsampled_graphs = cell(1, nsamples);\n%sampled_bitv = zeros(nsamples, n^2);\n\nfor t=1:T\n [dag, nbrs, ops, nodes, A, accept] = take_step(dag, nbrs, ops, ...\n                    nodes, ns, data, clamped, A, ...\n                      scoring_fn, discrete, type, params);\n num_edges(t) = sum(dag(:));\n num_accepts = num_accepts + accept;\n num_rejects = num_rejects + (1-accept);\n accept_ratio(t) =  num_accepts/num_rejects;\n if t > burnin\n   sampled_graphs{t-burnin} = dag;\n   %sampled_bitv(t-burnin, :) = dag(:)';\n end\n fprintf('MCMC: %d/%d\\n',t,T);\nend\n\n\n%%%%%%%%%\n\n\nfunction [new_dag, new_nbrs, new_ops, new_nodes, A,  accept] = ...\n   take_step(dag, nbrs, ops, nodes, ns, data, clamped, A,  ...\n     scoring_fn, discrete, type, params, prior_w)\n\nglobal gconstraint;   %Added by Mingyi\nuse_giudici = ~isempty(A);\nif use_giudici\n [new_dag, op, i, j, new_A] =  pick_digraph_nbr(dag, nbrs, ops, nodes,A); % updates A\n [new_nbrs, new_ops, new_nodes] =  mk_nbrs_of_digraph(new_dag,new_A);  \nelse\n d = sample_discrete(normalise(ones(1, length(nbrs))));\n new_dag = nbrs{d};\n op = ops{d};\n i = nodes(d, 1); j = nodes(d, 2);\n [new_nbrs, new_ops, new_nodes] = mk_nbrs_of_dag1(new_dag);   \nend\n%For debug\n% fprintf('op:%s,i:%d,j:%d\\n',op,i,j);\n% if ~acyclic(new_dag)\n%     error('new dag must be acyclic!')\n% end\n% if size(find(diag(new_A)),1)>0\n%   A=A\n%   new_A=new_A\n%   error('new A must be acyclic!')\n%  end\n%debug ends\n\nbf =  bayes_factor(dag, new_dag, op, i, j, ns, data, clamped, scoring_fn, discrete, type, params);\n\n%R = bf * (new_prior / prior) * (length(nbrs) / length(new_nbrs)); \nR = bf * (length(nbrs) / length(new_nbrs)); \nu = rand(1,1);\nif u > min(1,R) % reject the move\n accept = 0;\n new_dag = dag;\n new_nbrs = nbrs;\n new_ops = ops;\n new_nodes = nodes;\nelse\n accept = 1;\n if use_giudici\n    A = new_A; % new_A already updated in pick_digraph_nbr\n end\nend\n\n\n%%%%%%%%%\n\nfunction bfactor = bayes_factor(old_dag, new_dag, op, i, j, ns, data, clamped, scoring_fn, discrete, type, params)\n\nu = find(clamped(j,:)==0);\nLLnew = score_family(j, parents(new_dag, j), type{j}, scoring_fn, ns, discrete, data(:,u), params{j});\nLLold = score_family(j, parents(old_dag, j), type{j}, scoring_fn, ns, discrete, data(:,u), params{j});\nbf1 = exp(LLnew - LLold);\n\nif strcmp(op, 'rev')  % must also multiply in the changes to i's family\n u = find(clamped(i,:)==0);\n LLnew = score_family(i, parents(new_dag, i), type{i}, scoring_fn, ns, discrete, data(:,u), params{i});\n LLold = score_family(i, parents(old_dag, i), type{i}, scoring_fn, ns, discrete, data(:,u), params{i});\n bf2 = exp(LLnew - LLold);\nelse\n bf2 = 1;\nend\nbfactor = bf1 * bf2;\n\n\n%%%%%%%% Giudici stuff follows %%%%%%%%%%\n\n\n% SML: This now updates A as it goes from digraph it choses\nfunction [new_dag, op, i, j, new_A] = pick_digraph_nbr(dag, digraph_nbrs, ops, nodes, A)\n\nd = sample_discrete(normalise(ones(1, length(digraph_nbrs))));\n%d = myunidrnd(length(digraph_nbrs),1,1);\ni = nodes(d, 1); j = nodes(d, 2);\nnew_dag = digraph_nbrs(:,:,d);\n\nop = ops{d};\nnew_A = update_ancestor_matrix(A, op, i, j, dag); \n%for debug\n% if op=='add'\n%     if ~(dag(i,j)==0 & new_dag(i,j)==1)\n%         fprintf('error add\\n');\n%     end\n% end\n% if op=='del'\n%     if ~(dag(i,j)==1 & new_dag(i,j)==0)\n%       fprintf('new dag del calculation is error!\\n')\n%     end\n% end\n% if op=='rev'\n%     if ~(dag(i,j)==1 & dag(j,i)==0 & new_dag(i,j)==0 & new_dag(j,i)==1)\n%       fprintf('new dag rev calculation is error!\\n')\n%     end\n% end\n% new_AA = reachability_graph(new_dag');\n% if find(diag(new_AA)==1)\n%     fprintf('cyclic\\n');\n% end\n% if ~isequal(new_A,new_AA)\n%    fprintf('new A calculation is error!\\n')\n% end\n%debug ends\n\n%%%%%%%%%%%%%%\n\nfunction A = update_ancestor_matrix(A,  op, i, j, dag)\n\nswitch op\ncase 'add',\n A = do_addition(A,  op, i, j, dag);\ncase 'del', \n A = do_removal(A,  op, i, j, dag);\ncase 'rev', \n A = do_removal(A,  op, i, j, dag);\n A = do_addition(A,  op, j, i, dag);\nend\n\n \n%%%%%%%%%%%%\n\nfunction A = do_addition(A, op, i, j, dag)\n\nA(j,i) = 1;     % i is an ancestor of j\nanci = find(A(i,:));\nif ~isempty(anci)\n A(j,anci) = 1;   % all of i's ancestors are added to Anc(j)\nend\n\ndescj = find(A(:,j));  %all the descendants of j are selected \nif ~isempty(descj)\n for k=descj(:)'\n   A(k,i) = 1;        % i is the ancestor of descj\n   if ~isempty(anci)  % all of i's ancestors are also the ancestor of each descendant of j\n       A(k,anci)=1;\n   end   \n end\nend\n\n\n%%%%%%%%%%%\n\nfunction A = do_removal(A, op, i, j, dag)\ndescj = find(A(:,j)); \nA = update_row(A,i, j, dag);   % compute the A(j,:) row for dag i->j removal\n\nif ~isempty(descj) \n  order = topological_sort(dag);  %all the parent nodes are before to the children nodes\n  [junk, perm] = sort(order);     %node i is perm(i)-TH in order\n  descj_topnum = perm(descj);     %descj(i) is descj_topnum(i)-th in order\n\n% SML: now re-sort descj by rank in descj_topnum\n  [junk, perm] = sort(descj_topnum);\n  descj = descj(perm); \n  for k = descj(:)'\n    A = old_update_row(A, k, dag);\n  end\nend\n\n%%%%%%%%%\n\nfunction A = update_row(A, i,j, dag)\n% We compute row j of A\nA(j, :) = 0;\nps = parents(dag, j);\nps=setdiff(ps,i);  % All the parents except i\nif ~isempty(ps)\n A(j, ps) = 1;\nend\nfor k=ps(:)'\n anck = find(A(k,:));\n if ~isempty(anck)\n   A(j, anck) = 1;\n end\nend\n\n%%%%%%%%%\n\nfunction A = old_update_row(A, j, dag)\n\n% We compute row j of A\nA(j, :) = 0;\nps = parents(dag, j);\nif ~isempty(ps)\n A(j, ps) = 1;\nend\nfor k=ps(:)'\n anck = find(A(k,:));\n if ~isempty(anck)\n   A(j, anck) = 1;\n end\nend\n\n%%%%%%%%\n\nfunction A = init_ancestor_matrix(dag)\n\norder = topological_sort(dag);\nA = zeros(length(dag));\nfor j=order(:)'\n A = update_row(A, j, dag);\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/learning/learn_struct_mcmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24876810030794266}}
{"text": "function dataNdConcat = concat(this, dataNdArray, concatDims, tolerance)\n%Concatenate an array of MrDataNd along one specified dimension\n%\n%   Y = MrDataNd()\n%   dataNdConcat = Y.concat(dataNdArray, concatDims, tolerance)\n%\n% This is a method of class MrDataNd. It is very similar to combine with\n% the difference that non-singleton dimensions can be concatenated (e.g.,\n% volume 1-10 and 11-20). \n% Note: Multi-dimensional concatenation is supported,\n% but it will leave parts of the array empty \n%   - e.g., volume 1-10 of slice 1-9 concatenated with volume 11-20 \n%     of slice 10-20 would leave the \"cross-terms\" of the dim Matrix like \n%     slice 1-9 of volume 11-10 undefined (we set them to 0).\n%\n% NOTE: The order of data in the dataNdArray will *not* define the \n%       concatenation order. Ratherthe actual values of the samplingPoints\n%       in dimInfo along the concat dimensions specify the position of the\n%       data.\n%\n% IN\n%   dataNdArray     cell(nDatasets,1) of MrDataNd to be concatenated\n%                       OR\n%                   single MrDataNd object. In this case, the input object\n%                   and the calling object will be concatenated\n%   concatDims       index or string (label) of dimension along which data\n%                   should be concatenated\n%   tolerance                   dimInfos are only combined, if their\n%                               information is equal for all but the\n%                               concatDims (because only one\n%                               representation is retained for those,\n%                               usually from the first of the dimInfos). \n%                               However, sometimes numerical precision,\n%                               e.g., rounding errors, preclude the\n%                               combination. Then you can increase this\n%                               tolerance; \n%                               default: single precision (eps('single')\n%                               ~1.2e-7)   \n% OUT\n%\n% EXAMPLE\n%   concat\n%\n%   See also MrDataNd MrDataNd.combine MrDimInfo.combine\n \n% Author:   Lars Kasper\n% Created:  2019-04-15\n% Copyright (C) 2019 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public License (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\nif nargin < 4\n    tolerance = eps('single');\nend\n\nif ~iscell(dataNdArray)\n    dataNdArray = {this, dataNdArray};\nend\n\nnImages = numel(dataNdArray);\n    \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Split all images in array along specified dimensions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndataNdArraySplit = {};\nfor iImage = 1:nImages\n    dataNdArraySplit = [dataNdArraySplit; ...\n        reshape(dataNdArray{iImage}.split('splitDims', concatDims), ...\n        [], 1)];\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Combine all image arrays and reconcatenate!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Note that not the order here will be important, but the actual value of\n% the slice position in dimInfo\n\ndataNdConcat = dataNdArraySplit{1}.combine(dataNdArraySplit, concatDims, ...\n    tolerance);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDataNd/concat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24875115963771738}}
{"text": "function options = rbfOptions\n\n% RBFOPTIONS Default options for RBF network.\n\n% MLTOOLS\n\noptions.outFunc = 'linear';\noptions.activeFunc = 'gaussian';\noptions.hiddenDim = 20;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/rbfOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24840810641101047}}
{"text": "function [B, tau] = mex_dgeqrf(A)\n% B = mex_dgeqrf(A)\n%\n% Interface to LAPACK's DGEQRF function.\n% Upper part of B is the triangular factor.\n%          \n% 6-December 2009, Version 1.3\n% Copyright (C) 2009, Haim Avron and Sivan Toledo.", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25241-blendenpik/blendenpik/mex_dgeqrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.24830922356592014}}
{"text": "%CROP_BORDERS Crop the borders of an image or stack of images\n%\n%   [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])\n%\n%IN:\n%   A - HxWxCxN stack of images.\n%   bcol - Cx1 background colour vector.\n%   padding - scalar indicating how much padding to have in relation to\n%             the cropped-image-size (0<=padding<=1). Default: 0\n%\n%OUT:\n%   B - JxKxCxN cropped stack of images.\n%   vA     - coordinates in A that contain the cropped image\n%   vB     - coordinates in B where the cropped version of A is placed\n%   bb_rel - relative bounding box (used for eps-cropping)\n\n% 06/03/15: Improved image cropping thanks to Oscar Hartogensis\n\nfunction [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding)\nif nargin < 3\n    padding = 0;\nend\n[h, w, c, n] = size(A);\nif isscalar(bcol)\n    bcol = bcol(ones(c, 1));\nend\nbail = false;\nfor l = 1:w\n    for a = 1:c\n        if ~all(col(A(:,l,a,:)) == bcol(a))\n            bail = true;\n            break;\n        end\n    end\n    if bail\n        break;\n    end\nend\nbcol = A(ceil(end/2),w,:,1);\nbail = false;\nfor r = w:-1:l\n    for a = 1:c\n        if ~all(col(A(:,r,a,:)) == bcol(a))\n            bail = true;\n            break;\n        end\n    end\n    if bail\n        break;\n    end\nend\nbcol = A(1,ceil(end/2),:,1);\nbail = false;\nfor t = 1:h\n    for a = 1:c\n        if ~all(col(A(t,:,a,:)) == bcol(a))\n            bail = true;\n            break;\n        end\n    end\n    if bail\n        break;\n    end\nend\nbcol = A(h,ceil(end/2),:,1);\nbail = false;\nfor b = h:-1:t\n    for a = 1:c\n        if ~all(col(A(b,:,a,:)) == bcol(a))\n            bail = true;\n            break;\n        end\n    end\n    if bail\n        break;\n    end\nend\n% Crop the background, leaving one boundary pixel to avoid bleeding on resize\n%v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];\n%A = A(v(1):v(2),v(3):v(4),:,:);\nif padding == 0  % no padding\n    padding = 1;\nelseif abs(padding) < 1  % pad value is a relative fraction of image size\n    padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING\nelse  % pad value is in units of 1/72\" points\n    padding = round(padding);  % fix cases of non-integer pad value\nend\nif padding > 0  % extra padding\n    % Create an empty image, containing the background color, that has the\n    % cropped image size plus the padded border\n    B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2);\n    % vA - coordinates in A that contain the cropped image\n    vA = [t b l r];\n    % vB - coordinates in B where the cropped version of A will be placed\n    vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];\n    % Place the original image in the empty image\n    B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :);\n    A = B;    \nelse  % extra cropping\n    vA = [t-padding b+padding l-padding r+padding];\n    A = A(vA(1):vA(2), vA(3):vA(4), :);\n    vB = [NaN NaN NaN NaN];\nend\n% For EPS cropping, determine the relative BoundingBox - bb_rel\nbb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];\nend\n\nfunction A = col(A)\nA = A(:);\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/export_fig/crop_borders.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24829818486025249}}
{"text": "function [sfmL,sfm,names] = spm2delta(SPM,varargin)\n% [d_hires,d_atTR,names] = spm2delta(SPM,varargin)\n% or \n% [onsets,delta_atTR,names] = spm2delta(SPM,varargin)\n% \n% Example: for SPM99\n% [dL,d] = spm2delta([],Sess);\n\nif length(varargin) > 0, \n    Sess = varargin{1};,\n    SPM.Sess = Sess;\nelse\n    % SPM2\n    Sess = SPM.Sess;\nend\n\nif iscell(Sess)\n    \n    ons = {};\n    \n    for i = 1:length(Sess)\n    \n        [sfc,sfm{i}] = downsample_delta(Sess{i}.sf,16);\n    \n        for j = 1:size(sfm{i},2)                % save onsets\n            ons{end+1} = find(sfm{i}(:,j)) - 1; % in TRs, starting with 0\n        end\n        \n        %sfmL{i} = cat(2,Sess{i}.sf{:});        % delta hires\n    end\n\n    sfm = cat(1,sfm{:});\n    sfmL = ons;         % save onsets\n    %sfmL = cat(1,sfmL{:}); % save delta_hires\n    names = SPM.Sess{1}.name;\nelse\n\n    % new spm2 way?\n    ons = [];\n    wh = [];, for i = 1:length(Sess), if isempty(Sess(i).U), wh(i) = 1;,end,end\n        Sess(find(wh)) = [];\n        \n    delta = cell(1,length(Sess(1).U));\n    \n    for i = 1:length(Sess)\n        sessons = [];\n        for j = 1:length(Sess(i).U)\n            ons{end+1} = Sess(i).U(j).ons/SPM.xY.RT;      % all onsets\n            sessons{end+1} = Sess(i).U(j).ons/SPM.xY.RT;  % onsets this session\n        end\n        \n        % add delta functions for this session to overall\n        sessdelt = onsets2delta(sessons,size(SPM.xX.X,1) ./ length(Sess));\n        for k = 1:size(sessdelt,2)\n            \n            % just in case some sessions do not have some\n                    % regressors\n            if k > length(delta)\n            \tdelta{k} = zeros(size(delta{1}));\n            end\n                    \n            try\n                delta{k} = cat(1,[delta{k}; sessdelt(:,k)]);\n            catch\n                 delta{k} = cat(1,[delta{k}; sessdelt(:,k)']);\n            end\n        end\n    end\n    sfmL = ons;\n    sfm = delta;\n    \n    names = cat(2,SPM.Sess(1).U(:).name);\nend\n            \n    \n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Support_functions/spm2delta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24829818486025246}}
{"text": "function hit_node(varargin)\n%Function for generating Another metabolite-metabolite interaction network\n%if the node is clicked in the figure that produced by createMetIntrcNetwork.\n%Right click and left click has different properties.\n%Left click :Generate sub-metabolite-metabolite network from the created figure, \n%            this functionality was added for better looking at the created network \n%            and showing flux values on edges lines.\n%\n%Right click :Generate metabolite metabolite network from model, this\n%             functionality were added for creating metabolite-metabolite network using\n%             clicked metabolite and model.\n%The produced figure from main figure also has same property with main\n%figure, and it is clickable too.\n\n    f = varargin{1}.Parent.Parent;\n    if (strcmp(f.SelectionType, 'normal') | strcmp(f.SelectionType, 'alt'))\n        metofInt=varargin{1}.String;\n        adjncMtrx=varargin{3};\n        mets=varargin{4};\n        model=varargin{5} ;\n        excludedMets=varargin{7};\n        fluxes=varargin{6};\n        Graphtitle=varargin{8};\n        nodecolour=varargin{9};\n        Hnodecolour=varargin{10};\n        fcont=varargin{11};\n        scaleMin=varargin{12};\n        scaleMax=varargin{13};\n        nodeSize=varargin{14};\n        HnodeSize=varargin{15};\n        arrowSize=varargin{16};\n        threshold=varargin{17};\n        excNodesWithDeg=varargin{18};\n        \n% Define function of left click        \n        if strcmp(f.SelectionType, 'normal')        \n            idx=ismember(mets,metofInt);\n            newadjMtrx=zeros(size(adjncMtrx));\n            newadjMtrx(idx,:)=adjncMtrx(idx,:);\n            newadjMtrx(:,idx)=adjncMtrx(:,idx);\n            rows=any(newadjMtrx,1);\n            cols=any(newadjMtrx,2);\n            indofMets=rows'|cols;\n            metnames=mets(indofMets);\n            newadjMtrx=newadjMtrx(indofMets,indofMets);\n            A=newadjMtrx;\n            G = digraph(A,metnames);\n            ttl=['Sub-', ' ',Graphtitle];\n        end\n% Define function of right click\n        if strcmp(f.SelectionType, 'alt')\n            IndexesofMets=find(ismember(model.mets,metofInt));    \n            metMatrix=~ismember(model.S(IndexesofMets,:),0);\n            Rxns=model.rxns(any(metMatrix,1));\n            FluxRes=fluxes(ismember(model.rxns,Rxns));\n            metmatrix=~ismember(model.S(:,any(metMatrix,1)),0);    \n            metnames=model.mets(any(metmatrix,2));\n            adjunc_mat=model.S(any(metmatrix,2),any(metMatrix,1));\n            FluxMatrix  =FluxRes + 1e-6;\n            FluxMatrix = repmat(FluxMatrix',size(adjunc_mat,1),1);\n            adjunc_mat=adjunc_mat.*FluxMatrix;\n            leftMatrix=adjunc_mat;\n            leftMatrix(leftMatrix > 0)=0;\n            rightMatrix=adjunc_mat;\n            rightMatrix(rightMatrix < 0)=0;\n            rightMatrix(rightMatrix > 0)=1;\n            metMatrix=leftMatrix*rightMatrix';\n            A=metMatrix*(-1);            \n            idx=ismember(metnames,metofInt);\n            newadjMtrx=zeros(size(A));\n            newadjMtrx(idx,:)=A(idx,:);\n            newadjMtrx(:,idx)=A(:,idx);\n            rows=any(newadjMtrx,1);\n            cols=any(newadjMtrx,2);\n            indofMets=rows'|cols;\n            metnames=metnames(indofMets);\n            newadjMtrx=newadjMtrx(indofMets,indofMets);\n            A=newadjMtrx;\n            G = digraph(A,metnames);\n            ttl=Graphtitle;\n        end    \n        \n        G = rmnode(G,excludedMets);\n        G.Edges.Weight(G.Edges.Weight < 1e-4)=1e-6;\n        G.Edges.LWidths = (G.Edges.Weight-min(G.Edges.Weight))/(max(G.Edges.Weight)-min(G.Edges.Weight))+0.00001;\n        G.Edges.LWidths((isnan(G.Edges.LWidths)))=1e-6;\n        \n        if threshold~=1e-7 \n            edesBelowTresholdIdx=find(G.Edges.Weight<threshold);\n            G=rmedge(G,edesBelowTresholdIdx);\n        end\n        \n        nodesIndegree=indegree(G); \n        nodesoutdegree=outdegree(G);\n        totalDegree=nodesIndegree+nodesoutdegree;\n        G=rmnode(G,find(totalDegree<1));\n\n        figure;\n        hold on\n        h=plot(G,'MarkerSize',(nodeSize+5),'NodeColor',nodecolour,'ArrowSize',(arrowSize+5),'NodeLabelMode','auto');\n        layout(h,'layered','Direction','right')\n        highlight(h,metofInt,'NodeColor',Hnodecolour,'MarkerSize',(HnodeSize+5));\n        nl = h.NodeLabel;\n        h.NodeLabel = '';\n        xd = get(h, 'XData');\n        yd = get(h, 'YData');\n        title([metofInt,' ', 'Centred', ' ',ttl],'Interpreter', 'none');\n        txt=text(xd, yd, nl, 'FontSize',8, 'FontWeight','bold', 'HorizontalAlignment','center', 'VerticalAlignment','middle');\n        set(txt,'Interpreter', 'none');\n        set(txt,'ButtonDownFcn',{@hit_node,A,metnames,model,fluxes,excludedMets,Graphtitle,nodecolour,Hnodecolour,fcont,scaleMin,scaleMax,nodeSize,HnodeSize,arrowSize,threshold,excNodesWithDeg});\n        if  fcont==1\n            h.LineWidth=1;\n        elseif ~any(isnan(G.Edges.LWidths))\n            h.EdgeLabel=G.Edges.Weight;  \n            h.LineWidth=G.Edges.LWidths*2.5;\n            colormap jet(10)\n            h.EdgeCData=G.Edges.Weight; \n            hcb=colorbar;\n            colorTitleHandle = get(hcb,'Title');\n\n        else   \n            h.LineWidth=1;\n            colormap jet(10)\n            h.EdgeCData=G.Edges.Weight; \n            hcb=colorbar;\n            colorTitleHandle = get(hcb,'Title');\n        end\n        \n        if  fcont==0\n        if ~(scaleMax==1e-6 && scaleMin==0) \n            caxis([scaleMin scaleMax])\n            titleBar = ['Scaled Fluxes',' ', '(', num2str(scaleMin),' - ',num2str(scaleMax),')'];\n            set(colorTitleHandle ,'String',titleBar,'FontWeight','Bold');\n        else\n            set(colorTitleHandle ,'String','Fluxes','FontWeight','Bold');\n        end\n        end\n\n        \n        set(gca,'XTickLabel',{' '});\n        set(gca,'YTickLabel',{' '});\n        set(gca,'YTick',[]);\n        set(gca,'XTick',[]);\n        set(gca,'XColor', 'none','YColor','none');\n    end\n  \nend\n\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/visualization/createMetIntrcNetwork/hit_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24828294112005586}}
{"text": "classdef InitialStateModel < matlab.mixin.SetGet\n    %InitialStateModel Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        orbitModel(1,1) = GeographicElementSet.getDefaultElements();\n\n        lvState LaunchVehicleState\n        stageStates LaunchVehicleStageState\n        \n        aero(1,1) LaunchVehicleAeroState\n        thirdBodyGravity(1,1) LaunchVehicle3BodyGravState\n        \n        steeringModels SteeringModelsSet\n        throttleModels ThrottleModelsSet\n        \n        optVar InitialStateVariable\n    end\n\n    %deprecated\n    properties(Access=private)\n        steeringModel AbstractSteeringModel = RollPitchYawPolySteeringModel.getDefaultSteeringModel();\n        throttleModel(1,1) AbstractThrottleModel = ThrottlePolyModel.getDefaultThrottleModel();\n    end\n    \n    properties(Dependent)\n        time(1,1) double\n        centralBody(1,1) KSPTOT_BodyInfo\n    end\n    \n    methods\n        function obj = InitialStateModel()\n            obj.steeringModels = SteeringModelsSet();\n            obj.throttleModels = ThrottleModelsSet();\n        end\n        \n        function time = get.time(obj)\n            time = obj.orbitModel.time;\n        end\n        \n        function set.time(obj, newTime)\n            obj.orbitModel.time = newTime;\n        end\n        \n        function time = get.centralBody(obj)\n            time = obj.orbitModel.frame.getOriginBody();\n        end\n        \n        function set.centralBody(obj, newCentralBody)\n            if(isempty(obj.orbitModel.frame))\n                obj.orbitModel.frame = newCentralBody.getBodyCenteredInertialFrame();\n            end\n            obj.orbitModel.frame.setOriginBody(newCentralBody);\n        end\n        \n        function set.orbitModel(obj, newOrbitModel)\n            if(isa(newOrbitModel,'AbstractOrbitStateModel'))\n                if(isa(newOrbitModel,'BodyFixedOrbitStateModel'))\n                    newFrame = obj.centralBody.getBodyFixedFrame(); %#ok<MCSUP> \n                    elemSet = GeographicElementSet(obj.time, newOrbitModel.lat, newOrbitModel.long, newOrbitModel.alt, ...\n                                                   newOrbitModel.vVectNEZ_az, newOrbitModel.vVectNEZ_el, newOrbitModel.vVectNEZ_mag, newFrame); %#ok<MCSUP>\n\n                elseif(isa(newOrbitModel,'KeplerianOrbitStateModel'))\n                    newFrame = obj.centralBody.getBodyCenteredInertialFrame(); %#ok<MCSUP> \n                    elemSet = KeplerianElementSet(obj.time, newOrbitModel.sma, newOrbitModel.ecc, newOrbitModel.inc, ...\n                                                  newOrbitModel.raan, newOrbitModel.arg, newOrbitModel.tru, newFrame); %#ok<MCSUP>\n                    \n                elseif(isa(newOrbitModel,'CR3BPOrbitStateModel'))\n                    error('No conversion available for CR3BPOrbitStateModel to new element set models.');\n                end\n\n                obj.orbitModel = elemSet;\n            else\n                obj.orbitModel = newOrbitModel;\n            end\n        end\n        \n        function cb = getCentralBodyForStateLog(obj)\n            cb = obj.orbitModel.frame.getOriginBody();\n        end\n        \n        function addStageState(obj, newStageState)\n            obj.stageStates(end+1) = newStageState;\n        end\n        \n        function removeStageStateForStage(obj, stage)\n            stageStateInd = find([obj.stageStates.stage] == stage,1,'first');\n            \n            obj.stageStates(stageStateInd) = [];\n        end\n        \n        function stateLogEntry = getInitialStateLogEntry(obj)\n            stateLogEntry = LaunchVehicleStateLogEntry();\n            \n            ut = obj.time;\n            stateLogEntry.time = ut;\n            \n            iFrame = obj.centralBody.getBodyCenteredInertialFrame();\n            cartElemSet = obj.orbitModel.convertToFrame(iFrame).convertToCartesianElementSet();\n            stateLogEntry.position = cartElemSet.rVect;\n            stateLogEntry.velocity = cartElemSet.vVect;\n            \n            stateLogEntry.centralBody = obj.getCentralBodyForStateLog();\n            stateLogEntry.lvState = obj.lvState.deepCopy();\n        \n            for(i=1:length(obj.stageStates))\n                stateLogEntry.stageStates(i) = obj.stageStates(i).deepCopy(true, stateLogEntry.lvState);\n            end\n\n            tankStates = stateLogEntry.getAllTankStates();\n            for(i=1:length(tankStates))\n                tankState = tankStates(i);\n                tankState.tankMass = tankState.tank.initialMass;\n            end\n            \n            stateLogEntry.event = LaunchVehicleEvent.empty(0,1);\n            stateLogEntry.aero = obj.aero.deepCopy();\n            stateLogEntry.thirdBodyGravity = obj.thirdBodyGravity.copy();\n            \n            stopwatches = stateLogEntry.launchVehicle.stopwatches;\n            for(i=1:length(stopwatches))\n                stateLogEntry.stopwatchStates(end+1) = stopwatches(i).createInitialState();\n            end\n            \n            extrema = stateLogEntry.launchVehicle.extrema;\n            for(i=1:length(extrema))\n                stateLogEntry.extremaStates(end+1) = extrema(i).createInitialState();\n            end\n            \n            calcObjs = stateLogEntry.launchVehicle.calcObjs;\n            for(i=1:length(calcObjs))\n                stateLogEntry.calcObjStates(end+1) = calcObjs(i).createInitialState();\n            end\n            \n            obj.steeringModels.selectedModel.setT0(obj.time);\n            obj.throttleModels.selectedModel.setT0(obj.time);\n            \n            stateLogEntry.steeringModel = obj.steeringModels.selectedModel;\n            stateLogEntry.throttleModel = obj.throttleModels.selectedModel;\n            \n            [~,sensors] = stateLogEntry.launchVehicle.lvdData.sensors.getListboxStr();\n            for(i=1:length(sensors))\n                stateLogEntry.sensorStates(end+1) = sensors(i).getInitialState();\n            end\n        end\n        \n        function optVar = getNewOptVar(obj)\n            optVar = InitialStateVariable(obj);\n        end\n        \n        function optVar = getExistingOptVar(obj)\n            optVar = obj.optVar;\n        end\n        \n        function vars = getAllOptVars(obj)\n            vars = obj.getExistingOptVar();\n            \n            steeringVar = obj.steeringModels.selectedModel.getExistingOptVar();\n            if(not(isempty(steeringVar)))\n                vars(end+1) = obj.steeringModels.selectedModel.getExistingOptVar();\n            end\n            \n            throttleVar = obj.throttleModels.selectedModel.getExistingOptVar();\n            if(not(isempty(throttleVar)))\n                vars(end+1) = throttleVar;\n            end\n        end\n        \n        function clearAllTankStatesAndRegenerate(obj)\n            for(i=1:length(obj.stageStates))\n                stgState = obj.stageStates(i);\n                \n                stgState.tankStates = LaunchVehicleTankState.empty(1,0);\n                \n                stage = stgState.stage;\n                for(j=1:length(stage.tanks))\n                    tank = stage.tanks(j);\n                    \n                    newTankState = LaunchVehicleTankState(stgState);\n                    newTankState.tank = tank;\n                    newTankState.tankMass = tank.initialMass;\n                    \n                    stgState.addTankState(newTankState);\n                end\n            end\n        end\n        \n        function clearDuplicateEngineStates(obj)\n            for(i=1:length(obj.stageStates))\n                stgState = obj.stageStates(i);\n                \n                stage = stgState.stage;\n                for(j=1:length(stage.engines))\n                    engine = stage.engines(j);\n                    engineStates = stgState.engineStates;\n                    \n                    thisEngineStates = engineStates([engineStates.engine] == engine);\n                    if(length(thisEngineStates) > 1)\n                        thisEngineStateToSave = thisEngineStates(1);\n                        \n                        engineStates(engineStates == engine) = LaunchVehicleEngineState.empty(1,0);\n                        engineStates(end+1) = thisEngineStateToSave; %#ok<AGROW>\n                    elseif(isempty(thisEngineStates))\n                        newEngineState = LaunchVehicleEngineState(stgState);\n                        newEngineState.engine = engine;\n                        engineStates(end+1) = newEngineState; %#ok<AGROW>\n                    end\n                    \n%                     notThisEngineStates = engineStates([engineStates.engine] ~= engine);\n%                     if(not(isempty(notThisEngineStates)))\n%                         engineStates = setdiff(engineStates, notThisEngineStates);\n%                     end\n                    \n                    stgState.engineStates = engineStates;\n                end\n            end\n        end\n        \n        function tf = isVarFromInitialState(obj, var)           \n            tf = obj.optVar == var;\n            \n            if(not(isempty(obj)) && not(isempty(obj.optVar)))\n                tf = tf || obj.optVar.isVarContainedWithin(var);\n            end\n            \n            if(not(isempty(obj.steeringModels.selectedModel.getExistingOptVar())))\n                tf = tf || obj.steeringModels.selectedModel.getExistingOptVar() == var;\n            end\n            \n            if(not(isempty(obj.throttleModels.selectedModel.getExistingOptVar())))\n                tf = tf || obj.throttleModels.selectedModel.getExistingOptVar() == var;\n            end\n        end\n        \n        function setInitialStateFromStateLogEntry(obj, stateLogEntry)\n            lvdData = stateLogEntry.lvdData;\n            varSet = lvdData.optimizer.vars;\n            \n            %remove variables\n            orbitVar = obj.optVar.orbitVar;\n            varSet.removeVariable(orbitVar);\n            \n            initStateVar = obj.optVar;\n            varSet.removeVariable(initStateVar);\n            \n            steerVar = obj.steeringModels.selectedModel.getExistingOptVar();\n            varSet.removeVariable(steerVar);\n            \n            throttleVar = obj.throttleModels.selectedModel.getExistingOptVar();\n            varSet.removeVariable(throttleVar);\n            \n            %set elements\n            obj.orbitModel = stateLogEntry.getCartesianElementSetRepresentation();\n\n            obj.lvState = stateLogEntry.lvState;\n            obj.stageStates = stateLogEntry.stageStates;\n\n            tankStates = stateLogEntry.getAllTankStates();\n            for(i=1:length(tankStates))\n                tankState = tankStates(i);\n                tankState.tank.initialMass = tankState.tankMass;\n            end\n\n            obj.aero = stateLogEntry.aero;\n            obj.thirdBodyGravity = stateLogEntry.thirdBodyGravity;\n            \n            oldSteerModelT0 = stateLogEntry.steeringModel.getT0();\n            newSteerModelT0 = stateLogEntry.time;\n            tOffsetDelta = newSteerModelT0 - oldSteerModelT0;\n            obj.steeringModels.selectedModel = stateLogEntry.steeringModel;\n            obj.steeringModels.selectedModel.setInitialAttitudeFromState(stateLogEntry, tOffsetDelta);\n            \n            oldThrottleModelT0 = stateLogEntry.throttleModel.getT0();\n            newThrottleModelT0 = stateLogEntry.time;\n            tOffsetDelta = newThrottleModelT0 - oldThrottleModelT0;\n            obj.throttleModels.selectedModel = stateLogEntry.throttleModel;\n            obj.throttleModels.selectedModel.setInitialThrottleFromState(stateLogEntry, tOffsetDelta);\n            \n            %clean up\n            obj.clearDuplicateEngineStates();\n        end\n    end\n\n    methods(Static)\n        function stateLogModel = getDefaultInitialStateLogModelForLaunchVehicle(lv, bodyInfo)\n            celBodyData = lv.lvdData.celBodyData;\n            stateLogModel = InitialStateModel();\n            \n            ut = 0;\n            bfFrame = bodyInfo.getBodyFixedFrame();\n            geoElemSet = GeographicElementSet(ut, 0, 0, 0, 0, 0, 0, bfFrame);\n            stateLogModel.orbitModel = geoElemSet;\n            \n            lvsState = LaunchVehicleState(lv);\n            stateLogModel.lvState = lvsState;\n            lvsState.holdDownEnabled = false;\n            \n            for(i=1:length(lv.engineTankConns)) %#ok<*NO4LP>\n                e2TConnState = EngineToTankConnState(lv.engineTankConns(i));\n                e2TConnState.active = true;\n                lvsState.e2TConns(end+1) = e2TConnState;\n            end\n            \n            stageStates = LaunchVehicleStageState.empty(1,0);\n            for(i=1:length(lv.stages))\n                stage = lv.stages(i);\n                stgState = LaunchVehicleStageState(stage);\n                stgState.active = true;\n                \n                engines = stage.engines;\n                for(j=1:length(engines))\n                    engine = engines(j);\n                    \n                    engineState = LaunchVehicleEngineState(stgState);\n                    engineState.engine = engine;\n                    engineState.active = true;\n                    \n                    stgState.engineStates(end+1) = engineState;\n                end\n                 \n                tanks = stage.tanks;\n                for(j=1:length(tanks))\n                    tank = tanks(j);\n                    \n                    tankState = LaunchVehicleTankState(stgState);\n                    tankState.tank = tank;\n                    tankState.tankMass = tank.initialMass;\n                    \n                    stgState.tankStates(end+1) = tankState;\n                end\n                \n                stageStates(end+1) = stgState; %#ok<AGROW>\n            end\n            stateLogModel.stageStates = stageStates;\n            \n            aeroState = LaunchVehicleAeroState();\n            stateLogModel.aero = aeroState;\n            \n            grav3Body = LaunchVehicle3BodyGravState();\n            grav3Body.celBodyData = celBodyData;\n            stateLogModel.thirdBodyGravity = grav3Body;\n            \n            rpyModel = RollPitchYawPolySteeringModel.getDefaultSteeringModel();\n            stateLogModel.steeringModel = rpyModel;\n            \n            throtModel = ThrottlePolyModel.getDefaultThrottleModel();\n            stateLogModel.throttleModel = throtModel;\n        end\n\n        function obj = loadobj(obj)\n            arguments\n                obj InitialStateModel\n            end\n\n            if(isempty(obj.steeringModels))\n                obj.steeringModels = SteeringModelsSet();\n                obj.steeringModels.selectedModel = obj.steeringModel;\n\n            elseif(obj.steeringModels.selectedModel ~= obj.steeringModel)\n                obj.steeringModels.selectedModel = obj.steeringModel;\n            end\n\n            if(isempty(obj.throttleModels))\n                obj.throttleModels = ThrottleModelsSet();\n                obj.throttleModels.selectedModel = obj.throttleModel;\n\n            elseif(obj.throttleModels.selectedModel ~= obj.throttleModel)\n                obj.throttleModels.selectedModel = obj.throttleModel;\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/StateLog/initialState/@InitialStateModel/InitialStateModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24822907631646585}}
{"text": "function update_from_affine_matrix(this, ...\n    affineMatrix)\n% Updates properties of MrImageGeometry from affine 4x4 transformation\n% matrix\n%\n%   Y = MrImageGeometry()\n%   Y.update_from_affine_matrix(affineMatrix)\n%\n% This is a method of class MrImageGeometry.\n%\n% IN\n%\n% OUT\n%\n% EXAMPLE\n%   update_from_affine_matrix\n%\n%   See also MrImageGeometry tapas_uniqc_spm_matrix, tapas_uniqc_spm_imatrix\n\n% Author:   Saskia Bollmann & Lars Kasper\n% Created:  2014-07-27\n% Copyright (C) 2014 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3.\n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\n% round to N decimals for specified precision, to avoid small numbers < double precision\nN = floor(abs(log10(eps('double'))));\nP = round(tapas_uniqc_spm_imatrix(affineMatrix),N);\n\nthis.offcenter_mm       = P(1:3);\nthis.rotation_deg       = P(4:6)/pi*180;\nthis.resolution_mm      = P(7:9);\nthis.shear              = P(10:12);\nthis.FOV_mm             = this.resolution_mm.*...\n    this.nVoxels(1:3);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImageGeometry/update_from_affine_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24822907062145755}}
{"text": "function meshI = genIVmesh(mesh)\n\nNp = size(mesh.p,1);\nnode = [mesh.p;mesh.eIntP];\nallCutElem = mesh.t(mesh.tLoc<0,:);\nisCutElem = (mesh.tLoc<0);\nvSign = [mesh.pLoc;zeros(size(mesh.eIntP,1),1)];\nisInterfaceNode = false(size(node,1), 1);\nisInterfaceNode(allCutElem(:)) = true; % include the vertices of allCutElem\nnumCutElemV1 = sum(isInterfaceNode);\nisInterfaceNode(Np+1:end) = true;    % and the cut points and the aux points\nallCutElemReoderTmp = zeros(size(node,1),1);\nnumCutElemV2 = sum(isInterfaceNode);\nallCutElemReoderTmp(isInterfaceNode) = 1:numCutElemV2;\nallCutElemReoder = allCutElemReoderTmp(allCutElem);\ninterfaceNode = node(isInterfaceNode,:);\nntI = -min(mesh.tLoc);\nintID = find(mesh.tLoc<0);\n\ntetElem = zeros(12*ntI,4);\ntetElemLoc = zeros(12*ntI,1);\nidx2cube = zeros(12*ntI,1);\ntetcount = 0;\n\nfor i = 1:ntI\n    if i == 3\n        stp = 1;\n    end\n    tID = intID(i);\n    t_e = mesh.t_e(tID,:);\n    pLocK = mesh.pLoc(mesh.t(tID,:));\n    vert0 = mesh.p(mesh.t(tID,:),:);\n    nodeid = [allCutElemReoder(i,:),numCutElemV1-mesh.eLoc(t_e(mesh.eLoc(t_e)<0))'];\n    vert2 = vert0(pLocK>0,:); % plus domain\n    vert1 = vert0(pLocK<0,:); % minus domain\n    intpt0 = mesh.eIntP(-mesh.eLoc(t_e(mesh.eLoc(t_e)<0)),:);\n    id1 = [find(pLocK<0)', 5:4+size(intpt0,1)];\n    id2 = [find(pLocK>0)', 5:4+size(intpt0,1)];\n    p1 = [vert1;intpt0]; DT = delaunayTriangulation(p1); t1 = DT.ConnectivityList;\n    p2 = [vert2;intpt0]; DT = delaunayTriangulation(p2); t2 = DT.ConnectivityList;\n    tetElem(tetcount+1:tetcount+size(t1,1),:) = nodeid(id1(t1));\n    idx2cube(tetcount+1:tetcount+size(t1,1)) = tID;\n    tetElemLoc(tetcount+1:tetcount+size(t1,1)) = 1; % inside subdomain\n    tetcount = tetcount+size(t1,1);\n    tetElem(tetcount+1:tetcount+size(t2,1),:) = nodeid(id2(t2));\n    idx2cube(tetcount+1:tetcount+size(t2,1)) = tID;\n    tetElemLoc(tetcount+1:tetcount+size(t2,1)) = 2; % outside subdomain\n    tetcount = tetcount+size(t2,1);\nend\ntetElem(tetcount+1:end,:) = [];\ntetElemLoc(tetcount+1:end,:) = [];\nidx2cube(tetcount+1:end,:) = [];\n[tetElem, ortidx, volume] = fixorder3(interfaceNode, tetElem);\n\n% there are some tets which are coplane, need to get rid of them\nd12 = interfaceNode(tetElem(:,2),:) - interfaceNode(tetElem(:,1),:);\nd13 = interfaceNode(tetElem(:,3),:) - interfaceNode(tetElem(:,1),:);\nd14 = interfaceNode(tetElem(:,4),:) - interfaceNode(tetElem(:,1),:);\nd12 = sum(d12.^2,2).^(1/2); d13 = sum(d13.^2,2).^(1/2); d14 = sum(d14.^2,2).^(1/2);\nld = max([d12,d13,d14],[],2);\nidPlane = (volume./ld<=10^(-16));\n\n\ntetElem(idPlane,:) = [];\nvolume(idPlane,:) = [];\ntetElemLoc(idPlane,:) = [];\nidx2cube(idPlane,:) = [];\nlocalidx2globalidx = find(isInterfaceNode); % tetElem points to interfaceNode\ntetElem = localidx2globalidx(tetElem);  % map to the global index of node\n% there are some tets which are on the interface, but contained in the surrounding tets\n% need to get rid of them (but the following algorithm may not be robust)\ntetSign = vSign(tetElem);\nidSliver = (sum(abs(tetSign),2)==0);\ntetElem(idSliver,:) = [];\nvolume(idSliver,:) = [];\ntetElemLoc(idSliver,:) = [];\nidx2cube(idSliver,:) = [];\nPolyVolume = accumarray([idx2cube,tetElemLoc],volume);\nPolyVolume = PolyVolume(mesh.tLoc<0,:);\n\n\n%% Get triangular faces for interrior elements and interface\nlocalFace = [2 3 4; 1 4 3; 1 2 4; 1 3 2];\nNT = size(tetElem,1);\ntface = zeros(4*NT, 3);\ntface2elem = zeros(4*NT, 1);\niface = zeros(4*NT, 3);\niface2elem = zeros(4*NT, 1);\n% find the interior tet elements\nisIntTet1 = min(vSign(tetElem),[], 2) == -1; % can not be == -1 as there is sliver\nisIntTet2 = sum(abs(vSign(tetElem)),2) == 0;\nisIntTet = isIntTet1 | isIntTet2;\nintTet = tetElem(isIntTet,:);\n% find the corresponding cube indices\nintIdx2cube = idx2cube(isIntTet); \n% find triangular interface\nT = auxstructure3(intTet);\nneighbor = T.neighbor; % if a face is on the boundary, then the neighbor element index is itself\nclear T;\ntmp = (1:size(intTet, 1))';\nct = 0;\nci = 0;\nfor i = 1:4\n    face = intTet(:, localFace(i,:));\n    % find the triangle faces of polyhedron\n    % 1. face and its neighbor associated to different cubes, and\n    % 2. face is not on the boundary of all cut elements (which are squares)\n    isPolyTriFace = ((neighbor(:, i) == tmp) | (intIdx2cube ~= intIdx2cube(neighbor(:,i)))) &...\n        (sum(abs(vSign(face)), 2) >= 10^(-12));% & (sum(abs(vSign(face)), 2) > 0);\n    c2 = ct + sum(isPolyTriFace);\n    tface((ct+1):c2,:) = face(isPolyTriFace,:);\n    tface2elem((ct+1):c2,:) = intIdx2cube(isPolyTriFace); % the indices of the polyhedron\n    ct = c2;\n    % note that only interior elements are treated\n    \n    % find the triangle faces on interface with normal points to exterior\n    % 1. face is on the boundary and\n    % 2. all vertices are on the interface\n    isInterface = (sum(abs(vSign(face)), 2) <= 10^(-12));\n    \n    % add to interface    \n    c4 = ci + sum(isInterface);\n    iface((ci+1):c4,:) = face(isInterface,:); % the interface tri faces.\n    iface2elem((ci+1):c4,:) = intIdx2cube(isInterface); % the indices of the polyhedron\n    ci = c4;\nend\niface((ci+1):end,:) = [];\niface2elem((ci+1):end,:) = [];\nc2old = c2;\n% plot to check\n%trisurf(tface(1:c2,:),node(:,1),node(:,2),node(:,3))\n%trisurf(iface(1:ci,:),node(:,1),node(:,2),node(:,3))\n\n% Find the triangular faces for exterior elements \nextTet = tetElem(~isIntTet, :);\nextIdx2cube = idx2cube(~isIntTet);\n\nT = auxstructure3(extTet);\nneighbor = T.neighbor;\nclear T;\ntmp = (1:size(extTet,1))';\nfor i = 1:4\n    face = extTet(:, localFace(i,:));\n    % find the triangle faces of polyhedron\n    % 1. face and its neighbor associated to different cubes, and\n    % 2. face is not on the boundary of all cut elements (which are squares)\n    isPolyTriFace = ((neighbor(:, i) == tmp) | (extIdx2cube ~= extIdx2cube(neighbor(:,i)))) &...\n        (sum(abs(vSign(face)), 2) > 0);\n    c2 = ct + sum(isPolyTriFace);\n    tface((ct+1):c2,:) = face(isPolyTriFace,:);\n    tface2elem((ct+1):c2,:) = extIdx2cube(isPolyTriFace); \n    % index of exterior polyhedron is append to the end of elem\n    ct = c2;\n    \nend\n\n% plot to check\n%trisurf(tface(c2old+1:c2,:),node(:,1),node(:,2),node(:,3))\n\ntface((ct+1):end,:) = [];    % remove empty meomory\ntface2elem((ct+1):end) = [];\nface2elemLoc = [ones(c2old,1);2*ones(c2-c2old,1)]; % face2elemLoc is the same as face location\n\n\nmeshI.tface = tface;\nmeshI.tface2elem = tface2elem;\nmeshI.iface = iface;\nmeshI.iface2elem = iface2elem;\nmeshI.face2elemLoc = face2elemLoc;\nmeshI.PolyVolume = PolyVolume;\n% meshI.vSign = vSign;\nmeshI.node = node;\nmeshI.tetElem = tetElem;\nmeshI.tetElemLoc = tetElemLoc;\nmeshI.idx2cube = idx2cube;\nmeshI.tetVolume = volume;\nmeshI.vSign = vSign;\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genIVmesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24816274571748081}}
{"text": "function estimate_rr(up)\n%ESTIMATE_RR estimates RR from respiratory signals using each possible set\n% of RR estimation options, as specified in PC's literature review.\n%\t            estimate_rr(up)\n%\n%\tInputs:\n%\t\tdata            data files should be stored in the specified format\n%       up              universal parameters structure\n%\n%\tOutputs:\n%       \tfor each subject, n:\n%       n_rrEsts.m      - a file of RR estimates\n%\n\nfprintf('\\n--- Estimating RRs ');\n%% Extract list of resp signals from the first pt:\nsubj = up.paramSet.subj_list(1);\nloadpath = [up.paths.data_save_folder, num2str(subj), up.paths.filenames.respSigs];\nif exist(loadpath, 'file')\n    filecontents = whos('-file', loadpath);\n    respSigs = extractfield(filecontents, 'name');\nelse\n    warning(['No respiratory signals found for Subject ', num2str(subj) '.'])\nend\n\n%% Cycle through each patient\nfor subj = up.paramSet.subj_list\n    loaded_this_subj_respSigs = 0;\n    %% Make window timings if necessary\n    identify_subj_wins(subj, up);\n    %% Cycle through each resp signal\n    for respSig_no = 1:length(respSigs)\n        for option_no = 1 : length(up.al.options.estimate_rr)\n            % Skip if this processing has been done previously\n            if strcmp(up.al.options.estimate_rr{option_no}, 'GCE')\n                save_name = [ respSigs{respSig_no}(1:3) '_' up.al.options.estimate_rr{option_no} ];\n            else\n                save_name = [ respSigs{respSig_no} '_' up.al.options.estimate_rr{option_no} ];\n            end\n            savepath = [up.paths.data_save_folder, num2str(subj), up.paths.filenames.rrEsts, '.mat'];\n            exist_log = check_exists(savepath, save_name);\n            if exist_log\n                continue\n            end\n            \n            % load data if it hasn't yet been loaded\n            if ~loaded_this_subj_respSigs\n                % Signals\n                load([up.paths.data_save_folder, num2str(subj), up.paths.filenames.respSigs]);\n                % Window timings\n                load([up.paths.data_save_folder, num2str(subj), up.paths.filenames.win_timings, '.mat']);\n                loaded_this_subj_respSigs = 1;\n            end\n            % Identify the relevant respSig data\n            eval(['rel_data = ' respSigs{respSig_no} ';']);\n            % add current subject and resp sig for any methods that do not use a resp sig.\n            rel_data.subj = subj;\n            rel_data.respSig = respSigs{respSig_no};\n            %% Calculate RR from this resp sig using each option for estimating RR\n            if (length(rel_data.t) == 1 && isnan(rel_data.t)) || sum(isnan(rel_data.v))==length(rel_data.v)\n                temp_rr.t = mean([wins.t_start(:)' ; wins.t_end(:)']); temp_rr.t = temp_rr.t(:);\n                temp_rr.v = nan(length(temp_rr.t),1);\n            else\n                temp_rr = feval(up.al.options.estimate_rr{option_no}, rel_data, wins, up);\n            end\n            % store this series of rrs:\n            if strcmp(up.al.options.estimate_rr{option_no}, 'GCE')\n                eval([respSigs{respSig_no}(1:3) '_' up.al.options.estimate_rr{option_no} ' = temp_rr;']);\n            else\n                eval([respSigs{respSig_no} '_' up.al.options.estimate_rr{option_no} ' = temp_rr;']);\n            end\n            \n            clear temp_rr\n            %% Save RRs to file\n            save_or_append_data\n        end\n    end\n    clear ekg* ppg* wins            % clear resp sigs\nend\n\nend", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v2.0/Algorithms/estimate_rr/estimate_rr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24816274571748076}}
{"text": "function [el, lab] = read_elec(fn)\n\n% READ_ELEC reads \"la/mu\" electrode parameters from a MBF electrode file\n% which are used to position them on a triangulated surface\n%\n% [el, lab] = read_elec(filename)\n%\n% where el = [tri, la, mu]\n% and lab contains the electrode labels (if present)\n%\n% See also READ_TRI, TRANSFER_ELEC\n\n% Copyright (C) 1998, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nfid = fopen_or_error(fn, 'rt');\n\n% read the number of electrodes\nNel = sscanf(fgetl(fid), '%d'); \n\n% read the electrode triangle, lambda and mu\nfor i=1:Nel\n  str = fgetl(fid);\n  el(i,:)  = sscanf(str, '%f %f %f')';\n  indx = find(str=='!');\n  if (indx)\n    lab(i,:) = sprintf('%6s', str((indx+1):length(str)));\n  end\nend\nfclose(fid);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_elec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24816273895567365}}
{"text": "% --------------------------------------------------------\n% MDP Tracking\n% Copyright (c) 2015 CVGL Stanford\n% Licensed under The MIT License [see LICENSE for details]\n% Written by Yu Xiang\n% --------------------------------------------------------\n%\n% cross_validation on the MOT benchmark\nfunction MOT_cross_validation\n\n% set is_train to 0 if testing trained trackers only\nis_train = 1;\nopt = globals();\n\nmot2d_train_seqs = {'TUD-Stadtmitte', 'TUD-Campus', 'PETS09-S2L1', ...\n   'ETH-Bahnhof', 'ETH-Sunnyday', 'ETH-Pedcross2', 'ADL-Rundle-6', ...\n   'ADL-Rundle-8', 'KITTI-13', 'KITTI-17', 'Venice-2'};\n\n% training and testing pairs\nseq_idx_train = {{1}, {4},    {7},     {9}};\nseq_idx_test  = {{2}, {5, 6}, {8, 11}, {10}};\n\nseq_set_test = 'train';\nN = numel(seq_idx_train);\n\n% for each training-testing pair\nfor i = 1:N\n    % training\n    idx_train = seq_idx_train{i};\n    \n    if is_train\n        % number of training sequences\n        num = numel(idx_train);\n        tracker = [];\n        \n        % online training\n        for j = 1:num\n            fprintf('Online training on sequence: %s\\n', mot2d_train_seqs{idx_train{j}});\n            tracker = MDP_train(idx_train{j}, tracker);\n        end\n        fprintf('%d training examples after online training\\n', size(tracker.f_occluded, 1));\n        \n    else\n        % load tracker from file\n        filename = sprintf('%s/%s_tracker.mat', opt.results, mot2d_train_seqs{idx_train{end}});\n        object = load(filename);\n        tracker = object.tracker;\n        fprintf('load tracker from file %s\\n', filename);\n    end\n    \n    % testing\n    idx_test = seq_idx_test{i};\n    % number of testing sequences\n    num = numel(idx_test);\n    for j = 1:num\n        fprintf('Testing on sequence: %s\\n', mot2d_train_seqs{idx_test{j}});\n        MDP_test(idx_test{j}, seq_set_test, tracker);\n    end    \nend\n\n% evaluation for all test sequences\nbenchmark_dir = fullfile(opt.mot, opt.mot2d, seq_set_test, filesep);\nseqs = {'TUD-Campus', 'ETH-Sunnyday', 'ETH-Pedcross2', ...\n   'ADL-Rundle-8', 'Venice-2', 'KITTI-17'};\nevaluateTracking(seqs, opt.results, benchmark_dir);", "meta": {"author": "yuxng", "repo": "MDP_Tracking", "sha": "2f452a1f7204b6e3344925b8eaf39db1c7eecf2c", "save_path": "github-repos/MATLAB/yuxng-MDP_Tracking", "path": "github-repos/MATLAB/yuxng-MDP_Tracking/MDP_Tracking-2f452a1f7204b6e3344925b8eaf39db1c7eecf2c/MOT_cross_validation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.24801663865091345}}
{"text": "function varargout = subsref(F, ref)\n%SUBSREF   SPHEREFUNV subsref.\n% \n% ( )\n%   F(LAM,TH) returns the values of the SPHEREFUNV F evaluated on the array\n%   (LAM,TH) in spherical coordinates.\n%\n%   F(X,Y,Z) returns the values of the SPHEREFUNV F evaluated on the array\n%   (X,Y,Z) in Cartesian coordinates.\n%\n%   F(k) returns the first component of F if k=1, the second if k=2, and\n%   the third if k=3.\n%  .\n%   F.PROP returns the property PROP of F as defined by GET(F,'PROP').\n%  \n% { }\n%    Throws an error.\n\n% Check for empty SPHEREFUNV object. \nif ( isempty(F) )\n   varargout = {[]};\n   return\nend\n\nindx = ref(1).subs;\n\nswitch ( ref(1).type )\n    \n    case '.'\n        if ( numel(ref) == 1 )\n            % This is a get call to get a property. \n            varargout = { get(F, indx) };\n        else\n            t2 = ref(2).type;\n            if ( strcmp(t2,'.') )\n                out = get(F, indx, ref(2).subs{:});\n            else\n                out = get(F, indx);\n                out = out(ref(2).subs{:});\n            end\n            if ( numel(ref) > 2 )\n                varargout = {subsref(out, ref(3:end))};\n            else\n                varargout = { out };\n            end\n        end\n        \n    case '()'\n        if ( length(indx) == 2 ) % spherical coordinates\n            lam = indx{1}; \n            th = indx{2}; \n            vals = feval(F, lam, th); \n            varargout = { vals }; \n        elseif ( length(indx) == 3 ) % Cartesian coordinates\n            x = indx{1}; \n            y = indx{2};\n            z = indx{3};\n            vals = feval(F, x, y, z); \n            varargout = { vals };             \n        else\n            if ( isa(indx{1},'double') )\n                if all( indx{1} == 1  )\n                    varargout = F.components(1);\n                elseif ( all( indx{1} == 2 ) )\n                    varargout = F.components(2);\n                elseif ( ( all(indx{1} == 3) )  )\n                    varargout = F.components(3);\n                else\n                    error('SPHEREFUN:SPHEREFUNV:subsref:index', ...\n                        'SPHEREFUNV only contains three components.');\n                end\n            end\n        end\n        \n    otherwise\n        error('SPHEREFUN:SPHEREFUNV:subsref:unexpectedType', ...\n            ['??? Unexpected index.type of ' index(1).type]);\n        \nend\n\n% Recurse down: \nif ( numel( ref ) > 1 )\n   ref(1) = []; \n   varargout = { subsref( varargout{ : }, ref ) }; \nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefunv/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}}
{"text": "% Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich, \n%   Switzerland\n%   You can contact the author at <titus at ifi dot uzh dot ch>\n% Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing,\n%   Georgia Institute of Technology, Atlanta, GA, USA\n% Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich, \n%   Switzerland\n%\n% This file is part of dslam_open.\n%\n% dslam_open is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% dslam_open is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with dslam_open. If not, see <http://www.gnu.org/licenses/>.\n\nfunction quiver = posesToQuiver(T)\nn = numel(T);\nquiver = zeros(n, 6);\nfor i = 1:n\n    quiver(i, :) = poseToQuiver(T{i});\nend\nend\n\n", "meta": {"author": "uzh-rpg", "repo": "dslam_open", "sha": "3428893cffa5e832e8d51a6f3e18213b47205a83", "save_path": "github-repos/MATLAB/uzh-rpg-dslam_open", "path": "github-repos/MATLAB/uzh-rpg-dslam_open/dslam_open-3428893cffa5e832e8d51a6f3e18213b47205a83/dslam/matlab/posesToQuiver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}}
{"text": "function [EEGout cfg] = pop_sim_eegdata(EEG,typeproc,varargin)\n%\n% Simulate EEG data using a dynamical modeling framework and \n% a forward head model.\n%\n% Input:\n% Optional:\n%\n%   EEG:            existing EEG dataset (configs will be retrived from\n%                   here)\n%   typeproc:       if 'nogui' don't generate GUI\n%\n%   <'Name',value> pairs as defined in sim_varmodel()\n%\n% Output:\n%\n%   EEGout:         Simulated EEG structure(s).\n%                   Optionally this may be an array of\n%                   EEG structs with the second struct \n%                   being the ground truth model.\n%   cfg:            Argument specification structure.\n%\n%\n% See Also: sim_varmodel(), sim_eegdata(),\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual.\n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift\n%\n% Author: Tim Mullen 2013, SCCN/INC, UCSD.\n% Email:  tim@sccn.ucsd.edu\n%\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nif nargin<1\n    EEG = [];     \nend\nif nargin<2\n    typeproc = 0; \nend\nEEGout = EEG;\ncfg    = [];\n        \nfcnName     = strrep(mfilename,'pop_','');\nfcnHandle   = str2func(fcnName);\n\nif isempty(hlp_checkeegset(EEG,{'cat'})) && isfield(EEG.CAT.configs,fcnName)\n    % get default configuration (from prior use) and merge with varargin\n    varargin = [hlp_struct2varargin(EEG.CAT.configs.(fcnName)) varargin];\nend\n\nif strcmpi(typeproc,'nogui')\n    % get the default config from function and overload supplied args\n    cfg = arg_tovals(arg_report('rich',fcnHandle,varargin),false);\nelse\n    % render the GUI\n    [PGh figh] = feval(['gui_' fcnName],varargin{:});\n    \n    if isempty(PGh)\n        % user chose to cancel\n        return;\n    end\n    \n    % get the specification of the PropertyGrid\n    ps = PGh.GetPropertySpecification;\n    cfg = arg_tovals(ps,false);\nend\n\ndrawnow;\n\nif ~cfg.srcdyn.makeEEGset.arg_selection\n    error('SIFT:sim_varmodel',['If using pop_' fcnName '(), you must enable the BuildEEGLABStructure option.\\n' ...\n                               'Use ' fcnName '() from the command-line to return a raw dataset']);\nend\n\nif strcmpi(typeproc,'cfg_only')\n    return;\nend\n\n% execute the low-level function\n[EEGout GroundTruth] = feval(fcnHandle,cfg);\n\nif ~isempty(GroundTruth)\n    EEGout = eeg_store(EEGout,GroundTruth,2);\nend\nif ~isempty(cfg)\n    for k=1:length(EEGout)\n        % store the configuration structure\n        EEGout(k).CAT.configs.(fcnName) = cfg;\n    end\nend\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/pop/pop_sim_eegdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}}
{"text": "function [new,messages] = searchbk (w, i, thres,freq,thres_alpha,messages)\n%performs the searching back when no qrs has been detected for\n% 1.5 times the RR before.  i is the beginning sample.  thres\n% is the threshold for scale 4;\n% Last update: Rute Almeida 27Jan2012\n\nif nargin<6 || (isempty(freq) && (~isfield(messages.setup.wavedet,'freq') || ~(messages.setup.wavedet.freq>0)))\n    messages.errors=[messages.errors {'Fatal error in wavedet_3D: no sampling frequency variable found.'}];\n    warning(char(messages.errors(end)))\n    messages.errors_desc=[messages.errors_desc {'No sampling frequency variable give to seachbk from fiducialf.m.'}];\n    new=0;\n    return\nelseif ~isempty(freq) && isfield(messages.setup.wavedet,'freq') && messages.setup.wavedet.freq>0 && freq~=messages.setup.wavedet.freq\n    messages.warnings=[messages.warnings {'sampling frequency used in searchbk is different from messages.setup.wavedet.freq.'}];\nelseif isempty(freq)\n    freq=messages.setup.wavedet.freq;\nend\n\nif ~isfield(messages.setup.wavedet,'refrper') || ~isfield(messages.setup.wavedet,'peakcriteria') || ~isfield(messages.setup.wavedet,'timelapthr') || ~isfield(messages.setup.wavedet,'timelapthr') || ~isfield(messages.setup.wavedet,'intvlthr1') || ~isfield(messages.setup.wavedet,'intvlthr2') || ~isfield(messages.setup.wavedet,'nghbhd')\n    messages.errors=[messages.errors {'Fatal error in wavedet_3D: missing parameters on seachbk.'}];\n    warning(char(messages.errors(end)))\n    messages.errors_desc=[messages.errors_desc {'Setup value is missing on seachbk from fiducialf.m.'}];\n    new=0;\n    return\nend\nif ~isfield(messages.setup.wavedet,'intvlthr1_2_sbk')\n    messages.setup.wavedet.intvlthr1_2_sbk=2;%reduction on threshold interval for considering redundancy if it subsists\nend\nif ~isfield(messages.setup.wavedet,'thfraction_sbk')\n    if isfield(messages.setup.wavedet,'thfraction')\n        messages.setup.wavedet.thfraction_sbk=messages.setup.wavedet.thfraction;\n    else\n        messages.errors=[messages.errors {'Fatal error in wavedet_3D: missing parameters on seachbk.'}];\n        warning(char(messages.errors(end)))\n        messages.errors_desc=[messages.errors_desc {'Setup value thfraction is missing on seachbk from fiducialf.m.'}];\n        new=0;\n        return\n    end\nend\n\nif ~isfield(messages.setup.wavedet,'nghbhd')\n    messages.setup.wavedet.nghbhd=0.025; % neighbourwood fro maximum across scales in sec\nend\n\nthfraction_sbk=messages.setup.wavedet.thfraction_sbk;\npeakcriteria=messages.setup.wavedet.peakcriteria;\ntimelap = ceil(messages.setup.wavedet.timelapthr*freq);\n\n\nthres = thres/2;  % When searching back we take half\nthres(4) = thres(4)/2; % so new thres(4) = old thres (4)/4\n\nn = modmax(w(:,4),2,thres(4),0);  % Search maximum moduli at scale 4\nneighb = ceil(freq*messages.setup.wavedet.nghbhd);        % Neighbourhood = 25 ms\n\nm = zeros(4,length(n));\nsigno = sign(w(n,4))';\nif ~isempty(n),\n    m(4,:) = n';\nend\nnew = []; %#ok<NASGU>\n\n\nfor k = 1:size(m,2),\n    window = [max(n(k)-neighb,1), min(n(k)+neighb,size(w,1))];\n    n3 = modmax(w(window(1):window(2),3),2,thres(3),signo(k));\n    n3 =window(1)-1+n3;\n    num = length(n3);\n    if num>0,\n        if num==1,\n            m(3,k)= n3;\n        elseif num>1\n            if length(find(max(abs(w(n3,3)))./abs(w(n3,3))<peakcriteria))==1,\n                [aux1,ind]=max(abs(w(n3,3))); %#ok<ASGLU> % greatest modulus\n                m(3,k)= n3(ind);\n            else                              % minimum distance\n                [aux1,ind]=min(abs(m(4,k)-n3)); %#ok<ASGLU>\n                m(3,k)= n3(ind);\n            end\n        end\n    end\nend\nind = find(m(3,:)==0);\nm(:,ind) = [];\nsigno(ind) = [];\n\n% Search for maximum moduli in the neighborhood at scale 2\nfor k = 1:size(m,2),\n    window = [max(m(3,k)-neighb,1), min(m(3,k)+neighb,size(w,1))];\n    n2 =modmax(w(window(1):window(2),2),2,thres(2),signo(k));\n    n2 =window(1)-1+n2;\n    num = length(n2);\n    if num>0,\n        if num==1,\n            m(2,k)= n2;\n        elseif num>1\n            if length(find(max(abs(w(n2,2)))./abs(w(n2,2))<peakcriteria))==1,\n                [aux1,ind]=max(abs(w(n2,2))); %#ok<ASGLU> % greatest modulus\n                m(2,k)= n2(ind);\n            else                            % shortest distance\n                [aux1,ind]=min(abs(m(3,k)-n2)); %#ok<ASGLU>\n                m(2,k)= n2(ind);\n            end\n        end\n    end\nend\nind = find(m(2,:)==0);\nm(:,ind) = [];\nsigno(ind) = [];\n\nfor k = 1:size(m,2),\n    window = [max(m(2,k)-neighb,1), min(m(2,k)+neighb,size(w,1))];\n    n1 =modmax(w(window(1):window(2),1),2,thres(1),signo(k));\n    n1 =window(1)-1+n1;\n    num = length(n1);\n    if num>0,\n        if num==1,\n            m(1,k)= n1;\n        elseif num>1\n            if length(find(max(abs(w(n1,1)))./abs(w(n1,1))<peakcriteria))==1,\n                [aux1,ind]=max(abs(w(n1,1)));%#ok<ASGLU> % greatest modulus\n                m(1,k)= n1(ind);\n            else                             % shortest distance\n                [aux1,ind]=min(abs(m(2,k)-n1)); %#ok<ASGLU>\n                m(1,k)= n1(ind);\n            end\n        end\n    end\nend\n\nind = find(m(1,:)==0);               %Discard all maximum lines with no\nm(:,ind) = [];                       % associated maximum at scale 1\nsigno(ind) = [];\n\n% Regularity Exponent Validation\n% alpha proportional to log(a3(nk3))-log(a1(nk1))\nalpha = log(abs(w(m(3,:),3)));  %%!!!!\n% alpha = log(abs(w(m(3,:),3))) - log (abs(w(m(1,:),1)));  !!!\nind = find(alpha <= thres_alpha-thfraction_sbk);   %%%% !!!\nm(:,ind) = [];\nsigno(ind) = [];\n\nthresinterval = ceil(messages.setup.wavedet.intvlthr2 * freq);         % 120 ms. (Li)\n\nif size(m,2)>2,\n    ind = find( ((m(1,2:end-1)-m(1,1:end-2))>thresinterval) ...\n        &      (m(1,3:end)- m(1,2:end-1))>thresinterval)+1;\n    if (m(1,2)-m(1,1))>thresinterval,\n        ind = [1 ind];\n    end\n    if (m(1,end)-m(1,end-1))>thresinterval,\n        ind = [ind size(m,2)];\n    end\n    m(:,ind) =[];                     % Discard isolated maximum lines\n    signo(ind) = [];\n    \nelseif size(m,2)==2,                 % If only two lines\n    if (m(1,2)-m(1,1))>thresinterval, % discard them if too separated\n        m(:,1:2)=[];\n        signo(1:2)=[];\n    end\nelseif size(m,2)==1,                % If only one, discard it\n    m(:,1)=[];\n    signo(1)=[];\nend\n\n% Threshold interval for considering redundancy\nredundant= [];\nthresinterval = ceil(messages.setup.wavedet.intvlthr1*freq);           % 120 ms. (li)\n\nfor l = find(signo>0),                      % For each positive maximum line\n    if ~any(redundant ==l),                   % If it has not been declared redundant yet\n        ind=find((m(3,:)>m(3,l)-messages.setup.wavedet.intvlthr1_2_sbk*thresinterval)&(m(3,:)<m(3,l)+messages.setup.wavedet.intvlthr1_2_sbk*thresinterval)&signo>0);\n        % index of positive lines near the present one (including it)\n        if length(ind)>1,                        % If more than one --> redundancy\n            [mx,ind2]= max(abs(w(m(3,ind),3))); %#ok<ASGLU>\n            ind(ind2)=[];\n            redundant = [redundant ind];             %#ok<AGROW> % All but the greatest are redundant\n        end\n    end\nend\n\nm(:,redundant)=[];                         % Discard redundant lines\nsigno(redundant)=[];\nredundant= [];\n\n\nfor l = find(signo>0),              % For each remaining positive maximum line\n    ind = find((m(3,:)>m(3,l)-thresinterval)&(m(3,:)<m(3,l)+thresinterval)&signo<0);\n    % Search for negative minima near it\n    if length(ind)>1,               % If more than one ---> redundancy\n        aux = abs(w(m(3,ind),3)./(m(3,ind)'-m(3,l)));\n        % auxiliary variable: height over distance\n        [mx,indmx]=max(aux);\n        ind2=ind;\n        aux(indmx)=[]; ind2(indmx)=[];\n        if all((mx./aux)>peakcriteria),        % RULE 2 (see PFC or Li's paper)\n            redundant = [redundant ind2]; %#ok<AGROW>\n        else\n            [aux,aux2]=min(abs(m(3,l)-m(3,ind))); %#ok<ASGLU>\n            ind(aux2)=[];              % RULE 1 (see PFC or Li's paper)\n            redundant = [redundant ind]; %#ok<AGROW>\n        end\n    end\nend\nm(:,redundant)=[];                  % Discard redundant lines\nsigno(redundant)=[];\nredundant = [];\nfor l = find(signo<0),              % For each remaining negative minimum line\n    ind = find((m(3,:)>m(3,l)-thresinterval)&(m(3,:)<m(3,l)+thresinterval)&signo>0);\n    % Search for positive maxima near it\n    if length(ind)>1,                % If more than one ----> redundancy\n        aux = abs(w(m(3,ind),3)./(m(3,ind)'-m(3,l)));\n        % auxiliary variable: height over distance\n        [mx,indmx]=max(aux);\n        ind2=ind;\n        aux(indmx)=[]; ind2(indmx)=[];\n        if all((mx./aux)>peakcriteria),\n            redundant = [redundant ind2]; %#ok<AGROW>   % RULE 2\n        else\n            [aux,aux2]=min(abs(m(3,l)-m(3,ind))); %#ok<ASGLU>\n            ind(aux2)=[];\n            redundant = [redundant ind]; %#ok<AGROW>    % RULE 1\n        end\n    end\nend\nm(:,redundant)=[];\nsigno(redundant)=[];\n\n%%%%%%%%%%%%%% isolated maximum lines resulting from Discarded\n%%%%%%%%%%%%%% redundant OUT1011\n\nind = find( ((m(1,2:end-1)-m(1,1:end-2))>thresinterval) ...\n    &      (m(1,3:end)- m(1,2:end-1))>thresinterval)+1;\n\n\nif size(m,2)<2 && ~isempty(ind), ind=1; end  % when only one maximum %16DEZ08\nm(:,ind) = [];                     %Discard isolated maximum lines\nsigno(ind)=[];\nif size(m,2)<2\n    m=[];\n    signo=[];\nend\n\neliminar=[];\n%%%%extra protection% OUT2011\nfor ii=1:size(m,2)\n    pa = picant(w(max(1,m(2,ii)-round(messages.setup.wavedet.pictime*freq)):m(2,ii),2),m(2,ii));\n    % first peak before detected qrs position at scale 2\n    pp = picpost(w(m(2,ii):min(size(w,1),m(2,ii)+round(messages.setup.wavedet.pictime*freq)),2),m(2,ii));\n    \n    if isempty(pa) || isempty(pp)\n        eliminar=[eliminar ii]; %#ok<AGROW>\n    end\nend\n\nm(:,eliminar)=[];\nsigno(eliminar)=[];\n\n\n\n% QRS peak detection / wavelet Zero cross detection\ntime = [];\naux=[]; %Rute26Jun09\nif length(signo)>1,\n    for l = find(signo>0),\n        if (l==1)\n            if (signo(2)<0)&&(m(1,2)-m(1,1)<thresinterval),\n                ind = zerocros(w(m(1,l):min(m(1,l)+timelap,size(w,1)),1));\n                % Zero crossing at scale 1\n                time = [time ind+m(1,l)-1]; %#ok<AGROW>\n                aux=[aux abs(w(m(1,l))-w(m(1,l+1)))];  %#ok<AGROW> %Rute26Jun09\n            end\n        elseif (l==size(m,2))                % Special case: last line\n            if (signo(l-1)<0)&&(m(1,end)-m(1,end-1)<thresinterval),\n                ind = zerocros(w(m(1,l-1):min(m(1,l-1)+timelap,size(w,1)),1));\n                time = [time ind+m(1,l-1)-1]; %#ok<AGROW>\n                aux=[aux abs(w(m(1,l-1))-w(m(1,l)))];  %#ok<AGROW>  %Rute26Jun09\n            end\n        elseif signo(l+1)<0 && ((signo(l-1)>0) ...\n                || ((m(1,l+1)-m(1,l))<(m(1,l)-m(1,l-1))))\n            ind = zerocros(w(m(1,l):min(m(1,l)+timelap,size(w,1)),1));\n            time = [time ind+m(1,l)-1]; %#ok<AGROW>\n            aux=[aux abs(w(m(1,l))-w(m(1,l+1)))]; %#ok<AGROW>  %Rute26Jun09\n        elseif signo(l-1)<0,\n            ind = zerocros(w(m(1,l-1):min(m(1,l-1)+timelap,size(w,1)),1));\n            time = [time ind+m(1,l-1)-1]; %#ok<AGROW>\n            aux=[aux abs(w(m(1,l-1))-w(m(1,l)))]; %#ok<AGROW> %Rute 26Jun09\n        end\n    end\nend\n\n% Refractary period after a QRS detection (200 ms).\nrr = (time(2:end)-time(1:end-1));\nind = find(rr<ceil(messages.setup.wavedet.refrper(end)*freq));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%RUTE 26Jun09\n%time(ind+1)=[]; % always the second one is eliminated!!! to be changed\nfor auxi=1:length(ind) %RUTE 27Jun11\n    [M,ii]=min([aux(ind(auxi)) aux(ind(auxi)+1)]); %#ok<ASGLU> % 18JUL2011\n    if ii==2, ind(auxi)=ind(auxi)+1; end\nend\ntime(ind)=[]; %RUTE 27Jun11\naux(ind)=[]; %#ok<NASGU>\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nnew = time +i -1;", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/wavedet/searchbk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2479878547346572}}
{"text": "% clear\nsavethis = 1;\nif exist('peval','var')\n    fpirntf('There is a variable called peval already. Saved in peval_bckp.')\n    peval_bckp = peval; \n    clear peval\nend\n\nncomp = [10 20 30]; \n\n\nitervec=1; %number of evaluation of each dataset\npeval.sript_name = mfilename; \n\n% set here the path to the data (in this case data must be in mat format):\npeval.data_path = '~/project/data/qdots/....';\npeval.data_file = 'dpixc';\n\nload([peval.data_path '/' peval.data_file])\n\n% uncomment this for callibration of the data to photon counts:\n% bgOffset=700; % this is from the background images\n% photonFactor = .2612; %from EM ccd callibration: https://docs.google.com/spreadsheet/ccc?key=0AlBph96P6KPwdEtOcGJWampsaHpGOHBDYUtIZ19LS2c&hl=en_US#gid=0\n% dpixc = photonFactor*(dpixc-bgOffset); \n% dpixc=dpixc(:,:,1:300);\n\n% bacground estimation is here:\npeval.bg=100; \n\n[peval.nx, peval.ny, peval.nt]=size(dpixc);\nfor nc = ncomp;\n%     for iterindex=1:niter\n    for iterindex=itervec\n        if savethis\n            [peval.logfile, peval.fid] = initlogfile;\n        end\n        if sum(dpixc(:)<=0)\n            mfprintf(peval.fid,'Clipping negative values in the dpixc!\\n')\n            dpixc(dpixc<=0)=eps; % to avoid negative values and zeros...\n        end\n\n        \n        params %reads the parameters        \n%         datasource = [peval.home '/' peval.data_path '/' peval.data_dir '/' peval.data_file];\n        \n%         readdata\n        \n        % Estimating / subtracting background:\n        %         [dpixc, peval]=backgroundestimation(dpixc, peval, p.offset);\n        \n%         peval.bg=p.offset;\n        %         dpixc=bgsubtractbyhand(dpixc,peval);\n        peval.ncomp=nc;\n        \n        dvec=reshape(dpixc,peval.nx*peval.ny,peval.nt);\n        \n        for indexrestart=0:peval.nrestarts-1\n            % Initialization of W:\n            %             winit = init_wmap('rand',peval,double(array2im(dpixc_ind)));\n            if indexrestart>0\n                mfprintf(peval.fid, '\\nRestart %g: h restarted and w reused\\n',indexrestart);\n                winit = init_w_general('res',peval,res.w);\n                peval.fix_bg_h=0; mfprintf(peval.fid,'\\nBackground component of h will be updated\\n')\n                \n            else            \n                winit = init_w_general(peval.init_w_method,peval,[]);\n            end\n            hinit = init_h_general(peval.init_h_method,peval,[],dpixc);\n            \n            % Main computation:\n            [res, peval]=peval.fun(peval, dvec,winit, hinit);\n        end\n        \n        if savethis\n            res.data_file = peval.data_path; % just to keep track where the filel is\n            peval = createresname(peval,iterindex);\n            if ~exist('p','var')\n                p = [];\n            end\n            saveresults(res, peval, p, [peval.res_path peval.res_dir '/' peval.res_name])\n            fclose(peval.fid(2));\n        end\n    end\n    if savethis\n        % Saving parametes and logfile into the directory with resuls\n        saveparameters(peval,p)\n    end\nend\n% plottingmulti\n% plotscattehvsblinkmat\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/qdots/Default/Default_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.24797006726805892}}
{"text": "function [ int, count, msg ] = pnmgeti( fid, n )\n%PNMGETI Get integers from an ascii encoded PBM/PGM/PPM file.\n%\n%   [ INT, COUNT, MSG ] = PNMGETI( FID, N ) tries to read N integers\n%   from the ascii encoded PBM/PGM/PPM file with file identifier FID and\n%   returns the integers in the vector INT. COUNT is an optional output\n%   argument that returns the number of elements successfully read. MSG\n%   is an optional output argument that returns an error message string\n%   if an error occurred or an empty matrix if an error did not occur.\n%\n%   If N is omitted, the whole remaining of the file is read.\n%\n%   The main difference between PNMGETI( FID ) and FSCANF( FID, '%d' )\n%   is that PNMGETI ignores comments (from # to end of line). PNMGETI\n%   also ignores garbage, which is anything that is neither whitespace,\n%   digit nor comment.\n\n%   Author:      Peter J. Acklam\n%   Time-stamp:  1998-04-06 02:38:34\n%   E-mail:      jacklam@math.uio.no (Internet)\n%   URL:         http://www.math.uio.no/~jacklam\n\n%\n% Check number of input arguments and assign default value to omitted\n% argument.\n%\nerror( nargchk( 1, 2, nargin ) );\nif nargin < 2\n   n = Inf;\nend\n\n% Initialize output arguments.\nint   = [];             % Image data vector.\ncount = 0;              % Number of elements read. Same as length(int).\nmsg   = '';             % Error message string.\n\nwhile 1\n\n   % Calculate number of integers missing and try to read that many.\n   ints_missing = n - count;\n   [ x, this_count ] = fscanf( fid, '%d', ints_missing );\n\n   % Append new data to main data vector and increment counter.\n   int = [ int ; x ];\n   count = count + this_count;\n\n   % Return if we have got the desired number of elements.\n   if count == n\n      return\n   end\n\n   % Return if we have reached EOF.\n   if feof( fid )\n      msg = 'End of file reached too early.';\n      return\n   end\n\n   %\n   % If we get here we have reached a comment or some garbage. Garbage\n   % is anything that is neither whitespace, digit nor comment.\n   %\n\n   char = fscanf( fid, '%c', 1 );\n   if ( char == '#' )\n\n      % Found a comment, so skip the rest of the line and redo the loop.\n      fgetl( fid );\n\n   else\n\n      % We found some garbage, so give a message.\n      msg = 'Garbage found where image data was expected.';\n\n      %\n      % Read past the garbage and following whitespace (i.e., until\n      % first number character). This would probably be faster if we\n      % read and checked a whole vector of data, but it probably won't\n      % be executed often. char is empty at EOF.\n      %\n      while ~isempty( char ) & ( char < '0' | char > '9' )\n         char = fscanf( fid, '%c', 1 );\n      end\n\n      %\n      % Return if we have reached EOF. This error message may overwrite\n      % any error message telling about garbage, but that doesn't matter\n      % since reaching EOF too early is a more serious error.\n      %\n      if feof( fid )\n         msg = 'End of file reached too early.';\n         return\n      end\n\n      %\n      % We found a number character, so jump back one byte so fscanf\n      % catches it.\n      %\n      fseek( fid, -1, 0 );\n\n   end\n\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/134-pnm/pnm/pnmgeti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24795609398754398}}
{"text": "function varargout = colorspace(Conversion,varargin)\n%COLORSPACE  Convert a color image between color representations.\n%   B = COLORSPACE(S,A) converts the color representation of image A\n%   where S is a string specifying the conversion.  S tells the\n%   source and destination color spaces, S = 'dest<-src', or\n%   alternatively, S = 'src->dest'.  Supported color spaces are\n%\n%     'RGB'              R'G'B' Red Green Blue (ITU-R BT.709 gamma-corrected)\n%     'YPbPr'            Luma (ITU-R BT.601) + Chroma \n%     'YCbCr'/'YCC'      Luma + Chroma (\"digitized\" version of Y'PbPr)\n%     'YUV'              NTSC PAL Y'UV Luma + Chroma\n%     'YIQ'              NTSC Y'IQ Luma + Chroma\n%     'YDbDr'            SECAM Y'DbDr Luma + Chroma\n%     'JPEGYCbCr'        JPEG-Y'CbCr Luma + Chroma\n%     'HSV'/'HSB'        Hue Saturation Value/Brightness\n%     'HSL'/'HLS'/'HSI'  Hue Saturation Luminance/Intensity\n%     'XYZ'              CIE XYZ\n%     'Lab'              CIE L*a*b* (CIELAB)\n%     'Luv'              CIE L*u*v* (CIELUV)\n%     'Lch'              CIE L*ch (CIELCH)\n%\n%  All conversions assume 2 degree observer and D65 illuminant.  Color\n%  space names are case insensitive.  When R'G'B' is the source or\n%  destination, it can be omitted. For example 'yuv<-' is short for\n%  'yuv<-rgb'.\n%\n%  MATLAB uses two standard data formats for R'G'B': double data with\n%  intensities in the range 0 to 1, and uint8 data with integer-valued\n%  intensities from 0 to 255.  As MATLAB's native datatype, double data is\n%  the natural choice, and the R'G'B' format used by colorspace.  However,\n%  for memory and computational performance, some functions also operate\n%  with uint8 R'G'B'.  Given uint8 R'G'B' color data, colorspace will\n%  first cast it to double R'G'B' before processing.\n%\n%  If A is an Mx3 array, like a colormap, B will also have size Mx3.\n%\n%  [B1,B2,B3] = COLORSPACE(S,A) specifies separate output channels.\n%  COLORSPACE(S,A1,A2,A3) specifies separate input channels.\n\n% Pascal Getreuer 2005-2006\n\n%%% Input parsing %%%\nif nargin < 2, error('Not enough input arguments.'); end\n[SrcSpace,DestSpace] = parse(Conversion);\n\nif nargin == 2\n   Image = varargin{1};\nelseif nargin >= 3\n   Image = cat(3,varargin{:});\nelse\n   error('Invalid number of input arguments.');\nend\n\nFlipDims = (size(Image,3) == 1);\n\nif FlipDims, Image = permute(Image,[1,3,2]); end\nif ~isa(Image,'double'), Image = double(Image)/255; end\nif size(Image,3) ~= 3, error('Invalid input size.'); end\n\nSrcT = gettransform(SrcSpace);\nDestT = gettransform(DestSpace);\n\nif ~ischar(SrcT) & ~ischar(DestT)\n   % Both source and destination transforms are affine, so they\n   % can be composed into one affine operation\n   T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];      \n   Temp = zeros(size(Image));\n   Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);\n   Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);\n   Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);\n   Image = Temp;\nelseif ~ischar(DestT)\n   Image = rgb(Image,SrcSpace);\n   Temp = zeros(size(Image));\n   Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);\n   Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);\n   Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);\n   Image = Temp;\nelse\n   Image = feval(DestT,Image,SrcSpace);\nend\n\n%%% Output format %%%\nif nargout > 1\n   varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};\nelse\n   if FlipDims, Image = permute(Image,[1,3,2]); end\n   varargout = {Image};\nend\n\nreturn;\n\n\nfunction [SrcSpace,DestSpace] = parse(Str)\n% Parse conversion argument\n\nif isstr(Str)\n   Str = lower(strrep(strrep(Str,'-',''),' ',''));\n   k = find(Str == '>');\n   \n   if length(k) == 1         % Interpret the form 'src->dest'\n      SrcSpace = Str(1:k-1);\n      DestSpace = Str(k+1:end);\n   else\n      k = find(Str == '<');\n      \n      if length(k) == 1      % Interpret the form 'dest<-src'\n         DestSpace = Str(1:k-1);\n         SrcSpace = Str(k+1:end);\n      else\n         error(['Invalid conversion, ''',Str,'''.']);\n      end   \n   end\n   \n   SrcSpace = alias(SrcSpace);\n   DestSpace = alias(DestSpace);\nelse\n   SrcSpace = 1;             % No source pre-transform\n   DestSpace = Conversion;\n   if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end\nend\nreturn;\n\n\nfunction Space = alias(Space)\nSpace = strrep(Space,'cie','');\n\nif isempty(Space)\n   Space = 'rgb';\nend\n\nswitch Space\ncase {'ycbcr','ycc'}\n   Space = 'ycbcr';\ncase {'hsv','hsb'}\n   Space = 'hsv';\ncase {'hsl','hsi','hls'}\n   Space = 'hsl';\ncase {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}\n   return;\nend\nreturn;\n\n\nfunction T = gettransform(Space)\n% Get a colorspace transform: either a matrix describing an affine transform,\n% or a string referring to a conversion subroutine\nswitch Space\ncase 'ypbpr'\n   T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];\ncase 'yuv'\n   % R'G'B' to NTSC/PAL YUV\n   % Wikipedia: http://en.wikipedia.org/wiki/YUV\n   T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];\ncase 'ydbdr'\n   % R'G'B' to SECAM YDbDr\n   % Wikipedia: http://en.wikipedia.org/wiki/YDbDr\n   T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];\ncase 'yiq'\n   % R'G'B' in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];\n   % Wikipedia: http://en.wikipedia.org/wiki/YIQ\n   T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];\ncase 'ycbcr'\n   % R'G'B' (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr\n   % Wikipedia: http://en.wikipedia.org/wiki/YCbCr\n   % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion\n   T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];\ncase 'jpegycbcr'\n   % Wikipedia: http://en.wikipedia.org/wiki/YCbCr\n   T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;\ncase {'rgb','xyz','hsv','hsl','lab','luv','lch'}\n   T = Space;\notherwise\n   error(['Unknown color space, ''',Space,'''.']);\nend\nreturn;\n\n\nfunction Image = rgb(Image,SrcSpace)\n% Convert to Rec. 709 R'G'B' from 'SrcSpace'\nswitch SrcSpace\ncase 'rgb'\n   return;\ncase 'hsv'\n   % Convert HSV to R'G'B'\n   Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));\ncase 'hsl'\n   % Convert HSL to R'G'B'\n   L = Image(:,:,3);\n   Delta = Image(:,:,2).*min(L,1-L);\n   Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));\ncase {'xyz','lab','luv','lch'}\n   % Convert to CIE XYZ\n   Image = xyz(Image,SrcSpace);\n   % Convert XYZ to RGB\n   T = [3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311];\n   R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3);  % R\n   G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3);  % G\n   B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3);  % B\n   % Desaturate and rescale to constrain resulting RGB values to [0,1]   \n   AddWhite = -min(min(min(R,G),B),0);\n   Scale = max(max(max(R,G),B)+AddWhite,1);\n   R = (R + AddWhite)./Scale;\n   G = (G + AddWhite)./Scale;\n   B = (B + AddWhite)./Scale;   \n   % Apply gamma correction to convert RGB to Rec. 709 R'G'B'\n   Image(:,:,1) = gammacorrection(R);  % R'\n   Image(:,:,2) = gammacorrection(G);  % G'\n   Image(:,:,3) = gammacorrection(B);  % B'\notherwise  % Conversion is through an affine transform\n   T = gettransform(SrcSpace);\n   temp = inv(T(:,1:3));\n   T = [temp,-temp*T(:,4)];\n   R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);\n   G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);\n   B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);\n   AddWhite = -min(min(min(R,G),B),0);\n   Scale = max(max(max(R,G),B)+AddWhite,1);\n   R = (R + AddWhite)./Scale;\n   G = (G + AddWhite)./Scale;\n   B = (B + AddWhite)./Scale;\n   Image(:,:,1) = R;\n   Image(:,:,2) = G;\n   Image(:,:,3) = B;\nend\n\n% Clip to [0,1]\nImage = min(max(Image,0),1);\nreturn;\n\n\nfunction Image = xyz(Image,SrcSpace)\n% Convert to CIE XYZ from 'SrcSpace'\nWhitePoint = [0.950456,1,1.088754];  \n\nswitch SrcSpace\ncase 'xyz'\n   return;\ncase 'luv'\n   % Convert CIE L*uv to XYZ\n   WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n   WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n   L = Image(:,:,1);\n   Y = (L + 16)/116;\n   Y = invf(Y)*WhitePoint(2);\n   U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;\n   V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;\n   Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V);                  % X\n   Image(:,:,2) = Y;                                             % Y\n   Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V);  % Z\ncase {'lab','lch'}\n   Image = lab(Image,SrcSpace);\n   % Convert CIE L*ab to XYZ\n   fY = (Image(:,:,1) + 16)/116;\n   fX = fY + Image(:,:,2)/500;\n   fZ = fY - Image(:,:,3)/200;\n   Image(:,:,1) = WhitePoint(1)*invf(fX);  % X\n   Image(:,:,2) = WhitePoint(2)*invf(fY);  % Y\n   Image(:,:,3) = WhitePoint(3)*invf(fZ);  % Z\notherwise   % Convert from some gamma-corrected space\n   % Convert to Rec. 701 R'G'B'\n   Image = rgb(Image,SrcSpace);\n   % Undo gamma correction\n   R = invgammacorrection(Image(:,:,1));\n   G = invgammacorrection(Image(:,:,2));\n   B = invgammacorrection(Image(:,:,3));\n   % Convert RGB to XYZ\n   T = inv([3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311]);\n   Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B;  % X \n   Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B;  % Y\n   Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B;  % Z\nend\nreturn;\n\n\nfunction Image = hsv(Image,SrcSpace)\n% Convert to HSV\nImage = rgb(Image,SrcSpace);\nV = max(Image,[],3);\nS = (V - min(Image,[],3))./(V + (V == 0));\nImage(:,:,1) = rgbtohue(Image);\nImage(:,:,2) = S;\nImage(:,:,3) = V;\nreturn;\n\n\nfunction Image = hsl(Image,SrcSpace)\n% Convert to HSL \nswitch SrcSpace\ncase 'hsv'\n   % Convert HSV to HSL   \n   MaxVal = Image(:,:,3);\n   MinVal = (1 - Image(:,:,2)).*MaxVal;\n   L = 0.5*(MaxVal + MinVal);\n   temp = min(L,1-L);\n   Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));\n   Image(:,:,3) = L;\notherwise\n   Image = rgb(Image,SrcSpace);  % Convert to Rec. 701 R'G'B'\n   % Convert R'G'B' to HSL\n   MinVal = min(Image,[],3);\n   MaxVal = max(Image,[],3);\n   L = 0.5*(MaxVal + MinVal);\n   temp = min(L,1-L);\n   S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));\n   Image(:,:,1) = rgbtohue(Image);\n   Image(:,:,2) = S;\n   Image(:,:,3) = L;\nend\nreturn;\n\n\nfunction Image = lab(Image,SrcSpace)\n% Convert to CIE L*a*b* (CIELAB)\nWhitePoint = [0.950456,1,1.088754];\n\nswitch SrcSpace\ncase 'lab'\n   return;\ncase 'lch'\n   % Convert CIE L*CH to CIE L*ab\n   C = Image(:,:,2);\n   Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C;  % a*\n   Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C;  % b*\notherwise\n   Image = xyz(Image,SrcSpace);  % Convert to XYZ\n   % Convert XYZ to CIE L*a*b*\n   X = Image(:,:,1)/WhitePoint(1);\n   Y = Image(:,:,2)/WhitePoint(2);\n   Z = Image(:,:,3)/WhitePoint(3);\n   fX = f(X);\n   fY = f(Y);\n   fZ = f(Z);\n   Image(:,:,1) = 116*fY - 16;    % L*\n   Image(:,:,2) = 500*(fX - fY);  % a*\n   Image(:,:,3) = 200*(fY - fZ);  % b*\nend\nreturn;\n\n\nfunction Image = luv(Image,SrcSpace)\n% Convert to CIE L*u*v* (CIELUV)\nWhitePoint = [0.950456,1,1.088754];\nWhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\nWhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n\nImage = xyz(Image,SrcSpace); % Convert to XYZ\nU = (4*Image(:,:,1))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));\nV = (9*Image(:,:,2))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));\nY = Image(:,:,2)/WhitePoint(2);\nL = 116*f(Y) - 16;\nImage(:,:,1) = L;                        % L*\nImage(:,:,2) = 13*L.*(U - WhitePointU);  % u*\nImage(:,:,3) = 13*L.*(V - WhitePointV);  % v*\nreturn;  \n\n\nfunction Image = lch(Image,SrcSpace)\n% Convert to CIE L*ch\nImage = lab(Image,SrcSpace);  % Convert to CIE L*ab\nH = atan2(Image(:,:,3),Image(:,:,2));\nH = H*180/pi + 360*(H < 0);\nImage(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2);  % C\nImage(:,:,3) = H;                                        % H\nreturn;\n\n\nfunction Image = huetorgb(m0,m2,H)\n% Convert HSV or HSL hue to RGB\nN = size(H);\nH = min(max(H(:),0),360)/60;\nm0 = m0(:);\nm2 = m2(:);\nF = H - round(H/2)*2;\nM = [m0, m0 + (m2-m0).*abs(F), m2];\nNum = length(m0);\nj = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;\nk = floor(H) + 1;\nImage = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);\nreturn;\n\n\nfunction H = rgbtohue(Image)\n% Convert RGB to HSV or HSL hue\n[M,i] = sort(Image,3);\ni = i(:,:,3);\nDelta = M(:,:,3) - M(:,:,1);\nDelta = Delta + (Delta == 0);\nR = Image(:,:,1);\nG = Image(:,:,2);\nB = Image(:,:,3);\nH = zeros(size(R));\nk = (i == 1);\nH(k) = (G(k) - B(k))./Delta(k);\nk = (i == 2);\nH(k) = 2 + (B(k) - R(k))./Delta(k);\nk = (i == 3);\nH(k) = 4 + (R(k) - G(k))./Delta(k);\nH = 60*H + 360*(H < 0);\nH(Delta == 0) = nan;\nreturn;\n\n\nfunction Rp = gammacorrection(R)\nRp = real(1.099*R.^0.45 - 0.099);\ni = (R < 0.018);\nRp(i) = 4.5138*R(i);\nreturn;\n\n\nfunction R = invgammacorrection(Rp)\nR = real(((Rp + 0.099)/1.099).^(1/0.45));\ni = (R < 0.018);\nR(i) = Rp(i)/4.5138;\nreturn;\n\n\nfunction fY = f(Y)\nfY = real(Y.^(1/3));\ni = (Y < 0.008856);\nfY(i) = Y(i)*(841/108) + (4/29);\nreturn;\n\n\nfunction Y = invf(fY)\nY = fY.^3;\ni = (Y < 0.008856);\nY(i) = (fY(i) - 4/29)*(108/841);\nreturn;\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dtcwt_toolbox/colorspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24782206554097855}}
{"text": "function [ eddies ] = bottom_up_single(ssh_data, lat, lon, areamap, cyc, varargin)\n%BOTTOM_UP_SINGLE Finds eddies using the Bottom Up method\n%   Will return an array of struct's that contain the eddy data.\n%   ssh_data: A 2D array of double's that contain the sea surface heights (latsxlons)\n%   lat: A 1D array of double's that gives the latitude for a given index (dimension should match\n%         that of ssh_data)\n%   lon: A 1D array of double's that gives the longitude for a given index (dimension should match\n%         that of ssh_data)\n%   areamap: A 2D array that refer to the area of each pixel in SSH data (should have same size as ssh), or 1D array \n%   that refer to area of each pixel for a specific lat in a regular grid (pixeld have same area for the same \n%   latitude)\n%   cyc: Pass 1 to output anticyclonic eddies or -1 to output cyclonic eddies\n%   Optional parameters:\n%   'minimumArea': minimum number of pixels for an eddy, used for validating eddies\n%   'thresholdStep': the minimum step for thresholding, the unit is SSH's unit\n%   'isPadding': whether or not to pad SSH data, should be true when scanning SSH data of the whole map. Set to false if\n%   only partial SSH data is used.\n%   'sshUnits': The units the SSH data is in. bottom_up_single is built to work natively on centimeter SSH data.\n%   Valid parameters are 'meters' and 'centimeters'. If the paramater passed in is 'meters', the SSH data will\n%   be multiplied by 100. No changes will be made if the paramater passed in is 'centimeters'.\n%   The default value of 'sshUnits' is centimeters.\n    p = inputParser;\n    defaultMinPixelSize = 9;\n    defaultThresholdStep = 0.05;\n    defaultSSHUnits = 'centimeters';\n    defaultPaddingFlag = true;\n    addRequired(p, 'ssh_data');\n    addRequired(p, 'lat');\n    addRequired(p, 'lon');\n    addRequired(p, 'areamap');\n    addRequired(p, 'cyc');\n    addParameter(p, 'minimumArea', defaultMinPixelSize, @isnumeric);\n    addParameter(p, 'thresholdStep', defaultThresholdStep, @isnumeric);\n    addParameter(p, 'isPadding', defaultPaddingFlag);\n    addParameter(p, 'sshUnits', defaultSSHUnits);\n    parse(p, ssh_data, lat, lon, areamap, cyc, varargin{:});\n    minimumArea = p.Results.minimumArea;\n    thresholdStep = p.Results.thresholdStep;\n    isPadding = p.Results.isPadding;\n    SSH_Units = p.Results.sshUnits;\n    \n    if strcmp(SSH_Units, 'meters')\n        ssh_data = ssh_data * 100;\n    elseif strcmp(SSH_Units, 'centimeters')\n        max_val = max(ssh_data(:));\n        min_val = max(ssh_data(:));\n        if max_val < 1.5 && min_val > -1.5\n            ssh_data = ssh_data * 100;\n        elseif max_val < 150 && min_val > -150\n        \n        else\n            disp('Could not figure out what units the SSH data provided is in. Running the scan assuming units of centimeters');\n            disp('To specify SSH unit data, include an additional parameter of sshUnits, followed by the unit type, E.G. meters');\n        end\n    end\n\n    %Check if the grid is regular (differences between lats and lons are equal)\n    lat_diffs = lat(2:end) - lat(1:end-1);\n    lat_diffs2 = lat_diffs(2:end) - lat_diffs(1:end-1);\n    lon_diffs = lon(2:end) - lon(1:end-1);\n    lon_diffs(lon_diffs <= -180) = lon_diffs(lon_diffs <= -180) + 360;\n    lon_diffs(lon_diffs >= 180) = lon_diffs(lon_diffs >= 180) - 360;\n    lon_diffs = abs(lon_diffs);\n    lon_diffs2 = lon_diffs(2:end) - lon_diffs(1:end-1);\n    if all(lat_diffs2 == 0) && all(lon_diffs2 == 0)\n        % Regular grid, create a georasterref object to get eddy's centroid\n        geo_raster_lat_limit = [lat(1) lat(end)];\n        if lon(1) > lon(end)\n            geo_raster_lon_limit = [lon(1) (360 + lon(end))];\n        else\n            geo_raster_lon_limit = [lon(1) lon(end)];\n        end\n\n        R = georasterref('LatLim', geo_raster_lat_limit, 'LonLim', geo_raster_lon_limit, 'RasterSize', ...\n         size(ssh_data), 'ColumnsStartFrom', 'south', 'RowsStartFrom', 'west');\n    else\n        % Use normal indexing to get eddy's centroid\n        R = [];\n    end\n    \n    extrema = get_extrema(ssh_data, cyc);\n    \n    if isPadding\n        origExtrema = extrema;\n        extrema = [zeros(size(extrema, 1), 200), extrema, zeros(size(extrema, 1), 200)];\n        sshExtended = [ssh_data(:, end-199:end), ssh_data(:, :), ssh_data(:, 1:200)];\n        [extrema_lat_indexes, extrema_lon_indexes] = ind2sub(size(extrema), find(extrema == 1));\n\n        extrema(:, 1:200) = origExtrema(:, end-199:end);\n        extrema(:, end-199:end) = origExtrema(:, 1:200);\n    else\n        [extrema_lat_indexes, extrema_lon_indexes] = ind2sub(size(extrema), find(extrema == 1));\n        sshExtended = ssh_data;\n    end\n        \n\n    eddies = new_eddy();\n    eddies(length(extrema_lat_indexes)).Date = NaN;\n    cyc_sshExtended = sshExtended * cyc;\n    parfor i = 1:length(extrema_lat_indexes)\n        curr_lat_index = extrema_lat_indexes(i); curr_lon_index = extrema_lon_indexes(i);\n        e = thresholdBU(cyc, curr_lat_index-5, curr_lat_index+5, curr_lon_index-5, curr_lon_index+5, ...\n            sshExtended, extrema, curr_lat_index, curr_lon_index, sshExtended(curr_lat_index, curr_lon_index), ...\n            thresholdStep, NaN, ...\n            zeros(size(sshExtended)), lat, lon, R, areamap, minimumArea, isPadding, cyc_sshExtended);\n        if ~isempty(e)\n            eddies(i) = e;\n        end\n    end\n    mask = cellfun('isempty', {eddies.Lat});\n    eddies = eddies(~mask);\nend\n", "meta": {"author": "jfaghm", "repo": "OceanEddies", "sha": "a5e33155f9cc534093c88b1a514b0c8281591755", "save_path": "github-repos/MATLAB/jfaghm-OceanEddies", "path": "github-repos/MATLAB/jfaghm-OceanEddies/OceanEddies-a5e33155f9cc534093c88b1a514b0c8281591755/eddyscan/lib/bottom_up_single.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24782205935626178}}
{"text": "function [grad] = AssignCostGradFrame(grad, nFrOrig, nSeg, mask, Cost_layer)\nD = size(grad,1);\n\nwords = ExtractWordsFromString_v2(Cost_layer.costFrameSelection);\nselectionType = words{1};\n\nswitch selectionType\n    case 'last'\n        if strcmpi(Cost_layer.name, 'MSE')\n            return;\n        end\n        \n        if length(words)>1\n            N = str2num(words{2});\n        else\n            N = 1;\n        end\n        \n        gradTmp = grad;\n        precision = class(gather(grad(1,1,1)));\n        if strcmpi(class(grad), 'gpuArray')\n            grad = gpuArray.zeros(D,nFrOrig, nSeg, precision);\n        else\n            grad = zeros(D,nFrOrig, nSeg, precision);\n        end\n        if numel(mask)>0 && sum(sum(mask))>0   % if the trajectories have variable length\n            for i=1:nSeg\n                idx = find(mask(:,i)==1);\n                if isempty(idx)\n                    grad(:,max(1,end-N+1):end,i) = gradTmp(:,:,i);\n                else\n                    grad(:,max(1,idx(1)-N):max(1,idx(1)-1),i) = gradTmp(:,:,i);\n                end\n            end\n            grad = PadShortTrajectory(grad, mask, -1e10);\n        else\n            grad(:,max(1,end-N+1):end,:) = gradTmp;\n        end\nend\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/AssignCostGradFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2478220531715449}}
{"text": "% The COBRAToolbox: testpFBA.m\n%\n% Purpose:\n%     - tests the basic functionality of pFBA\n%       Tests the basic solution for both minimizing the flux of gene-\n%       associated reactions and all rxns, while growing on gluose or lactose\n%       minimal media. Does not test the functionality of the map function.\n%\n% Authors:\n%     - Original file: Nathan Lewis 08/30/10\n%     - CI integration: Laurent Heirendt February 2017\n%\n% Note:\n%     - The solver libraries must be included separately\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testpFBA'));\ncd(fileDir);\n\n%tolerance\ntol = 1e-8;\n\n% load models and expected results\nmodel_glc = readCbModel('testpFBAData.mat','modelName','model_glc');\nmodel_lac = readCbModel('testpFBAData.mat','modelName','model_lac');\n\nobjGenes = load('testpFBAData.mat', 'GeneClasses_glc2', 'GeneClasses_glc1', 'GeneClasses_glc0', 'GeneClasses_lac2', 'GeneClasses_lac1', 'GeneClasses_lac0');\nobjRxns = load('testpFBAData.mat', 'RxnClasses_glc2', 'RxnClasses_glc1', 'RxnClasses_glc0', 'RxnClasses_lac2', 'RxnClasses_lac1', 'RxnClasses_lac0');\nobjModel = load('testpFBAData.mat', 'modelIrrev_glc2', 'modelIrrev_glc1', 'modelIrrev_glc0', 'modelIrrev_lac2', 'modelIrrev_lac1', 'modelIrrev_lac0');\n\n% list of solver packages\nsolverPkgs = {'gurobi'}; % 'tomlab_cplex', 'glpk'\n\n% create a parallel pool\ntry\n    minWorkers = 2;\n    myCluster = parcluster(parallel.defaultClusterProfile);\n\n    if myCluster.NumWorkers >= minWorkers\n        poolobj = gcp('nocreate');  % if no pool, do not create new one.\n        if isempty(poolobj)\n            parpool(minWorkers);  % launch minWorkers workers\n        end\n    end\ncatch\n    disp('Trying non parallel test')\nend\n\nfor k = 1:length(solverPkgs)\n\n    fprintf(' -- Running testfindBlockedReaction using the solver interface: %s ... \\n', solverPkgs{k});\n\n    solverLPOK = changeCobraSolver(solverPkgs{k}, 'LP', 0);\n\n    if solverLPOK\n\n        % run pFBA\n        fprintf('\\n*** Test basic pFBA calculations ***\\n\\n');\n        fprintf('\\n** Optimal solution - minimize flux not associated with gene: glucose\\n');\n        [t_objGenes.GeneClasses_glc1 t_objRxns.RxnClasses_glc1 t_objModel.modelIrrev_glc1] = pFBA(model_glc, 'geneoption', 2);\n\n        fprintf('\\n** Optimal solution - minimize flux not associated with gene: lactate\\n');\n        [t_objGenes.GeneClasses_lac1 t_objRxns.RxnClasses_lac1 t_objModel.modelIrrev_lac1] = pFBA(model_lac, 'geneoption', 2);\n\n        fprintf('\\n** Optimal solution - minimize gene-associated flux: glucose\\n');\n        [t_objGenes.GeneClasses_glc1 t_objRxns.RxnClasses_glc1 t_objModel.modelIrrev_glc1] = pFBA(model_glc, 'geneoption', 1);\n\n        fprintf('\\n** Optimal solution - minimize gene-associated flux: lactate\\n');\n        [t_objGenes.GeneClasses_lac1 t_objRxns.RxnClasses_lac1 t_objModel.modelIrrev_lac1] = pFBA(model_lac, 'geneoption', 1);\n\n        fprintf('\\n** Optimal solution - minimize all flux: glucose **\\n');\n        [t_objGenes.GeneClasses_glc0 t_objRxns.RxnClasses_glc0 t_objModel.modelIrrev_glc0] = pFBA(model_glc, 'geneoption', 0);\n\n        fprintf('\\n** Optimal solution - minimize all flux: lactate **\\n');\n        [t_objGenes.GeneClasses_lac0 t_objRxns.RxnClasses_lac0 t_objModel.modelIrrev_lac0] = pFBA(model_lac, 'geneoption', 0);\n\n        t_objGenesf = fieldnames(t_objGenes);\n        t_objRxnsf = fieldnames(t_objRxns);\n        t_objModelf = fieldnames(t_objModel);\n\n        % testing if gene lists are consistent with expected lists\n        t_fg = zeros(40, 1);\n        cnt = 0;\n        for i = 1:length(t_objGenesf)\n            tmp_lists = fieldnames(t_objGenes.(t_objGenesf{i}));\n            for j = 1:length(tmp_lists)\n                t1 = find(~ismember(t_objGenes.(t_objGenesf{i}).(tmp_lists{j}), objGenes.(t_objGenesf{i}).(tmp_lists{j})));\n                t2 = find(~ismember(objGenes.(t_objGenesf{i}).(tmp_lists{j}), t_objGenes.(t_objGenesf{i}).(tmp_lists{j})));\n                cnt = cnt + 1;\n                if isempty(t1)\n                    t_fg(cnt) = 1;\n                end\n                cnt = cnt + 1;\n                if isempty(t2)\n                    t_fg(cnt) = 1;\n                end\n            end\n        end\n\n        assert(min(t_fg) == 1)\n\n        % testing if rxn lists are consistent with expected lists\n        t_fr = zeros(40, 1);\n        cnt = 0;\n        for i = 1:length(t_objRxnsf)\n            tmp_lists = fieldnames(t_objRxns.(t_objRxnsf{i}));\n            for j = 1:length(tmp_lists)\n                t1 = find(~ismember(t_objRxns.(t_objRxnsf{i}).(tmp_lists{j}), objRxns.(t_objRxnsf{i}).(tmp_lists{j})));\n                t2 = find(~ismember(objRxns.(t_objRxnsf{i}).(tmp_lists{j}), t_objRxns.(t_objRxnsf{i}).(tmp_lists{j})));\n                cnt = cnt + 1;\n                if isempty(t1)\n                    t_fr(cnt) = 1;\n                end\n                cnt = cnt + 1;\n                if isempty(t2)\n                    t_fr(cnt) = 1;\n                end\n            end\n        end\n\n        assert(min(t_fr) == 1)\n\n        % testing if flux minima are consistent with expected values\n        t_fm = zeros(8, 1);\n        cnt = 0;\n        for i = 1:length(t_objModelf)\n            t1 = t_objModel.(t_objModelf{i}).lb(findRxnIDs(t_objModel.(t_objModelf{i}), 'netFlux')) - objModel.(t_objModelf{i}).lb(findRxnIDs(objModel.(t_objModelf{i}), 'netFlux'));\n            t2 = t_objModel.(t_objModelf{i}).ub(findRxnIDs(t_objModel.(t_objModelf{i}), 'netFlux')) - objModel.(t_objModelf{i}).ub(findRxnIDs(objModel.(t_objModelf{i}), 'netFlux'));\n            cnt = cnt + 1;\n            if t1 < tol\n                t_fm(cnt) = 1;\n            end\n            cnt = cnt + 1;\n            if t2 < tol\n                t_fm(cnt) = 1;\n            end\n        end\n\n        assert(min(t_fm) == 1)\n\n        x = min([t_fm; t_fg; t_fr]);\n\n        % output a success message\n        fprintf('Done.\\n');\n    end\nend\n\n\n% change back to the root directory\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/analysis/testpFBA/testpFBA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24781621564305217}}
{"text": "function PlotCSD(csd,varargin)\n\n%PlotCSD - Plot current source density.\n%\n%  USAGE\n%\n%    PlotCSD(csd,<options>)\n%\n%    csd            current source density (see <a href=\"matlab:help CSD\">CSD</a>)\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'lfp'         local field potential\n%     'scale'       scale (arbitrary units) for LFP traces (default = 1)\n%     'cutoffs'     cutoff values (default = [-M M] where M is the maximum\n%                   amplitude of the CSD)\n%    =========================================================================\n%\n%  SEE\n%\n%    See <a href=\"matlab:help CSD\">CSD</a>.\n\n% Copyright (C) 2008-2011 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Default values\nlfp = [];\nscale = 1;\ncutoffs = [];\n\n% Check number of parameters\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n  error('Incorrect number of parameters (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).');\nend\n\n% Parse parameter list\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\terror(['Parameter ' num2str(i+1) ' is not a property (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'lfp',\n\t\t\tlfp = varargin{i+1};\n\t\t\tif ~isdmatrix(lfp) | size(lfp,1) ~= size(csd,1) | size(lfp,2) ~= size(csd,2)+2,\n\t\t\t\terror('Incorrect size for parameter ''lfp'' (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).');\n\t\t\tend\n\t\tcase 'scale',\n\t\t\tscale = varargin{i+1};\n\t\t\tif ~isdscalar(scale,'>0'),\n\t\t\t\terror('Incorrect value for property ''scale'' (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).');\n\t\t\tend\n\t\tcase 'cutoffs',\n\t\t\tcutoffs = varargin{i+1};\n\t\t\tif ~isdvector(cutoffs,'#2','<'),\n\t\t\t\terror('Incorrect value for property ''cutoffs'' (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).');\n\t\t\tend\n\t\totherwise,\n\t\t\terror(['Unknown property ''' num2str(varargin{i}) ''' (type ''help <a href=\"matlab:help PlotCSD\">PlotCSD</a>'' for details).']);\n\tend\nend\n\nd = csd(:,2:end);\nd = interp2(d);\nd = d(1:2:size(d,1),:);\n\npcolor(csd(:,1),1:size(d,2),flipud(transpose(d)));\nshading interp;\nif ~isempty(cutoffs),\n\tset(gca,'clim',cutoffs);\nend\n\nif ~isempty(lfp),\n\thold on;\n\ty = lfp(:,2:end);\n\ty = y - repmat(mean(y),size(y,1),1);\n\ty = y / max(max(abs(y)))*scale;\n\tn = size(y,2);\n\tfor i = 1:n,\n\t\tplot(lfp(:,1),y(:,i)+(n-i)*2-1,'k');\n    end\n    ylim([-2 (n-1)*2]);\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Plot/PlotCSD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2478155451490631}}
{"text": "function [estimate] = ft_inverse_beamformer_dics(leadfield, Cf, varargin)\n\n% FT_INVERSE_BEAMFORMER_DICS estimates the source power or source\n% coherence according to the Dynamic Imaging of Coherent Sources\n% method.\n%\n% Use as\n%   estimate = ft_inverse_beamformer_dics(leadfield, Cf, ...)\n% where\n%   leadfield  = leadfield of the source of interest or a cell-array with leadfields for multiple sources\n%   Cf         = cross-spectral density matrix of the data\n% and\n%   estimate   = structure with the estimated source parameters\n%\n% Additional options should be specified in key-value pairs and can be\n%  'Pr'               = power of the external reference channel\n%  'Cr'               = cross spectral density between all data channels and the external reference channel\n%  'refdip'           = location of dipole with which coherence is computed\n%  'lambda'           = regularisation parameter\n%  'powmethod'        = can be 'trace' or 'lambda1'\n%  'feedback'         = give ft_progress indication, can be 'text', 'gui' or 'none'\n%  'fixedori'         = use fixed or free orientation,                 can be 'yes' or 'no'\n%  'projectnoise'     = project noise estimate through filter,         can be 'yes' or 'no'\n%  'realfilter'       = construct a real-valued filter,                can be 'yes' or 'no'\n%  'keepfilter'       = remember the beamformer filter,                can be 'yes' or 'no'\n%  'keepleadfield'    = remember the forward computation,              can be 'yes' or 'no'\n%  'keepcsd'          = remember the estimated cross-spectral density, can be 'yes' or 'no'\n%\n% This implements Joachim Gross et al. 2001\n\n% Copyright (C) 2003-2010, Robert Oostenveld\n\n% these optional settings do not have defaults\nPr             = keyval('Pr',            varargin);\nCr             = keyval('Cr',            varargin);\nrefdip         = keyval('refdip',        varargin);\npowmethod      = keyval('powmethod',     varargin); % the default for this is set below\nrealfilter     = keyval('realfilter',    varargin); % the default for this is set below\n% these optional settings have defaults\nfeedback       = keyval('feedback',      varargin); if isempty(feedback),      feedback = 'text';            end\nkeepcsd        = keyval('keepcsd',       varargin); if isempty(keepcsd),       keepcsd = 'no';               end\nkeepfilter     = keyval('keepfilter',    varargin); if isempty(keepfilter),    keepfilter = 'no';            end\nkeepleadfield  = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no';         end\nlambda         = keyval('lambda',        varargin); if isempty(lambda  ),      lambda = 0;                   end\nprojectnoise   = keyval('projectnoise',  varargin); if isempty(projectnoise),  projectnoise = 'yes';         end\nfixedori       = keyval('fixedori',      varargin); if isempty(fixedori),      fixedori = 'no';              end\n\n% convert the yes/no arguments to the corresponding logical values\n% FIXME use istrue\nkeepcsd        = strcmp(keepcsd,       'yes');\nkeepfilter     = strcmp(keepfilter,    'yes');\nkeepleadfield  = strcmp(keepleadfield, 'yes');\nprojectnoise   = strcmp(projectnoise,  'yes');\nfixedori       = strcmp(fixedori,      'yes');\n\n% FIXME besides regular/complex lambda1, also implement a real version\n\n% default is to use the largest singular value of the csd matrix, see Gross 2001\nif isempty(powmethod)\n  powmethod = 'lambda1';\nend\n\n% default is to be consistent with the original description of DICS in Gross 2001\nif isempty(realfilter)\n  realfilter = 'no';\nend\n\n% use these two logical flags instead of doing the string comparisons each time again\npowtrace   = strcmp(powmethod, 'trace');\npowlambda1 = strcmp(powmethod, 'lambda1');\n\n% dics has the following sub-methods, which depend on the additional input arguments\nif ~isempty(Cr) && ~isempty(Pr) && isempty(refdip)\n  % compute cortico-muscular coherence, using reference cross spectral density\n  submethod = 'dics_refchan';\nelseif isempty(Cr) && isempty(Pr) && ~isempty(refdip)\n  % compute cortico-cortical coherence with a dipole at the reference position\n  submethod = 'dics_refdip';\nelseif isempty(Cr) && isempty(Pr) && isempty(refdip)\n  % only compute power of a dipole at the grid positions\n  submethod = 'dics_power';\nelse\n  error('invalid combination of input arguments for dics');\nend\n\nif ~iscell(leadfield)\n  % the leadfield specifies a single source\n  leadfield = {leadfield};\nend\nndipoles = length(leadfield);\n\nif ~isempty(Cr)\n  % ensure that the cross-spectral density with the reference signal is a column matrix\n  Cr = Cr(:);\nend\n\nisrankdeficient = (rank(Cf)<size(Cf,1));\nif isrankdeficient\n  warning('cross-spectral density matrix is rank deficient')\nend\n\n% it is difficult to give a quantitative estimate of lambda, therefore also\n% support relative (percentage) measure that can be specified as string (e.g. '10%')\nif ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'\n  ratio = sscanf(lambda, '%f%%');\n  ratio = ratio/100;\n  lambda = ratio * trace(Cf)/size(Cf,1);\nend\n\nif projectnoise\n  % estimate the noise power, which is further assumed to be equal and uncorrelated over channels\n  if isrankdeficient\n    % estimated noise floor is equal to or higher than lambda\n    noise = lambda;\n  else\n    % estimate the noise level in the covariance matrix by the smallest singular value\n    noise = svd(Cf);\n    noise = noise(end);\n    % estimated noise floor is equal to or higher than lambda\n    noise = max(noise, lambda);\n  end\nend\n\n% the inverse only has to be computed once for all dipoles\nif strcmp(realfilter, 'yes')\n  % the filter is computed using only the leadfield and the inverse covariance or CSD matrix\n  % therefore using the real-valued part of the CSD matrix here ensures a real-valued filter\n  invCf = pinv(real(Cf) + lambda * eye(size(Cf)));\nelse\n  invCf = pinv(Cf + lambda * eye(size(Cf)));\nend\n\n% start the scanning with the proper metric\nft_progress('init', feedback, 'scanning grid');\nswitch submethod\n\n  case 'dics_power'\n    % only compute power of a dipole at the grid positions\n    for i=1:ndipoles\n      lf = leadfield{i};\n\n      if fixedori\n        % compute the leadfield for the optimal dipole orientation\n        % subsequently the leadfield for only that dipole orientation will be used for the final filter computation\n        filt = pinv(lf' * invCf * lf) * lf' * invCf;\n        [u, s, v] = svd(real(filt * Cf * ctranspose(filt)));\n        maxpowori = u(:,1);\n        eta = s(1,1)./s(2,2);\n        lf  = lf * maxpowori;\n        estimate.ori{i} = maxpowori;\n        estimate.eta{i} = eta;\n      end\n\n      % construct the spatial filter\n      filt = pinv(lf' * invCf * lf) * lf' * invCf;                % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield\n      csd = filt * Cf * ctranspose(filt);                         % Gross eqn. 4 and 5\n\n      % assign the output values\n      if powlambda1\n        estimate.pow(i) = lambda1(csd);                             % compute the power at the dipole location, Gross eqn. 8\n      elseif powtrace\n        estimate.pow(i) = real(trace(csd));                         % compute the power at the dipole location\n      end\n      if keepcsd\n        estimate.csd{i} = csd;\n      end\n      if projectnoise\n        if powlambda1\n          estimate.noise(i) = noise * lambda1(filt * ctranspose(filt));\n        elseif powtrace\n          estimate.noise(i) = noise * real(trace(filt * ctranspose(filt)));\n        end\n        if keepcsd\n          estimate.noisecsd{i} = noise * filt * ctranspose(filt);\n        end\n      end\n      if keepfilter\n        estimate.filter{i} = filt;\n      end\n      if keepleadfield\n        estimate.leadfield{i} = lf;\n      end\n      ft_progress(i/ndipoles, 'scanning grid %d/%d\\n', i, ndipoles);\n    end\n\n  case 'dics_refchan'\n    % compute cortico-muscular coherence, using reference cross spectral density\n    for i=1:ndipoles\n\n      % get the leadfield for this source\n      lf = leadfield{i};\n\n      if fixedori\n        % compute the leadfield for the optimal dipole orientation\n        % subsequently the leadfield for only that dipole orientation will be used for the final filter computation\n        filt = pinv(lf' * invCf * lf) * lf' * invCf;\n        [u, s, v] = svd(real(filt * Cf * ctranspose(filt)));\n        maxpowori = u(:,1);\n        lf  = lf * maxpowori;\n        estimate.ori{i} = maxpowori;\n      end\n\n      % construct the spatial filter\n      filt = pinv(lf' * invCf * lf) * lf' * invCf;                     % use PINV/SVD to cover rank deficient leadfield\n\n      if powlambda1\n        [pow, ori] = lambda1(filt * Cf * ctranspose(filt));            % compute the power and orientation at the dipole location, Gross eqn. 4, 5 and 8\n      elseif powtrace\n        pow = real(trace(filt * Cf * ctranspose(filt)));               % compute the power at the dipole location\n      end\n      csd = filt*Cr;                                                   % Gross eqn. 6\n      if powlambda1\n        % FIXME this should use the dipole orientation with maximum power\n        coh = lambda1(csd)^2 / (pow * Pr);                             % Gross eqn. 9\n      elseif powtrace\n        coh = norm(csd)^2 / (pow * Pr);\n      end\n\n      estimate.pow(i) = pow;\n      estimate.coh(i) = coh;\n      if keepcsd\n        estimate.csd{i} = csd;\n      end\n      if projectnoise\n        if powlambda1\n          estimate.noise(i) = noise * lambda1(filt * ctranspose(filt));\n        elseif powtrace\n          estimate.noise(i) = noise * real(trace(filt * ctranspose(filt)));\n        end\n        if keepcsd\n          estimate.noisecsd{i} = noise * filt * ctranspose(filt);\n        end\n      end\n      if keepfilter\n        estimate.filter{i} = filt;\n      end\n      ft_progress(i/ndipoles, 'scanning grid %d/%d\\n', i, ndipoles);\n    end\n\n  case 'dics_refdip'\n\n    if fixedori\n      error('fixed orientations are not supported for beaming cortico-cortical coherence');\n    end\n\n    % get the leadfield of the reference source\n    lf1 = refdip;\n\n    % construct the spatial filter for the first (reference) dipole location\n    filt1 = pinv(lf1' * invCf * lf1) * lf1' * invCf;       % use PINV/SVD to cover rank deficient leadfield\n    if powlambda1\n      Pref = lambda1(filt1 * Cf * ctranspose(filt1));      % compute the power at the first dipole location, Gross eqn. 8\n    elseif powtrace\n      Pref = real(trace(filt1 * Cf * ctranspose(filt1)));  % compute the power at the first dipole location\n    end\n\n    for i=1:ndipoles\n\n      % get the leadfield for the second source, i.e. the one that is being scanned\n      lf2 = leadfield{i};\n\n      % construct the spatial filter for the second source\n      filt2 = pinv(lf2' * invCf * lf2) * lf2' * invCf;     % use PINV/SVD to cover rank deficient leadfield\n      csd = filt1 * Cf * ctranspose(filt2);                % compute the cross spectral density between the two dipoles, Gross eqn. 4\n\n      if powlambda1\n        pow = lambda1(filt2 * Cf * ctranspose(filt2));     % compute the power at the second dipole location, Gross eqn. 8\n      elseif powtrace\n        pow = real(trace(filt2 * Cf * ctranspose(filt2))); % compute the power at the second dipole location\n      end\n      if powlambda1\n        coh = lambda1(csd)^2 / (pow * Pref);               % compute the coherence between the first and second dipole\n      elseif powtrace\n        coh = real(trace((csd)))^2 / (pow * Pref);         % compute the coherence between the first and second dipole\n      end\n\n      estimate.pow(i) = pow;\n      estimate.coh(i) = coh;\n      if keepcsd\n        estimate.csd{i} = csd;\n      end\n      if projectnoise\n        if powlambda1\n          estimate.noise(i) = noise * lambda1(filt2 * ctranspose(filt2));\n        elseif powtrace\n          estimate.noise(i) = noise * real(trace(filt2 * ctranspose(filt2)));\n        end\n        if keepcsd\n          estimate.noisecsd{i} = noise * filt2 * ctranspose(filt2);\n        end\n      end\n      ft_progress(i/ndipoles, 'scanning grid %d/%d\\n', i, ndipoles);\n    end\n\nend % switch submethod\n\nft_progress('close');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to obtain the largest singular value\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [s, ori] = lambda1(x)\n% determine the largest singular value, which corresponds to the power along the dominant direction\n[u, s, v] = svd(x);\ns   = s(1);\nori = u(:,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute the pseudo inverse. This is the same as the\n% standard Matlab function, except that the default tolerance is twice as\n% high.\n%   Copyright 1984-2004 The MathWorks, Inc.\n%   $Revision: 2710 $  $Date: 2009/06/17 13:40:37 $\n%   default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction X = pinv(A,varargin)\n[m,n] = size(A);\nif n > m\n  X = pinv(A',varargin{:})';\nelse\n  [U,S,V] = svd(A,0);\n  if m > 1, s = diag(S);\n  elseif m == 1, s = S(1);\n  else s = 0;\n  end\n  if nargin == 2\n    tol = varargin{1};\n  else\n    tol = 10 * max(m,n) * max(s) * eps;\n  end\n  r = sum(s > tol);\n  if (r == 0)\n    X = zeros(size(A'),class(A));\n  else\n    s = diag(ones(r,1)./s(1:r));\n    X = V(:,1:r)*s*U(:,1:r)';\n  end\nend\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fieldtrip_partial/inverse/new/ft_inverse_beamformer_dics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.24763647117836754}}
{"text": "function val = hrfGet(prfParams,hrfParam)\n% hrfGet - get the hrfParameters from each of the scans\n%\n%   val = hrfGet(params,val)\n%\n% Brief description:\n%   The vistasoft scans have an implicit HRF attached to them.  This\n%   function gets the HRF for the parameters attached to a particular\n%   scan.\n%\n% Inputs\n%\n% Key/value pairs\n%   N/A\n% \n% Return\n%  \n% Example:\n%   \n%\n% 2009/03 SOD: modified from readHRFParams\nif notDefined('prfParams'), error('prfParams needed'); end\nif notDefined('hrfParam'),  error('hrfParam needed');  end\n\nnScans = length(prfParams.stim);\n\nval = [];\nswitch lower(hrfParam)\n    case {'hrfparams'}\n        val  = cell(nScans,1);\n        for n = 1:nScans\n            switch prfParams.stim(n).hrfType\n                case 'one gamma (Boynton style)'\n                    val{n} = prfParams.stim(n).hrfParams{1};\n                case 'two gammas (SPM style)'\n                    val{n} = prfParams.stim(n).hrfParams{2};\n                case 'impulse'\n                    % is this what we want??\n                    val{n} = 1;\n                otherwise\n                    fprintf(1,'[%s]:Unknown hrf type (%s)',mfilename,prfParams.stim(n).hrfType);\n            end\n        end\n        \n    case {'hrftype'}\n        val  = cell(nScans,1);\n        for n = 1:nScans\n            val{n} = prfParams.stim(n).hrfType;\n        end\n        \n    otherwise\n        fprintf(1,'[%s]:Unknown parameter (%s)',mfilename,hrfParam);\nend\n\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/HRFestimation/hrfGet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24759329033606817}}
{"text": "function res=cosmo_distatis(ds, varargin)\n% apply DISTATIS measure to each feature\n%\n% res=cosmo_statis_measure(ds, opt)\n%\n% Inputs:\n%    ds               dataset struct with dissimilarity values; usually\n%                     the output from @cosmo_dissimilarity_matrix_measure\n%                     applied to each subject followed by cosmo_stack. It\n%                     can also be a cell with datasets (one per subject).\n%    'return', d      d can be 'distance' (default) or 'crossproduct'.\n%                     'distance' returns a distance matrix, whereas\n%                     'crossproduct' returns a crossproduct matrix\n%    'split_by', s    sample attribute that discriminates chunks\n%                     (participants) (default: 'chunks')\n%    'shape', sh      shape of output if it were unflattened using\n%                     cosmo_unflatten, either 'square' (default) or\n%                     'triangle' (which gives the lower diagonal of the\n%                     distance matrix)\n%\n% Returns:\n%    res              result dataset struct with feature-wise optimal\n%                     compromise distance matrix across subjects\n%      .samples\n%\n%\n% Example:\n%     % (This example cannot be documentation tested using Octave,\n%     %  since Octave does not allow for-loops with evalc)\n%     cosmo_skip_test_if_no_external('matlab');\n%     %\n%     ds=cosmo_synthetic_dataset('nsubjects',5,'nchunks',1,'ntargets',4);\n%     %\n%     % define neighborhood (here a searchlight with radius of 1 voxel)\n%     nbrhood=cosmo_spherical_neighborhood(ds,'radius',1,'progress',false);\n%     %\n%     % define measure\n%     measure=@cosmo_dissimilarity_matrix_measure;\n%     % each subject is a chunk\n%     ds.sa.chunks=ds.sa.subject;\n%     % compute DSM for each subject\n%     sp=cosmo_split(ds,'chunks');\n%     for k=1:numel(sp)\n%         sp{k}=cosmo_searchlight(sp{k},nbrhood,measure,'progress',false);\n%         sp{k}.sa.chunks=ones(6,1)*k;\n%     end\n%     % merge results\n%     dsms=cosmo_stack(sp);\n%     %\n%     r=cosmo_distatis(dsms,'return','distance','progress',false);\n%     cosmo_disp(r);\n%     %|| .samples\n%     %||   [     0         0         0         0         0         0\n%     %||     0.818      1.09      0.77     0.653      1.03     0.421\n%     %||     0.869       1.3      1.06      1.04     0.932      1.07\n%     %||       :         :         :         :         :         :\n%     %||      1.16     0.889      0.99     0.631      1.48     0.621\n%     %||     0.268     0.952     0.965     0.462     0.943      1.04\n%     %||         0         0         0         0         0         0 ]@16x6\n%     %|| .fa\n%     %||   .center_ids\n%     %||     [ 1         2         3         4         5         6 ]\n%     %||   .i\n%     %||     [ 1         2         3         1         2         3 ]\n%     %||   .j\n%     %||     [ 1         1         1         2         2         2 ]\n%     %||   .k\n%     %||     [ 1         1         1         1         1         1 ]\n%     %||   .nvoxels\n%     %||     [ 3         4         3         3         4         3 ]\n%     %||   .radius\n%     %||     [ 1         1         1         1         1         1 ]\n%     %||   .quality\n%     %||     [ 0.685     0.742     0.617     0.648     0.757     0.591 ]\n%     %||   .nchunks\n%     %||     [ 5         5         5         5         5         5 ]\n%     %|| .a\n%     %||   .fdim\n%     %||     .labels\n%     %||       { 'i'  'j'  'k' }\n%     %||     .values\n%     %||       { [ 1         2         3 ]  [ 1         2 ]  [ 1 ] }\n%     %||   .sdim\n%     %||     .labels\n%     %||       { 'targets1'  'targets2' }\n%     %||     .values\n%     %||       { [ 1    [ 1\n%     %||           2      2\n%     %||           3      3\n%     %||           4 ]    4 ] }\n%     %||   .vol\n%     %||     .mat\n%     %||       [ 2         0         0        -3\n%     %||         0         2         0        -3\n%     %||         0         0         2        -3\n%     %||         0         0         0         1 ]\n%     %||     .dim\n%     %||       [ 3         2         1 ]\n%     %||     .xform\n%     %||       'scanner_anat'\n%     %|| .sa\n%     %||   .targets1\n%     %||     [ 1\n%     %||       2\n%     %||       3\n%     %||       :\n%     %||       2\n%     %||       3\n%     %||       4 ]@16x1\n%     %||   .targets2\n%     %||     [ 1\n%     %||       1\n%     %||       1\n%     %||       :\n%     %||       4\n%     %||       4\n%     %||       4 ]@16x1\n%\n% Reference:\n%   - Abdi, H., Valentin, D., O?Toole, A. J., & Edelman, B. (2005).\n%     DISTATIS: The analysis of multiple distance matrices. In\n%     Proceedings of the IEEE Computer Society: International conference\n%     on computer vision and pattern recognition, San Diego, CA, USA\n%     (pp. 42?47).\n%\n% Notes:\n%   - DISTATIS tries to find an optimal compromise distance matrix across\n%     the different samples (participants)\n%   - Output can be reshape to matrix or array form using\n%     cosmo_unflatten(res,1)\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n\n    cosmo_check_external('distatis');\n\n    defaults.return='distance';\n    defaults.split_by='chunks';\n    defaults.shape='square';\n    defaults.mask_output=[];\n    defaults.progress=100;\n    defaults.feature_ids=[];\n    defaults.autoscale=true;\n    defaults.abs_correlation=false;\n    defaults.weights='eig';\n\n    opt=cosmo_structjoin(defaults,varargin);\n\n    subject_cell=get_subject_data(ds,opt);\n    nsubj=numel(subject_cell);\n\n\n    [dsms,nclasses,dim_labels,dim_values]=get_dsms(subject_cell);\n\n    feature_ids=get_feature_ids(size(dsms{1},3),opt);\n    nfeatures=numel(feature_ids);\n\n    quality=zeros(1,nfeatures);\n    nobservations=zeros(1,nfeatures);\n\n    prev_msg='';\n    clock_start=clock();\n    show_progress=nfeatures>1 && opt.progress;\n\n    for k=1:nfeatures\n        feature_id=feature_ids(k);\n        x=zeros(nclasses*nclasses,nsubj);\n\n        for j=1:nsubj\n            dsm=dsms{j}(:,:,feature_id);\n            x(:,j)=distance2crossproduct(dsm, opt.autoscale);\n        end\n\n        [x,subj_msk]=cosmo_remove_useless_data(x);\n        nkeep=sum(subj_msk);\n\n        % equivalent, but slower:\n        % [e,v]=eigs(c,1);\n\n        [ew,v]=get_weights(x, feature_id, nkeep, opt);\n\n        % compute compromise\n        compromise=x*ew;\n\n        result=convert_compromise(compromise, opt);\n\n        if feature_id==1\n            % allocate space\n            samples=zeros(numel(result),nfeatures);\n        end\n\n        samples(:,k)=result;\n\n        quality(:,k)=v/nkeep;\n        nobservations(:,k)=nkeep;\n\n\n        if show_progress && (k<10 || ...\n                                mod(k, opt.progress)==0 || ...\n                                k==nfeatures)\n            status=sprintf('quality=%.3f%% (avg)',mean(quality(1:k)));\n            prev_msg=cosmo_show_progress(clock_start,k/nfeatures,...\n                                                        status,prev_msg);\n        end\n    end\n\n    % set output in either triangular or square shape\n    [res,i,j]=get_samples_in_shape(samples,nclasses,opt.shape);\n    res=copy_fields(ds,res,{'fa','a'});\n\n    % add attributes\n    res.fa.quality=quality;\n    res.fa.nchunks=nobservations;\n    res.a.sdim=struct();\n    res.a.sdim.labels=dim_labels;\n    res.a.sdim.values=dim_values;\n\n    res.sa.(dim_labels{1})=i(:);\n    res.sa.(dim_labels{2})=j(:);\n\n    cosmo_check_dataset(res);\n\nfunction [res,i,j]=get_samples_in_shape(samples,nclasses,shape)\n    res=struct();\n    switch shape\n        case 'triangle'\n            [msk,i,j]=distance_matrix_mask(nclasses);\n            res.samples=samples(msk(:),:);\n        case 'square'\n            res.samples=samples;\n            [i,j]=find(ones(nclasses));\n        otherwise\n            error('unsupported direction %s', shape);\n    end\n\n\n\nfunction dst=copy_fields(src,dst,keys)\n    for k=1:numel(keys)\n        key=keys{k};\n        if isfield(src,key)\n            dst.(key)=src.(key);\n        end\n    end\n\n\nfunction feature_ids=get_feature_ids(nfeatures, opt)\n    feature_ids=opt.feature_ids;\n    if isempty(feature_ids);\n        feature_ids=1:nfeatures;\n    end\n\n\nfunction [ew,v]=get_weights(x, feature_id, nkeep, opt)\n    switch opt.weights\n        case 'eig'\n            [ew,v]=eigen_weights(x, feature_id);\n\n        case 'uniform'\n            % all the same (allowing for comparison with 'eig')\n            ew=ones(nkeep,1)/nkeep;\n            v=0;\n\n        otherwise\n            error('illegal weight %s', opt.weights);\n    end\n\n\n\nfunction subject_cell=get_subject_data(ds,opt)\n    if isstruct(ds)\n        subject_cell=cosmo_split(ds,opt.split_by);\n    else\n        subject_cell=ds;\n    end\n\n    if numel(subject_cell)==0\n        error('empty input');\n    end\n\n\nfunction [ew,v]=eigen_weights(x, feature_id)\n\n    c=cosmo_corr(x);\n\n    negative_c=c<0;\n\n    if any(negative_c(:))\n\n        [i,j]=find(negative_c);\n        error(['feature %d has negative correlation between '...\n                'sample %d and %d, which is not supported by '...\n                'distatis. DISTATIS assumes that the similarity '...\n                'data from all samples (typically: participants) '...\n                'correlate positively. Because that is not the '...\n                'case, you cannot use DISTATIS analysis on this '...\n                'data. '],...\n                feature_id,i(1),j(1));\n    end\n\n    [v,e]=fast_eig1(c);\n\n    if all(e<0)\n        e=-e;\n    end\n\n    assert(all(e>0));\n    assert(v>0);\n\n    % normalize first eigenvector\n    ew=e/sum(e);\n\n\nfunction result=convert_compromise(compromise, opt)\n    switch opt.return\n        case 'crossproduct'\n            result=compromise;\n        case 'distance'\n            result=crossproduct2distance(compromise);\n        otherwise\n            error('illegal opt.return');\n    end\n\nfunction z=crossproduct2distance(x)\n    n=sqrt(numel(x));\n    e=ones(n,1);\n    d=x(1:(n+1):end);\n    dd=d*e';\n    ddt=dd';\n    y=dd(:)+ddt(:)-2*x;\n    z=ensure_distance_vector(y);\n\nfunction assert_symmetric(x, tolerance)\n    if nargin<2, tolerance=1e-8; end\n\n    % assert x is a square matrix\n    sz=size(x);\n    assert(isequal(sz,sz([2 1])));\n\n\n    xx=x'-x;\n\n    msk=xx>tolerance;\n    if any(msk)\n        [i,j]=find(msk,1);\n        error('not symmetric: x(%d,%d)=%d ~= %d=x(%d,%d)',...\n                i,j,x(i,j),x(j,i),j,i);\n    end\n\nfunction z_vec=distance2crossproduct(x, autoscale)\n\n    n=size(x,1);\n    e=ones(n,1);\n    m=e*(1/n);\n    ee=eye(n)-e*m';\n    y=-.5*ee*(x+x')*ee';\n    if autoscale\n        z=(1/fast_eig1(y))*y;\n    else\n        z=y;\n    end\n    assert_symmetric(z);\n    % equivalent, but slower:\n    % z=(1/eigs(y,1))*y(:);\n\n    z_vec=z(:);\n\nfunction [lambda,pivot]=fast_eig1(x)\n    % returns the first eigenvalue in lambda, and the corresponding\n    % eigenvector in pivot\n    if cosmo_wtf('is_matlab')\n        [pivot,lambda]=eigs(x,1);\n    else\n        % There seems a bug in Octave for 'eigs',\n        % so use 'eig' instead.\n        % http://savannah.gnu.org/bugs/?44004\n        [e,v]=eig(x);\n        diag_v=diag(v);\n\n        % find largest eigenvalue and eigenvector\n        [lambda,i]=max(diag_v);\n        pivot=e(:,i);\n    end\n\n    % The code below is disabled because under certain circumstances\n    % it would return a near-zero eigenvalue if indeed one eigenvalue (but\n    % not the largest one) is zero.\n    % % compute first (largest) eigenvalue and corresponding eigenvector\n    % % using power iteration method; benchmarking suggests this can be up to\n    % % five times as fast as using eigs(x,1)\n    % n=size(x,1);\n    % pivot=ones(n,1);\n    % tolerance=1e-8;\n    % max_iter=1000;\n    %\n    % old_lambda=NaN;\n    % for k=1:max_iter\n    %     z=x*pivot;\n    %     pivot=z / norm(z);\n    %\n    %     lambda=pivot'*z;\n    %     if abs(lambda-old_lambda)/lambda<tolerance\n    %         z=x*pivot;\n    %         pivot=z / sqrt(sum(z.^2));\n    %\n    %         lambda=pivot'*z;\n    %         return\n    %     end\n    %     old_lambda=lambda;\n    % end\n    %\n    % % matlab fallback\n    % [pivot,lambda]=eigs(x,1);\n\nfunction y=ensure_distance_vector(x)\n    tolerance=1e-8;\n\n    n=sqrt(numel(x));\n    xsq=reshape(x,n,n);\n\n    dx=diag(xsq);\n    assert(all(dx<tolerance));\n\n    xsq=xsq-diag(dx);\n\n    delta=xsq-xsq';\n    assert(all(delta(:)<tolerance));\n\n    xsq=.5*(xsq+xsq');\n    y=xsq(:);\n\n\nfunction [dsms,nclasses,dim_labels,dim_values]=get_dsms(data_cell)\n    nsubj=numel(data_cell);\n\n    % allocate\n    dsms=cell(nsubj,1);\n    for k=1:numel(data_cell)\n        data=data_cell{k};\n\n        % get data\n        [dsm,dim_labels,dim_values,is_ds]=get_dsm(data);\n\n        % store data\n        dsms{k}=dsm;\n\n        if k==1\n            nclasses=size(dsm,1);\n            first_dim_labels=dim_labels;\n            first_dim_values=dim_values;\n\n            data_first=data;\n        else\n\n            if ~isequal(first_dim_labels,dim_labels)\n                error('dim label mismatch between subject 1 and %d',k);\n            end\n            if ~isequal(first_dim_values,dim_values)\n                error('dim label mismatch between subject 1 and %d',k);\n            end\n\n            % check for compatibility over subjects, raises an error if not\n            % kosher\n            if is_ds\n                cosmo_stack({cosmo_slice(data,1),...\n                                cosmo_slice(data_first,1)},1,'unique');\n            end\n        end\n    end\n\nfunction [msk,i,j]=distance_matrix_mask(nclasses)\n    msk=triu(repmat(1:nclasses,nclasses,1),1)'>0;\n    [i,j]=find(msk);\n\nfunction [dsm, dim_labels, dim_values, is_ds]=get_dsm(data)\n    is_ds=isstruct(data);\n    if is_ds\n        [dsm,dim_labels,dim_values]=cosmo_unflatten(data,1);\n    elseif isnumeric(data)\n        sz=size(data);\n        if numel(sz)~=2\n            error('only vectorized distance matrices are supported');\n        end\n        [n,nfeatures]=size(data);\n\n        side=(1+sqrt(1+8*n))/2; % so that side*(side-1)/2==n\n        if ~isequal(side, round(side))\n            error(['size %d of input vector is not correct for '...\n                    'the number of elements below the diagonal of a '...\n                    'square (distance) matrix'], n);\n        end\n\n        [msk,i,j]=distance_matrix_mask(side);\n        dsm=zeros([side,side,nfeatures]);\n\n        assert(numel(i)==n);\n        for pos=1:n\n            dsm(i(pos),j(pos),:)=data(pos,:);\n        end\n\n        sq1=cosmo_squareform(data(:,1));\n        dsm1=dsm(:,:,1);\n        assert(isequal(sq1,dsm1+dsm1'));\n\n\n        dim_labels={'targets1','targets2'};\n        dim_values={(1:side)',(1:side)'};\n    else\n        error('illegal input: expect dataset struct, or cell with arrays');\n    end\n\n\n\n\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_distatis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24759329033606814}}
{"text": "function [curr_segments] = filter_segments(seg_obj, gp_obj, graph_idx, ...\n                                           curr_segments)\n%FILTER_SEGMENTS filters (discards) the segments based on different \n% criterion\n%\n% @authors:     Ahmad Humayun,  Fuxin Li\n% @contact:     ahumayun@cc.gatech.edu\n% @affiliation: Georgia Institute of Technology\n% @date:        Fall 2013 - Summer 2014\n\n    % first check if we want to filter segments for the current graph\n    if ~seg_obj.segm_params.graph_filter_segs{graph_idx}\n        curr_segments.segs_meta_info.energies = [];\n        return;\n    end\n        \n    fprintf('\\tFiltering segments\\n');\n    \n    t_fltr = tic;\n    % if no segments, return\n    if isempty(curr_segments.cut_segs)\n        return;\n    end\n    \n    % separate each segment into its connected components. Also remove the\n    % components (split segments) which are below min_npixels size\n    [curr_segments] = ...\n        separate_conn_comp(curr_segments, seg_obj, ...\n                           seg_obj.segm_params.filter_min_seg_pixels);\n    \n    % just computes the pairwise edges cut value divided by the number of\n    % pairwise edges cut (this is called the cut ratio)\n    [curr_segments, t_energy] = compute_energies(curr_segments, ...\n                                                 seg_obj, gp_obj);\n    \n    % filter segment which are above the filter_max_energy cut ratio\n    [curr_segments] = filter_energies(curr_segments, seg_obj, ...\n                                seg_obj.segm_params.filter_max_energy, ...\n                                t_energy);\n    \n    % randomly throw away segments if more than filter_max_rand                  \n    [curr_segments] = filter_rand(curr_segments, seg_obj, ...\n                                  seg_obj.segm_params.filter_max_rand);\n    \n    % if multiple segments overlap, only keep the one with the lowest cut \n    % ratio\n    [curr_segments] = remove_repeated_segments(curr_segments, seg_obj, ...\n                                               gp_obj);\n    \n    % if user specified specified seeds, discard anything that doesn't\n    % include the seed location itself (which can happen with color unaries\n    % for instance)\n    if strcmp(seg_obj.segm_params.graph_seed_gen_method,'gen_user_seeds')\n        % find segments which cover all the seed superpixels (supposes that\n        % there is only one seed in seed_sets)\n        seed_cover = ...\n            curr_segments.cut_segs(seg_obj.precomputed_seeds.seed_sets,:);\n        conn = (sum(seed_cover,1) ...\n            == sum(seg_obj.precomputed_seeds.seed_sets));\n        [curr_segments] = cherry_pick_segments(curr_segments, conn);\n    end\n\n    seg_obj.timings.seg_filtering_time = ...\n        [seg_obj.timings.seg_filtering_time, toc(t_fltr)];\nend\n\n\nfunction [curr_segments] = separate_conn_comp(curr_segments, seg_obj, ...\n                                              min_npixels)\n    fprintf('\\t\\tSeparating connected components ... ');\n    \n    t_conn = tic;\n    \n    if(nargin == 1)\n        min_npixels = 25;\n    end\n\n    % separate each segment into its connected components by\n    % finding connected components on the induced graph. Also remove the\n    % components which are below min_npixels size\n    [segms, num_comps] = sp_conncomp_mex(curr_segments.cut_segs, ...\n                                         seg_obj.sp_data.edgelet_sp, ...\n                                         seg_obj.sp_data.sp_seg_szs, ...\n                                         min_npixels);\n    \n    % make the mapping which is an array of the length of the total \n    % number of new segments (each of which forms a connected\n    % component) where each array location gives the index/id of\n    % the original segment returned by the min-cut\n    temp = duplicateElems(1:length(num_comps), num_comps);\n    curr_segments.segs_meta_info.seg_mapping_final_to_orig = ...\n        curr_segments.segs_meta_info.seg_mapping_final_to_orig(temp);\n\n    curr_segments.cut_segs = segms;\n    \n    seg_obj.num_segs.after_splitting_conncomp = ...\n        [seg_obj.num_segs.after_splitting_conncomp, sum(num_comps)];\n    \n    time_util(seg_obj, 'init_filter_time', t_conn, 1, 1);\nend\n\nfunction [curr_segments, t_energy] = compute_energies(curr_segments, ...\n                                                      seg_obj, gp_obj)\n    fprintf('\\t\\tComputing energies ... ');\n    \n    t_energy = tic;\n    \n    cut_ratio = zeros(1,size(curr_segments.cut_segs,2));\n    for i = 1:length(cut_ratio)\n        links_across = ...\n            gp_obj.pairwise_graph(~curr_segments.cut_segs(:,i), ...\n                                  curr_segments.cut_segs(:,i));\n        cut = full(sum(links_across(:)));\n        % cut ratio (minimizing it is called the sparsest cut problem)\n        n_edges_across = nnz(links_across);\n        cut_ratio(i) = cut / n_edges_across;\n    end\n    curr_segments.segs_meta_info.energies = cut_ratio;\n    \n    fprintf('%.2fs\\n', toc(t_energy));\nend\n\nfunction [curr_segments] = filter_energies(curr_segments, seg_obj, ...\n                                           max_energy, t_energy)\n    fprintf('\\t\\tRemoving high energy solutions ... ');\n    \n    t_energy_fltr = tic;\n    \n    % minimum number of segments to keep\n    min_n_segms = 5;\n    \n    [sorted_cut_ratio, sorted_ind] = ...\n        sort(curr_segments.segs_meta_info.energies, 'ascend');\n    last_acceptable = find(sorted_cut_ratio <= max_energy, 1, 'last');\n    reject_segs_ind = sorted_ind(last_acceptable+1:end);\n    % if the remaining number of segments would be less\n    num_remain_segs = length(sorted_cut_ratio) - length(reject_segs_ind);\n    if num_remain_segs < min_n_segms\n        num_keep_more = min_n_segms - num_remain_segs;\n        num_keep_more = min(num_keep_more, length(reject_segs_ind));\n        reject_segs_ind(1:num_keep_more) = [];\n    end\n\n    % remove segments not wanted from curr_segments\n    [curr_segments] = cherry_pick_segments(curr_segments, ...\n                                           setdiff(1:length(sorted_ind), ...\n                                                   reject_segs_ind));\n    \n    seg_obj.num_segs.after_energy_filtering = ...\n        [seg_obj.num_segs.after_energy_filtering, ...\n         size(curr_segments.cut_segs,2)];\n    \n    fprintf('%.2fs\\n', toc(t_energy_fltr));\n    \n    time_util(seg_obj, 'energy_filter_time', t_energy, 1, 0);\nend\n\nfunction [curr_segments] = filter_rand(curr_segments, seg_obj, ...\n                                       max_rand_pick)\n    fprintf('\\t\\tPick %d random segments ... ', max_rand_pick);\n    \n    t_rand = tic;\n    \n    if size(curr_segments.cut_segs,2) > max_rand_pick\n        randn = randperm(size(curr_segments.cut_segs,2));\n        curr_segments = cherry_pick_segments(curr_segments, ...\n                                             randn(1:max_rand_pick));\n    end\n    \n    seg_obj.num_segs.after_random_picking = ...\n        [seg_obj.num_segs.after_random_picking, ...\n         size(curr_segments.cut_segs,2)];\n    \n    time_util(seg_obj, 'rand_filter_time', t_rand, 1, 1);\nend\n\nfunction [curr_segments] = remove_repeated_segments(curr_segments, ...\n                                                    seg_obj, gp_obj)\n    fprintf('\\t\\tRemoving repeated segments ... ');\n    \n    OVERLAP_THRESH = 0.95;\n\n    t_repeat = tic;\n    \n    seg_sel = [];\n    \n    % divide segments by their graph sub-methods\n    ub = cumsum(gp_obj.graph_sets_per_method);\n    lb = [1, ub(1:end-1)+1];\n%     % if you don't want division by graph sub-methods (comment out above)\n%     ub = inf;\n%     lb = 1;\n    \n    % find sols_to_unary_mapping for the segments remaining\n    sols_to_unary_map = curr_segments.segs_meta_info.sols_to_unary_mapping;\n    seg_mapping = curr_segments.segs_meta_info.seg_mapping_final_to_orig;\n    curr_unary_mapping = sols_to_unary_map(seg_mapping);\n    for gsubm = 1:length(ub)\n        subm_idx = curr_unary_mapping >= lb(gsubm) & ...\n                   curr_unary_mapping <= ub(gsubm);\n        cut_segs = curr_segments.cut_segs(:,subm_idx);\n        \n        % smart way to compute pairwise overlaps btw segments if above 0.95\n        overlap_mat = overlap_over_threshold(cut_segs, OVERLAP_THRESH);\n    \n        % find segment sets which are stringed together with high overlap\n        bw_mat = overlap_mat >= OVERLAP_THRESH;\n        [num_conn, conncomps_t] = graphconncomp(sparse(bw_mat));\n        conncomps = zeros(size(subm_idx));\n        conncomps(subm_idx) = conncomps_t;\n        this_sel = zeros(1,num_conn);\n        % for each segment set, select one segment with lowest energy\n        for i = 1:num_conn\n            s1 = find(conncomps == i);\n            [~,b] = min(curr_segments.segs_meta_info.energies(conncomps == i));\n            this_sel(i) = s1(b);\n        end\n        % collate to the list of segments to be cherry picked\n        seg_sel = [seg_sel, this_sel];\n    end\n    \n    % keep only segments which have lowest energy amongst similar segments\n    [curr_segments] = cherry_pick_segments(curr_segments, seg_sel);\n    \n    seg_obj.num_segs.after_repeat_remove = ...\n        [seg_obj.num_segs.after_repeat_remove, length(seg_sel)];\n\n    time_util(seg_obj, 'seg_similar_filter_time', t_repeat, 1, 1);\nend\n\nfunction [curr_segments] = cherry_pick_segments(curr_segments, to_pick_idxs)\n% this function removes segments from curr_segments structure\n\n    curr_segments.cut_segs = curr_segments.cut_segs(:, to_pick_idxs);\n    curr_segments.segs_meta_info.seg_mapping_final_to_orig = ...\n        curr_segments.segs_meta_info.seg_mapping_final_to_orig(:, to_pick_idxs);\n\n    if isfield(curr_segments.segs_meta_info, 'energies') && ...\n            ~isempty(curr_segments.segs_meta_info.energies)\n        curr_segments.segs_meta_info.energies = ...\n            curr_segments.segs_meta_info.energies(to_pick_idxs);\n    end\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rigor/rigor_src/@Segmenter/filter_segments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24759329033606814}}
{"text": "function C = construct_winning_matrix(M, num_method)\n% -------------------------------------------------------------------------\n%   Description:\n%       function to construct a winning matrix C ftom vote matrix M\n%\n%   Input:\n%       - M: N x 4 vote matrix, N is the number of images\n%            M(i, 1) is image id\n%            M(i, 2) is method1 id\n%            M(i, 3) is method2 id\n%            M(i, 4) is compared result, 1 if user chooses method1, 2 if user chooses method2\n%\n%       - num_method: the number of evaluated methods\n%\n%   Output:\n%       - C: winning matrix, C(i, j) is the number of times that user choose i over j\n%\n%   Citation: \n%       A Comparative Study for Single Image Blind Deblurring\n%       Wei-Sheng Lai, Jia-Bin Huang, Zhe Hu, Narendra Ahuja, and Ming-Hsuan Yang\n%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016\n%\n%   Contact:\n%       Wei-Sheng Lai\n%       wlai24@ucmerced.edu\n%       University of California, Merced\n% -------------------------------------------------------------------------\n\n    C = zeros(num_method, num_method);\n    \n    for i = 1:size(M, 1)\n\n        img_id  = M(i, 1);\n        method1 = M(i, 2);\n        method2 = M(i, 3);\n        result  = M(i, 4);\n\n        if( result == 1 )\n            C(method1, method2) = C(method1, method2) + 1;\n        elseif( result == 2 )\n            C(method2, method1) = C(method2, method1) + 1;\n        end\n\n    end\n\nend", "meta": {"author": "phoenix104104", "repo": "cvpr16_deblur_study", "sha": "d8751a80fd905fc0fceaf442cd6f85f0084a2570", "save_path": "github-repos/MATLAB/phoenix104104-cvpr16_deblur_study", "path": "github-repos/MATLAB/phoenix104104-cvpr16_deblur_study/cvpr16_deblur_study-d8751a80fd905fc0fceaf442cd6f85f0084a2570/construct_winning_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24759329033606808}}
{"text": "% Defines the class headModel for solving forward/inverse problem of the EEG. \n% This class is part of MoBILAB software. \n% For more details visit:  https://code.google.com/p/mobilab/\n% \n% Author: Alejandro Ojeda, SCCN/INC/UCSD, Jan-2012\n\nclassdef headModel < handle\n    properties(GetAccess=public, SetAccess=public,SetObservable)\n        channelSpace = [];     % xyz coordinates of the sensors.\n        \n        fiducials = [];        % xyz of the fiducial landmarks: nassion, lpa, rpa, vertex, and inion.\n        \n        surfaces = [];         % Pointer to the file where the surfaces representing different layers \n                               % of tissue are stored. The surfaces must be in an array of MATLAB patches\n                               % in the following order: 1) scalp, 2) skull, 3) brain (gray matter or \n                               % average between gray and white matter)\n                               \n        atlas                  % Atlas that labels each vertex in the most internal surface (gray matter).\n        \n        leadFieldFile = [];    % Pointer to the file where the lead field matrix was stored.\n        \n        channelLabel = []\n    end\n    properties(GetAccess = private, SetAccess = private)\n        label;\n        F = [];\n    end\n%     properties(Dependent)\n%     end\n    methods\n        function obj = headModel(varargin)\n            if length(varargin)==1, varargin = varargin{1};end\n            \n            if ~iscell(varargin) && ischar(varargin) && exist(varargin,'file')\n                [obj.channelSpace,obj.label,obj.fiducials] = readMontage(varargin);\n                return\n            end\n            \n            ind = find(ismember(varargin(1:2:length(varargin)-1),'channelSpace'));\n            if ~isempty(ind), obj.channelSpace = varargin{ind*2};end\n            \n            ind = find(ismember(varargin(1:2:length(varargin)-1),'surfaces'));\n            if ~isempty(ind), obj.surfaces = varargin{ind*2};end\n            if ~isempty(obj.surfaces)\n                [~,~,e] = fileparts(obj.surfaces);\n                if isempty(e), obj.surfaces = [obj.surfaces,'.mat'];end\n            end            \n            ind = find(ismember(varargin(1:2:length(varargin)-1),'atlas'));\n            if ~isempty(ind)\n                tmpAtlas = varargin{ind*2};\n                if isfield(tmpAtlas,'color'),\n                    tmpAtlas.colorTable = tmpAtlas.color;\n                    tmpAtlas = rmfield(tmpAtlas,'color');\n                end\n                obj.atlas = tmpAtlas;\n            end\n            ind = find(ismember(varargin(1:2:length(varargin)-1),'fiducials'));\n            if ~isempty(ind), obj.fiducials = varargin{ind*2};end\n            \n            ind = find(ismember(varargin(1:2:length(varargin)-1),'leadFieldFile'));\n            if ~isempty(ind), obj.leadFieldFile = varargin{ind*2};end\n            ind = find(ismember(varargin(1:2:length(varargin)-1),'label'));\n            if ~isempty(ind),\n                obj.channelLabel = varargin{ind*2};\n                obj.label = varargin{ind*2};\n            else\n                N = size(obj.channelSpace,1);\n                labels = num2str((1:N)');\n                obj.label =num2cell(labels',[N,1])';\n                for it=1:N, obj.label{it} = deblank(obj.label{it});end\n            end\n        end\n        function labels = getChannelLabels(obj)\n            labels = obj.label;\n            warning('This method will be deprecated in the future, instead you can access directly the property channelLabel.')\n        end\n        function channelLabel = get.channelLabel(obj)\n            channelLabel = obj.label;\n        end\n        function set.channelLabel(obj, val)\n            obj.label = val;\n        end\n        function dropChannels(obj, ind)\n            obj.label(ind) = [];\n            obj.channelSpace(ind, :) = [];\n        end\n        %%\n        function [roiname,roinumber] = labelDipole(obj,dipole)\n            if isempty(obj.F)\n                load(obj.surfaces)\n                obj.F = scatteredInterpolant(surfData(end).vertices(:,1),...\n                    surfData(end).vertices(:,2),surfData(end).vertices(:,3),...\n                    obj.atlas.colorTable,'nearest');\n            end\n            roinumber = obj.F(dipole(:,1),dipole(:,2),dipole(:,3));\n            roiname = obj.atlas.label(roinumber);\n        end\n        %%\n        function chanlocs = makeChanlocs(obj)\n            % make EEGLAB chanlocs structure from channel locations and\n            % labels\n            if isempty(which('convertlocs'))\n                error('EEGLAB function convertlocs.m is missing.');\n            end\n            for k=1:length(obj.label)\n                chanlocs(k) = struct('labels',obj.label{k}, ...\n                                     'ref','', ...\n                                     'theta',[], ...\n                                     'radius',[], ...\n                                     'X',obj.channelSpace(k,1), ...\n                                     'Y',obj.channelSpace(k,2), ...\n                                     'Z',obj.channelSpace(k,3), ...\n                                     'sph_theta', [], ...\n                                     'sph_phi',[], ...\n                                     'sph_radius',[], ...\n                                     'type', 'EEG', ...\n                                     'urchan', []);\n            end\n            chanlocs = convertlocs( chanlocs, 'cart2all');\n        end\n        %%\n        function h = plotHeadModel(obj,~) % do not remove the circumflex, I'm passging a second arguments when this method is called from MoBILAB's gui\n            % Plots the different layers of tissue, the sensor positions, and their labels.\n            % It colors different regions of the cortical surface according to a defined\n            % anatomical atlas. Several interactive options for customizing the figure are\n            % available.\n            \n            if isempty(obj.channelSpace) || isempty(obj.label) || isempty(obj.surfaces);\n                error('Head model is incomplete or missing.');\n            end\n            h = headModelViewerHandle(obj,obj.label);\n        end\n       %%\n        function h = plotMontage(obj,showNewfig)\n            % Plots a figure with the xyz distribution of sensors, fiducial landmarks, and\n            % coordinate axes.\n            \n            if isempty(obj.channelSpace) || isempty(obj.label);error('MoBILAB:noChannelSpace','Channel space is empty.');end\n            if nargin < 2, showNewfig = true;end\n            \n            if isa(obj,'eeg')\n                color = [0.93 0.96 1];\n            else\n                color = [0.76 0.77 1];\n            end\n            if showNewfig, figure('Color',color);end\n            h = scatter3(obj.channelSpace(:,1),obj.channelSpace(:,2),obj.channelSpace(:,3),'filled',...\n                'MarkerEdgeColor','k','MarkerFaceColor','y','parent',gca);\n            \n            hold on;\n            N = length(obj.label);\n            k = 1.1;\n            for it=1:N, text('Position',k*obj.channelSpace(it,:),'String',obj.label{it});end\n            mx = max(obj.channelSpace);\n            k = 1.2;\n            line([0 k*mx(1)],[0 0],[0 0],'LineStyle','-.','Color','b','LineWidth',2)\n            line([0 0],[0 k*mx(2)],[0 0],'LineStyle','-.','Color','g','LineWidth',2)\n            line([0 0],[0 0],[0 k*mx(3)],'LineStyle','-.','Color','r','LineWidth',2)\n            text('Position',[k*mx(1) 0 0],'String','X','FontSize',12,'FontWeight','bold','Color','b')\n            text('Position',[0 k*mx(2) 0],'String','Y','FontSize',12,'FontWeight','bold','Color','g')\n            text('Position',[0 0 k*mx(3)],'String','Z','FontSize',12,'FontWeight','bold','Color','r')\n            \n            try %#ok\n                scatter3(obj.fiducials.nasion(1),obj.fiducials.nasion(2),obj.fiducials.nasion(3),'filled','MarkerEdgeColor','k','MarkerFaceColor','K');\n                text('Position',1.1*obj.fiducials.nasion,'String','Nas','FontSize',12,'FontWeight','bold','Color','k');\n                \n                scatter3(obj.fiducials.lpa(1),obj.fiducials.lpa(2),obj.fiducials.lpa(3),'filled','MarkerEdgeColor','k','MarkerFaceColor','K');\n                text('Position',1.1*obj.fiducials.lpa,'String','LPA','FontSize',12,'FontWeight','bold','Color','k');\n                \n                scatter3(obj.fiducials.rpa(1),obj.fiducials.rpa(2),obj.fiducials.rpa(3),'filled','MarkerEdgeColor','k','MarkerFaceColor','K');\n                text('Position',1.1*obj.fiducials.rpa,'String','RPA','FontSize',12,'FontWeight','bold','Color','k');\n                \n                scatter3(obj.fiducials.vertex(1),obj.fiducials.vertex(2),obj.fiducials.vertex(3),'filled','MarkerEdgeColor','k','MarkerFaceColor','K');\n                text('Position',1.1*obj.fiducials.vertex,'String','Ver','FontSize',12,'FontWeight','bold','Color','k');\n                \n                scatter3(obj.fiducials.inion(1),obj.fiducials.inion(2),obj.fiducials.inion(3),'filled','MarkerEdgeColor','k','MarkerFaceColor','K');\n                text('Position',1.1*obj.fiducials.inion,'String','Ini','FontSize',12,'FontWeight','bold','Color','k');\n            end\n            \n            % box on;\n            hold off;\n            axis equal\n            axis vis3d\n            grid on;\n        end\n       %%\n        function individualHeadModelFile = warpTemplate2channelSpace(obj,headModelFile,individualHeadModelFile)\n            % Warps a template head model to the space defined by the sensor positions (channelSpace). It uses Dirk-Jan Kroon's\n            % nonrigid_version23 toolbox.\n            %\n            % For more details see: http://www.mathworks.com/matlabcentral/fileexchange/20057-b-spline-grid-image-and-point-based-registration\n            % \n            % Input arguments:\n            %       headModelFile:           pointer to the template head model file. To see an example of\n            %                                templates see the folder mobilab/data/headModelXX.mat\n            %       individualHeadModelFile: pointer to the warped head model (output file)\n            % \n            % Output arguments:\n            %       individualHeadModelFile: pointer to the warped head model (same as the second input argument)\n            %\n            % References: \n            %    D. Rueckert et al. \"Nonrigid Registration Using Free-Form Deformations: Application to Breast MR Images\".\n            %    Seungyong Lee, George Wolberg, and Sung Yong Shing, \"Scattered Data interpolation with Multilevel B-splines\"\n\n            if nargin < 2, error('Reference head model is missing.');end\n            if nargin < 3, individualHeadModelFile = [tempname '.mat'];end\n            if isempty(obj.channelSpace) || isempty(obj.label), error('Channel space or labels are missing.');end\n            if ~exist(headModelFile,'file'), error('The file you''ve entered does not exist.');end\n            \n            template = load(headModelFile);\n            gTools = geometricTools;\n            th = norminv(0.90);\n            % mapping source to target spaces: S->T\n            % target space: individual geometry\n            \n            try\n                T = [obj.fiducials.nasion;...\n                    obj.fiducials.lpa;...\n                    obj.fiducials.rpa];\n                \n                % source space: template\n                S = [template.fiducials.nasion;...\n                    template.fiducials.lpa;...\n                    template.fiducials.rpa;...\n                    template.fiducials.vertex];\n                \n                % estimates vertex if is missing\n                if isfield(obj.fiducials,'vertex')\n                    if numel(obj.fiducials.vertex) == 3\n                        T = [T;obj.fiducials.vertex];\n                    else\n                        point = 0.5*(obj.fiducials.lpa + obj.fiducials.rpa);\n                        point = ones(50,1)*point;\n                        point(:,3) = linspace(point(3),1.5*max(obj.channelSpace(:,3)),50)';\n                        [~,d] = gTools.nearestNeighbor(obj.channelSpace,point);\n                        [~,loc] = min(d);\n                        point = point(loc,:);\n                        T = [T;point];\n                    end\n                else\n                    point = 0.5*(obj.fiducials.lpa + obj.fiducials.rpa);\n                    point = ones(50,1)*point;\n                    point(:,3) = linspace(point(3),1.5*max(obj.channelSpace(:,3)),50)';\n                    [~,d] = gTools.nearestNeighbor(obj.channelSpace,point);\n                    [~,loc] = min(d);\n                    point = point(loc,:);\n                    T = [T;point];\n                end\n                \n                if isfield(obj.fiducials,'inion')\n                    if numel(obj.fiducials.vertex) == 3\n                        T = [T;obj.fiducials.inion];\n                        S = [S;template.fiducials.inion];\n                    end\n                end\n            catch\n                disp('Fiducials are missing in the individual head model, selecting the common set of points based on the channel labels.')\n                [~,loc1,loc2] = intersect(channelLabel,template.label,'stable');\n                T = obj.channelSpace(loc1,:);\n                S = template.channelSpace(loc2,:);\n            end\n            try obj.initStatusbar(1,8,'Co-registering...');end %#ok\n            \n            % affine co-registration\n            [Aff,~,scale] = gTools.affineMapping(S,T);\n            if isa(obj,'eeg'), obj.statusbar(1);end\n            \n            % b-spline co-registration (only fiducial landmarks)\n            options.Verbose = true;\n            options.MaxRef = 2;\n            surfData = template.surfData;\n            Ns = length(surfData);\n            for it=1:Ns\n                surfData(it).vertices = gTools.applyAffineMapping(template.surfData(it).vertices,Aff);\n            end\n            Saff = gTools.applyAffineMapping(S,Aff);\n            [Def,spacing,offset] = gTools.bSplineMapping(Saff,T,surfData(1).vertices,options);\n            try obj.statusbar(2);end %#ok\n            \n            % b-spline co-registration (second pass)\n            for it=1:Ns\n                surfData(it).vertices = gTools.applyBSplineMapping(Def,spacing,offset,surfData(it).vertices);\n            end\n            T = obj.channelSpace;\n            T(T(:,3) <= min(surfData(1).vertices(:,3)),:) = [];\n            [S,d] = gTools.nearestNeighbor(surfData(1).vertices,T);\n            z = zscore(d);\n            S(abs(z)>th,:) = [];\n            T(abs(z)>th,:) = [];\n            [Def,spacing,offset] = gTools.bSplineMapping(S,T,surfData(1).vertices,options);\n            try obj.statusbar(3);end %#ok\n            \n            % b-spline co-registration (third pass)\n            for it=1:Ns\n                surfData(it).vertices = gTools.applyBSplineMapping(Def,spacing,offset,surfData(it).vertices);\n            end\n            T = obj.channelSpace;\n            T(T(:,3) <= min(surfData(1).vertices(:,3)),:) = [];\n            [S,d] = gTools.nearestNeighbor(surfData(1).vertices,T);\n            z = zscore(d);\n            S(abs(z)>th,:) = [];\n            T(abs(z)>th,:) = [];\n            Tm = 0.5*(T+S);\n            [Def,spacing,offset] = gTools.bSplineMapping(S,Tm,surfData(1).vertices,options);\n            try obj.statusbar(4);end %#ok\n            \n            % apply the final transformation\n            for it=1:Ns\n                surfData(it).vertices = gTools.applyBSplineMapping(Def,spacing,offset,surfData(it).vertices);\n                surfData(it).vertices = gTools.smoothSurface(surfData(it).vertices,surfData(it).faces);\n            end\n            \n            % fixing topological defects\n            try obj.container.container.statusBar.setText('Fixing topological defects...');end %#ok\n            dmax = ones(Ns-1,1)*5;\n            dmax(1) = 8;\n            dmax = dmax*scale;\n            ind = fliplr(1:Ns);\n            for it=1:Ns-1\n                surfData(ind(it+1)).vertices = gTools.repareIntersectedSurface(surfData(ind(it)),surfData(ind(it+1)),dmax(it));\n                try obj.statusbar(it+5);end %#ok\n            end\n            \n            ind =  obj.channelSpace(:,3) > min(surfData(1).vertices(:,3));\n            T = gTools.nearestNeighbor(surfData(1).vertices,obj.channelSpace);\n            channelSpace = obj.channelSpace; %#ok\n            channelSpace(ind,:) = T(ind,:);  %#ok\n            [~,loc] = unique(channelSpace,'rows');%#ok\n            indInterp = setdiff(1:size(obj.channelSpace,1),loc);\n            if ~isempty(indInterp)\n                x = setdiff(channelSpace,channelSpace(indInterp,:),'rows');%#ok\n                xi = gTools.nearestNeighbor(x,channelSpace(indInterp,:));%#ok\n                channelSpace(indInterp,:) = 0.5*(xi + channelSpace(indInterp,:));%#ok\n            end\n            obj.channelSpace = channelSpace; %#ok\n            \n            if isfield(template,'atlas'), \n                if isfield(template.atlas,'color')\n                    colorTable = template.atlas.color;\n                    template.atlas = rmfield(template.atlas,'color');\n                    template.atlas.colorTable = colorTable;\n                end\n                obj.atlas = template.atlas;\n            end\n            if exist(obj.surfaces,'file'), delete(obj.surfaces);end\n            obj.surfaces = individualHeadModelFile;\n            save(obj.surfaces,'surfData');\n            try obj.statusbar(8);end %#ok\n            disp('Done!')\n        end\n       %%\n        function hFigureObj = plotOnModel(obj,J,V,figureTitle)\n            % Plots cortical/topographical maps onto the cortical/scalp surface.\n            % \n            % Input parameters:\n            %       J:           cortical map size number of vertices of the cortical surface by number of time points\n            %       V:           topographic map size number of vertices of the scalp surface by number of time points; \n            %                    if V is empty, a single color is used simulating the color of the skin \n            %       figureTitle: title of the figure (optional)\n            %                    \n            % Output argument:   \n            %       hFigure:     figure handle \n            \n            if nargin < 2, error('Not enough input arguments');end\n            if nargin < 3, V = [];end\n            if nargin < 4, figureTitle = '';end\n            if isa(obj,'pcdStream'), channelLabels = obj.parent.channelLabel;else channelLabels = obj.channelLabel;end\n            hFigureObj = currentSourceViewer(obj,J,V,figureTitle,channelLabels);\n        end\n       %%\n        function Aff = warpChannelSpace2Template(obj,headModelFile,individualHeadModelFile,regType)\n            % Estimates a mapping from channel space to a template's head. It uses Dirk-Jan Kroon's\n            % nonrigid_version23 toolbox.\n            %\n            % For more details see: http://www.mathworks.com/matlabcentral/fileexchange/20057-b-spline-grid-image-and-point-based-registration\n            %\n            % Input arguments:\n            %       headModelFile:           pointer to the template head model file. To see an example\n            %                                of templates see the folder mobilab/data/headModelXX.mat\n            %       individualHeadModelFile: pointer to the warped head model (output file)\n            %       regType:                 co-registration type, could be 'affine' or 'bspline'. In case\n            %                                of 'affine' only the affine mapping is estimated (rotation,\n            %                                traslation, and scaling). 'bspline' starts from the affine \n            %                                mapping and goes on to estimate a non-linear defformation\n            %                                field that captures better the shape of the head.\n            %\n            % Output arguments:\n            %       Aff: affine matrix\n            %\n            % References: \n            %    D. Rueckert et al. \"Nonrigid Registration Using Free-Form Deformations: Application to Breast MR Images\".\n            %    Seungyong Lee, George Wolberg, and Sung Yong Shing, \"Scattered Data interpolation with Multilevel B-splines\"\n\n            if nargin < 2, error('Reference head model is missing.');end\n            if nargin < 3, individualHeadModelFile = ['surfaces_' num2str(round(1e5*rand)) '.mat'];end\n            if nargin < 4, regType = 'bspline';end\n            if isempty(obj.channelSpace) || isempty(obj.label) || isempty(obj.fiducials), error('Channel space or fiducials are missing.');end\n            if ~exist(headModelFile,'file'), error('The file you''ve entered does not exist.');end\n                       \n            template = load(headModelFile);\n            surfData = template.surfData;\n            gTools = geometricTools;\n            th = norminv(0.90);\n            % mapping source to target spaces: S->T\n            % target space: template\n            T = [template.fiducials.nasion;...\n                template.fiducials.lpa;...\n                template.fiducials.rpa;...\n                template.fiducials.vertex];\n            \n            % source space: individual geometry\n            S = [obj.fiducials.nasion;...\n                obj.fiducials.lpa;...\n                obj.fiducials.rpa];\n            \n            % estimates vertex if is missing\n            if isfield(obj.fiducials,'vertex')\n                if numel(obj.fiducials.vertex) == 3\n                    S = [S;obj.fiducials.vertex];\n                else\n                    point = 0.5*(obj.fiducials.lpa + obj.fiducials.rpa);\n                    point = ones(50,1)*point;\n                    point(:,3) = linspace(point(3),1.5*max(obj.channelSpace(:,3)),50)';\n                    [~,d] = gTools.nearestNeighbor(obj.channelSpace,point);\n                    [~,loc] = min(d);\n                    point = point(loc,:);\n                    S = [S;point];\n                end\n            else\n                point = 0.5*(obj.fiducials.lpa + obj.fiducials.rpa);\n                point = ones(50,1)*point;\n                point(:,3) = linspace(point(3),1.5*max(obj.channelSpace(:,3)),50)';\n                [~,d] = gTools.nearestNeighbor(obj.channelSpace,point);\n                [~,loc] = min(d);\n                point = point(loc,:);\n                S = [S;point];\n            end\n            \n            if isfield(obj.fiducials,'inion')\n                if numel(obj.fiducials.vertex) == 3\n                    S = [S;obj.fiducials.inion];\n                    T = [T;template.fiducials.inion];\n                end\n            end\n            if isa(obj,'eeg')\n                obj.initStatusbar(1,8,'Co-registering...');\n            else\n                disp('Co-registering...');\n            end\n            \n            % affine co-registration\n            Aff = gTools.affineMapping(S,T);\n            if isa(obj,'eeg'), obj.statusbar(1);end\n            \n            obj.channelSpace = gTools.applyAffineMapping(obj.channelSpace,Aff);\n            obj.fiducials.lpa = gTools.applyAffineMapping(obj.fiducials.lpa,Aff);\n            obj.fiducials.rpa = gTools.applyAffineMapping(obj.fiducials.rpa,Aff);\n            obj.fiducials.nasion = gTools.applyAffineMapping(obj.fiducials.nasion,Aff);\n            \n            if ~strcmp(regType,'affine')\n                % b-spline co-registration (only fiducial landmarks)\n                options.Verbose = true;\n                options.MaxRef = 2;\n                Saff = gTools.applyAffineMapping(S,Aff);\n                [Def,spacing,offset] = gTools.bSplineMapping(Saff,T,obj.channelSpace,options);\n                if isa(obj,'eeg'), obj.statusbar(2);end\n                \n                % b-spline co-registration (second pass)\n                obj.channelSpace = gTools.applyBSplineMapping(Def,spacing,offset,obj.channelSpace);\n                obj.fiducials.lpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.lpa);\n                obj.fiducials.rpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.rpa);\n                obj.fiducials.nasion = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.nasion);\n                \n                T = template.surfData(1).vertices;\n                S = obj.channelSpace;\n                S(S(:,3) <= min(T(:,3)),:) = [];\n                [S,d] = gTools.nearestNeighbor(S,T);\n                z = zscore(d);\n                S(abs(z)>th,:) = [];\n                T(abs(z)>th,:) = [];\n                [Def,spacing,offset] = gTools.bSplineMapping(S,T,obj.channelSpace,options);\n                if isa(obj,'eeg'), obj.statusbar(3);end\n                \n                % b-spline co-registration (third pass)\n                obj.channelSpace = gTools.applyBSplineMapping(Def,spacing,offset,obj.channelSpace);\n                obj.fiducials.lpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.lpa);\n                obj.fiducials.rpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.rpa);\n                obj.fiducials.nasion = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.nasion);\n                \n                T = template.surfData(1).vertices;\n                S = obj.channelSpace;\n                S(S(:,3) <= min(T(:,3)),:) = [];\n                [S,d] = gTools.nearestNeighbor(S,T);\n                z = zscore(d);\n                S(abs(z)>th,:) = [];\n                T(abs(z)>th,:) = [];\n                Tm = 0.5*(T+S);\n                [Def,spacing,offset] = gTools.bSplineMapping(S,Tm,obj.channelSpace,options);\n                if isa(obj,'eeg'), obj.statusbar(4);end\n                \n                % apply the final transformation\n                obj.channelSpace = gTools.applyBSplineMapping(Def,spacing,offset,obj.channelSpace);\n                obj.fiducials.lpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.lpa);\n                obj.fiducials.rpa = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.rpa);\n                obj.fiducials.nasion = gTools.applyBSplineMapping(Def,spacing,offset,obj.fiducials.nasion);\n            end\n            \n            % fixing topological defects\n            if isa(obj,'eeg')\n                obj.statusbar.setText('Fixing topological defects...');\n            else\n                disp('Fixing topological defects...');\n            end\n            Ns = length(surfData);\n            dmax = ones(Ns-1,1)*5;\n            dmax(1) = 8;\n            ind = fliplr(1:Ns);\n            for it=1:Ns-1\n                surfData(ind(it+1)).vertices = gTools.repareIntersectedSurface(surfData(ind(it)),surfData(ind(it+1)),dmax(it));\n                if isa(obj,'eeg'), obj.statusbar(it+5);end\n            end\n            \n            ind =  obj.channelSpace(:,3) > min(surfData(1).vertices(:,3));\n            T = gTools.nearestNeighbor(surfData(1).vertices,obj.channelSpace);\n            channelSpace = obj.channelSpace; %#ok\n            channelSpace(ind,:) = T(ind,:);  %#ok\n            [~,loc] = unique(channelSpace,'rows');%#ok\n            indInterp = setdiff(1:size(obj.channelSpace,1),loc);\n            if ~isempty(indInterp)\n                x = setdiff(channelSpace,channelSpace(indInterp,:),'rows');%#ok\n                xi = gTools.nearestNeighbor(x,channelSpace(indInterp,:));%#ok\n                channelSpace(indInterp,:) = 0.5*(xi + channelSpace(indInterp,:));%#ok\n            end\n            obj.channelSpace = channelSpace; %#ok\n            \n            if isfield(template,'atlas'), obj.atlas = template.atlas;end\n            if exist(obj.surfaces,'file'), delete(obj.surfaces);end\n            obj.surfaces = individualHeadModelFile;\n            save(obj.surfaces,'surfData');\n            if isa(obj,'eeg'), obj.statusbar(8);end\n        end\n       %%\n        function computeLeadFieldBEM(obj, conductivity,orientation)\n            % Computes the lead field matrix interfacing OpenMEEG toolbox [1].\n            %\n            % Input arguments:\n            %       conductivity: conductivity of each layer of tissue, scalp - skull - brain,\n            %                     default: 0.33-0.022-0.33 S/m. See [2, 3, 4] for details.\n            %        orientation: if true, computes the orientation free lead field, otherwise\n            %                     it constrain the dipoles to be normal to the cortical surface\n            %\n            % The computed lead field is stored inside the object in obj.leadFieldFile.\n            %\n            % References:\n            %   [1] Gramfort, A., Papadopoulo, T., Olivi, E., & Clerc, M. (2010).\n            %         OpenMEEG: opensource software for quasistatic bioelectromagnetics.\n            %         Biomedical engineering online, 9, 45. doi:10.1186/1475-925X-9-45\n            %   [2] Vald??s-Hern??ndez, P.A., Von Ellenrieder, N., Ojeda-Gonzalez, A., Kochen, S.,\n            %         Alem??n-G??mez, Y., Muravchik, C., & A Vald??s-Sosa, P. (2009). Approximate\n            %         average head models for EEG source imaging. Journal of Neuroscience Methods,\n            %         185(1), 125???132.\n            %   [3] Wendel, K., Malmivuo, J., 2006. Correlation between live and post mortem skull\n            %         conductivity measurements. Conf Proc IEEE Eng Med Biol Soc 1, 4285-4288.\n            %   [4] Oostendorp, T.F., Delbeke, J., Stegeman, D.F., 2000. The conductivity of the \n            %         human skull: Results of in vivo and in vitro measurements. Ieee Transactions\n            %         on Biomedical Engineering 47, 1487-1492.\n                        \n            dispCommand = false;\n            if nargin < 2, conductivity = [0.33 0.022 0.33];end\n            if nargin < 3, orientation = true;end\n            if isempty(obj.channelSpace) || isempty(obj.label) || isempty(obj.surfaces);\n                error('Head model is incomplete or missing.');\n            end\n            if any(conductivity == -1)\n                prefObj = [...\n                    PropertyGridField('conductivity',[0.33 0.022 0.33],'DisplayName','Conductivity','Description',sprintf('Conductivity values are taken from Valdes-Hernandez et al., 2006, check \\nalso Oostendrop TF, 2000; Wendel and Malmivuo, 2006. \\nbrain and scalp: 0.33 S/m\\nskull: 0.022 S/m'))...\n                    PropertyGridField('orientation',true,'DisplayName','Orientation free','Description','If true, computes the LF matrix with orientation free dipoles, resulting in a matris Nsensors X 3*Nvertices. If false the LF matrix is computed with dipoles normal to the cortical surface, then the size would be Nsensors X Nvertices')...\n                    ];\n                hFigure = figure('MenuBar','none','Name','OpenMEEG solver','NumberTitle', 'off','Toolbar', 'none','Units','pixels','Color',obj.container.container.preferences.gui.backgroundColor,...\n                    'Resize','off','userData',0);\n                position = get(hFigure,'position');\n                set(hFigure,'position',[position(1:2) 303 250]);\n                hPanel = uipanel(hFigure,'Title','','BackgroundColor','white','Units','pixels','Position',[0 55 303 175],'BorderType','none');\n                g = PropertyGrid(hPanel,'Properties', prefObj,'Position', [0 0 1 1]);\n                uicontrol(hFigure,'Position',[72 15 70 21],'String','Cancel','ForegroundColor',obj.container.container.preferences.gui.fontColor,...\n                    'BackgroundColor',obj.container.container.preferences.gui.buttonColor,'Callback',@cancelCallback);\n                uicontrol(hFigure,'Position',[164 15 70 21],'String','Ok','ForegroundColor',obj.container.container.preferences.gui.fontColor,...\n                    'BackgroundColor',obj.container.container.preferences.gui.buttonColor,'Callback',@okCallback);\n                uiwait(hFigure);\n                if ~ishandle(hFigure), return;end\n                if ~get(hFigure,'userData'), close(hFigure);return;end\n                close(hFigure);\n                drawnow;\n                val = g.GetPropertyValues();\n                conductivity = val.conductivity;\n                orientation = val.orientation;\n                dispCommand = true;\n            end\n            \n            if dispCommand\n                disp('Running:');\n                if isa(obj,'coreStreamObject')\n                    itemIndex = obj.container.findItem(obj.uuid);\n                    fprintf('  mobilab.allStreams.item{%i}.computeLeadFieldBEM( [ %i %i %i ], %i );\\n',itemIndex,conductivity(1),conductivity(2),conductivity(3),orientation);\n                else fprintf('  obj.computeLeadFieldBEM( [ %i %i %i ], %i );\\n',conductivity(1),conductivity(2),conductivity(3),orientation);\n                end\n            end\n            \n            if ~exist(obj.surfaces,'file'), error('The file containing the surfaces is missing.');end\n            status = system('which om_assemble');\n            existOM = ~status;\n            if ~existOM\n                try\n                    mobilab = evalin('base','mobilab');\n                    mobilabPath = mobilab.path;\n                catch\n                    mobilabPath = which('mobilabApplication');\n                    if ~isempty(mobilabPath), mobilabPath = fileparts(mobilabPath);\n                    else error('OpenMEEG is not intalled. Please download and install the sources you need from https://gforge.inria.fr/frs/?group_id=435.');\n                    end\n                end\n                openmeegDir = [mobilabPath filesep 'dependency' filesep 'openmeeg'];\n                \n                %---\n                % Approach taken from Brainstorm's function bst_openmeeg,\n                % Francois Tadel & Alexandre Gramfort, 2011\n                %---\n                if ~ispc\n                    if ismember(computer, {'GLNX86','GLNXA64'}), varname = 'LD_LIBRARY_PATH';\n                    else varname = 'DYLD_LIBRARY_PATH';\n                    end\n                    libpath = getenv(varname);\n                    if ~isempty(libpath), libpath = [libpath ':'];end\n                    if isempty(strfind(lower(libpath),'openmeeg')), setenv(varname, [libpath openmeegDir]);end\n                end\n                % Set number of cores used\n                try numcores = feature('numcores');\n                catch\n                    numcores = 4;\n                end\n                setenv('OMP_NUM_THREADS', num2str(numcores));\n                %---\n            end\n            \n            load(obj.surfaces);\n            Ns = length(surfData); %#ok\n            gTools = geometricTools;            \n            rootDir = fileparts(obj.surfaces);\n            if isempty(rootDir), rootDir = pwd;end\n            binDir = fileparts(which('libmatio.a'));\n            [~,rname] = fileparts(tempname);\n            headModelGeometry = fullfile(rootDir,[rname '.geom']);\n            try %#ok\n                copyfile( which('head_model.geom'),headModelGeometry,'f');\n                c1 = onCleanup(@()delete(headModelGeometry));\n            end\n            \n            headModelConductivity = fullfile(rootDir,[rname '.cond']);\n            fid = fopen(headModelConductivity,'w');\n            fprintf(fid,'# Properties Description 1.0 (Conductivities)\\n\\nAir         0.0\\nScalp       %.3f\\nBrain       %0.3f\\nSkull       %0.3f',...\n                conductivity(1),conductivity(3),conductivity(2));\n            fclose(fid);\n            c2 = onCleanup(@()delete(headModelConductivity));\n            \n            dipolesFile = fullfile(rootDir,[rname '_dipoles.txt']);\n            normalsIn = false;\n            [normals,surfData(Ns).faces] = gTools.getSurfaceNormals(surfData(Ns).vertices,surfData(Ns).faces,normalsIn);\n            \n            normalityConstrained = ~orientation;\n            if normalityConstrained, sourceSpace = [surfData(Ns).vertices normals];\n            else One = ones(length(normals(:,2)),1);\n                Zero = 0*One;\n                sourceSpace = [surfData(Ns).vertices One Zero Zero;...\n                    surfData(Ns).vertices Zero One Zero;...\n                    surfData(Ns).vertices Zero Zero One];\n            end\n            dlmwrite(dipolesFile, sourceSpace, 'precision', 6,'delimiter',' ')\n            c3 = onCleanup(@()delete(dipolesFile));\n            \n            electrodesFile = fullfile(rootDir,[rname '_elec.txt']);\n            dlmwrite(electrodesFile, obj.channelSpace, 'precision', 6,'delimiter',' ')\n            c4 = onCleanup(@()delete(electrodesFile));\n            \n            normalsIn = true;\n            brain = fullfile(rootDir,'brain.tri');\n            if Ns == 4\n                [normals,surfData(3).faces] = gTools.getSurfaceNormals(surfData(3).vertices,surfData(3).faces,normalsIn);\n                om_save_tri(brain,surfData(3).vertices,surfData(3).faces,normals)\n            else\n                [normals,surfData(2).faces] = gTools.getSurfaceNormals(surfData(2).vertices,surfData(2).faces,normalsIn);\n                csfSurf = surfData(2);\n                csfSurf.vertices     = surfData(2).vertices + 1.05*normals;\n                surfData(2).vertices = surfData(2).vertices - 1.05*normals;\n                csfSurf.vertices     = gTools.repareIntersectedSurface(surfData(end),csfSurf,1);\n                surfData(2).vertices = gTools.repareIntersectedSurface(csfSurf,surfData(2),2);\n                surfData(1).vertices = gTools.repareIntersectedSurface(surfData(2),surfData(1),2);\n                [normals,csfSurf.faces] = gTools.getSurfaceNormals(csfSurf.vertices,csfSurf.faces,normalsIn);\n                om_save_tri(brain,csfSurf.vertices,csfSurf.faces,normals)\n            end\n            c5 = onCleanup(@()delete(brain));\n            \n            skull = fullfile(rootDir,'skull.tri');\n            [normals,surfData(2).faces] = gTools.getSurfaceNormals(surfData(2).vertices,surfData(2).faces,normalsIn);\n            om_save_tri(skull,surfData(2).vertices,surfData(2).faces,normals)\n            c6 = onCleanup(@()delete(skull));\n            \n            head = fullfile(rootDir,'head.tri');\n            [normals,surfData(1).faces] = gTools.getSurfaceNormals(surfData(1).vertices,surfData(1).faces,normalsIn);\n            om_save_tri(head,surfData(1).vertices,surfData(1).faces,normals)\n            c7 = onCleanup(@()delete(head));\n            \n            hmFile    = fullfile(rootDir,'hm.bin');    c8  = onCleanup(@()delete(hmFile));\n            hmInvFile = fullfile(rootDir,'hm_inv.bin');c9  = onCleanup(@()delete(hmInvFile));\n            dsmFile   = fullfile(rootDir,'dsm.bin');   c10 = onCleanup(@()delete(dsmFile));\n            h2emFile  = fullfile(rootDir,'h2em.bin');  c11 = onCleanup(@()delete(h2emFile));\n            lfFile    = fullfile(rootDir,[rname '_LF.mat']);\n            \n            if ~existOM\n                runHere = './';\n                wDir = pwd;\n                cd(binDir);\n            else runHere = '';\n            end\n            try\n                out = system([runHere 'om_assemble -HM \"' headModelGeometry '\" \"' headModelConductivity '\" \"' hmFile '\"']);\n                if out, error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n                \n                out = system([runHere 'om_minverser \"' hmFile '\" \"' hmInvFile '\"']);\n                if out, error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n                \n                out = system([runHere 'om_assemble -DSM \"' headModelGeometry '\" \"' headModelConductivity '\" \"' dipolesFile '\" \"' dsmFile '\"']);\n                if out, error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n                \n                out = system([runHere 'om_assemble -H2EM \"' headModelGeometry '\" \"' headModelConductivity '\" \"' electrodesFile '\" \"' h2emFile '\"']);\n                if out, error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n                \n                out = system([runHere 'om_gain -EEG \"' hmInvFile '\" \"' dsmFile '\" \"' h2emFile '\" \"' lfFile '\"']);\n                if out, error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n            catch ME\n                if strcmp(pwd,binDir), cd(wDir);end\n                ME.rethrow;\n            end\n            if strcmp(pwd,binDir), cd(wDir);end\n            if ~exist(lfFile,'file'), error('An unexpected error occurred running OpenMEEG binaries. Report this to alejandro@sccn.ucsd.edu');end\n                        \n            load(lfFile);\n            K = linop;\n            clear linop;\n            \n            %-- Remove extreme values due to numerical instability\n            z = zscore(K(:));\n            a = 0.00001;\n            ind = find(z<norminv(a) | z>norminv(1-a));\n            ind_i = setdiff(1:numel(K),ind);\n            K(ind) = interp1(ind_i,K(ind_i),ind,'nearest','extrap');\n            %--\n            \n            if exist(lfFile,'file'), delete(lfFile);end\n            if exist(obj.leadFieldFile,'file'), delete(obj.leadFieldFile);end\n            if isa(obj,'coreStreamObject'), lfFile = fullfile(obj.container.mobiDataDirectory,['lf_' obj.name '_' obj.uuid '_' obj.sessionUUID '.mat']);end\n            obj.leadFieldFile = lfFile;\n            save(obj.leadFieldFile,'K');\n            if isa(obj,'coreStreamObject'), saveProperty(obj,'leadFieldFile',obj.leadFieldFile);end\n            disp('Done.')\n        end\n       %%\n        function [sourceSpace,K,L,rmIndices] = getSourceSpace4PEB(obj,structName, rmIndices)\n            if isempty(obj.surfaces) || isempty(obj.leadFieldFile), error('Head model or leadfield are missing.');end\n            if nargin < 2\n                structName = {'Thalamus_L' 'Thalamus_R'};\n                disp('Undefined structure to remove. Opening the surface by the Thalamus.')\n            end\n            if nargin < 3, rmIndices = [];end\n            maxNumVertices2rm = 10;\n            load(obj.surfaces,'-mat');\n            sourceSpace = surfData(end); %#ok\n            load(obj.leadFieldFile,'-mat');\n            if ~exist('L','var'),\n                disp('Computing the Laplacian operator...')\n                L = geometricTools.getSurfaceLaplacian(sourceSpace.vertices,sourceSpace.faces);\n                save(obj.leadFieldFile,'K','L','-mat')\n            end\n            \n            try \n                [sourceSpace,rmIndices] = obj.removeStructureFromSourceSpace(structName,maxNumVertices2rm, rmIndices);\n            catch ME\n                warning(ME.message);\n                disp('Doing my best to open the surface.')\n                n = size(sourceSpace.vertices,1);\n                rmIndices = fix(n/2)-maxNumVertices2rm/2:fix(n/2)+maxNumVertices2rm/2;\n            end\n            dim = size(K); %#ok\n            L(rmIndices,:) = [];\n            L(:,rmIndices) = [];\n            if dim(2)/3 == size(surfData(end).vertices,1) %#ok\n                K = reshape(K,[dim(1) dim(2)/3 3]);\n                K(:,rmIndices,:) = [];\n                % K = permute(K,[1 3 2]);\n                K = reshape(K,[dim(1) (dim(2)/3-length(rmIndices))*3]);\n                L = kron(eye(3),L);\n            else\n                K(:,rmIndices) = [];\n            end\n        end\n       %%\n        function indices = indices4Structure(obj,structName)\n            if nargin < 2, error('Not enough input arguments.');end\n            ind = find(ismember(obj.atlas.label,structName));\n            if isempty(ind), error('MoBILAB:noStructureMatched','The structure you want to remove is not defined in this atlas.');end\n            indices = bsxfun(@eq,obj.atlas.colorTable,ind');\n        end\n       %%\n        function xyz = getCentroidROI(obj,ROInames)\n            if nargin < 2, error('Not enough input arguments.');end\n            if isempty(obj.atlas) || isempty(obj.surfaces), error('Head model or atlas are missing.');end\n            if ~iscell(ROInames), ROInames = {ROInames}; end\n            N = length((ROInames));\n            xyz = nan(N,3);\n            load(obj.surfaces);\n            for it=1:N\n                try indices = obj.indices4Structure(ROInames{it});\n                    xyz(it,:) = mean(surfData(end).vertices(indices,:));\n                end\n            end\n        end\n       %%\n        function [FP,S] = getForwardProjection(obj,xyz)\n            if nargin < 2, error('Not enough input arguments.');end\n            if isempty(obj.atlas) || isempty(obj.surfaces), error('Head model or atlas are missing.');end\n            if ~exist(obj.surfaces,'file'), error('Head model is missing.');end\n            if isempty(obj.leadFieldFile), error('Lead field is missing.');end\n            if ~exist(obj.leadFieldFile,'file'), error('Lead field is missing.');end\n            load(obj.leadFieldFile);\n            if ~exist('K','var'), error('Lead field is missing.');end\n            \n            load(obj.surfaces);\n            [~,~,loc] = geometricTools.nearestNeighbor(surfData(end).vertices,xyz);\n            dim = size(K);\n            if size(surfData(end).vertices,1) == dim(2)/3, K = reshape(K,[dim(1) dim(2)/3 3]);end\n            FP = sum(K(:,loc,:),3);\n            S = geometricTools.simulateGaussianSource(surfData(end).vertices,xyz,0.01);\n        end\n       %%\n        function hFigureObj = plotDipoles(obj,xyz,ecd,dipoleLabel,figureTitle)\n            if nargin < 2, error('Not enough input arguments.');end\n            if isempty(obj.surfaces), error('Head model is missing.');end\n            N = size(xyz,1);\n            if nargin < 3, ecd = 3*ones(N,3);end\n            if isempty(ecd), ecd = 3*ones(N,3);end\n            if nargin < 4, dipoleLabel = [];end\n            if nargin < 5, figureTitle = '';end\n            hFigureObj = equivalentCurrentDipoleViewer(obj,xyz,ecd,dipoleLabel,figureTitle);\n        end\n        function hFigureObj = plotDipolesForwardProjection(obj,xyz,figureTitle)\n            [FP,S] = getForwardProjection(obj,xyz);\n            hFigureObj = obj.plotOnModel(S,FP);\n        end\n       %%\n        function [sourceSpace,rmIndices] = removeStructureFromSourceSpace(obj,structName,maxNumVertices2rm, structIndices)\n            if isempty(obj.atlas) || isempty(obj.surfaces), error('Head model or atlas are missing.');end\n            if nargin < 2, error('Not enough input arguments.');end\n            if nargin < 3, maxNumVertices2rm = [];end\n            if nargin < 4, structIndices = [];end\n            if ~iscell(structName), structName = {structName}; end\n            \n            load(obj.surfaces,'-mat');\n            sourceSpace = surfData(end);%#ok\n            \n            tmpIndices = indices4Structure(obj,structName);\n            if ~any(tmpIndices(:)) && isempty(structIndices),\n                error('The structure you want to remove is not defined in this atlas.');\n            end\n            \n            if ~isempty(structIndices)\n                % concatenate elements of structIndices into a single column vector\n                structIndices = cellfun(@(x)x(:),structIndices,'UniformOutput',false)';\n                structIndices = cell2mat(structIndices);\n            end\n            if ~isempty(maxNumVertices2rm) && any(sum(tmpIndices) > maxNumVertices2rm+1)\n                I = [];\n                maxNumVertices2rm = fix(maxNumVertices2rm/size(tmpIndices,2));\n                for it=1:size(tmpIndices,2)\n                    ind = find(tmpIndices(:,it));\n                    if length(ind) > maxNumVertices2rm\n                        I = [I; ind(1:maxNumVertices2rm)];\n                    else\n                        I = [I; ind];\n                    end\n                end\n                tmpIndices = I;\n            end\n            rmIndices = unique_bc([tmpIndices(:) ; structIndices]);\n            \n            [nVertices,nFaces] = geometricTools.openSurface(sourceSpace.vertices,sourceSpace.faces,rmIndices);\n            sourceSpace.vertices = nVertices;\n            sourceSpace.faces = nFaces;\n        end\n       %%\n        function saveToFile(obj,file)\n            metadata = struct(obj);\n            if exist(metadata.surfaces,'file')\n                metadata.surfData = load(metadata.surfaces);\n            else metadata.surfData = [];\n            end\n            if exist(metadata.leadFieldFile,'file')\n                metadata.leadField = load(metadata.leadFieldFile);\n            else metadata.leadField = []; %#ok\n            end\n            save(file,'metadata','-mat');\n        end\n        function delete(obj)\n            if exist(obj.surfaces,'file')\n                [~,filename] = fileparts(obj.surfaces);\n                if filename(1) == '.', delete(obj.surfaces);end\n            end\n            if exist(obj.leadFieldFile,'file')\n                [~,filename] = fileparts(obj.leadFieldFile);\n                if filename(1) == '.', delete(obj.leadFieldFile);end\n            end\n        end\n    end\n    methods(Static)\n        function obj = loadFromFile(file)\n            metadata = load(file,'-mat');\n            if isfield(metadata,'metadata')\n                metadata = metadata.metadata;\n            end\n            if ~isempty(metadata.surfData)\n                surfData = metadata.surfData;\n                if isfield(surfData,'surfData'), surfData = surfData.surfData;end%#ok\n                % [~,filename] = fileparts(tempname);\n                % metadata.surfaces = [getHomeDir filesep '.' filename '.mat'];\n                metadata.surfaces = [tempname '.mat'];\n                save(metadata.surfaces,'surfData');\n            end\n            if isfield(metadata,'leadField') && ~isempty(metadata.leadField)\n                % [~,filename] = fileparts(tempname);\n                % metadata.leadFieldFile = [getHomeDir filesep '.' filename '.mat'];\n                metadata.leadFieldFile = [tempname '.mat'];\n                if isfield(metadata.leadField,'K')\n                    K = metadata.leadField.K; %#ok\n                else\n                    K = metadata.leadField; %#ok\n                end\n                if isfield(metadata.leadField,'L')\n                    L = metadata.leadField.L; %#ok\n                    save(metadata.leadFieldFile,'K','L');\n                else save(metadata.leadFieldFile,'K');\n                end\n            else\n                metadata.leadFieldFile = [];\n            end\n            obj = headModel('channelSpace',metadata.channelSpace,'fiducials',metadata.fiducials,'surfaces',metadata.surfaces,...\n                'atlas',metadata.atlas,'leadFieldFile',metadata.leadFieldFile,'label',metadata.label);\n        end\n    end\nend\n\n%--\nfunction [elec,labels,fiducials] = readMontage(file)\n[eloc, labels] = readlocs(file);\nelec = [cell2mat({eloc.X}'), cell2mat({eloc.Y}'), cell2mat({eloc.Z}')];\nNl = length(labels);\ncount = 1;\nlowerLabels = lower(labels);\nrmThis = false(Nl,1);\nfor it=1:Nl\n    if ~isempty(strfind(lowerLabels{it},'fidnz')) || ~isempty(strfind(lowerLabels{it},'nasion')) || ~isempty(strfind(lowerLabels{it},'Nz'))\n        fiducials.nasion = elec(it,:);\n        rmThis(it) = true;\n        count = count+1;\n    elseif ~isempty(strfind(lowerLabels{it},'fidt9')) || ~isempty(strfind(lowerLabels{it},'lpa')) || ~isempty(strfind(lowerLabels{it},'LPA'))\n        fiducials.lpa = elec(it,:);  \n        rmThis(it) = true;\n        count = count+1;\n    elseif ~isempty(strfind(lowerLabels{it},'fidt10')) || ~isempty(strfind(lowerLabels{it},'rpa')) || ~isempty(strfind(lowerLabels{it},'RPA'))\n        fiducials.rpa = elec(it,:);\n        rmThis(it) = true;\n        count = count+1;\n    elseif ~isempty(strfind(lowerLabels{it},'fidt10')) || ~isempty(strfind(lowerLabels{it},'vertex'))\n        fiducials.vertex = elec(it,:);\n        rmThis(it) = true;\n        count = count+1;\n    end\n    if count > 4, break;end\nend\nelec(rmThis,:) = [];\nlabels(rmThis) = [];\nend\n\n\n%% unique_bc - unique backward compatible with Matlab versions prior to 2013a\nfunction [C,IA,IB] = unique_bc(A,varargin);\n\nerrorFlag = error_bc;\n\nv = version;\nindp = find(v == '.');\nv = str2num(v(1:indp(2)-1));\nif v > 7.19, v = floor(v) + rem(v,1)/10; end;\n\nif nargin > 2\n    ind = strmatch('legacy', varargin);\n    if ~isempty(ind)\n        varargin(ind) = [];\n    end;\nend;\n\nif v >= 7.14\n    [C,IA,IB] = unique(A,varargin{:},'legacy');\n    if errorFlag\n        [C2,IA2] = unique(A,varargin{:});\n        if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)\n            warning('backward compatibility issue with call to unique function');\n        end;\n    end;\nelse\n    [C,IA,IB] = unique(A,varargin{:});\nend\nend\n\n%% ismember_bc - ismember backward compatible with Matlab versions prior to 2013a\nfunction [C,IA] = ismember_bc(A,B,varargin);\n\nerrorFlag = error_bc;\n\nv = version;\nindp = find(v == '.');\nv = str2num(v(1:indp(2)-1));\nif v > 7.19, v = floor(v) + rem(v,1)/10; end;\n\nif nargin > 2\n    ind = strmatch('legacy', varargin);\n    if ~isempty(ind)\n        varargin(ind) = [];\n    end;\nend;\n\nif v >= 7.14\n    [C,IA] = ismember(A,B,varargin{:},'legacy');\n    if errorFlag\n        [C2,IA2] = ismember(A,B,varargin{:});\n        if (~isequal(C, C2) || ~isequal(IA, IA2))\n            warning('backward compatibility issue with call to ismember function');\n        end;\n    end;\nelse\n    [C,IA] = ismember(A,B,varargin{:});\nend\nend\n\n%%\nfunction res = error_bc\nres = false;\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/MoBILAB/headModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.24752149926240472}}
{"text": "function model = vargplvmModelInit(model, globalOpt)\n\n% VARGPLVMMODELINIT Initialise a vargplvm model given global demo options\n% COPYRIGHT: Andreas C. Damianou, 2012\n% SEEALSO: vargplvmCreate\n% VARGPLVM\n\n%if globalOpt.DgtN\n   % model.mOrig = model.m;\n%    model = vargplvmParamInit(model, model.mOrig, model.X);\n%else\n    model = vargplvmParamInit(model, model.y, model.X);\n%end\n\n% Lengthscales\nif strcmp(model.kern.type, 'rbfardjit')\n    model.kern.inputScales = globalOpt.invWidthMult./(((max(model.X)-min(model.X))).^2); % Default 5\nelse\n    model.kern.comp{1}.inputScales = globalOpt.invWidthMult./(((max(model.X)-min(model.X))).^2); % Default 5\nend\n\n\n\nmodel.vardist.covars = 0.5*ones(size(model.vardist.covars)) + 0.001*randn(size(model.vardist.covars));\n%model.kern.comp{1}.variance = max(var(Y)); %%%\n\n\n\nif model.N > 50 && globalOpt.enableParallelism\n    fprintf('# Parallel computations w.r.t the datapoints!\\n');\n    model.vardist.parallel = 1;\nend\n\n%%%\nif ~isfield(globalOpt, 'beta') || isempty(globalOpt.betaInit)\n    if model.DgtN\n        model.beta = 1/((1/globalOpt.initSNR * var(model.mOrig(:))));\n    else\n        model.beta = 1/((1/globalOpt.initSNR * var(model.m(:))));\n    end\nelse\n    model.beta = globalOpt.betaInit;\nend\n\nif model.beta < 1e-7\n    warning('Beta was too small... Setting beta to 1e-7')\n    model.beta = 1e-7;\nelseif model.beta > 1e+7\n    warning('Beta was too big... Setting beta to 1e+7')\n    model.beta = 1e+7;\nend\n\n% Check for inconsistencies\nif isfield(model, 'dynamics') && ~isempty(model.dynamics)\n    if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise\n        if isfield(model, 'fixInducing') && model.fixInducing\n            msg = sprintf('Reoptimising inducing points for test and fixing ind. points are incompatible!\\nSetting reoptimising to false.');\n            warning(msg);\n            model.dynamics.reoptimise = false;\n            globalOpt.testReoptimise = false;\n        end\n    end\nend\n\n\nmodel.dataSetInfo.dataSetName = globalOpt.dataSetName;\n\nparams = vargplvmExtractParam(model);\nmodel = vargplvmExpandParam(model, params);\n\nmodel.date = date;\nmodel.globalOpt = globalOpt;\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/vargplvmModelInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.247459429932631}}
{"text": "function strDate = str_date(s, dateFormat)\n% STR_Date: Reformat date string to dd-MMM-yyyy.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2018\n\n% Parse inputs\nif (nargin < 2) || isempty(dateFormat)\n    dateFormat = [];\nend\n% Clean string\nif ischar(s)\n    s = strtrim(strrep(s, char(0), ''));\nend\n% Check various input formats\ntry\n    if ~isempty(dateFormat) && strcmpi(dateFormat, 'posix')\n        strDate = datestr(double(s) ./ 86400 + datenum(1970,1,1,0,0,0), 'dd-mmm-yyyy');\n    elseif ~isempty(dateFormat)\n        strDate = datestr(datenum(s, dateFormat), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '/'), [3 6]) && ((length(s) == 10) || (length(s) == 19))\n        strDate = datestr(datenum(s, 'dd/mm/yyyy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '/'), [3 6]) && ((length(s) == 8) || (length(s) == 17))\n        strDate = datestr(datenum(s, 'dd/mm/yy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '.'), [3 6]) && ((length(s) == 10) || (length(s) == 19))\n        strDate = datestr(datenum(s, 'dd.mm.yyyy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '.'), [3 6]) && ((length(s) == 8) || (length(s) == 17))\n        strDate = datestr(datenum(s, 'dd.mm.yy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '-'), [3 6]) && ((length(s) == 10) || (length(s) == 19))\n        strDate = datestr(datenum(s, 'dd-mm-yyyy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '-'), [3 7]) && (length(s) == 11)\n        strDate = datestr(datenum(s, 'dd-mmm-yyyy'), 'dd-mmm-yyyy');\n    elseif isequal(find(s == '-'), [5 8]) && ((length(s) == 10) || (length(s) == 19))\n        strDate = datestr(datenum(s, 'yyyy-mm-dd'), 'dd-mmm-yyyy');\n    else\n        strDate = [];\n    end\ncatch\n    strDate = [];\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/misc/str_date.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24745942993263098}}
{"text": "function [ fHdl ] = plot( obj, subjects )\n% Plot cluster and subject-level estimation result from HUGE model.\n% \n% INPUTS:\n%   obj - A tapas_Huge object containing estimation results.\n% \n% OPTIONAL INPUTS:\n%   subjects - A vector containing indices of subjects for which to plot\n%              detailed results.\n% \n% OUTPUTS:\n%   fHdl - Handle of first figure.\n% \n% See also tapas_Huge.ESTIMATE\n% \n\n% Author: Yu Yao (yao@biomed.ee.ethz.ch)\n% Copyright (C) 2019 Translational Neuromodeling Unit\n%                    Institute for Biomedical Engineering,\n%                    University of Zurich and ETH Zurich.\n% \n% This file is part of TAPAS, which is released under the terms of the GNU\n% General Public Licence (GPL), version 3. For further details, see\n% <https://www.gnu.org/licenses/>.\n% \n% This software is provided \"as is\", without warranty of any kind, express\n% or implied, including, but not limited to the warranties of\n% merchantability, fitness for a particular purpose and non-infringement.\n% \n% This software is intended for research only. Do not use for clinical\n% purpose. Please note that this toolbox is under active development.\n% Considerable changes may occur in future releases. For support please\n% refer to:\n% https://github.com/translationalneuromodeling/tapas/issues\n% \n\n\nif nargout > 0\n    fHdl = figure( );\nelse\n    figure( );\nend\nif nargin < 2\n    subjects = [];\nend\n\ntickLabels = obj.parse_labels( obj.dcm, obj.labels, obj.idx );\n\n%% assignments/boxplot\n% figure;\nif obj.K > 1\n    % subject assignment\n    bar(obj.posterior.q_nk,'stacked');\n    axis([0 obj.N+1 0 1])\n    title('assignments')\n    ylabel('q_{nk}')\n    xlabel('subject index')\n    title('Assignment');\nelse\n    % boxplot of MAP estimates of DCM parameters\n    hold on\n    line([0 obj.idx.P_c + obj.idx.P_h], [0 0], 'color', 'k')\n    boxplot(obj.posterior.mu_n)\n    ylabel('\\mu_n')\n    title('Empirical Bayes');\n    set(gca,'XTick',1:obj.idx.P_c + obj.idx.P_h, 'XTickLabelRotation', 60, ...\n        'XTickLabel', tickLabels, 'TickLabelInterpreter', 'none');\nend\n\n%% cluster\nfigure\nhold on\n% plot posterior cluster mean and 95% marginal credible intervals\nlegends = cell(obj.K,1);\nfor k = 1:obj.K\n    xOffset = ((k-1)/max(1,(obj.K-1)) - .5)/4;\n    switch obj.posterior.method\n        case 'VB'\n            clMean = obj.posterior.m(k,:);\n            clStd = sqrt(diag(obj.posterior.S(:,:,k))'/...\n                (obj.posterior.tau(k)*...\n                (obj.posterior.nu(k) - obj.idx.P_c + 1)));\n            s = tinv(1-0.025, obj.posterior.nu(k));\n            errorbar((1:obj.idx.P_c) + xOffset, clMean, s*clStd, 'd');\n        case 'MH'\n            clMean = obj.posterior.mean.mu(k,:);\n            [~,i1] = min(abs(obj.posterior.quantile.levels - .025));\n            [~,i2] = min(abs(obj.posterior.quantile.levels - .975));\n            neg = clMean - obj.posterior.quantile.mu(k,:,i1);\n            pos = obj.posterior.quantile.mu(k,:,i2) - clMean;\n            errorbar((1:obj.idx.P_c) + xOffset, clMean, neg, pos, 'd');\n    end\n    legends{k} = ['cluster ' num2str(k)];\nend\nline([0 obj.idx.P_c+1], [0 0], 'color', 'k')\nxlim([0 obj.idx.P_c+1])\nylabel('\\mu_k')\nset(gca,'XTick',1:obj.idx.P_c, 'XTickLabelRotation', 60, ...\n    'XTickLabel', tickLabels(1:obj.idx.P_c), 'TickLabelInterpreter', 'none');\nlegend(legends)\ntitle('Clusters')\n\n%% DCM\n% plot 25 samples from posterior over (noise free) BOLD response \nnSmp = 25;\nfor n = subjects(:)'\n    figure\n    hold on\n    % draw samples from posterior over DCM parameters\n    switch obj.posterior.method\n        case 'VB'\n            postMean = obj.posterior.mu_n(n,:);\n            postStd = chol(obj.posterior.Sigma_n(:,:,n));\n            postSmp = randn(nSmp,obj.idx.P_c + obj.idx.P_h);\n            postSmp = bsxfun(@plus, postSmp*postStd, postMean);\n        case 'MH'\n            nTrace = length(obj.trace.smp);\n            nSmp = min(nSmp, nTrace);\n            idx = randsample(nTrace, nSmp);\n            tmp = [reshape([obj.trace.smp(idx).theta_c], obj.N, obj.idx.P_c, []), ...\n                reshape([obj.trace.smp(idx).theta_h], obj.N, obj.idx.P_h, [])];\n            postSmp = permute(tmp(n,:,:), [3 2 1]);\n    end\n    legends = {'measured'};\n    plot(obj.data(n).bold(:),'k')\n    % plot ground truth if available\n    if ~isempty(obj.model)\n        [ ~, epsilon ] = obj.gen_bold( n, obj.model.theta(n,:) );\n        plot(obj.data(n).bold(:) - epsilon(:),'r')\n        legends = [legends, {'ground truth'}]; %#ok<AGROW>\n    end\n    legends = [legends ,{'posterior samples'}]; %#ok<AGROW>\n    for iSmp = 1:nSmp\n        [ ~, epsilon ] = obj.gen_bold( n, postSmp(iSmp,:) );\n        plot(obj.data(n).bold(:) - epsilon(:),'b')\n    end\n    legend(legends);\n    title(['Subject ' num2str(n)]);\n    ylabel('BOLD')\n    xlabel('sample index')\nend\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/huge/@tapas_Huge/plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24745942398012855}}
{"text": "function [engine, loglik] = enter_evidence(engine, evidence, varargin)\n% ENTER_EVIDENCE Add the specified evidence to the network (frontier)\n% [engine, loglik] = enter_evidence(engine, evidence, ...)\n%\n% evidence{i,t} = [] if if X(i,t) is hidden, and otherwise contains its observed value (scalar or column vector)\n%\n% The following optional arguments can be specified in the form of name/value pairs:\n% [default value in brackets]\n%\n% maximize - if 1, does max-product (not yet supported), else sum-product [0]\n% filter -   if 1, do filtering, else smoothing [0]\n%\n% e.g., engine = enter_evidence(engine, ev, 'maximize', 1)\n\nmaximize = 0;\nfilter = 0;\n\n% parse optional params\nargs = varargin;\nnargs = length(args);\nif nargs > 0\n  for i=1:2:nargs\n    switch args{i},\n     case 'maximize', maximize = args{i+1}; \n     case 'filter', filter = args{i+1}; \n     otherwise,  \n      error(['invalid argument name ' args{i}]);       \n    end\n  end\nend\n\nassert(~maximize);\n\n[ss T] = size(evidence);\nbnet = bnet_from_engine(engine);\nonodes = find(~isemptycell(evidence));\ncnodes = unroll_set(bnet.cnodes(:), ss, T);\npot_type = determine_pot_type(bnet, onodes);\n\nCPDpot = convert_dbn_CPDs_to_pots(bnet, evidence, pot_type);\n\n[engine.fwdback, loglik, engine.fwd_frontier, engine.back_frontier] = ...\n    enter_soft_evidence(engine, CPDpot, onodes, pot_type, filter);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/dynamic/@frontier_inf_engine/enter_evidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24745941802762592}}
{"text": "% apply the ECO tracking for each target (modified based on the original ECO code)\nfunction tracker = ECO_tracking(frame_id, im, bboxes_det, tracker, opt)\n\ntracker.eco.n_frame = tracker.eco.n_frame + 1;\nframe = tracker.eco.n_frame;\n\n% variables from ECO_initialize.m\nparams = tracker.eco.params;\nmax_train_samples = tracker.eco.max_train_samples;\nfeatures = tracker.eco.features;\nglobal_fparams = tracker.eco.global_fparams;\npos = tracker.eco.pos;\ntarget_sz = tracker.eco.target_sz;\ncurrentScaleFactor = tracker.eco.currentScaleFactor;\nbase_target_sz = tracker.eco.base_target_sz;\nimg_support_sz = tracker.eco.img_support_sz;\nfeature_dim = tracker.eco.feature_dim;\nnum_feature_blocks = tracker.eco.num_feature_blocks;\nfeature_reg = tracker.eco.feature_reg;\nfeature_extract_info = tracker.eco.feature_extract_info;\ncompressed_dim = tracker.eco.compressed_dim;\ncompressed_dim_cell = tracker.eco.compressed_dim_cell;\nfilter_sz = tracker.eco.filter_sz;\nfilter_sz_cell = tracker.eco.filter_sz_cell;\noutput_sz = tracker.eco.output_sz;\npad_sz = tracker.eco.pad_sz;\nkx = tracker.eco.kx;\nky = tracker.eco.ky;\nyf = tracker.eco.yf;\ncos_window = tracker.eco.cos_window;\ninterp1_fs = tracker.eco.interp1_fs;\ninterp2_fs = tracker.eco.interp2_fs;\nreg_filter = tracker.eco.reg_filter;\nreg_energy = tracker.eco.reg_energy;\nnScales = tracker.eco.nScales;\nscaleFactors = tracker.eco.scaleFactors;\nscale_filter = tracker.eco.scale_filter;\nmin_scale_factor = tracker.eco.min_scale_factor;\nmax_scale_factor = tracker.eco.max_scale_factor;\ninit_CG_opts = tracker.eco.init_CG_opts;\nCG_opts = tracker.eco.CG_opts;\nrect_position = tracker.eco.rect_position;\nprior_weights = tracker.eco.prior_weights;\nsample_weights = tracker.eco.sample_weights;\nsamplesf = tracker.eco.samplesf;\nscore_matrix = tracker.eco.score_matrix;\nlatest_ind = tracker.eco.latest_ind;\nframes_since_last_train = tracker.eco.frames_since_last_train;\nnum_training_samples = tracker.eco.num_training_samples;\nminimum_sample_weight = tracker.eco.minimum_sample_weight;\nres_norms = tracker.eco.res_norms;\nis_color_image = tracker.eco.is_color_image;\n\n% variables which are useful when frame == 1\nsample_pos = tracker.eco.sample_pos;\nsample_scale = tracker.eco.sample_scale;\nxl = tracker.eco.xl;\nxlf = tracker.eco.xlf;\nprojection_matrix = tracker.eco.projection_matrix;\nshift_samp = tracker.eco.shift_samp;\nxlf_proj = tracker.eco.xlf_proj;\nhf = tracker.eco.hf;\nlf_ind = tracker.eco.lf_ind;\nproj_energy = tracker.eco.proj_energy;\nsample_energy = tracker.eco.sample_energy;\nrhs_samplef = tracker.eco.rhs_samplef;\ndiag_M = tracker.eco.diag_M;\np = tracker.eco.p;\nrho = tracker.eco.rho;\nr_old = tracker.eco.r_old;\ninit_samplef = tracker.eco.init_samplef;\ninit_samplef_H = tracker.eco.init_samplef_H;\nprojection_matrix_init = tracker.eco.projection_matrix_init;\ninit_samplef_proj = tracker.eco.init_samplef_proj;\ninit_hf = tracker.eco.init_hf;\nfyf = tracker.eco.fyf;\nres_norms_temp = tracker.eco.res_norms_temp;\n\n% other variables\nhf_full = tracker.eco.hf_full;\n\n% narrow the bbox to avoid tracking drift\ntarget_sz(2) = target_sz(2) * 0.5;\n\n% load image\nif size(im,3) > 1 && is_color_image == false\n    im = im(:,:,1);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Target localization step\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Do not estimate translation and scaling on the first frame, since we \n% just want to initialize the tracker there\n\nif frame > 1\n    old_pos = inf(size(pos));\n    iter = 1;\n    \n    %translation search\n    while iter <= params.refinement_iterations && any(old_pos ~= pos)\n        % Extract features at multiple resolutions\n        sample_pos = round(pos);\n        det_sample_pos = sample_pos;\n        sample_scale = currentScaleFactor*scaleFactors;\n        xt = extract_features(im, sample_pos, sample_scale, features, global_fparams, feature_extract_info);\n                    \n        % Project sample\n        xt_proj = project_sample(xt, projection_matrix);\n        \n        % Do windowing of features\n        xt_proj = cellfun(@(feat_map, cos_window) bsxfun(@times, feat_map, cos_window), xt_proj, cos_window, 'uniformoutput', false);\n        \n        % Compute the fourier series\n        xtf_proj = cellfun(@cfft2, xt_proj, 'uniformoutput', false);\n        \n        % Interpolate features to the continuous domain\n        xtf_proj = interpolate_dft(xtf_proj, interp1_fs, interp2_fs);\n        \n        % Compute convolution for each feature block in the Fourier domain\n        scores_fs_feat = cellfun(@(hf, xf, pad_sz) padarray(sum(bsxfun(@times, hf, xf), 3), pad_sz), hf_full, xtf_proj, pad_sz, 'uniformoutput', false);\n        \n        % Also sum over all feature blocks.\n        % Gives the fourier coefficients of the convolution response.\n        scores_fs = permute(sum(cell2mat(scores_fs_feat), 3), [1 2 4 3]);\n        \n        % Optimize the continuous score function with Newton's method.\n        [trans_row, trans_col, scale_ind] = optimize_scores(scores_fs, params.newton_iterations);\n        \n        % Compute the translation vector in pixel-coordinates and round\n        % to the closest integer pixel.\n        translation_vec = [trans_row, trans_col] .* (img_support_sz./output_sz) * currentScaleFactor * scaleFactors(scale_ind);\n        scale_change_factor = scaleFactors(scale_ind);\n        \n        % update position\n        old_pos = pos;\n        pos = sample_pos + translation_vec;\n        \n        if params.clamp_position\n            pos = max([1 1], min([size(im,1) size(im,2)], pos));\n        end\n        \n        % Do scale tracking with the scale filter\n        if nScales > 0 && params.use_scale_filter\n            scale_change_factor = scale_filter_track(im, pos, base_target_sz, currentScaleFactor, scale_filter, params);\n        end \n        \n        % Update the scale\n        currentScaleFactor = currentScaleFactor * scale_change_factor;\n        \n        % Adjust to make sure we are not to large or to small\n        if currentScaleFactor < min_scale_factor\n            currentScaleFactor = min_scale_factor;\n        elseif currentScaleFactor > max_scale_factor\n            currentScaleFactor = max_scale_factor;\n        end\n        \n        iter = iter + 1;\n    end\nend\n\npre_pos = tracker.eco.pos;\npre_target_sz = tracker.eco.target_sz;\npos_diff = double(sqrt((pos(1)-pre_pos(1)).^2 + (pos(2)-pre_pos(2)).^2));\nif pos_diff > 1.2 * double(pre_target_sz(2))\n    pos = pre_pos;\n    is_drift = 1;\nelse\n    is_drift = 0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Model update step\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Extract sample and init projection matrix\nif frame == 1\n    % Extract image region for training sample\n    sample_pos = round(pos);\n    sample_scale = currentScaleFactor;\n    xl = extract_features(im, sample_pos, currentScaleFactor, features, global_fparams, feature_extract_info);\n    \n    % Do windowing of features\n    xlw = cellfun(@(feat_map, cos_window) bsxfun(@times, feat_map, cos_window), xl, cos_window, 'uniformoutput', false);\n    \n    % Compute the fourier series\n    xlf = cellfun(@cfft2, xlw, 'uniformoutput', false);\n    \n    % Interpolate features to the continuous domain\n    xlf = interpolate_dft(xlf, interp1_fs, interp2_fs);\n    \n    % New sample to be added\n    xlf = compact_fourier_coeff(xlf);\n    \n    % Initialize projection matrix\n    xl1 = cellfun(@(x) reshape(x, [], size(x,3)), xl, 'uniformoutput', false);\n    xl1 = cellfun(@(x) bsxfun(@minus, x, mean(x, 1)), xl1, 'uniformoutput', false);\n    \n    if strcmpi(params.proj_init_method, 'pca')\n        [projection_matrix, ~, ~] = cellfun(@(x) svd(x' * x), xl1, 'uniformoutput', false);\n        projection_matrix = cellfun(@(P, dim) single(P(:,1:dim)), projection_matrix, compressed_dim_cell, 'uniformoutput', false);\n    elseif strcmpi(params.proj_init_method, 'rand_uni')\n        projection_matrix = cellfun(@(x, dim) single(randn(size(x,2), dim)), xl1, compressed_dim_cell, 'uniformoutput', false);\n        projection_matrix = cellfun(@(P) bsxfun(@rdivide, P, sqrt(sum(P.^2,1))), projection_matrix, 'uniformoutput', false);\n    elseif strcmpi(params.proj_init_method, 'none')\n        projection_matrix = [];\n    else\n        error('Unknown initialization method for the projection matrix: %s', params.proj_init_method);\n    end\n    clear xl1 xlw\n    \n    % Shift sample\n    shift_samp = 2*pi * (pos - sample_pos) ./ (sample_scale * img_support_sz);\n    xlf = shift_sample(xlf, shift_samp, kx, ky);\n    \n    % Project sample\n    xlf_proj = project_sample(xlf, projection_matrix);\nelseif params.learning_rate > 0\n    if ~params.use_detection_sample\n        % Extract image region for training sample\n        sample_pos = round(pos);\n        sample_scale = currentScaleFactor;\n        xl = extract_features(im, sample_pos, currentScaleFactor, features, global_fparams, feature_extract_info);\n        \n        % Project sample\n        xl_proj = project_sample(xl, projection_matrix);\n        \n        % Do windowing of features\n        xl_proj = cellfun(@(feat_map, cos_window) bsxfun(@times, feat_map, cos_window), xl_proj, cos_window, 'uniformoutput', false);\n        \n        % Compute the fourier series\n        xlf1_proj = cellfun(@cfft2, xl_proj, 'uniformoutput', false);\n        \n        % Interpolate features to the continuous domain\n        xlf1_proj = interpolate_dft(xlf1_proj, interp1_fs, interp2_fs);\n        \n        % New sample to be added\n        xlf_proj = compact_fourier_coeff(xlf1_proj);\n    else        \n        % Use the sample that was used for detection\n        sample_scale = sample_scale(scale_ind);\n        xlf_proj = cellfun(@(xf) xf(:,1:(size(xf,2)+1)/2,:,scale_ind), xtf_proj, 'uniformoutput', false);\n    end\n    \n    % Shift the sample so that the target is centered\n    shift_samp = 2*pi * (pos - sample_pos) ./ (sample_scale * img_support_sz);\n    xlf_proj = shift_sample(xlf_proj, shift_samp, kx, ky);\nend\n\nxlf_proj_perm = cellfun(@(xf) permute(xf, [4 3 1 2]), xlf_proj, 'uniformoutput', false);\n    \nif params.use_sample_merge\n    % Find the distances with existing samples\n    dist_vector = find_cluster_distances(samplesf, xlf_proj_perm, num_feature_blocks, num_training_samples, max_train_samples, params);\n    \n    [merged_sample, new_cluster, merged_cluster_id, new_cluster_id, score_matrix, prior_weights,num_training_samples] = ...\n        merge_clusters(samplesf, xlf_proj_perm, dist_vector, score_matrix, prior_weights,...\n                       num_training_samples,num_feature_blocks,max_train_samples,minimum_sample_weight,params);\nelse\n    % Do the traditional adding of a training sample and weight update\n    % of C-COT\n    [prior_weights, replace_ind] = update_prior_weights(prior_weights, sample_weights, latest_ind, frame, params);\n    latest_ind = replace_ind;\n    \n    merged_cluster_id = 0;\n    new_cluster = xlf_proj_perm;\n    new_cluster_id = replace_ind;\nend\n\nif frame > 1 && params.learning_rate > 0 || frame == 1 && ~params.update_projection_matrix\n    % Insert the new training sample\n    for k = 1:num_feature_blocks\n        if merged_cluster_id > 0\n            samplesf{k}(merged_cluster_id,:,:,:) = merged_sample{k};\n        end\n        \n        if new_cluster_id > 0\n            samplesf{k}(new_cluster_id,:,:,:) = new_cluster{k};\n        end\n    end\nend\n\nsample_weights = prior_weights;\n       \ntrain_tracker = (frame < params.skip_after_frame) || (frames_since_last_train >= params.train_gap);\n\nif train_tracker && is_drift == 0    \n    % Used for preconditioning\n    new_sample_energy = cellfun(@(xlf) abs(xlf .* conj(xlf)), xlf_proj, 'uniformoutput', false);\n    \n    if frame == 1\n        if params.update_projection_matrix\n            hf = cell(2,1,num_feature_blocks);\n            lf_ind = cellfun(@(sz) sz(1) * (sz(2)-1)/2 + 1, filter_sz_cell, 'uniformoutput', false);\n            proj_energy = cellfun(@(P, yf) 2*sum(abs(yf(:)).^2) / sum(feature_dim) * ones(size(P), 'single'), projection_matrix, yf, 'uniformoutput', false);\n        else\n            hf = cell(1,1,num_feature_blocks);\n        end\n        % Initialize the filter\n        for k = 1:num_feature_blocks\n            hf{1,1,k} = complex(zeros([filter_sz(k,1) (filter_sz(k,2)+1)/2 compressed_dim(k)], 'single'));\n        end\n        \n        % Initialize Conjugate Gradient parameters\n        CG_opts.maxit = params.init_CG_iter; % Number of initial iterations if projection matrix is not updated\n        init_CG_opts.maxit = ceil(params.init_CG_iter / params.init_GN_iter);\n        sample_energy = new_sample_energy;\n        rhs_samplef = cell(size(hf));\n        diag_M = cell(size(hf));\n        p = []; rho = []; r_old = [];\n    else\n        CG_opts.maxit = params.CG_iter;\n        \n        if params.CG_forgetting_rate == inf || params.learning_rate >= 1\n            % CG will be reset\n            p = []; rho = []; r_old = [];\n        else\n            rho = rho / (1-params.learning_rate)^params.CG_forgetting_rate;\n        end\n        % Update the approximate average sample energy using the learning\n        % rate. This is only used to construct the preconditioner.\n        sample_energy = cellfun(@(se, nse) (1 - params.learning_rate) * se + params.learning_rate * nse, sample_energy, new_sample_energy, 'uniformoutput', false);\n    end\n    \n    % Do training\n    if frame == 1 && params.update_projection_matrix\n        % Initial Gauss-Newton optimization of the filter and\n        % projection matrix.\n        \n        % Construct stuff for the proj matrix part\n        init_samplef = cellfun(@(x) permute(x, [4 3 1 2]), xlf, 'uniformoutput', false);\n        init_samplef_H = cellfun(@(X) conj(reshape(X, size(X,2), [])), init_samplef, 'uniformoutput', false);\n       \n        % Construct preconditioner\n        diag_M(1,1,:) = cellfun(@(m, reg_energy) (1-params.precond_reg_param) * bsxfun(@plus, params.precond_data_param * m, (1-params.precond_data_param) * mean(m,3)) + params.precond_reg_param*reg_energy, sample_energy, reg_energy, 'uniformoutput',false);\n        diag_M(2,1,:) = cellfun(@(m) params.precond_proj_param * (m + params.projection_reg), proj_energy, 'uniformoutput',false);\n        \n        projection_matrix_init = projection_matrix;\n        \n        for iter = 1:params.init_GN_iter\n            % Project sample with new matrix\n            init_samplef_proj = cellfun(@(x,P) mtimesx(x, P, 'speed'), init_samplef, projection_matrix, 'uniformoutput', false);\n            init_hf = cellfun(@(x) permute(x, [3 4 1 2]), hf(1,1,:), 'uniformoutput', false);\n            \n            % Construct the right hand side vector for the filter part\n            rhs_samplef(1,1,:) = cellfun(@(xf, yf) bsxfun(@times, conj(permute(xf, [3 4 2 1])), yf), init_samplef_proj, yf, 'uniformoutput', false);\n            \n            % Construct the right hand side vector for the projection matrix part\n            fyf = cellfun(@(f, yf) reshape(bsxfun(@times, conj(f), yf), [], size(f,3)), hf(1,1,:), yf, 'uniformoutput', false);\n            rhs_samplef(2,1,:) = cellfun(@(P, XH, fyf, fi) (2*real(XH * fyf - XH(:,fi:end) * fyf(fi:end,:)) - params.projection_reg * P), ...\n                projection_matrix, init_samplef_H, fyf, lf_ind, 'uniformoutput', false);\n            \n            % Initialize the projection matrix increment to zero\n            hf(2,1,:) = cellfun(@(P) zeros(size(P), 'single'), projection_matrix, 'uniformoutput', false);\n            \n            % do conjugate gradient\n            [hf, ~, ~, ~, res_norms_temp] = pcg_ccot(...\n                @(x) lhs_operation_joint(x, init_samplef_proj, reg_filter, feature_reg, init_samplef, init_samplef_H, init_hf, params.projection_reg),...\n                rhs_samplef, init_CG_opts, ...\n                @(x) diag_precond(x, diag_M), ...\n                [], hf);\n            \n            % Make the filter symmetric (avoid roundoff errors)\n            hf(1,1,:) = symmetrize_filter(hf(1,1,:));\n            \n            % Add to the projection matrix\n            projection_matrix = cellfun(@plus, projection_matrix, hf(2,1,:), 'uniformoutput', false);\n            \n            res_norms = [res_norms; res_norms_temp];\n        end\n        \n        % Extract filter\n        hf = hf(1,1,:);\n        \n        % Re-project and insert training sample\n        xlf_proj = project_sample(xlf, projection_matrix);\n        for k = 1:num_feature_blocks\n            samplesf{k}(1,:,:,:) = permute(xlf_proj{k}, [4 3 1 2]);\n        end\n        \n        if debug\n            norm_proj_mat_init = sqrt(sum(cellfun(@(P) norm(P(:))^2, projection_matrix_init)));\n            norm_proj_mat = sqrt(sum(cellfun(@(P) norm(P(:))^2, projection_matrix)));\n            norm_proj_mat_change = sqrt(sum(cellfun(@(P,P2) norm(P(:) - P2(:))^2, projection_matrix_init, projection_matrix)));\n            fprintf('Norm init: %f, Norm final: %f, Matrix change: %f\\n', norm_proj_mat_init, norm_proj_mat, norm_proj_mat_change / norm_proj_mat_init);\n        end\n    else\n        % Construct the right hand side vector\n        rhs_samplef = cellfun(@(xf) permute(mtimesx(sample_weights, 'T', xf, 'speed'), [3 4 2 1]), samplesf, 'uniformoutput', false);\n        rhs_samplef = cellfun(@(xf, yf) bsxfun(@times, conj(xf), yf), rhs_samplef, yf, 'uniformoutput', false);\n        \n        % Construct preconditioner\n        diag_M = cellfun(@(m, reg_energy) (1-params.precond_reg_param) * bsxfun(@plus, params.precond_data_param * m, (1-params.precond_data_param) * mean(m,3)) + params.precond_reg_param*reg_energy, sample_energy, reg_energy, 'uniformoutput',false);\n        \n        % do conjugate gradient\n        [hf, ~, ~, ~, res_norms, p, rho, r_old] = pcg_ccot(...\n            @(x) lhs_operation(x, samplesf, reg_filter, sample_weights, feature_reg),...\n            rhs_samplef, CG_opts, ...\n            @(x) diag_precond(x, diag_M), ...\n            [], hf, p, rho, r_old);\n    end\n    \n    % Reconstruct the full Fourier series\n    hf_full = full_fourier_coeff(hf);\n    \n    frames_since_last_train = 0;\nelse\n    frames_since_last_train = frames_since_last_train+1;\nend\n\n% Update the scale filter\nif nScales > 0 && params.use_scale_filter\n    scale_filter = scale_filter_update(im, pos, base_target_sz, currentScaleFactor, scale_filter, params);\nend\n\n% Update the target size (only used for computing output box)\ntarget_sz = base_target_sz * currentScaleFactor;\n\n% restore the size of bbox (narrowed before to avoid tracking drift)\ntarget_sz(2) = target_sz(2) * 2.0;\n\n%save position and calculate FPS\nrect_position(frame,:) = round([pos([2,1]) - (target_sz([2,1]) - 1)/2, target_sz([2,1])]);\n\nsampled_scores_display = fftshift(sample_fs(scores_fs(:,:,scale_ind), 10*output_sz));\n\npre_pos = tracker.eco.pos;\npre_target_sz = tracker.eco.target_sz;\nbbox.x = double(pre_pos(2) - (pre_target_sz(2) - 1)/2);\nbbox.y = double(pre_pos(1) - (pre_target_sz(1) - 1)/2);\nbbox.w = pre_target_sz(2);\nbbox.h = pre_target_sz(1);\n\nif isempty(bboxes_det.fr) == 0\n    o = calc_overlap(bbox, 1, bboxes_det, 1:numel(bboxes_det.fr));\n    [overlap_box, index] = max(o);\n    pre_area = bbox.w * bbox.h;\n    cur_area = bboxes_det.w(index) * bboxes_det.h(index);\n    if overlap_box > opt.det_overlap_thre && max(bbox.h, bboxes_det.h(index))/min(bbox.h, bboxes_det.h(index)) <= 1.3\n        pos_det = single([bboxes_det.y(index) + (bboxes_det.h(index) - 1)/2, bboxes_det.x(index) + (bboxes_det.w(index) - 1)/2]);\n        target_sz_det = [bboxes_det.h(index), bboxes_det.w(index)];\n        pos = single(overlap_box * pos_det + (1 - overlap_box) * pos);\n        target_sz = overlap_box * target_sz_det + (1 - overlap_box) * target_sz;\n    end\nend\n\n% variables from ECO_initialize.m\ntracker.eco.params = params;\ntracker.eco.max_train_samples = max_train_samples;\ntracker.eco.features = features;\ntracker.eco.global_fparams = global_fparams;\ntracker.eco.pos = pos;\ntracker.eco.target_sz = target_sz;\ntracker.eco.currentScaleFactor = currentScaleFactor;\ntracker.eco.base_target_sz = base_target_sz;\ntracker.eco.img_support_sz = img_support_sz;\ntracker.eco.feature_dim = feature_dim;\ntracker.eco.num_feature_blocks = num_feature_blocks;\ntracker.eco.feature_reg = feature_reg;\ntracker.eco.feature_extract_info = feature_extract_info;\ntracker.eco.compressed_dim = compressed_dim;\ntracker.eco.compressed_dim_cell = compressed_dim_cell;\ntracker.eco.filter_sz = filter_sz;\ntracker.eco.filter_sz_cell = filter_sz_cell;\ntracker.eco.output_sz = output_sz;\ntracker.eco.pad_sz = pad_sz;\ntracker.eco.kx = kx;\ntracker.eco.ky = ky;\ntracker.eco.yf = yf;\ntracker.eco.cos_window = cos_window;\ntracker.eco.interp1_fs = interp1_fs;\ntracker.eco.interp2_fs = interp2_fs;\ntracker.eco.reg_filter = reg_filter;\ntracker.eco.reg_energy = reg_energy;\ntracker.eco.nScales = nScales;\ntracker.eco.scaleFactors = scaleFactors;\ntracker.eco.scale_filter = scale_filter;\ntracker.eco.min_scale_factor = min_scale_factor;\ntracker.eco.max_scale_factor = max_scale_factor;\ntracker.eco.init_CG_opts = tracker.eco.init_CG_opts;\ntracker.eco.CG_opts = CG_opts;\ntracker.eco.rect_position = rect_position;\ntracker.eco.prior_weights = prior_weights;\ntracker.eco.sample_weights = sample_weights;\ntracker.eco.samplesf = samplesf;\ntracker.eco.score_matrix = score_matrix;\ntracker.eco.latest_ind = latest_ind;\ntracker.eco.frames_since_last_train = frames_since_last_train;\ntracker.eco.num_training_samples = num_training_samples;\ntracker.eco.minimum_sample_weight = minimum_sample_weight;\ntracker.eco.res_norms = res_norms;\ntracker.eco.is_color_image = is_color_image;\n\n% variables which are useful when frame == 1\ntracker.eco.sample_pos = sample_pos;\ntracker.eco.sample_scale = sample_scale;\ntracker.eco.xl = xl;\ntracker.eco.xlf = xlf;\ntracker.eco.projection_matrix = projection_matrix;\ntracker.eco.shift_samp = shift_samp;\ntracker.eco.xlf_proj = xlf_proj;\ntracker.eco.hf = hf;\ntracker.eco.lf_ind = lf_ind;\ntracker.eco.proj_energy = proj_energy;\ntracker.eco.sample_energy = sample_energy;\ntracker.eco.rhs_samplef = rhs_samplef;\ntracker.eco.diag_M = diag_M;\ntracker.eco.p = p;\ntracker.eco.rho = rho;\ntracker.eco.r_old = r_old;\ntracker.eco.init_samplef = init_samplef;\ntracker.eco.init_samplef_H = init_samplef_H;\ntracker.eco.projection_matrix_init = projection_matrix_init;\ntracker.eco.init_samplef_proj = init_samplef_proj;\ntracker.eco.init_hf = init_hf;\ntracker.eco.fyf = fyf;\ntracker.eco.res_norms_temp = res_norms_temp;\n\n% other variables\ntracker.eco.hf_full = hf_full;\n\ntracker.eco.bb = double([pos([2,1]) - (target_sz([2,1]) - 1)/2, pos([2,1]) + (target_sz([2,1]) - 1)/2]);\ntracker.eco.score = max(max(fftshift(sample_fs(scores_fs(:,:,scale_ind), 10*output_sz))));\n\nif tracker.eco.score > opt.tracking_score_thre\n    tracker.eco.is_confident = 1;\nelse\n    tracker.eco.is_confident = 0;\nend\n", "meta": {"author": "jizhu1023", "repo": "DMAN_MOT", "sha": "b522fc5ae8d8152c43be14126c4d6160fdf289f8", "save_path": "github-repos/MATLAB/jizhu1023-DMAN_MOT", "path": "github-repos/MATLAB/jizhu1023-DMAN_MOT/DMAN_MOT-b522fc5ae8d8152c43be14126c4d6160fdf289f8/ECO_tracking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.2473956204728107}}
{"text": "function [view,area3d] = measureFlatROIAreaMesh(view, grayThickness)\n%\n% [view,area3d] = measureFlatROIAreaMesh(view, [grayThickness])\n%\n% Measures the area on the 3D cortical surface of the current \n% flat-map ROI.  \n% \n%    1. Select ROI in the Flat window.\n% \n%    2. Use the Area Measure pull down in the Analysis pulldown of\n% the Flat window.  \n% \n% NOTE: this code must find the flat.mat file associated with the\n% unfold, load it, and find the 'unfoldMeshSummary' field. This extra\n% information is saved from within newer versions of mrFlatMesh when\n% you check 'save extra info'.\n%\n% The method here is much preferred to that in measureFlatROIArea, which\n% tries to create it's own triangulation based only on layer 1 nodes. This\n% usually works OK for ROIs that are convex, but can severely over-estimate\n% the area when the ROI has concavities. Here we just use the triangles\n% from the gray/white interface surface mesh.\n% \n% See Also: measureFlatROIArea, sumTriangularArea \n%\n% HISTORY:\n% 2003.01.07 RFD (bob@white.stanford.edu) wrote it.\n% 2003.01.30 RFD: minor cleaning, tested some alternative vertex inclusion\n% criteria.\n% 2006.04.10 RFD: addes comments about our preference for this function\n% over the older measureFlatROIArea.\n\nglobal mrSESSION;\n\nif(~exist('grayThickness','var') | isempty(grayThickness))\n    grayThickness = 3;\nend\n\n% If someone want the area returned, then we assume that we are scripted\n% and thus don't use gui stuff.\nif(nargout<2),  gui = 1;\nelse,  gui = 0; end\n\n% Get selpts from current ROI\nif view.selectedROI,   ROIcoords = getCurROIcoords(view);\nelse  error('No current ROI'); end\nROIname = view.ROIs(view.selectedROI).name;\n\nif isempty(ROIcoords), error('ROI is empty!'); end\n\nhemi = ROIcoords(3,1);\nif(~all(ROIcoords(3,:) == hemi))\n    error('ROI spans both hemispheres!');\nend\n\n% load the flat.mat file\nif(hemi==1)\n    hemiName = 'left';\n    unfoldFile = view.leftPath;\nelse\n    hemiName  = 'right';\n    unfoldFile = view.rightPath;\nend\nif(~exist(unfoldFile,'file'))\n    % Try to fix broken paths\n    warning([unfoldFile ' not found- trying to find it...']);\n    anatPath = getAnatomyPath(mrSESSION.subject);\n    indx = findstr(mrSESSION.subject,unfoldFile);\n    if(~isempty(indx))\n        unfoldFile = fullfile(fileparts(anatPath), unfoldFile(indx(1):end));\n        unfoldFile = strrep(unfoldFile, '\\', filesep);\n        unfoldFile = strrep(unfoldFile, '/', filesep);\n    end\n    if(exist(unfoldFile,'file'))\n        warning(['Using a similarly-named file (' unfoldFile ')...']);\n    else\n        disp(unfoldFile);\n        [f,p] = myUiGetFile(anatPath, {'*.mat';'*.*'}, ['Select ' hemiName ' unfold file...']);\n        unfoldFile = fullfile(p,f);\n    end\nend\n\nif(~isfield(view,'mesh') | size(view.mesh) < hemi | isempty(view.mesh{hemi}))\n    unfold = load(unfoldFile);\n    disp(['loaded unfold from ', unfoldFile,'...']);\n    if(~isfield(unfold,'unfoldMeshSummary'))\n        disp('*************************************************************');\n        disp('This flat.mat file does not have an unfoldMeshSummary field!');\n        disp('Redo the unfold and tell mrFlatMesh to save the extra info.');\n        disp('For now, you can get an area estimate from measureFlatROIArea.');\n        error('Missing the unfoldMeshSummary field.');\n    end\n    view.mesh{hemi} = unfold.unfoldMeshSummary;\nend\n\nlocs2d = view.mesh{hemi}.locs2d;\n\n% To convert raw glocs2d values to those used in mrLoadRet, we do:\nminLocs2d = min(locs2d);\nlocs2d(:,1) = locs2d(:,1) - minLocs2d(1) + 1;\nlocs2d(:,2) = locs2d(:,2) - minLocs2d(2) + 1;\nlocs2d = locs2d'; \n\nscaledVertices(:,1) = view.mesh{hemi}.uniqueVertices(:,1) .* view.mesh{hemi}.scaleFactor(1);\nscaledVertices(:,2) = view.mesh{hemi}.uniqueVertices(:,2) .* view.mesh{hemi}.scaleFactor(2);\nscaledVertices(:,3) = view.mesh{hemi}.uniqueVertices(:,3) .* view.mesh{hemi}.scaleFactor(3);\nareaList3d = findFaceArea(view.mesh{hemi}.connectionMatrix, ...\n    scaledVertices, ...\n    view.mesh{hemi}.uniqueFaceIndexList);\n% Lets also measure the 2d area, just for fun.\nareaList2d = findFaceArea(view.mesh{hemi}.connectionMatrix, ...\n    [locs2d',zeros(size(locs2d,2),1)], ...\n    view.mesh{hemi}.uniqueFaceIndexList);\n\n%\n% Find the triangles that overlap with the ROI.\n%\n\n% First we find all the vertices that fall within the ROI. \n%\n% Intersect returns only the unique matches, but we want them all.\n% So, we use ismember, which tells us for each row of the first matrix if\n% it matches any row in the second matrix.\nroiVertexIndices = find(ismember(round(locs2d)', ROIcoords(1:2,:)', 'rows'));\n\n% Now we find the triangles (faces) within the ROI by a simple heuristic-\n% any one of the triangle's vertices is in the ROI. What we should really \n% do is select only those triangles whose AREA falls mostly within the ROI. \n% But that's too hard (ie. would be slow in matlab).\nroiFaceIndices = find(ismember(view.mesh{hemi}.uniqueFaceIndexList(:,1), roiVertexIndices) ...\n    | ismember(view.mesh{hemi}.uniqueFaceIndexList(:,2), roiVertexIndices) ...\n    | ismember(view.mesh{hemi}.uniqueFaceIndexList(:,3), roiVertexIndices));\n% 2003.01.30 RFD: NOTE: I tried making the above inclusion criteria more \n% conservative- so that two of it's vertices needed to be within the ROI. \n% However, this wasn't much better, especially for thin ROIs, since it\n% erred in the other direction and eliminated too many triangles.\n% But that more conservative criteria would have the very desireable \n% property that any triangle will only get included in one of\n% two abutting ROIs, never in both like the old method sometimes did.\n% vertOne = ismember(view.mesh{hemi}.uniqueFaceIndexList(:,1), RoiVertexIndices);\n% vertTwo = ismember(view.mesh{hemi}.uniqueFaceIndexList(:,2), RoiVertexIndices);\n% vertThree = ismember(view.mesh{hemi}.uniqueFaceIndexList(:,3), RoiVertexIndices);\n% roiFaceIndices = find((vertOne & vertTwo) | (vertOne & vertThree) | (vertTwo & vertThree));\n\narea3d = sum(areaList3d(roiFaceIndices));\narea2d = sum(areaList2d(roiFaceIndices));\n\nareaStr = addText([],sprintf('%s area = %.0f mm^2 (%d triangles)\\n',ROIname,area3d,length(roiFaceIndices)));\nareaStr = addText(areaStr,sprintf('2d = %.0f~mm^2 and %.0f voxels',area2d,size(ROIcoords,2)));\n\nif(gui)\n    %msgbox([areaStr],[ROIname ' area']);\n    % Make the ROI coords point to the upper left of each ROI pixel\n    ROIcoords = ROIcoords-0.5;\n    % now define four the lines for each ROI coordinate.\n    roiLinesX = [[ ROIcoords(2,:);   ROIcoords(2,:)+1 ],...\n            [ ROIcoords(2,:);   ROIcoords(2,:)   ],...\n            [ ROIcoords(2,:)+1; ROIcoords(2,:)+1 ],...\n            [ ROIcoords(2,:)+1; ROIcoords(2,:)   ]];\n    roiLinesY =-[[ ROIcoords(1,:);   ROIcoords(1,:)   ],...\n            [ ROIcoords(1,:);   ROIcoords(1,:)+1 ],...\n            [ ROIcoords(1,:)+1; ROIcoords(1,:)   ],...\n            [ ROIcoords(1,:)+1; ROIcoords(1,:)+1 ]];\n    \n    roiFaces = view.mesh{hemi}.uniqueFaceIndexList(roiFaceIndices,:);\n    % This will color each triangle with the z-depth of the surface\n    % (something like curvature).\n    %colors = scaledVertices(roiFaces(:,1),3) + scaledVertices(roiFaces(:,2),3) + scaledVertices(roiFaces(:,3),3);\n    %colors = colors-mean(colors);\n    % Use abs to cope with the fact that we sometimes get negative numbers here...\n    colors = abs(log(areaList3d(roiFaceIndices)./areaList2d(roiFaceIndices)));\n    %areaStr = [areaStr ' (Color shows log 3D/2D area)'];\n    \n    figure;  hold on; axis equal; colormap(hot);\n    patch([locs2d(2,roiFaces(:,1));...\n            locs2d(2,roiFaces(:,2));...\n            locs2d(2,roiFaces(:,3))], ...\n        -[locs2d(1,roiFaces(:,1));...\n            locs2d(1,roiFaces(:,2));...\n            locs2d(1,roiFaces(:,3))], colors');\n    lineH = line(roiLinesX, roiLinesY,'Color','blue');\n    colorbar;\n    %plot(locs2d(2,roiVertexIndices), -locs2d(1,roiVertexIndices), '.r');\n    %plot(round(locs2d(2,roiVertexIndices)), -round(locs2dInt(1,roiVertexIndices)), '.g');\n    hold off;\n    title(areaStr);\nend\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/SurfaceMeasurements/measureFlatROIAreaMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836382, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24739561485137435}}
{"text": "function [TW, TPW, TR, TPR] = ft_realtime_benchmark(target)\n\n% FT_REALTIME_BENCHMARK times the reading and writing of data\n%\n% Use as\n%   ft_realtime_benchmark(target)\n% where target is the location of the buffer or the file, for\n% example 'buffer://localhost:1972'\n%\n% Please note that any data in the target will be overwritten.\n\n% Copyright (C) 2010, Stefan Klanke\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nN = 100;\n\nhdr        = [];\nhdr.Fs     = 1000; % this is not really used here\nhdr.nChans = 64; \n\nfprintf(1,'Writing header and flushing data in %s...\\n', target);\nft_write_data(target, single([]), 'header', hdr, 'append', false);\n\nblocklen = [8, 16, 32, 64, 128, 256, 512, 1024, 2048];\nblocksize = hdr.nChans * blocklen;\n\nTW  = zeros(N, length(blocklen));\t% Times for writing\nTPW = zeros(1, length(blocklen));\t% Throughput writing\nTR  = zeros(N, length(blocklen));\t% Times for reading\nTPR = zeros(1, length(blocklen));\t% Throughput reading\n\n\nfor k=1:length(blocklen);\n  fprintf(1,'\\nDetermining WRITE throughput at %ix%i samples per block...\\n', hdr.nChans, blocklen(k));\n  % generate random data for writing\n  X = single(randn(hdr.nChans, blocklen(k)));\n  for n=1:N;\n    tic;\n    ft_write_data(target, X, 'header', hdr, 'append', true);\n    TW(n,k) = toc;\n  end\n  mt = mean(TW(:,k));\n  st = std(TW(:,k));\n  ss = blocksize(k) * N / sum(TW(:,k));\n  fprintf(1,'Time per block %f +/- %f  => %d samples/sec\\n', mt, st, ss);\n  TPW(k) = ss;\n  \n  hdr = ft_read_header(target);\n  \n  fprintf(1,'\\nDetermining READ throughput at %ix%i samples per block...\\n', hdr.nChans, blocklen(k));\n  begS = 1;\n  for n=1:N;\n    endS = begS+blocklen(k)-1;\n    tic;\n    X = ft_read_data(target, 'header', hdr, 'begsample', begS, 'endsample', endS);\n    TR(n,k) = toc;\n    begS = endS+1;\n  end\n  mt = mean(TR(:,k));\n  st = std(TR(:,k));\n  ss = blocksize(k) * N / sum(TR(:,k));\n  fprintf(1,'Time per block %f +/- %f  => %d samples/sec\\n', mt, st, ss);\n  \n  TPR(k) = ss;\nend\n\nloglog(blocksize, TPW,'r+-', blocksize, TPR, 'b+-');\nlegend('Writing','Reading','Location','NorthWest');\nxlabel('block size');\nylabel('samples per sec');\n\n  \n  \n  \n  \n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/realtime/example/ft_realtime_benchmark.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24730549472371227}}
{"text": "function h = rxVisualizeRx(rx, loc);\n%\n% h = rxVisualizeRx(rx, [loc]);\n%\n% Display a visualization of the current prescription in a separate\n% figure. Shows a montage of interpolated slices, and, if the\n% Rx Figure is also open, adds a panel with sagittal, coronal, and\n% axial views with the prescription on it.\n%\n% 'loc' is an optional argument for visualizing the rx, specifying\n% the [axi cor sag] slices to show in the Rx views.\n%\n% ras, 01/2007.\nif notDefined('rx'), rx = get(findobj('Tag','rxControlFig'), 'UserData'); end\nif ishandle(rx),\trx = get(rx, 'UserData');\t\t\t\tend\n\nh = figure('Color', 'w');\n\nnSlices = rx.rxDims(3);\nfor slice = 1:nSlices\n\t[img2D images{slice}] = rxInterpSlice(rx, slice);\nend\n\nmontage = imageMontage(images);\nimagesc(montage); axis image; axis off;\ntitle('Prescribed Slices');\n\n\n%% draw ROIs if selected\nif ~isempty(rx.rois) & get(rx.ui.rxDrawRx, 'Value')==1\n\tfor r = 1:length(rx.rois)\n\t\t% convert coords from vol -> rx\n\t\trxCoords = vol2rx(rx, rx.rois(r).volCoords, 1);\n\n\t\t% now convert these coords to 2-D image coordinates\n\t\tpts = rxCoords2Montage(rxCoords, nSlices, size(img2D));\n\n        if isempty(pts), continue; end\n        \n        % remove pts outside range\n        outside = find(pts(1,:) < 1 | pts(1,:) > size(montage, 1) ...\n                       | pts(2,:) < 1 | pts(2,:) > size(montage, 2));\n        ok = setdiff(1:size(pts, 2), outside);\n        pts = pts(:,ok);\n        \n\t\t% draw the outline of this ROI\n\t\t% (rx.rois(r) doubles as a prefs struct, to set the color)\n\t\toutline(pts, rx.rois(r));\n\tend\nend\n\n\n%% add panel with views of the Rx on each plane\nif ishandle(rx.ui.rxAxes)\n\tif notDefined('loc'),   loc = round( rx.volDims / 2 );  end\n\tif ischar(loc),         loc = str2num(loc);             end\n    \n\n\t%% open a panel to the right of the main figure w/ the Rxs\n\thp = mrvPanel('right', .3);\n\n\t%% put up the prescriptions\n\tfor ori = 1:3\n\t\tvol = rx.vol;\n\t\tvolSlice = uint8(loc(ori));\n\n\t\t%% orient the slice properly\n\t\tif ori~=3   % do nothing for sagittal view\n\t\t\t% allow for radiological L/R\n\t\t\thRadiological = findobj('Tag','rxRadiologicalMenu');\n\t\t\tif isequal(get(hRadiological, 'Checked'), 'on')\n\t\t\t\tvol = flipdim(vol, 3);\n\t\t\tend\n\n\t\t\t% permute volume as needed\n\t\t\tif ori==1, vol = permute(vol,[2 3 1]); end   % axial\n\t\t\tif ori==2, vol = permute(vol,[1 3 2]); end   % coronal\n\t\tend\n\n\n\t\t%% plot the slice \n\t\t% get slice\n\t\tvolImg = vol(:,:,volSlice);\n\t\tvolImg = rxClip(volImg, [], rx.ui.volBright, rx.ui.volContrast);\n\n\t\t% make subplot\n\t\tpos = [0 1-(ori/3) 1 .3];\n\t\thax(ori) = axes('Parent', hp, 'Units', 'norm', 'Position', pos);\n\t\t\n\t\t% put up image\n\t\thtmp = image(volImg); colormap gray; axis off; axis equal;\n\t\t\n\t\t% draw Rx, label directions\n\t\trxDrawRx(rx, volSlice, ori);  hold on\n\t\trxLabelVolAxes(rx, ori);\n\n\t\t%% draw ROIs on prescription, if selected\n\t\tif ~isempty(rx.rois) & get(rx.ui.rxDrawRx, 'Value')==1\n\t\t\tfor r = 1:length(rx.rois)\n\t\t\t\tR  = rx.rois(r);  % ROI struct\n\t\t\t\tC  = R.volCoords; % coords (being terse b/c of indents)\n\n\t\t\t\t% map the [axi cor sag] positions in C to the\n\t\t\t\t% 2D [x y] positions in pts:\n\t\t\t\tinSlice = find( round(C(ori,:)) == volSlice );\n\t\t\t\tswitch ori\n\t\t\t\t\tcase 1, % axi\n\t\t\t\t\t\tpts = C([2 3],inSlice);\n\t\t\t\t\tcase 2, % cor\n\t\t\t\t\t\tpts = C([1 3],inSlice);\n\t\t\t\t\tcase 3, % sag\n\t\t\t\t\t\tpts = C([1 2],inSlice);\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% Draw the ROI outline\n\t\t\t\tif ~isempty(pts)\n\t\t\t\t\toutline(pts, R);\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\n\tend\nend\n\nreturn\n% /------------------------------------------------------------/ %\n\n\n\n% /------------------------------------------------------------/ %\nfunction pts = rxCoords2Montage(coords, nSlices, dims);\n% convert 3-D volume coordinates into 2-D points on a montage\n% of prescription slices.  This assumes that imageMontage has\n% been called on all slices (1:nSlices), with the default #\n% of columns and rows.\nncols = ceil( sqrt( nSlices ) );\nnrows = ceil( nSlices / ncols );\n\n% initialize pts output:\npts = [];\n\nfor slice = 1:nSlices\n\t% find (row, col) of this slice in the montage\n\trow = ceil(slice / ncols);\n\tcol = mod(slice-1, ncols) + 1;\n\n\t% find columns of coords in this slice\n\tI = find( round(coords(3,:)) == slice );\n\n\t% main part: compute (x,y) locations given the montage offset\n\ty = coords(1,I) + (row-1) * dims(1);\n\tx = coords(2,I) + (col-1) * dims(2);\n\n\t% add to points list:\n\t% we will shuffle the order of coordinates in coords,\n\t% but remove points outside the Rx.\n\tpts = [pts [y; x]];\nend\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrRx/rxVisualizeRx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2473054883831013}}
{"text": "function newimg = GPReduce2(img,blocksize,displayflag)\n\nif ~exist('displayflag')\n\tdisplayflag = 1;\nend\n\ndim = size(img);\n\nnewimg = [];\nfor b = 1:blocksize:dim(3)\n    if b<dim(3)\n        img2 = img(:,:,b:b+blocksize-1);\n    else\n        img2 = img(:,:,b);\n    end\n\tnewimg2 = GPReduce(img2,displayflag);\n\tnewimg = cat(3,newimg,newimg2);\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/OpticalFlow/GPReduce2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4687906266262438, "lm_q1q2_score": 0.24720104342547963}}
{"text": "% The COBRAToolbox: testReadSBML.m\n%\n% Purpose:\n%     - reads all the sbml files in this folder and\n%       checks if all the parameters are correctly written\n%     - loads certain xml files, runs and FBA, and compares the\n%       solution to pre-calculated values from FBAs run with .mat files\n%\n% Authors:\n%     - Partial original file: Joseph Kang 04/07/09\n%     - CI integration: Laurent Heirendt\n%\n% Note:\n%     - The solver libraries must be included separately\n\nglobal CBTDIR\n\n%Check the requirements (a LP solver is necessary)\nsolvers = prepareTest('needsLP',true,'requireOneSolverOf',{'gurobi','ibm_cplex','glpk','mosek','quadMinos'});\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testReadSBML'));\ncd(fileDir);\n\n%Check if the model contains the same information\n\n% initialize the test\ncd([CBTDIR, filesep, 'test', filesep, 'models']);\n\n\n% load the models\nmodelArr = { 'Abiotrophia_defectiva_ATCC_49176.xml', 'STM_v1.0.xml', 'iIT341.xml'};\n\n%loop through the models\nfor i = 1:length(modelArr)\n    %reading the models takes quite a bit of time, so only do it once for\n    %all solvers.\n    % output a line before launching the test for model i\n    fprintf('   Testing %s ...\\n', modelArr{i});\n    \n    % load the model (actually supply the full filename of the path\n    % where the model is found)\n    model = getDistributedModel(modelArr{i});\n    for k = 1:length(solvers.LP)\n        fprintf(' -- Running testReadSBML using the solver interface: %s ... ', solvers.LP{k});\n        solverOK = changeCobraSolver(solvers.LP{k}, 'LP', 0);\n        \n        fprintf('   Testing loaded model ... \\n');\n        \n        % set the tolerance\n        tol = 1e-6;\n        \n        \n        % define the maximum objective values calculated from pre-converted .mat files\n        modelFBAf_max = [0.149475406282249; 0.477833660760744; 0.692812693473487];\n        \n        % define the minimum objective values\n        modelFBAf_min = [0.0; 0.0; 0.0];\n        \n        % solve the maximisation problem\n        FBA = optimizeCbModel(model, 'max');\n        \n        % test the maximisation solution\n        assert(FBA.stat == 1);\n        assert(abs(FBA.f - modelFBAf_max(i)) < tol);\n        assert(norm(model.S * FBA.x) < tol);\n        \n        % solve the minimisation problem\n        FBA = optimizeCbModel(model, 'min');\n        \n        % test the minimisation solution\n        assert(FBA.stat == 1);\n        assert(abs(FBA.f - modelFBAf_min(i)) < tol);\n        assert(norm(model.S * FBA.x) < tol);\n        \n        % print a line for success of loop i\n        fprintf(' Done.\\n');\n        \n        \n        % test that gene rules are generated correctly\n        % needs testing on model with large number of genes, i.e.,\n        % 'Abiotrophia_defectiva_ATCC_49176.xml'\n        if strcmp(modelArr{i}, 'Abiotrophia_defectiva_ATCC_49176.xml')\n            % test that rules are correctly generated, i.e. no gene partially matched\n            % no indication of x(1)23 instead of x(123).\n            assert(~any(~cellfun(@isempty, regexp(model.rules, '\\(\\d+\\)\\d+')))) %incorrect\n        end\n    end\nend\n\n% test reading COBRA models with symbols in objective reactions and multiple objective reactions\nfor jTest = 1:2\n    if jTest == 1\n        % test objective reactions with symbols\n        fprintf('   Testing readSBML for models with symbols in objective reactions ...\\n');\n        model = createModel({'EX_a(e)'; 'EX_b(e)'}, {'Test A'; 'Test B'}, {'a[e] <=>'; 'b[e] <=>'});\n        model.c = [1; 0];\n\n    elseif jTest == 2\n        % test more than one objective reactions with >1 objective reactions\n        fprintf('   Testing readSBML for models with >1 objective reactions ...\\n');\n        model = createModel({'EX_a'; 'EX_b'}, {'Test A'; 'Test B'}, {'a[e] <=>'; 'b[e] <=>'});\n        model.c = [1; -2];\n    end\n\n    model.lb = model.lb(:);\n    model.ub = model.ub(:);\n    model.comps = {'e'};\n    model.compNames = {'ExtraCellular'};\n    % add the fields outputted by readSBML\n    [model.modelVersion.SBML_level, model.modelVersion.SBML_version, model.modelVersion.fbc_version] = deal(3, 1, 2);\n    model.metCharges = zeros(numel(model.mets), 1);\n    model.metFormulas = {'C'; 'C'};\n    model.osense = -1;\n    model.description = 'test_sbml_obj.xml';\n    model.genes = {'gene1'; 'gene2'};\n    model.rules = {''; ''};\n    model.rxnGeneMat = zeros(2, 2);\n\n    model = convertOldStyleModel(model);\n\n    % write the model\n    writeCbModel(model, 'sbml', 'test_sbml_obj');\n\n\n    % read in the model\n    model2 = readCbModel('test_sbml_obj.xml');    \n    %We are creating a few default fields in readCbModel. \n    DefaultFields = {'S','b','csense','lb','ub','c','osense','rxns','mets','genes','rules','subSystems'};\n\n    model2 = convertOldStyleModel(model2);\n    \n    modelFields = fieldnames(model);    \n    modelFields = setdiff(modelFields,'rxnGeneMat'); %rxnGeneMat did not contain any information and is not created by readCbModel.\n    for i = 1:numel(modelFields)\n        if iscell(model.(modelFields{i}))\n            if ~all(cellfun(@isempty, model.(modelFields{i})))  || any(ismember(modelFields{i},DefaultFields))\n                assert(isequal(model.(modelFields{i}),model2.(modelFields{i})));\n            else\n                assert(~isfield(model2, modelFields{i}));\n            end\n        else\n            if isnumeric(model.(modelFields{i}))\n                if ~all(isnan(model.(modelFields{i})(:))) || any(ismember(modelFields{i},DefaultFields))                                        \n                    assert(isequal(model.(modelFields{i})(~isnan(model.(modelFields{i}))),model2.(modelFields{i})(~isnan(model.(modelFields{i})))));\n                    assert(isequal(~isnan(model.(modelFields{i})),~isnan(model2.(modelFields{i}))));\n                else\n                    assert(~isfield(model2, modelFields{i}));\n                end\n            else\n                %Not numeric, i.e. another field.\n                assert(isequal(model.(modelFields{i}),model2.(modelFields{i})));\n            end\n        end\n    end\n    fprintf(' Done.\\n\\n');\nend\ndelete('test_sbml_obj.xml')\n\n% change the directory\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/base/testIO/testReadSBML.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24708377318878272}}
{"text": "%CODEGENERATOR.GENFKINE Generate code for forward kinematics\n%\n% T = cGen.genfkine() generates a symbolic homogeneous transform matrix (4x4) representing\n% the pose of the robot end-effector in terms of the symbolic joint coordinates q1, q2, ...\n%\n% [T, ALLT] = cGen.genfkine() as above but also generates symbolic homogeneous transform \n% matrices (4x4xN) for the poses of the individual robot joints.\n%\n% Notes::\n% - Side effects of execution depends on the cGen flags:\n%   - saveresult: the symbolic expressions are saved to\n%     disk in the directory specified by cGen.sympath\n%   - genmfun: ready to use m-functions are generated and\n%     provided via a subclass of SerialLink stored in cGen.robjpath\n%   - genslblock: a Simulink block is generated and stored in a\n%     robot specific block library cGen.slib in the directory\n%     cGen.basepath\n%   - genccode: generates C-functions and -headers in the directory \n%     specified by the ccodepath property of the CodeGenerator object.\n%   - mex: generates robot specific MEX-functions as replacement for the \n%     m-functions mentioned above. Access is provided by the SerialLink \n%     subclass. The MEX files rely on the C code generated before.\n%\n% Author::\n%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)\n%\n% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genjacobian.\n\n% Copyright (C) 2012-2014, by Joern Malzahn\n%\n% This file is part of The Robotics Toolbox for Matlab (RTB).\n%\n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n%\n% The code generation module emerged during the work on a project funded by\n% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully \n% acknowledge the financial support.\n\nfunction [t,allT] = genfkine(CGen)\n\n%% Derivation of symbolic expressions\nCGen.logmsg([datestr(now),'\\tDeriving forward kinematics']);\n\nq = CGen.rob.gencoords;\n[t, allT] = CGen.rob.fkine(q);\n\nCGen.logmsg('\\t%s\\n',' done!');\n\n%% Save symbolic expressions\nif CGen.saveresult\n    CGen.logmsg([datestr(now),'\\tSaving symbolic forward kinematics up to end-effector frame']);\n    \n    CGen.savesym(t,'fkine','fkine.mat')\n    \n    CGen.logmsg('\\t%s\\n',' done!');\n    \n    CGen.logmsg([datestr(now),'\\tSaving symbolic forward kinematics for joint']);\n    \n    for iJoint = 1:CGen.rob.n\n        CGen.logmsg(' %s ',num2str(iJoint));\n        tName = ['T0_',num2str(iJoint)];\n        eval([tName,' = allT(',num2str(iJoint),');']);\n        CGen.savesym(eval(tName),tName,[tName,'.mat']);\n    end\n    \n    CGen.logmsg('\\t%s\\n',' done!');\nend\n\n%% M-Functions\nif CGen.genmfun\n    CGen.genmfunfkine;\nend\n\n%% Embedded Matlab Function Simulink blocks\nif CGen.genslblock\n    genslblockfkine(CGen);\nend\n\n%% C-Code\nif CGen.genccode\n    CGen.genccodefkine;\nend\n\n%% MEX\nif CGen.genmex\n    CGen.genmexfkine;\nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/@CodeGenerator/genfkine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24708376773634724}}
{"text": "function packFonts()\n% run extra/genfont.sh first\n\nfonts = dir(fullfile('extra','fonts')) ;\nfonts = {fonts([fonts.isdir]).name} ;\nfonts(ismember(fonts,{'.','..'})) = [] ;\nchars = 'a':'z' ;\n\nim = cell(numel(fonts), numel(chars)) ;\nlabels = cell(numel(fonts), numel(chars)) ;\n\nfor i = 1:numel(fonts)\n  for j = 1:numel(chars)\n    [p,cmap] = imread(fullfile('extra', 'fonts', fonts{i}, [chars(j) '.png'])) ;\n    if isempty(cmap)\n      im{i,j} = im2single(p) ;\n    else\n      im{i,j} = im2single(ind2gray(p,cmap)) ;\n    end\n    labels{i,j} = j ;\n  end\nend\n\nimdb.meta.classes = chars ;\nimdb.meta.sets = {'train', 'val'} ;\nimdb.meta.fonts = fonts ;\nimdb.images.id = 1:numel(im) ;\nimdb.images.data = cat(3, im{:}) ;\nimdb.images.label = cat(2, labels{:}) ;\n\n% Create training and validation sets\nsets = ones(numel(fonts), numel(chars)) ;\nsets(end-349:end,:) = 2 ;\nimdb.images.set = sets(:)' ;\n\nsave('data/charsdb.mat', '-struct', 'imdb') ;\n", "meta": {"author": "vedaldi", "repo": "practical-cnn", "sha": "54c807d995d0ed1c152eefa1b589f669a8324429", "save_path": "github-repos/MATLAB/vedaldi-practical-cnn", "path": "github-repos/MATLAB/vedaldi-practical-cnn/practical-cnn-54c807d995d0ed1c152eefa1b589f669a8324429/extra/packFonts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24703296844699485}}
{"text": "function val = get(c,prop_name)\n   \n   % GET - Get correlation properties\n   %\n   % VAL = get(C,PROP_NAME)\n   % See HELP CORRELATION for description of primary property names:\n   %   Waveforms, Trig, Corr, Lag, Stat, Link, Clust\n   %\n   % Additional scalar properties:\n   %   Traces:         number of traces\n   %   Data_Length:    number of samples in each trace\n   %   Fs:             Frequency\n   %   Period:         Period\n   %   Nyq:            Nyquist frequency\n   %   **NOTE - The scalar properties listed above exist for each waveform\n   %   (except Traces). However, the correlation object requires them to be\n   %   the same. GET only reads the value associated with the first waveform\n   %   Normally this will not be an issue. If the correlation object\n   %   was created manually it is possible for these fields to be different.\n   %\n   % Additional vector properties (nx1):\n   %   Start, Trig, End:             same as Start_Matlab, End_Matlab\n   %   Start_Str, Trig_Str, End_Str:           String times\n   %   Start_Matlab, Trig_Matlab, End_Matlab:  Matlab-format times\n   %   Start_Epoch, Trig_Epoch, End_Epoch:     Epoch-format times\n   %\n   % Additional vector properties (nx1 cell vector)\n   %   Sta (or Station):       Cell vector of station names\n   %   Chan (or Component):    Cell vector of channel names\n   %\n   % Additional matrix properties (nxm matrix)\n   %   Data:                    Matrix of raw trace data\n   %                           (n traces) x (m samples)\n   \n   % Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n   % $Date$\n   % $Revision$\n   \n   warning('using NewCorrelation/get, alternate ways exist of accessing data.')\n   \n   narginchk(2,inf)\n   \n   % got rid of test for c\n   \n   switch upper(prop_name)\n      case {'WAVEFORMS', 'WAVEFORM', 'WAVES'}\n         val = c.W;\n      case {'TRIG'}\n         val = c.trig;\n      case {'TRIG_STR'}\n         val = cellstr(datestr(c.trig,'dd-mmm-yyyy HH:MM:SS.FFF'));\n      case {'TRIG_MATLAB'}\n         val = c.trig;\n      case {'CORR'}\n         val = c.corrmatrix;\n      case {'LAG'}\n         val = c.lags;\n      case {'STAT'}\n         val = c.stat;\n      case {'LINK'}\n         val = c.link;\n      case {'CLUST'}\n         val = c.clust;\n      case {'TRACES'}\n         val = c.ntraces;\n         \n         % FROM WAVEFORM/GET (SCALAR OUTPUT)\n      case {'DATA_LENGTH'}\n         val = c.traces(1).nsamples();\n      case {'FS'}\n         val = c.traces(1).samplerate;\n         \n         %     % FROM WAVEFORM/GET (VECTOR)\n      case {'STATION', 'STA'}\n         val = c.stations;\n      case {'COMPONENT', 'CHAN'}\n         val = c.channels;\n         \n         % OTHER ROUTINES\n      case {'DATA'}\n         val = double(c.traces);\n         \n      otherwise\n         try\n            % see if it is a valid waveform property\n            warning('accessing a waveform property %s. ', prop_name);\n            val = get(c.W,prop_name);\n         catch er\n            error('''%s'' is not a valid argument for correlation/get\\n%s\\n', prop_name, er.message);\n         end\n   end;\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CHECKVALS\n% This function checks to see if each waveform has the same parameters\n\nfunction checkvals(vals)\n   \n   same = all(vals(:) == vals(1));\n   \n   if ~same\n      % Warning is disabled because it gets called repeatedly (annoyingly)\n      % from within other scripts\n      % warning('Waveforms have different frequencies or different numbers of samples. Consider VERIFY function');\n   end;\nend\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/dev/@NewCorrelation/get.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2469600724097323}}
{"text": "function str = get_structure( name )\n%STRUCTURE Summary of this function goes here\n% \n% Structure used in this toolbox.\n% \n% individual structure:\n% parameter: the parameter space point of the individual. it's a column-wise\n% vector.\n% objective: the objective space point of the individual. it's column-wise\n% vector. It only have value after evaluate function is called upon the\n% individual.\n% estimation: Also a structure array of the individual. It's not used in\n% MOEA/D but used in MOEA/D/GP. For every objective, the field contains the\n% estimation from the GP model. \n% \n% estimation structure:\n% obj: the estimated mean.\n% std: the estimated standard deviation for the mean.\n%\n% subproblem structure:\n% weight: the decomposition weight for the subproblem.\n% optimal: the current optimal value of the current structure.\n% curpoiont: the current individual of the subproblem.\n% optpoint: the point that gain the optimal on the subproblem.\n%\n\nswitch name\n    case 'individual' \n        str = struct('parameter',[],'objective'[],'estimation'[]);\n    case 'subproblem' \n        str = struct('weight',[],'optimal',[],'curpoint',[],'optpoint',[]);\n    case 'estimation' \n        str = struct();                \n    otherwise        \nend\n        ", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/\u7f8e\u8d5bA\u9898\u5e38\u89c1\u4ee3\u7801/\u666e\u901a\u591a\u76ee\u6807\u4f18\u5316\u7b97\u6cd5\u4ee3\u7801/get_structure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2469600724097323}}
{"text": "function [elec_realigned] = ft_electroderealign(cfg, elec_original)\n\n% FT_ELECTRODEREALIGN rotates, translates, scales and warps electrode positions. The\n% default is to only rotate and translate, i.e. to do a rigid body transformation in\n% which only the coordinate system is changed. With the right settings if can apply\n% additional deformations to the input sensors (e.g. scale them to better fit the\n% skin surface). The different methods are described in detail below.\n%\n% INTERACTIVE - You can display the skin surface together with the electrode or\n% gradiometer positions, and manually (using the graphical user interface) adjust the\n% rotation, translation and scaling parameters, so that the electrodes correspond\n% with the skin.\n%\n% FIDUCIAL - You can apply a rigid body realignment based on three fiducial\n% locations. After realigning, the fiducials in the input electrode set (typically\n% nose, left and right ear) are along the same axes as the fiducials in the template\n% electrode set.\n%\n% TEMPLATE - You can apply a spatial transformation/deformation that automatically\n% minimizes the distance between the electrodes or gradiometers and a template or\n% sensor array. The warping methods use a non-linear search to minimize the distance\n% between the input sensor positions and the corresponding template sensors.\n%\n% HEADSHAPE - You can apply a spatial transformation/deformation that automatically\n% minimizes the distance between the electrodes and the head surface. The warping\n% methods use a non-linear search to minimize the distance between the input sensor\n% positions and the projection of the electrodes on the head surface.\n%\n% PROJECT - This projects all electrodes to the nearest point on the\n% head surface mesh.\n%\n% MOVEINWARD - This moves all electrodes inward according to their normals\n%\n% Use as\n%   [elec_realigned] = ft_sensorrealign(cfg)\n% with the electrode or gradiometer details in the configuration, or as\n%   [elec_realigned] = ft_sensorrealign(cfg, elec_orig)\n% with the electrode or gradiometer definition as 2nd input argument.\n%\n% The configuration can contain the following options\n%   cfg.method         = string representing the method for aligning or placing the electrodes\n%                        'interactive'     realign manually using a graphical user interface\n%                        'fiducial'        realign using three fiducials (e.g. NAS, LPA and RPA)\n%                        'template'        realign the electrodes to match a template set\n%                        'headshape'       realign the electrodes to fit the head surface\n%                        'project'         projects electrodes onto the head surface\n%                        'moveinward'      moves electrodes inward along their normals\n%   cfg.warp          = string describing the spatial transformation for the template and headshape methods\n%                        'rigidbody'       apply a rigid-body warp (default)\n%                        'globalrescale'   apply a rigid-body warp with global rescaling\n%                        'traditional'     apply a rigid-body warp with individual axes rescaling\n%                        'nonlin1'         apply a 1st order non-linear warp\n%                        'nonlin2'         apply a 2nd order non-linear warp\n%                        'nonlin3'         apply a 3rd order non-linear warp\n%                        'nonlin4'         apply a 4th order non-linear warp\n%                        'nonlin5'         apply a 5th order non-linear warp\n%                        'dykstra2012'     back-project ECoG onto the cortex using energy minimzation\n%                        'hermes2010'      back-project ECoG onto the cortex along the local norm vector\n%                        'fsaverage'       surface-based realignment with FreeSurfer fsaverage brain (left->left or right->right)\n%                        'fsaverage_sym'   surface-based realignment with FreeSurfer fsaverage_sym left hemisphere (left->left or right->left)\n%                        'fsinflated'      surface-based realignment with FreeSurfer individual subject inflated brain (left->left or right->right)\n%   cfg.channel        = Nx1 cell-array with selection of channels (default = 'all'),\n%                        see  FT_CHANNELSELECTION for details\n%   cfg.keepchannel    = string, 'yes' or 'no' (default = 'no')\n%   cfg.fiducial       = cell-array with the name of three fiducials used for\n%                        realigning (default = {'nasion', 'lpa', 'rpa'})\n%   cfg.casesensitive  = 'yes' or 'no', determines whether string comparisons\n%                        between electrode labels are case sensitive (default = 'yes')\n%   cfg.feedback       = 'yes' or 'no' (default = 'no')\n%\n% The electrode positions can be present in the 2nd input argument or can be specified as\n%   cfg.elec          = structure with electrode positions or filename, see FT_READ_SENS\n%\n% If you want to realign the EEG electrodes using anatomical fiducials, you should\n% specify the target location of the three fiducials, e.g.\n%   cfg.target.pos(1,:) = [110 0 0]     % location of the nose\n%   cfg.target.pos(2,:) = [0  90 0]     % location of the left ear\n%   cfg.target.pos(3,:) = [0 -90 0]     % location of the right ear\n%   cfg.target.label    = {'NAS', 'LPA', 'RPA'}\n%\n% If you want to align EEG electrodes to a single or multiple template electrode sets\n% (which will be averaged), you should specify the template electrode sets either as\n% electrode structures (i.e. when they are already read in memory) or their file\n% names using\n%   cfg.target          = single electrode set that serves as standard\n% or\n%   cfg.target{1..N}    = list of electrode sets that will be averaged\n%\n% If you want to align EEG electrodes to the head surface, you should specify the head surface as\n%   cfg.headshape      = a filename containing headshape, a structure containing a\n%                        single triangulated boundary, or a Nx3 matrix with surface\n%                        points\n%\n% If you want to align ECoG electrodes to the pial surface, you first need to compute\n% the cortex hull with FT_PREPARE_MESH. Then use either the algorithm described in\n% Dykstra et al. (2012, Neuroimage) or in Hermes et al. (2010, J Neurosci methods) to\n% snap the electrodes back to the cortical hull, e.g.\n%   cfg.method         = 'headshape'\n%   cfg.warp           = 'dykstra2012', or 'hermes2010'\n%   cfg.headshape      = a filename containing headshape, a structure containing a\n%                        single triangulated boundary, or a Nx3 matrix with surface\n%                        points\n%   cfg.feedback       = 'yes' or 'no' (default), feedback of the iteration procedure\n%\n% Additional configuration options for cfg.warp = 'dykstra2012'\n%   cfg.maxiter        = number (default: 50), maximum number of optimization iterations\n%   cfg.pairmethod     = 'pos' (default) or 'label', the method for electrode\n%                        pairing on which the deformation energy is based\n%   cfg.isodistance    = 'yes', 'no' (default) or number, to enforce isotropic\n%                        inter-electrode distances (pairmethod 'label' only)\n%   cfg.deformweight   = number (default: 1), weight of deformation relative \n%                        to shift energy cost (lower increases grid flexibility)\n%\n% If you want to move the electrodes inward, you should specify\n%   cfg.moveinward     = number, the distance that the electrode should be moved\n%                        inward (negative numbers result in an outward move)\n%\n% If you want to align ECoG electrodes to the freesurfer average brain, you should\n% specify the path to your headshape (e.g., lh.pial), and ensure you have the\n% corresponding registration file (e.g., lh.sphere.reg) in the same directory.\n% Moreover, the path to the local freesurfer home is required. Note that, because the\n% electrodes are being aligned to the fsaverage brain, the corresponding brain should\n% be also used when plotting the data, i.e. use freesurfer/subjects/fsaverage/surf/lh.pial\n% rather than surface_pial_left.mat\n%   cfg.method         = 'headshape'\n%   cfg.warp           = 'fsaverage'\n%   cfg.headshape      = string, filename containing subject headshape (e.g. <path to freesurfer/surf/lh.pial>)\n%   cfg.fshome         = string, path to freesurfer\n%\n% See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN,\n% FT_DETERMINE_COORDSYS, FT_PREPARE_MESH\n\n% Copyright (C) 2005-2019, Robert Oostenveld, Arjen Stolk\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% the interactive method uses a global variable to get the data from the figure when it is closed\nglobal norm\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar    elec_original\nft_preamble provenance elec_original\nft_preamble trackconfig\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed',    {'template', 'target'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial',  'fiducial'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogenous', 'rigidbody'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogeneous', 'rigidbody'});\ncfg = ft_checkconfig(cfg, 'forbidden', 'outline');\n\n% set the defaults\ncfg.warp          = ft_getopt(cfg, 'warp', 'rigidbody');\ncfg.channel       = ft_getopt(cfg, 'channel',  'all');\ncfg.keepchannel   = ft_getopt(cfg, 'keepchannel', 'no');\ncfg.feedback      = ft_getopt(cfg, 'feedback', 'no');\ncfg.casesensitive = ft_getopt(cfg, 'casesensitive', 'no');\ncfg.headshape     = ft_getopt(cfg, 'headshape', []);     % for triangulated head surface, without labels\ncfg.target        = ft_getopt(cfg, 'target',  []);       % for electrodes or fiducials, always with labels\ncfg.coordsys      = ft_getopt(cfg, 'coordsys');          % this allows for automatic template fiducial placement\n\nif isempty(cfg.target)\n  % remove the field, otherwise ft_checkconfig will complain\n  cfg = rmfield(cfg, 'target');\nend\n\nif ~isempty(cfg.coordsys) && isempty(cfg.target)\n  % set the template fiducial locations according to the coordinate system\n  switch lower(cfg.coordsys)\n    case 'ctf'\n      cfg.target = [];\n      cfg.target.coordsys = 'ctf';\n      cfg.target.pos(1,:) = [100  0 0];\n      cfg.target.pos(2,:) = [0   80 0];\n      cfg.target.pos(3,:) = [0  -80 0];\n      cfg.target.label{1} = 'NAS';\n      cfg.target.label{2} = 'LPA';\n      cfg.target.label{3} = 'RPA';\n    otherwise\n      ft_error('the %s coordinate system is not automatically supported, please specify fiducial details in cfg.target')\n  end\nend\n\n% ensure that the right cfg options have been set corresponding to the method\nswitch cfg.method\n  case 'template'        % realign the sensors to match a template set\n    cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');\n  case 'headshape'     % realign the sensors to fit the head surface\n    cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target');\n  case 'fiducial'        % realign using the NAS, LPA and RPA fiducials\n    cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');\n  case 'moveinward'      % moves eletrodes inward\n    cfg = ft_checkconfig(cfg, 'required', 'moveinward');\nend % switch cfg.method\n\nif strcmp(cfg.method, 'fiducial') && isfield(cfg, 'warp') && ~isequal(cfg.warp, 'rigidbody')\n  ft_warning('The method ''fiducial'' implies a rigid body tramsformation. See also http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1722');\n  cfg.warp = 'rigidbody';\nend\n\nif isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')\n  % convert the nested config-object back into a normal structure\n  cfg.headshape = struct(cfg.headshape);\nend\n\nif isfield(cfg, 'target') && isa(cfg.target, 'config')\n  % convert the nested config-object back into a normal structure\n  cfg.target = struct(cfg.target);\nend\n\n% the data can be passed as input arguments or can be read from disk\nhasdata = exist('elec_original', 'var');\n\n% get the electrode definition that should be warped\nif ~hasdata\n  elec_original = ft_fetch_sens(cfg);\nelse\n  % the input electrodes were specified as second input argument\n  % or read from cfg.inputfile\nend\n\n% ensure that the units are specified\nelec_original = ft_determine_units(elec_original);\n\n% ensure up-to-date sensor description (Oct 2011)\nelec_original = ft_datatype_sens(elec_original);\n\n% ensure that channel and electrode positions are the same\nassert(isequaln(elec_original.elecpos, elec_original.chanpos), 'this function requires same electrode and channel positions');\n\n% remember the original electrode locations and labels and do all the work with a\n% temporary copy, this involves channel selection and changing to lower case\nelec = elec_original;\n\n% instead of working with all sensors, only work with the fiducials\n% this is useful for gradiometer structures\nif strcmp(cfg.method, 'fiducial') && isfield(elec, 'fid')\n  fprintf('using the fiducials instead of the sensor positions\\n');\n  elec.fid.unit = elec.unit;\n  elec          = elec.fid;\nend\n\nusetarget    = isfield(cfg, 'target')    && ~isempty(cfg.target);\nuseheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);\n\nif usetarget\n  % get the template electrode definitions\n  if ~iscell(cfg.target)\n    cfg.target = {cfg.target};\n  end\n  Ntemplate = length(cfg.target);\n  for i=1:Ntemplate\n    if isstruct(cfg.target{i})\n      target(i) = cfg.target{i};\n    else\n      target(i) = ft_read_sens(cfg.target{i}, 'senstype', 'eeg');\n    end\n  end\n  clear tmp\n  for i=1:Ntemplate\n    % ensure up-to-date sensor description\n    % ensure that the units are consistent with the electrodes\n    tmp(i) = ft_convert_units(ft_datatype_sens(target(i)), elec.unit);\n  end\n  target = tmp;\nend\n\nif useheadshape\n  % get the surface describing the head shape\n  [headshape.pos, headshape.tri] = headsurface([], [], 'headshape', cfg.headshape);\n  \n  % ensure that the units are consistent with the electrodes\n  headshape = ft_convert_units(headshape, elec.unit);\nend\n\n% convert all labels to lower case for string comparisons\ncfg.channel = ft_channelselection(cfg.channel, elec.label);\nif strcmp(cfg.casesensitive, 'no')\n  elec.label  = lower(elec.label);\n  cfg.channel = lower(cfg.channel);\n  if usetarget\n    for j=1:length(target)\n      for i=1:length(target(j).label)\n        target(j).label{i} = lower(target(j).label{i});\n      end\n    end\n  end\nend\n[cfgsel, datsel] = match_str(cfg.channel, elec.label);\n% keep the original channel labels\nlabel_original = elec_original.label(datsel);\n\n% start with an empty structure, this will be returned at the end\nnorm = [];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif strcmp(cfg.method, 'template')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % determine electrode selection and overlapping subset for warping\n  cfg.channel = ft_channelselection(cfg.channel, elec.label);\n  for i=1:Ntemplate\n    cfg.channel = ft_channelselection(cfg.channel, target(i).label);\n  end\n\n  % make consistent subselection of electrodes\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label = elec.label(datsel);\n  elec.elecpos   = elec.elecpos(datsel,:);\n  for i=1:Ntemplate\n    [cfgsel, datsel] = match_str(cfg.channel, target(i).label);\n    target(i).label   = target(i).label(datsel);\n    target(i).elecpos = target(i).elecpos(datsel,:);\n  end\n\n  % compute the average of the target electrode positions\n  average = ft_average_sens(target);\n\n  fprintf('warping electrodes to average template... '); % the newline comes later\n  [norm.elecpos, norm.m] = ft_warp_optim(elec.elecpos, average.elecpos, cfg.warp);\n  norm.label = elec.label;\n\n  dpre  = mean(sqrt(sum((average.elecpos - elec.elecpos).^2, 2)));\n  dpost = mean(sqrt(sum((average.elecpos - norm.elecpos).^2, 2)));\n  fprintf('mean distance prior to warping %f, after warping %f\\n', dpre, dpost);\n\n  if strcmp(cfg.feedback, 'yes')\n    % create an empty figure, continued below...\n    figure\n    axis equal\n    axis vis3d\n    hold on\n    xlabel('x')\n    ylabel('y')\n    zlabel('z')\n\n    % plot all electrodes before warping\n    ft_plot_sens(elec, 'r*');\n\n    % plot all electrodes after warping\n    ft_plot_sens(norm, 'm.', 'label', 'label');\n\n    % plot the template electrode locations\n    ft_plot_sens(average, 'b.');\n\n    % plot lines connecting the input and the realigned electrode locations with the template locations\n    my_line3(elec.elecpos, average.elecpos, 'color', 'r');\n    my_line3(norm.elecpos, average.elecpos, 'color', 'm');\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'headshape')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % determine electrode selection and overlapping subset for warping\n  cfg.channel = ft_channelselection(cfg.channel, elec.label);\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label   = elec.label(datsel);\n  elec.elecpos = elec.elecpos(datsel,:);\n\n  norm.label = elec.label;\n  if strcmp(cfg.warp, 'dykstra2012')\n    norm.elecpos = warp_dykstra2012(cfg, elec, headshape);\n  elseif strcmp(cfg.warp, 'hermes2010')\n    norm.elecpos = warp_hermes2010(cfg, elec, headshape);\n  elseif strcmp(cfg.warp, 'fsaverage')\n    norm.elecpos = warp_fsaverage(cfg, elec);\n  elseif strcmp(cfg.warp, 'fsaverage_sym')\n    norm.elecpos = warp_fsaverage_sym(cfg, elec);\n  elseif strcmp(cfg.warp, 'fsinflated')\n    norm.elecpos = warp_fsinflated(cfg, elec);\n  else\n    fprintf('warping electrodes to skin surface... '); % the newline comes later\n    [norm.elecpos, norm.m] = ft_warp_optim(elec.elecpos, headshape, cfg.warp);\n\n    dpre  = ft_warp_error([],     elec.elecpos, headshape, cfg.warp);\n    dpost = ft_warp_error(norm.m, elec.elecpos, headshape, cfg.warp);\n    fprintf('mean distance prior to warping %f, after warping %f\\n', dpre, dpost);\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'fiducial')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % the fiducials have to be present in the electrodes and in the template set\n  label = intersect(lower(elec.label), lower(target.label));\n\n  if ~isfield(cfg, 'fiducial') || isempty(cfg.fiducial)\n    % try to determine the names of the fiducials automatically\n    option1 = {'nasion' 'left' 'right'};\n    option2 = {'nasion' 'lpa' 'rpa'};\n    option3 = {'nz' 'left' 'right'};\n    option4 = {'nz' 'lpa' 'rpa'};\n    option5 = {'nas' 'left' 'right'};\n    option6 = {'nas' 'lpa' 'rpa'};\n    if length(match_str(label, option1))==3\n      cfg.fiducial = option1;\n    elseif length(match_str(label, option2))==3\n      cfg.fiducial = option2;\n    elseif length(match_str(label, option3))==3\n      cfg.fiducial = option3;\n    elseif length(match_str(label, option4))==3\n      cfg.fiducial = option4;\n    elseif length(match_str(label, option5))==3\n      cfg.fiducial = option5;\n    elseif length(match_str(label, option6))==3\n      cfg.fiducial = option6;\n    else\n      ft_error('could not determine consistent fiducials in the input and the target, please specify cfg.fiducial or cfg.coordsys')\n    end\n  end\n  fprintf('matching fiducials {''%s'', ''%s'', ''%s''}\\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});\n\n  % determine electrode selection\n  cfg.channel = ft_channelselection(cfg.channel, elec.label);\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label     = elec.label(datsel);\n  elec.elecpos   = elec.elecpos(datsel,:);\n\n  if length(cfg.fiducial)~=3\n    ft_error('you must specify exactly three fiducials');\n  end\n\n  % do case-insensitive search for fiducial locations\n  nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));\n  if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1\n    ft_error('not all fiducials were found in the electrode set');\n  end\n  elec_nas = elec.elecpos(nas_indx,:);\n  elec_lpa = elec.elecpos(lpa_indx,:);\n  elec_rpa = elec.elecpos(rpa_indx,:);\n\n  % FIXME change the flow in the remainder\n  % if one or more template electrode sets are specified, then align to the average of those\n  % if no template is specified, then align so that the fiducials are along the axis\n\n  % find the matching fiducials in the template and average them\n  tmpl_nas = nan(Ntemplate,3);\n  tmpl_lpa = nan(Ntemplate,3);\n  tmpl_rpa = nan(Ntemplate,3);\n  for i=1:Ntemplate\n    nas_indx = match_str(lower(target(i).label), lower(cfg.fiducial{1}));\n    lpa_indx = match_str(lower(target(i).label), lower(cfg.fiducial{2}));\n    rpa_indx = match_str(lower(target(i).label), lower(cfg.fiducial{3}));\n    if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1\n      ft_error('not all fiducials were found in template %d', i);\n    end\n    tmpl_nas(i,:) = target(i).elecpos(nas_indx,:);\n    tmpl_lpa(i,:) = target(i).elecpos(lpa_indx,:);\n    tmpl_rpa(i,:) = target(i).elecpos(rpa_indx,:);\n  end\n  tmpl_nas = mean(tmpl_nas,1);\n  tmpl_lpa = mean(tmpl_lpa,1);\n  tmpl_rpa = mean(tmpl_rpa,1);\n\n  % realign both to a common coordinate system\n  elec2common  = ft_headcoordinates(elec_nas, elec_lpa, elec_rpa);\n  templ2common = ft_headcoordinates(tmpl_nas, tmpl_lpa, tmpl_rpa);\n\n  % compute the combined transform\n  norm         = [];\n  norm.m       = templ2common \\ elec2common;\n\n  % apply the transformation to the fiducials as sanity check\n  norm.elecpos(1,:) = ft_warp_apply(norm.m, elec_nas, 'homogeneous');\n  norm.elecpos(2,:) = ft_warp_apply(norm.m, elec_lpa, 'homogeneous');\n  norm.elecpos(3,:) = ft_warp_apply(norm.m, elec_rpa, 'homogeneous');\n  norm.label        = cfg.fiducial;\n\n  nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));\n  dpre  = mean(sqrt(sum((elec.elecpos([nas_indx lpa_indx rpa_indx],:) - [tmpl_nas; tmpl_lpa; tmpl_rpa]).^2, 2)));\n  nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));\n  dpost = mean(sqrt(sum((norm.elecpos([nas_indx lpa_indx rpa_indx],:) - [tmpl_nas; tmpl_lpa; tmpl_rpa]).^2, 2)));\n  fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\\n', dpre, dpost);\n\n  if strcmp(cfg.feedback, 'yes')\n    % create an empty figure, continued below...\n    figure\n    axis equal\n    axis vis3d\n    hold on\n    xlabel('x')\n    ylabel('y')\n    zlabel('z')\n\n    % plot the first three electrodes before transformation\n    my_plot3(elec.elecpos(1,:), 'r*');\n    my_plot3(elec.elecpos(2,:), 'r*');\n    my_plot3(elec.elecpos(3,:), 'r*');\n    my_text3(elec.elecpos(1,:), elec.label{1}, 'color', 'r');\n    my_text3(elec.elecpos(2,:), elec.label{2}, 'color', 'r');\n    my_text3(elec.elecpos(3,:), elec.label{3}, 'color', 'r');\n\n    % plot the template fiducials\n    my_plot3(tmpl_nas, 'b*');\n    my_plot3(tmpl_lpa, 'b*');\n    my_plot3(tmpl_rpa, 'b*');\n    my_text3(tmpl_nas, ' nas', 'color', 'b');\n    my_text3(tmpl_lpa, ' lpa', 'color', 'b');\n    my_text3(tmpl_rpa, ' rpa', 'color', 'b');\n\n    % plot all electrodes after transformation\n    my_plot3(norm.elecpos, 'm.');\n    my_plot3(norm.elecpos(1,:), 'm*');\n    my_plot3(norm.elecpos(2,:), 'm*');\n    my_plot3(norm.elecpos(3,:), 'm*');\n    my_text3(norm.elecpos(1,:), norm.label{1}, 'color', 'm');\n    my_text3(norm.elecpos(2,:), norm.label{2}, 'color', 'm');\n    my_text3(norm.elecpos(3,:), norm.label{3}, 'color', 'm');\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'interactive')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  tmpcfg = [];\n  tmpcfg.individual.elec = elec;\n  if isfield(cfg, 'headshape') && ~isempty(cfg.headshape)\n    tmpcfg.template.headshape = cfg.headshape;\n  end\n  if isfield(cfg, 'target') && ~isempty(cfg.target)\n    if iscell(cfg.target)\n      if numel(cfg.target)>1\n        ft_notice('computing the average electrode positions');\n        tmpcfg.template.elec = ft_average_sens(cfg.target);\n      else\n        tmpcfg.template.elec = cfg.target{1};\n      end\n    elseif isstruct(cfg.target)\n      tmpcfg.template.elec = cfg.target;\n    end\n    tmpcfg.template.elecstyle = {'facecolor', 'blue'};\n    ft_info('plotting the target electrodes in blue');\n  end\n\n  % use the more generic ft_interactiverealign for the actual work\n  tmpcfg = ft_interactiverealign(tmpcfg);\n  % only keep the transformation, it will be applied to the electrodes further down\n  norm.m = tmpcfg.m;\n\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'project')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % determine electrode selection\n  cfg.channel = ft_channelselection(cfg.channel, elec.label);\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label     = elec.label(datsel);\n  elec.elecpos   = elec.elecpos(datsel,:);\n\n  norm.label = elec.label;\n  [dum, norm.elecpos] = project_elec(elec.elecpos, headshape.pos, headshape.tri);\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'moveinward')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % determine electrode selection\n  cfg.channel = ft_channelselection(cfg.channel, elec.label);\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label     = elec.label(datsel);\n  elec.elecpos   = elec.elecpos(datsel,:);\n\n  norm.label = elec.label;\n  norm.elecpos = moveinward(elec.elecpos, cfg.moveinward);\n\nelse\n  ft_error('unknown method');\nend % if method\n\n\n% apply the spatial transformation to all electrodes, and replace the\n% electrode labels by their case-sensitive original values\nswitch cfg.method\n  case {'template', 'headshape'}\n    if strcmpi(cfg.warp, 'dykstra2012') || strcmpi(cfg.warp, 'hermes2010') || ...\n        strcmpi(cfg.warp, 'fsaverage') || strcmpi(cfg.warp, 'fsaverage_sym') || strcmpi(cfg.warp, 'fsinflated')\n      elec_realigned = norm;\n      elec_realigned.label = label_original;\n    else\n      % the transformation is a linear or non-linear warp, i.e. a vector\n      try\n        % convert the vector with fitted parameters into a 4x4 homogenous transformation\n        % apply the transformation to the original complete set of sensors\n        elec_realigned = ft_transform_geometry(feval(cfg.warp, norm.m), elec_original);\n      catch\n        % the previous section will fail for nonlinear transformations\n        elec_realigned.label = label_original;\n        try\n          elec_realigned.elecpos = ft_warp_apply(norm.m, elec_original.elecpos, cfg.warp);\n        end % FIXME why is an error here not dealt with?\n      end\n      % remember the transformation\n      elec_realigned.(cfg.warp) = norm.m;\n    end\n\n  case  {'fiducial' 'interactive'}\n    % the transformation is a 4x4 homogenous matrix\n    % apply the transformation to the original complete set of sensors\n    elec_realigned = ft_transform_geometry(norm.m, elec_original);\n    % remember the transformation\n    elec_realigned.homogeneous = norm.m;\n\n  case {'project', 'moveinward'}\n    % nothing to be done\n    elec_realigned = norm;\n    elec_realigned.label = label_original;\n\n  otherwise\n    ft_error('unknown method');\nend\n\n% the coordinate system is in general not defined after transformation\nif isfield(elec_realigned, 'coordsys')\n  elec_realigned = rmfield(elec_realigned, 'coordsys');\nend\n\n% in some cases the coordinate system matches that of the input target or headshape\nswitch cfg.method\n  case 'template'\n    if isfield(target, 'coordsys')\n      elec_realigned.coordsys = target.coordsys;\n    end\n  case 'headshape'\n    if isfield(headshape, 'coordsys')\n      elec_realigned.coordsys = headshape.coordsys;\n    end\n    if isfield(elec_original, 'coordsys')\n      if strcmp(cfg.warp, 'dykstra2012') || strcmp(cfg.warp, 'hermes2010')  % this warp simply moves the electrodes in the same coordinate space\n        elec_realigned.coordsys = elec_original.coordsys;\n      elseif strcmp(cfg.warp, 'fsaverage')\n        elec_realigned.coordsys = 'fsaverage';\n      elseif strcmp(cfg.warp, 'fsaverage_sym')\n        elec_realigned.coordsys = 'fsaverage_sym';\n      end\n    end\n  case 'fiducial'\n    if isfield(target, 'coordsys')\n      elec_realigned.coordsys = target.coordsys;\n    end\n  case 'interactive'\n    % the coordinate system is not known\n  case {'project', 'moveinward'}\n    % the coordinate system remains the same\n    if isfield(elec_original, 'coordsys')\n      elec_realigned.coordsys = elec_original.coordsys;\n    end\n  otherwise\n    ft_error('unknown method');\nend\n\nif istrue(cfg.keepchannel)\n  % append the channels that are not realigned\n  [dum, idx] = setdiff(elec_original.label, elec_realigned.label);\n  idx = sort(idx);\n  elec_realigned.label = [elec_realigned.label; elec_original.label(idx)];\n  elec_realigned.elecpos = [elec_realigned.elecpos; elec_original.elecpos(idx,:)];\nend\n\n% channel positions are identical to the electrode positions (this was checked at the start)\nelec_realigned.chanpos = elec_realigned.elecpos;\nelec_realigned.tra = eye(numel(elec_realigned.label));\n\n% copy over unit, chantype, chanunit, and tra information in case this was not already done\nif ~isfield(elec_realigned, 'unit') && isfield(elec_original, 'unit')\n  elec_realigned.unit = elec_original.unit;\nend\nif ~isfield(elec_realigned, 'chantype') && isfield(elec_original, 'chantype')\n  idx = match_str(elec_original.label, elec_realigned.label);\n  elec_realigned.chantype = elec_original.chantype(idx);\nend\nif ~isfield(elec_realigned, 'chanunit') && isfield(elec_original, 'chanunit')\n  elec_realigned.chanunit = elec_original.chanunit;\n  idx = match_str(elec_original.label, elec_realigned.label);\n  elec_realigned.chanunit = elec_original.chanunit(idx);\nend\n\n% update it to the latest version\nelec_realigned = ft_datatype_sens(elec_realigned);\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble trackconfig\nft_postamble previous   elec_original\nft_postamble provenance elec_realigned\nft_postamble history    elec_realigned\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% some simple SUBFUNCTIONs that facilitate 3D plotting\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction h = my_plot3(xyz, varargin)\nh = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});\nfunction h = my_text3(xyz, varargin)\nh = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});\nfunction my_line3(xyzB, xyzE, varargin)\nfor i=1:size(xyzB,1)\n  line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/ft_electroderealign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2469533608534681}}
{"text": "function im = recomputeImage2(view,clipMode)\n%\n% im = recomputeImage2(view,clipMode)\n%\n% Recomputes the image (underlay/anat + overlay) for the\n% given view, returning the image. This is different from\n% recomputeImage in 3 ways:\n%       1) It produces a truecolor image;\n%       2) It returns the image rather than the view\n%          (I do this because I'm adding the option to\n%           work on mosaics of many of these images -- e.g.\n%           many inplane slices or flat levels)\n%       3) It doesn't take numGrays or numColors as arguments;\n%          (since it's true color, they're set to 256 each).\n%\n%\n% djh, sometime in '98\n% djh, 2/2001. version 3.0 \n% ras, 3/2004. An attempt to make the images true-color (3 image planes\n% (R,G,B), each ranging from 0-255, to allow for a full 256-value dynamic\n% range for both the anatomies and overlays). Will check that this doesn't\n% critically slow down updating the screen (with modern processors, this\n% seems unlikely).\n\n% Initialize images\nanatIm=[];\noverlay=[];\n\n% Get cothresh, phWindow, and mapWindow from sliders\ncothresh = getCothresh(view);\nphWindow = getPhWindow(view);\nmapWindow = getMapWindow(view);\n\n% although we accept numGrays and numColors for back-compatibility, now\n% that it's truecolor, we'll set these directly:\n% numGrays = 64;\n% numColors = 64;\n\nnumGrays = 256;\nnumColors = 256;\n\n% Get anatClip from sliders\nanatClip = getAnatClip(view);\n\n% Get anatomy image\nanatIm = cropCurAnatSlice(view);\n\n% Get overlay\noverlay = [];\nif ~strcmp(view.ui.displayMode,'anat')\n  overlay = cropCurSlice(view,view.ui.displayMode);\nend\n\n% Select pixels that satisfy cothresh, phWindow, and mapWindow\npts = [];\nif ~isempty(overlay)\n  pts = ones(size(overlay));\n  curCo=cropCurSlice(view,'co');\n  curPh=cropCurSlice(view,'ph');\n  curMap=cropCurSlice(view,'map');\n  if ~isempty(curCo) & cothresh>0\n    ptsCo = curCo > cothresh;\n    pts = pts & ptsCo;\n  end\n  if ~isempty(curPh)\n    if diff(phWindow) > 0\n      ptsPh = (curPh>=phWindow(1) & curPh<=phWindow(2));\n    else\n      ptsPh = (curPh>=phWindow(1) | curPh<=phWindow(2));\n    end\n    pts = pts & ptsPh;\n  end\n  if strcmp(view.ui.displayMode, 'amp')\n    curAmp = cropCurSlice(view, 'amp');\n    mnv = min(curAmp(:));\n    mxv = max(curAmp(:));\n    curMap = (curAmp - mnv) ./ (mxv - mnv);\n  end\n  if ~isempty(curMap)\n    ptsMap = (curMap>=mapWindow(1) & curMap<=mapWindow(2));\n    pts = pts & ptsMap;\n  end\nend\n\n% Rescale anatIm to [1:numGrays], anatClip determines the range\n% of anatomy values that gets mapped to the available grayscales.\n% If anatClip=[0,1] then there is no clipping and the entire\n% range of anatomy values is scaled to the range of available gray\n% scales.\nminVal = double(min(anatIm(:)));\nmaxVal = double(max(anatIm(:)));\nanatClipMin = min(anatClip)*(maxVal-minVal) + minVal;\nanatClipMax = max(anatClip)*(maxVal-minVal) + minVal;\nwarning off;\nanatIm = (rescale2(double(anatIm),[anatClipMin,anatClipMax],[1,numGrays]));\n%keyboard\n\nwarning backtrace;\n\n% Rescale overlay to [0 numGrays-1]\nif ~isempty(overlay)\n   if strcmp(clipMode,'auto')\n      if ~isempty(find(pts));\n         overClipMin = min(overlay(pts));\n         overClipMax = max(overlay(pts));\n      else\n         overClipMin = min(overlay(:));\n         overClipMax = max(overlay(:));\n      end\n   else\n      overClipMin = min(clipMode);\n      overClipMax = max(clipMode);\n   end\n   overlay=rescale2(overlay,[overClipMin overClipMax],[0 numGrays-1]);\nend\n\n% get, and threshold, the anatomical cmap:\nlightRng = [0.6 0.8];\ndarkRng = [0.2 0.4];\nthresh = 0.6;\nanatCmap = gray(256);\nanatCmap(anatCmap < thresh) = ...\n    normalize(anatCmap(anatCmap < thresh),darkRng(1),darkRng(2));\nanatCmap(anatCmap >= thresh) = ...\n    normalize(anatCmap(anatCmap >= thresh),lightRng(1),lightRng(2));\n\n% % convert into a truecolor RGB image, combining\n% % the overlay with the anatomy, if necessary\n% % Combine overlay with anatomy image\n% im = normalize(repmat(anatIm,[1 1 3]));\n%\n if ~isempty(overlay) & ~all(pts==0)\n     % for truecolor, we need to get the color map\n     % info directly.\n     cmapname = eval(['view.ui.' view.ui.displayMode 'Mode.name']);\n     cmapname = cmapname(1:end-4); % last 4 chars are 'Cmap'\n     cmap = feval(cmapname,0,256);\n     cmap = [anatCmap; cmap];\n     im = ind2rgb(overlay,cmap);\n     \n%     % get a set of R,G,B columns of values for each data point in the\n%     % overlay\n%     vals = cmap(overlay(pts)+1,:); \n%     \n%     % plug in the overlay into each R/G/B plane of the truecolor image:\n%     [indx,indy] = ind2sub(size(anatIm),find(pts));\n%     indz = [ones(length(indx),1); 2*ones(length(indx),1); 3*ones(length(indx),1)];\n%     indx = repmat(indx,3,1);\n%     indy = repmat(indy,3,1);\n%     final_ind = sub2ind(size(im),indx,indy,indz);\n%    im(final_ind) = vals\nelse\n    im = ind2rgb(anatIm,anatCmap);\nend\n\n% 2003.01.10 RFD: the following is no longer necessary- the uint8 data\n% can't have any NaNs! Also, it caused problems in matlab versions <6.5.\n% 2003.01.23 ARW: But without it, Matlab 6.5 fills in the Nans in the flat map as white.\n% Do a version check for now and replace NaNs if >=R13\nif (version('-release')>=13)\n    indices = find(isnan(im));\n    im(indices) = 1;\nend\n\n% Finally, set the view.ui.image field\n%view.ui.image = uint8(double(im)-1);\nview.ui.image = im;\n\nif isempty(overlay)\n   view.ui.cbarRange = [];\nelse\n   view.ui.cbarRange = [overClipMin overClipMax];  \nend\n\nreturn;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/View/recomputeImage2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24695336085346808}}
{"text": "function [DataMat, ChannelMat] = in_data_besa(DataFile)\n% IN_DATA_BESA: Read BESA EEG files.\n%\n% USAGE:  OutputData = in_data_besa( DataFile )\n%\n% INPUT:\n%     - DataFile : Full path to a recordings file.\n% OUTPUT: \n%     - DataMat : Brainstorm data (recordings) structure\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012-2015\n\n% Get format\n[fPath, fBase, fExt] = bst_fileparts(DataFile);\n% Initialize returned structure\nDataMat = db_template('DataMat');\nDataMat.Comment  = fBase;\nDataMat.Device   = 'BESA';\nDataMat.DataType = 'recordings';\nDataMat.nAvg     = 1;\nChanNames = {};\n\n% Open file\nfid = fopen(DataFile, 'r');\nif (fid == -1)\n    error('Cannot open file.');\nend\n\n% Switch according to file format\nswitch lower(fExt)\n    case {'.avr', '.mul'}\n        % Read header (first line)\n        hdr = fgetl(fid);\n        % Split to get all the parameters\n        hdr = str_split(hdr, ' =');\n        % Multiplexed/averaged files\n        if strcmpi(fExt, '.mul')\n            nTime     = str2num(hdr{2});\n            nChannels = str2num(hdr{4});\n            timeStart = str2num(hdr{6}) / 1000;  % Convert to seconds\n            timeStep  = str2num(hdr{8}) / 1000;  % Convert to seconds\n        else\n            nTime     = str2num(hdr{2});\n            timeStart = str2num(hdr{4}) / 1000;  % Convert to seconds\n            timeStep  = str2num(hdr{6}) / 1000;  % Convert to seconds\n            nChannels = 0;\n        end\n        % Read second line: Either the channel names or the first sensor\n        hdr = fgetl(fid);\n        % If there are alphabetical characters in the line: sensor names\n        if any(ismember(double(hdr), double('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz()[]/\\_@')))\n            % Replace spaces in channel names with _ (eg. \"TP 1\" to \"TP_1\")\n            for iDig = 0:9\n                hdr = strrep(hdr, sprintf(' %d', iDig), sprintf('_%d', iDig));\n            end\n            % Try to get the channel names\n            ChanNames = str_split(hdr, ' ');\n        % Else: It was the first sensor\n        else\n            % Restart reading the file at the beginning\n            fseek(fid, 0, 'bof');\n            hdr = fgetl(fid);\n        end\n        % Read the recordings in multiplexed/averaged mode\n        if strcmpi(fExt, '.mul')\n            DataMat.F = fscanf(fid, '%f', [nChannels, nTime]);\n        else\n            DataMat.F = fscanf(fid, '%f', [nTime, Inf])';\n        end\n        \n    case {'.mux'}\n        % Skip three lines\n        hdr = fgetl(fid);\n        hdr = fgetl(fid);\n        hdr = fgetl(fid);\n        % Read the recordings, line by line\n        allLines = {};\n        while 1\n            newLine = fgetl(fid);\n            if ~ischar(newLine)\n                break;\n            end\n            allLines{end+1} = str2num(newLine);\n        end\n        % Concatenate everything\n        DataMat.F = cat(1, allLines{:})';\n        \n        % Ask for time window\n        res = java_dialog('input', {'Start time (in miliseconds):', 'Sampling frequency'}, ...\n                                    'Time definition (in Hz)', [], {'0','1000'});\n        if isempty(res) || (length(str2num(res{1})) ~= 1) || (length(str2num(res{2})) ~= 1)\n            DataMat = [];\n        else\n            timeStart = str2num(res{1}) / 1000;\n            timeStep  = 1 / str2num(res{2});\n        end\n    otherwise\n        error(['Unsupported file extension: ' fExt]);\nend\n% Close file\nfclose(fid);\n\n% Rebuild time vector\nDataMat.Time = timeStart + (0:size(DataMat.F,2)-1) .* timeStep;\n% No bad channels defined in those files: all good\nnChannels = size(DataMat.F,1);\nDataMat.ChannelFlag = ones(nChannels, 1);\n\n% Try to build a channel file\nif ~isempty(ChanNames) && (length(ChanNames) == nChannels)\n    % Default channel structure\n    ChannelMat = db_template('channelmat');\n    ChannelMat.Comment = 'BESA channels';\n    ChannelMat.Channel = repmat(db_template('channeldesc'), [1, nChannels]);\n    % For each channel\n    for i = 1:nChannels\n        if ~isempty(ChanNames{i})\n            ChannelMat.Channel(i).Name = ChanNames{i};\n        elseif (length(ChannelMat.Channel) > 99)\n            ChannelMat.Channel(i).Name = sprintf('E%03d', i);\n        else\n            ChannelMat.Channel(i).Name = sprintf('E%02d', i);\n        end\n        ChannelMat.Channel(i).Type    = 'EEG';\n        ChannelMat.Channel(i).Loc     = [0; 0; 0];\n        ChannelMat.Channel(i).Orient  = [];\n        ChannelMat.Channel(i).Weight  = 1;\n        ChannelMat.Channel(i).Comment = [];\n    end\nelse\n    ChannelMat = [];\nend\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_data_besa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2469533556692104}}
{"text": "function [scoreF,score0] = argmax_fit_token(Mfit_init,lib)\n% ARGMAX_FIT_TOKEN Fit a parse to an image, with token-level parameters\n% only\n% \n%  Mfit_init : instance of class MotorProgramFit\n%\n% Output:\n%  scoreF : final score\n%  score0 : initial score\n% \n\n    % set up objective function\n    Mfit = Mfit_init.copy();    \n    fmin = @(theta) myscore(theta,Mfit,lib);\n\n    % Set-up the optimization problem  \n    [theta0,lb,ub] = model_to_vec_fit_token(Mfit);    \n    options = optimset('Display','off');\n    options = optimset(options,'Display','iter');\n    options = optimset(options,'TolFun',1e-4,'Algorithm','active-set');\n\n    % Run the optimization\n    score0 = -fmin(theta0);\n    try\n        thetaF = fmincon(fmin,theta0,[],[],[],[],lb,ub,[],options);\n    catch\n        fprintf(1,'*Warning*: optimization failed. Error caught.\\n'); \n        thetaF = theta0;\n    end\n    scoreF = -fmin(thetaF);\n    \n    refill(thetaF,Mfit_init);\n    \nend\n\nfunction refill(theta,M)\n    vec_to_model_fit_token(theta,M);\nend\n\n% fill the MotorProgram with parameters\n% and then score\nfunction minscore = myscore(theta,Mfit,lib)\n    Qfit = Mfit.copy(); % we don't want to modify the shared MotorProgramFit base\n    refill(theta,Qfit);\n    ll = scoreMP_fit(Qfit,lib);    \n    minscore = -ll;\nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/optimization/argmax_fit_token.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24676624590664595}}
{"text": "%% MEEG time-lock searchlight\n%\n% This example shows MVPA analyses performed on MEEG data.\n%\n% The input dataset involved a paradigm where a participant saw\n% images of six object categories.\n%\n%\n% The code presented here can be adapted for other MEEG analyses, but\n% there please note:\n% * the current examples do not perform baseline corrections or signal\n%   normalizations, which may reduce discriminatory power.\n%\n% Note: running this code requires FieldTrip.\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n\n\n%% get timelock data in CoSMoMVPA format\n\n% set configuration\nconfig=cosmo_config();\ndata_path=fullfile(config.tutorial_data_path,'meg_obj6');\n\n% show dataset information\nreadme_fn=fullfile(data_path,'README');\ncosmo_type(readme_fn);\n\n% reset citation list\ncosmo_check_external('-tic');\n\n% load preprocessed data\ndata_fn=fullfile(data_path,'meg_obj6_s00.mat');\ndata_tl=load(data_fn);\n\n% Show data_tl\n% >@@>\ncosmo_disp(data_tl);\n% <@@<\n\n%%\n\n% convert to cosmomvpa struct, using cosmo_meeg_dataset\n% >@@>\nds=cosmo_meeg_dataset(data_tl);\n% <@@<\n\n% show the dataset\n% >@@>\ncosmo_disp(ds);\n% <@@<\n\n\n%%\n\n% set the targets in ds.sa.targets (trial condition)\n% Hint: use the first column from ds.sa.trialinfo\n% >@@>\nds.sa.targets=ds.sa.trialinfo(:,1); % 6 categories\n% <@@<\n\n% set the chunks in ds.sa.chunks (independent measurements)\n% all trials are here considered to be independent, so the chunks\n% must all have a different value\n% >@@>\nnsamples=size(ds.samples,1);\nds.sa.chunks=(1:nsamples)';\n% <@@<\n\n% in addition give a label to each trial\nindex2label={'body','car','face','flower','insect','scene'};\nds.sa.labels=cellfun(@(x)index2label(x),num2cell(ds.sa.targets));\n\n% just to check everything is ok\ncosmo_check_dataset(ds);\n\n\n%% Count number of channels, time points and trials\n% >@@>\nfprintf('There are %d channels, %d time points and %d trials\\n',...\n        numel(unique(ds.fa.chan)),numel(unique(ds.fa.time)),...\n        size(ds.samples,1));\n% <@@<\n%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Part I: compute difference between faces and scenes\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% For each time point and sensor; then visualize the results\n% for the magnetometer (meg_axial) sensors.\n\n% slice 'ds' twice to get 'ds_face' and 'ds_scene', each with only trials\n% from the face and scene categories\n\n% >@@>\nds_face=cosmo_slice(ds,cosmo_match(ds.sa.labels,'face'));\nds_scene=cosmo_slice(ds,cosmo_match(ds.sa.labels,'scene'));\n% <@@<\n\n% prepare dataset for output\nds_faceVSscene=cosmo_slice(ds_face,1);\nds_faceVSscene.sa=struct(); % destroy sample attributes\n\n% Compute difference between average of faces versus average of scenes;\n% store the result in the samples field of ds_faceVSscene\n% >@@>\nds_faceVSscene.samples=mean(ds_face.samples)-mean(ds_scene.samples);\n% <@@<\n\n% Convert ds_faceVSscene to a fieldtrip structure and convert\nft_faceVSscene=cosmo_map2meeg(ds_faceVSscene);\n%%\n% Use FieldTrip to visualize the face versus house contrast\nchantype='meg_axial';\nlayout=cosmo_meeg_find_layout(ds_faceVSscene,'chantype',chantype);\n\nfigure();\ncfg=struct();\ncfg.interactive='yes';\ncfg.zlim=[-1 1];\ncfg.layout=layout;\n\n% show figure with plots for each sensor\nft_multiplotER(cfg, ft_faceVSscene);\n%%\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Part 2: run searchlight over time\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% set MVPA parameters\nfprintf('The input has feature dimensions %s\\n', ...\n                cosmo_strjoin(ds.a.fdim.labels,', '));\n\n% only select relevant time period and sensors\nsensor_posterior_axial={'MEG1631', 'MEG1641', 'MEG1731', 'MEG1841', ...\n                        'MEG1911', 'MEG1921', 'MEG1941', 'MEG2231', ...\n                        'MEG2311', 'MEG2321', 'MEG2341', 'MEG2431', ...\n                        'MEG2441', 'MEG2511', 'MEG2531'};\n\n% define the mask\nmsk=cosmo_dim_match(ds,'time',@(t) t>=-.1 & t<=.4,...\n                        'chan',sensor_posterior_axial);\n\n% first slice the dataset, then use cosmo_dim_prune to avoid using\n% non-selected data. Assign the result to ds_sel\n%%%% >>> Your code here <<< %%%%\nds_sel_orig=cosmo_slice(ds,msk,2);\ncosmo_disp(ds_sel_orig);\n\nft_orig=cosmo_map2meeg(ds_sel_orig);\n%%\nds_sel=cosmo_dim_prune(ds_sel_orig);\ncosmo_disp(ds_sel);\nft_sel=cosmo_map2meeg(ds_sel);\n\n%%\n\n% define the neighborhood for time with a time radius of 2 time points,\n% and assign to time_nbrhood.\n% Hint: use cosmo_interval_neighborhood,\n\ntime_nbrhood=cosmo_interval_neighborhood(ds_sel,'time','radius',2);\ncosmo_disp(time_nbrhood)\n\n%%\n\n%%%% >>> Your code here <<< %%%%\n\n% Define the measure to be cosmo_crossvalidation_measure,\n% and assign to measure\nmeasure=@cosmo_crossvalidation_measure;\n\n%%%% >>> Your code here <<< %%%%\n\n%nsamples=numel(ds_sel.samples);\n%rp=cosmo_randperm(nsamples);\n%ds_sel.sa.targets=ds_sel.sa.targets(rp);\n\npartitions=cosmo_independent_samples_partitioner(ds_sel,...\n                                    'fold_count',5,...\n                                    'test_ratio',0.2);\n\ncosmo_disp(partitions)\n%%\n% Define the partitioning scheme using\n% cosmo_independent_samples_partitioner, and assign to partitions.\n% Use 'fold_count',5 to use 5 folds,\n% and use 'test_ratio',.2 to use 20% of the data for testing (and 80% for\n% training) in each fold.\n\n%%%% >>> Your code here <<< %%%%\n\n% Use the LDA classifier and the partitions just defined,\nmeasure_args=struct();\nmeasure_args.partitions=partitions;\nmeasure_args.classifier=@cosmo_classify_lda;\n\n\n\nds_sl=cosmo_searchlight(ds_sel,time_nbrhood,measure,measure_args);\n\nplot(ds_sl.a.fdim.values{1},ds_sl.samples)\nxlabel('time');\nylabel('classification accuracy');\n\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Part III: channel-time searchlight\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% select limited time period\nmsk=cosmo_dim_match(ds,'time',@(t) t>=-.1 & t<=.4);\n\n% first slice the dataset using the mask and assign to 'ds_sel'\nds_sel=cosmo_slice(ds,msk,2);\n\n% Now use cosmo_dim_prune to avoid attempts to using\n% non-selected data in the searchlight\nds_sel=cosmo_dim_prune(ds_sel);\n\n% Set the seachlight parameters\nchan_count=10; % 10 center channels in each searchlight\ntime_radius=2; % 2*2+1=5 time bins\nchan_type='meg_combined_from_planar';\n\n% define the neighborhood for each dimensions\n% First, set 'chan_nbrhood' using cosmo_meeg_chan_neighborhood,\n% and use the 'chantype' and 'count' parameters to set the channel type\n% and the number of sensors in each searchlight.\nchan_nbrhood=cosmo_meeg_chan_neighborhood(ds_sel,'chantype',chan_type,...\n                                    'count',chan_count);\n\n\ncosmo_disp(chan_nbrhood);\n%%\n\n\n%%%% >>> Your code here <<< %%%%\n\n% Second, set 'time_nbrhood' using cosmo_interval_neighborhood,\n% using the 'time' dimension\n\ntime_nbrhood=cosmo_interval_neighborhood(ds_sel,'time','radius',2);\n\n%%%% >>> Your code here <<< %%%%\n\n% cross neighborhoods for chan-time searchlight\n% Hint: use cosmo_cross_neighborhood, and use chan_nbrhood and time_nbrhood\n% (in that order) in a cell as the second argument\nnbrhood=cosmo_cross_neighborhood(ds_sel,{chan_nbrhood,time_nbrhood});\n\n\n%%%% >>> Your code here <<< %%%%\n\n% print how many neighbors features have on average\nnbrhood_nfeatures=cellfun(@numel,nbrhood.neighbors);\nfprintf('Features have on average %.1f +/- %.1f neighbors\\n', ...\n            mean(nbrhood_nfeatures), std(nbrhood_nfeatures));\n\n%%\n\n% set the 'measure' variable to a function handle to the\n% split-half correlation measure\nmeasure=@cosmo_correlation_measure;\n\n\n% Define the partitioning scheme using\n% cosmo_independent_samples_partitioner.\n% Use 'fold_count',1 to use 1 folds,\n% and use 'test_ratio',.5 to use 50% of the data for testing (and 50% for\n% training) in the single fold.\npartitions=cosmo_independent_samples_partitioner(ds_sel,'fold_count',1,...\n                                            'test_ratio',0.5);\n\n\n\n%%%% >>> Your code here <<< %%%%\nmeasure_args=struct();\nmeasure_args.partitions=partitions;\n\n\n%% run searchlight\n% run the searchlight using the parameters above, and assign the result\n% to a varibale 'ds_sl'\n\nds_sl=cosmo_searchlight(ds_sel,nbrhood,measure,measure_args);\n\n%%%% >>> Your code here <<< %%%%\n\n%% visualize timeseries results\n\n% deduce layout from output\nlayout=cosmo_meeg_find_layout(ds_sl);\nfprintf('The output uses layout %s\\n', layout.name);\n\n% map ds_sl to a FieldTrip structure. Assign the result to 'sl_ft'\nsl_ft=cosmo_map2meeg(ds_sl);\n\n%%%% >>> Your code here <<< %%%%\n\nfigure();\ncfg = [];\ncfg.interactive = 'yes';\ncfg.zlim=[-1 1];\ncfg.layout       = layout;\n\n% show figure with fisher-transformed correlations for each sensor\nft_multiplotER(cfg, sl_ft);\n\n%% visualize topology results\n% show figure with topology for 100 before to 400ms after stimulus onset\n% in bins of 50 ms\nfigure();\ncfg.xlim=-0.1:0.05:0.4;\nft_topoplotER(cfg, sl_ft);\n\n%% Show citation information\ncosmo_check_external('-cite');\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/examples/run_meeg_timelock_measures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24676624590664595}}
{"text": "function y=ewmacovariance(R1,R2,n,s,lambda)\n%\n% implemented by ewmaestimatevar function\n%\n%% Written By Ali Najjar\n%\nif s==1 \n    y=R1(n-s)*R2(n-s);\nelse \n    y=((1-lambda)*((R1(n-1))*(R2(n-1))))+(lambda*ewmacovariance(R1,R2,n-1,s-1,lambda));\nend\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32251-estimation-value-at-risk-by-using-exponentially-weighted-moving-averagege/EWMA-Up20122808/ewmacovariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24676624590664586}}
{"text": "clear all;\nclose all;\nclc;\ncheck_yale_faces(4, @ssc_l1, 'ssc_l1');\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/ssc_yale_faces/ex_ssc_l1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24676624590664586}}
{"text": "function measPara = convertToMeasPara( drecksMDH, measPara )\n%CONVERTTOMEASPARA convert from drecksMDH 2.0-struct to measPara-struct,\n% but measPara-struct now contains just all needed variables\n%\n% (c) Thomas Kuestner\n% ---------------------------------------------------------------------\n\nif(drecksMDH.Seq.Is3D)\n    measPara.dimensionSeq = '3D';\nelse\n    measPara.dimensionSeq = '2D';\nend\nmeasPara.sliceThickness = drecksMDH.Geo.FOV(3)/drecksMDH.Geo.MatrixSize(3);\nmeasPara.lines = drecksMDH.Geo.MatrixSize(2);\nmeasPara.partitions = drecksMDH.Geo.MatrixSize(3);\nmeasPara.baseResolution = drecksMDH.Geo.MatrixSize(1);\nmeasPara.FOVread = drecksMDH.Geo.FOV(1);\nmeasPara.FOVphase = drecksMDH.Geo.FOV(2);\nmeasPara.sequenceName = drecksMDH.Seq.Sequence;\nif(isfield(drecksMDH.Geo,'FFTLength'))\n    measPara.ftlenPhase = drecksMDH.Geo.FFTLength(1);\n    measPara.ftlenPar = drecksMDH.Geo.FFTLength(2);\nelse\n    measPara.ftlenPhase = [];\n    measPara.ftlenPar = [];\nend\nmeasPara.imageWidth = [];\nmeasPara.imageHeight = [];\n\nif(isfield(drecksMDH,'Accel') && isfield(drecksMDH.Accel,'EspressoDir'))\n    dir_mapping = {'y', 'z', 'off'};\n    measPara.ESPReSSoDirection = dir_mapping{drecksMDH.Accel.EspressoDir};\n    pfn_mapping = [81, 90, 99, 108, 117; 1, 0.5, 0.625, 0.75, 0.875];\n    measPara.ESPReSSo = pfn_mapping(2,pfn_mapping(1,:) == drecksMDH.Accel.EspressoFactor);    \nelse\n    measPara.ESPReSSoDirection = 'off';\n    measPara.ESPReSSo = 1;\nend\n\nif(isfield(drecksMDH,'Wip'))\n    if(isfield(drecksMDH.Wip,'SamplingFactor'))\n        measPara.CSAcceleration = drecksMDH.Wip.SamplingFactor;\n    end\n    if(isfield(drecksMDH.Wip,'Phases'))\n       \tmeasPara.dim(4) = drecksMDH.Wip.Phases;\n    end    \n    if(isfield(drecksMDH.Wip,'FullySampled'))\n        measPara.CSFullySampled = drecksMDH.Wip.FullySampled;\n    end\n    if(isfield(drecksMDH.Wip,'Mask'))\n        switch drecksMDH.Wip.Mask(1:2)\n            case '06', measPara.CSSamplingType = 'Poisson';\n            case '07', measPara.CSSamplingType = 'Random';\n            case '08', measPara.CSSamplingType = 'Gaussian';\n        end\n        if(length(drecksMDH.Wip.Mask) > 3)\n            switch drecksMDH.Wip.Mask(4:5)\n                case '01', measPara.CSVDmap = 'None';\n                case '02', measPara.CSVDmap = 'Point';\n                case '03', measPara.CSVDmap = 'Block';\n                case '04', measPara.CSVDmap = 'Ellipse';\n                case '05', measPara.CSVDmap = 'Ring';\n            end\n    %         switch drecksMDH.Wip.Mask(7:8)\n    %             case '14', measPara.CSBodyRegion = 'None';\n    %             case '15', measPara.CSBodyRegion = 'Head';\n    %             case '16', measPara.CSBodyRegion = 'Thorax';\n    %             case '17', measPara.CSBodyRegion = 'Abdomen';\n    %             case '18', measPara.CSBodyRegion = 'Pelvis';\n    %         end\n        end\n    end\nend\n\nif(isfield(drecksMDH.Seq,'Bandwidth'))\n    measPara.bandwidthPerPixel = drecksMDH.Seq.Bandwidth;\nend\n\nif(isfield(drecksMDH.Geo,'NormSag'))\n    if(drecksMDH.Geo.NormSag)\n        measPara.orientation    = 'sagittal';\n    elseif(drecksMDH.Geo.NormCor)\n        measPara.orientation    = 'coronal';\n    elseif(drecksMDH.Geo.NormTra)\n        measPara.orientation    = 'transversal';\n    else\n        measPara.orientation = 'rotated';\n    end\n\n    % pixel positions\n    if(isfield(drecksMDH.Geo,'Shift'))\n        measPara.position = drecksMDH.Geo.Shift;\n    else\n        measPara.position = zeros(1,3);\n    end\n    measPara.pixelSpacing = [drecksMDH.Geo.FOV(2)/drecksMDH.Geo.MatrixSize(2), drecksMDH.Geo.FOV(1)/drecksMDH.Geo.MatrixSize(1), drecksMDH.Geo.FOV(3)/drecksMDH.Geo.MatrixSize(3)]; % y-x-z/slice\n    center = [drecksMDH.Geo.MatrixSize(2)/2, drecksMDH.Geo.MatrixSize(1)/2, drecksMDH.Geo.MatrixSize(3)/2];\n\n    switch measPara.orientation\n        case 'sagittal'\n            measPara.xPos = measPara.position(1) + ([1:drecksMDH.Geo.MatrixSize(3)].' - center(3)) .* measPara.pixelSpacing(3);\n            measPara.yPos = measPara.position(2) + ([1:drecksMDH.Geo.MatrixSize(2)].' - center(1)) .* measPara.pixelSpacing(1);\n            measPara.zPos = measPara.position(3) + ([1:drecksMDH.Geo.MatrixSize(1)].' - center(2)) .* measPara.pixelSpacing(2);\n        case 'coronal'\n            measPara.xPos = measPara.position(1) + ([1:drecksMDH.Geo.MatrixSize(1)].' - center(2)) .* measPara.pixelSpacing(2);\n            measPara.yPos = measPara.position(2) + ([1:drecksMDH.Geo.MatrixSize(3)].' - center(3)) .* measPara.pixelSpacing(3);\n            measPara.zPos = measPara.position(3) + ([1:drecksMDH.Geo.MatrixSize(2)].' - center(1)) .* measPara.pixelSpacing(1);\n        case 'transversal'\n            measPara.xPos = measPara.position(1) + ([1:drecksMDH.Geo.MatrixSize(1)].' - center(2)) .* measPara.pixelSpacing(2);\n            measPara.yPos = measPara.position(2) + ([1:drecksMDH.Geo.MatrixSize(2)].' - center(1)) .* measPara.pixelSpacing(1);\n            measPara.zPos = measPara.position(3) + ([1:drecksMDH.Geo.MatrixSize(3)].' - center(3)) .* measPara.pixelSpacing(3);\n        otherwise \n            %\n    end\nend\n\n% correct values\nif(~isfield(measPara,'dim'))\n    measPara.dim = zeros(1,5);\n    measPara.LCall = zeros(1,4);\nend\nmeasPara.dim(1) = measPara.lines;\nmeasPara.dim(2) = drecksMDH.Geo.OverSampling(1) * measPara.baseResolution; % due to CS_Trufi prescans\nmeasPara.dim(3) = measPara.partitions;\n% if(strcmp(measPara.sequenceName, 'CS_Trufi') && ~isempty(iLC)) % number of kernels (SetLC) = cardiac phases = time domain\n%     measPara.dim(4) = double(max(iLC(:,10)) - min(iLC(:,10)) + 1); % SetLC\n% end\nmeasPara.LCall(2) = drecksMDH.LC.Averages;\nif(measPara.dim(3) <= 1)\n    measPara.dimension = '2D';\nelse\n    if(measPara.dim(4) > 1)\n        measPara.dimension = '4D';\n    else\n        measPara.dimension = '3D';\n    end    \nend\nmeasPara.dim(6) = 1;\nif(isfield(drecksMDH,'Wip'))\n    if(isfield(drecksMDH.Wip,'NSamples') && drecksMDH.Wip.NSamples > 0)\n        measPara.dimension = '5D';\n        measPara.dim(6) = drecksMDH.Wip.NSamples;\n    elseif(isfield(drecksMDH.Wip,'NCardGates') && drecksMDH.Wip.NCardGates > 0)\n        measPara.dimension = '5D';\n        measPara.dim(6) = drecksMDH.Wip.NCardGates;        \n    end\nend\nif(isfield(measPara, 'sequenceName') && strcmp(measPara.sequenceName,'CS_Retro'))\n    measPara.CSAcceleration = 2; % something unequal to 1\nend\n\n% local variables, just needed for further calculations\nFOVphasePercentage = measPara.FOVphase/measPara.FOVread;\nphaseOversampling = drecksMDH.Geo.OverSampling(2) - 1;\nsliceOversampling = drecksMDH.Geo.OverSampling(3) - 1;\n\n%% oversampling and anisotropy\n\n% OVERSAMPLING PHASE INCORRECT!!!!!\n% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n% initialize anisotropic correction (y-x-z/slice-t)\nmeasPara.aniso = [measPara.dim(1), measPara.dim(2), measPara.dim(3), measPara.dim(4), measPara.dim(6)];\n% oversampling correction exactly possible => no case switch necessary later\nif(~isfield(measPara,'oversampling'))\n    measPara.oversampling = cell(2,3);\nend\nmeasPara.oversampling{2,2} = true;\nmeasPara.oversampling{2,3} = true;\n\n% readout oversampling\nreadoutDiff = (drecksMDH.Geo.OverSampling(1) - 1) * measPara.baseResolution;\nmeasPara.oversampling{1,1} = readoutDiff/2+1:measPara.dim(2)-readoutDiff/2;\nif(isempty(measPara.imageWidth) || measPara.imageWidth == 0)\n    measPara.imageWidth = length(measPara.oversampling{1,1});\nend\n\n% correct anisotropy if oversampling correction was done during recon\nif(measPara.oversampling{2,1})\n    measPara.aniso(2) = length(measPara.oversampling{1,1});\nend\n\n% phase anistropy\nif(isempty(measPara.ftlenPhase) || measPara.ftlenPhase == 0 || measPara.ftlenPhase ~= round(measPara.baseResolution * FOVphasePercentage * (1+phaseOversampling)))\n    measPara.ftlenPhase = round(measPara.baseResolution * FOVphasePercentage * (1+phaseOversampling)); \n    if(measPara.ftlenPhase > measPara.baseResolution && FOVphasePercentage < 1) % can occur that y>x\n        measPara.ftlenPhase = measPara.baseResolution;\n    end\nend\nif(drecksMDH.Geo.PhaseRes(1) ~= 1)\n    measPara.aniso(1) = measPara.ftlenPhase;\nend\n% phase oversampling\nif(isempty(measPara.imageHeight) || measPara.imageHeight == 0)\n    diffSize = abs(measPara.ftlenPhase - round(FOVphasePercentage * measPara.baseResolution));\n    measPara.imageHeight = measPara.ftlenPhase;\nelse\n    diffSize = abs(measPara.imageHeight - round(FOVphasePercentage * measPara.baseResolution));\nend\nif(mod(diffSize,2) == 0)\n    oversamplimits = [round(diffSize/2)+1, round(diffSize/2)];\nelse\n    oversamplimits = [round(diffSize/2)+1, 0];\n    oversamplimits(2) = abs(diffSize-(oversamplimits(1)-1));\nend\nmeasPara.oversampling{1,2} = oversamplimits(1):(measPara.aniso(1)-oversamplimits(2));\n\n\nif(strcmp(measPara.dimension,'3D') || strcmp(measPara.dimension,'4D') ||  strcmp(measPara.dimension,'5D'))\n    % slice anisotropy    \n    if(isempty(measPara.ftlenPar) || measPara.ftlenPar == 0 || measPara.ftlenPar ~= round(drecksMDH.Geo.ImagesPerSlab * (1+sliceOversampling)))\n        measPara.ftlenPar = round(drecksMDH.Geo.ImagesPerSlab * (1+sliceOversampling));  \n    end\n    if(drecksMDH.Geo.PhaseRes(2) ~= 1)\n        measPara.aniso(3) = measPara.ftlenPar;\n    end\n    % slice oversampling\n    diffSize = abs(measPara.ftlenPar - drecksMDH.Geo.ImagesPerSlab);\n    if(mod(diffSize,2) == 0)\n        oversamplimits = [round(diffSize/2)+1, round(diffSize/2)];\n    else\n        oversamplimits = [round(diffSize/2)+1, 0];\n        oversamplimits(2) = abs(diffSize-(oversamplimits(1)-1));\n    end\n    measPara.oversampling{1,3} = oversamplimits(1):(measPara.aniso(3)-oversamplimits(2));\n%     measPara.imageDepth = measPara.imagesPerSlab;  %% ATTENTION !!!!!!!!!!! depth does not support time yet\nelse\n    measPara.aniso(3) = measPara.LCall(1);\n    measPara.oversampling{1,3} = 1:measPara.LCall(1);\n%     measPara.imageDepth = measPara.LCall(1);     %% ATTENTION !!!!!!!!!!! depth does not support time yet\nend\n\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/preproc/convertToMeasPara.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24673349939284533}}
{"text": "function createSureFitRawData(volPixSize)\n% createSureFitRawData([volPixSize])\n%\n% volPixSize is in mm/pixel (defaults to [240/256 240/256 1.2])\n%\n% Converts Ifile data into the row-major ordered (8-bit uchar) data\n% format requried by SureFit. This script is essentiall the createVAnatomy script\n% with the output format modified slightly (in saveSureFitAnat()  -- which was\n% saveVAnat())\n% \n% 00.01.20 RFD\n%\n\nif ~exist('volPixSize','var')\n   volPixSize = [240/256 240/256 1.2];\n   disp(['volPixSize defaulting to [ ' num2str(volPixSize,'%.4f ') ...\n         \t'].  I hope this is correct!']);\nend\n\nvolume_pix_size = 1./volPixSize;\n\n[fname, path] = uigetfile('*.*', 'Select one of the I-files...');\n\n% load ifiles\n%\ndisp('Loading I-files...');\nimg = makeCubeIfiles([path 'I'], 256, [1:124]);\n\n\ndisp('Finding optimal clip values...');\nfigure(99);\nhist(img(:),100);\nlowerClip = 0;\nupperClip = 500;\nanswer = inputdlg({'lower clip value: ','upper clip value: '}, ...\n   'Set intensity clip values', 1, ...\n   {num2str(lowerClip),num2str(upperClip)}, 'on');\nif ~isempty(answer)\n\tlowerClip = str2num(answer{1});\n\tupperClip = str2num(answer{2});\nend\ndisp(['intensity clip values are: ' num2str(lowerClip) ', ' num2str(upperClip)]);\n\n% Scale image values to be 0-255\n% (if intensityClip <= 1, my scaleImage routine will clip the highest 'intensityClip' \n% proportion of values, or, if intensityClip > 1, it clips it to the image value \n% specified by intensityClip.\n%\n% I haven't been fully satisfied by just automatically clipping off the top,\n% say 2% of intensities (this is what mrInitRet currently does to the inplanes).\n% So, lately I've been looking at the histogram and picking intensityClip\n% by hand, then viewing the images to see how well it worked.\ndisp('Clipping intensities...');\nimg(img<lowerClip) = lowerClip;\nimg(img>upperClip) = upperClip;\nimg = img-lowerClip;\n\n% crop the image cube\n% (you can skip this if you want, and just do the crop in mrGray)\nfigure(1);image(squeeze(img2(round(end/2),:,:))./clip.*255);colormap(gray(256));axis image;\nfigure(2);image(squeeze(img2(:,round(end/2),:))./clip.*255);colormap(gray(256));axis image;\nfigure(3);image(squeeze(img2(:,:,round(end/2)))./clip.*255);colormap(gray(256));axis image;\nimg2 = img2(20:200,30:240,1:124);\nfigure(1);image(squeeze(img(round(end/2),:,:))./clip.*255);colormap(gray(256));axis image;\nfigure(2);image(squeeze(img(:,round(end/2),:))./clip.*255);colormap(gray(256));axis image;\nfigure(3);image(squeeze(img(:,:,round(end/2)))./clip.*255);colormap(gray(256));axis image;\n\ndisp('Scaling to 0-255...');\nimg = round(img./upperClip*255);\ndisp('Original orientation:');\nfigure(99);\nsubplot(2,2,1);\nimage(squeeze(img(round(end/2),:,:)));colormap(gray(256));axis image;axis off;\nsubplot(2,2,2);\nimage(squeeze(img(:,round(end/2),:)));colormap(gray(256));axis image;axis off;\nsubplot(2,2,4);\nimage(squeeze(img(:,:,round(end/2))));colormap(gray(256));axis image;axis off;\n\n\n% Reslice the data so that all voxels are cubic.\n% The image currently has a field of view (fov) of 240mm in 256 voxels on the x and y axes\n% and a fov of 148.800mm in 124 voxels on the z axis.\n\nreslicedImg = resliceVoxels(img, 240, 240, 148.800);\n\n\n% Reorient the data into the orientation expected by SureFit\n% Basically, the data needs to be rotated 90 degrees around the anterior-posterior axis of the brain\n% The image data is no 159x256x256\n\ndisp('Reorienting data...');\n\nrotImg= zeros(planes,rows,cols);\nfor index=1:rows\n   rotImg(:,index,:) = rot90(squeeze(reslicedImg(:,index,:)),3);\nend\n\ndisp(['Volume dimensions are now:' int2str(size(rotImg))]);\n\ndisp('The reoriented data:');\nfigure(100);\nsubplot(2,2,1);\nimage(squeeze(rotImg(round(end/2),:,:)));colormap(gray(256));axis image;axis off;\nsubplot(2,2,2);\nimage(squeeze(rotImg(:,round(end/2),:)));colormap(gray(256));axis image;axis off;\nsubplot(2,2,4);\nimage(squeeze(rotImg(:,:,round(end/2))));colormap(gray(256));axis image;axis off;\n\n% Save SureFitAnatomy\n%\ndisp('Saving data in SureFit raw Format...');\npath = saveSureFitAnat(rotImg);\nsave([path 'UnfoldParams'], 'volume_pix_size', 'lowerClip', 'upperClip');\ndisp(['SureFit raw data format saved to ' path]);\ndisp(['You should now run \"python SUREFit/bin/Raw2Minc \"' path size(rotImg)]);\n\nreturn;\n\n\nfunction path = saveSureFitAnat(imgCube, fileName)\n% path = saveSureFitAnat(imgCube, [fileName])\n% imgCube is a [rows x cols x planes] image array\n% It must already be scaled to 0-255!\n%\n% fileName specifies the output file location (full path!)\n% If omitted, then a save-file dialog box appears.\n% \n% The path to where the anatomy ends up is returned, in\n% case you care.\n% \n%\n% See Also: writeVolume, which does the same thing, but takes \n% the input data in a different format.\n%\n% RFD\n\nif ~exist('fileName', 'var')\n   fileName = '';\nend\n\n% open file for writing (little-endian mode)\nif isempty(fileName)\n\t[fname, path] = uiputfile('sureFitRawData.dat', 'Save SureFit raw data file...');\n   fileName = [path fname];\nelse\n   path = fileName;\nend\n\nvFile = fopen(fileName,'w','l');\nif vFile<1\n   while vFile<1;\n   disp('Couldn''t open that file- please try saving it somewhere else.');\n\t[fname, path] = uiputfile('sureFitRawData.dat', 'Save SureFit raw data file...');\n   fileName = [path fname];\n   vFile = fopen(fileName,'w','l');\n\tend\nend\n   \n% SureFit's Raw2Minc doesn't want any header, so nothing is written before the image data.\n\n\n% Write data\ncount = fwrite(vFile, imgCube, 'uchar');\nfclose(vFile);\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/SureFit/createSureFitRawData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.2467334993928453}}
{"text": "function [anal] = er_chopTSeriesMulti3D(view,coords,scans,varargin);\n% [anal] = er_chopTSeriesMulti3D(view,[roi],[scans],[options]);\n%\n% Chop an event-related tSeries according to specified parfiles,\n% separately for each voxel in an ROI.\n%\n% Returns two output structs. results is a struct with \n% certain summary statistics across voxels, such as the mean\n% amplitudes for each condition and voxel, sems, etc. anal\n% is a struct array containing one entry for each voxel. Each\n% entry contains fields from er_chopTSeries (type\n% help on that function for a list).\n%\n% Note: this does a minimal analysis only on each voxel, for \n% speed purposes, unless the 'fullanal' option is passed in. \n% In this case, calculations of SNR, fMRI relative amplitudes,\n% and t-tests for significant activation are performed for \n% each voxel, which would not otherwise be performed. \n% Be warned, however, that the analysis could take twice to four \n% times as long.\n%\n% 08/04 ras.\nglobal dataTYPES;\n\nif ieNotDefined('coords')\n    rois = viewGet(view,'rois');\n    selRoi = viewGet(view,'selectedroi');\n    coords = rois(selRoi).coords;\nend\n\ndt = viewGet(view,'curdt');\n\nif ieNotDefined('scans')\n    [scans dt] = er_getScanGroup(view);\n    view = viewSet(view,'curdt',dt);\nend\n\n%%%%% params/defaults %%%%%\nbarebones = 0;          % if 0, do full analysis; if 1, do minimal analysis\nnormBsl = 1;            % flag to zero baseline or not\nalpha = 0.05;           % threshold for significant activations\nbslPeriod = -6:0;       % period to use as baseline in t-tests, in seconds\npeakPeriod = 6:12;       % period to look for peaks in t-tests, in seconds\ntimeWindow = -6:22;     % seconds relative to trial onset to take for each trial\nonsetDelta = 0;         % # secs to shift onsets in parfiles, relative to time course\nsnrConds = [];          % For calculating SNR, which conditions to use (if empty, use all)\nwaitbarFlag = 0;        % flag to show a graphical mrvWaitbar to show load progress\n\n\n%%%%% get the parfile info\ntrials = er_concatParfiles(view,scans);\ncondNums = unique(trials.cond(trials.cond > 0));\nwhichconds=condNums;\n\n%%%%% parse the options %%%%%\nvarargin = unNestCell(varargin);\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch lower(varargin{i})\n        case 'barebones', barebones = 1;\n        case 'normbsl', normBsl = varargin{i+1};\n        case 'alpha', alpha = varargin{i+1};\n        case 'peakperiod', peakPeriod = varargin{i+1};\n        case 'bslperiod', bslPeriod = varargin{i+1};\n        case 'timewindow', timeWindow = varargin{i+1};\n        case 'onsetdelta', onsetDelta = varargin{i+1};\n        case 'snrconds', snrConds = varargin{i+1};\n        case 'whichconds', whichconds = varargin{i+1};    \n        case 'mrvWaitbar', waitbarFlag = 1;\n        otherwise, % ignore\n        end\n    end\nend\n\n%%%%% check if the full analysis option is set\nchk = 0;\nfor i = 1:length(varargin)\n    if isequal(lower(varargin{i}),'fullanal')\n        chk = 1;\n        break;\n    end \nend\nif chk==0\n    varargin{end+1} = 'barebones';\nend\n\n%%%%% get the tSeries for each voxel / concat across scans\ndt = viewGet(view,'curdt');\ntextstring=sprintf('Loading tSeries from %s datatype scans %d-%d...',dataTYPES(dt).name,min(scans),max(scans));\nh = mrvWaitbar(0,textstring);\n\ntSeries = [];\nfor s = 1:length(scans)\n     raw = ~(detrendFlag(view,s));\n    subt = getTseriesOneROI(view,coords,scans(s),raw);\n    tSeries = [tSeries; subt{1}];\n    mrvWaitbar(s/length(scans),h);\nend\n\nclose(h)\n\n%%%%% run the standard choptSeries analysis on each voxel\n\n\nnVoxels = size(tSeries,2);\nfprintf(1,'num voxels in view %s is %5d \\n',view.viewType,nVoxels);\n\n% jl101104 peak peropd 4:12 onset delta 0\n% jv062004 onset delta=-4 peakPeriod 6:16 \n% ras062304 onset delta=0 peakPeriod 6:14- \n% kgs080304  peak period 4:14 delta=0\n% kgs061504 peak period 4:14 delta  onset=0\n% skipped 3 frames adjusted par files;  use mc data\n% ras 041702 6:14 offset -6 blocks of 16s\n% js061504  4:12 onset 0 very noisy scan did not cover FFA\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% add menus (3): Settings\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndefaults{1} = num2str(timeWindow);\ndefaults{2} = num2str(bslPeriod);\ndefaults{3} = num2str(peakPeriod);\ndefaults{4} = num2str(alpha);\ndefaults{5} = num2str(onsetDelta);\ndefaults{6} = num2str(whichconds);\ndefaults{7} = num2str(normBsl);\ndefaults{8}='y';\ndefaults{9}='y';\ndefaults{10}='n';\n\nprompt{1} = 'Time Window, in seconds (incl. pre-stimulus onset period):';\nprompt{2} = 'Baseline Period, in seconds:';\nprompt{3} = 'Peak Period, in seconds:';\nprompt{4} = 'Alpha for significant activation (peak vs baseline):';\nprompt{5} = 'Shift onsets relative to time course, in seconds:';\nprompt{6} = 'Which conditions to calculate reliability?';\nprompt{7} = 'Normalize all trials during the baseline period? (0 for no, 1 for yes)';\nprompt{8}=  'Plot matrix of all voxels amps [y/n]?';\nprompt{9}=  'Conduct reliability analysis [y/n]?';\nprompt{10}= 'Load tcUI for ROI data [y/n]?';\nAddOpts.Resize = 'on';\nAddOpts.Interpreter = 'tex';\nAddOpts.WindowStyle = 'Normal';\nanswers = inputdlg(prompt,'Chop tSeries-Multi Settings...',1,defaults,AddOpts);\n   \n% exit if cancel is selected\nif isempty(answers)\n    return;\nend\n\n% parse the user responses / defaults\ntimeWindow = str2num(answers{1});\nbslPeriod = str2num(answers{2});\npeakPeriod = str2num(answers{3});\nalpha = str2num(answers{4});\nonsetDelta = str2num(answers{5});\nwhichconds = str2num(answers{6});\nnormBsl = str2num(answers{7});\n\nif answers{8}=='y' | answers{8}=='Y'\n    plotampsmat=1; \nelse\n    plotampsmat=0;\nend\n\nif answers{9}=='y' | answers{9}=='Y'\n    reliability=1;\nelse\n    reliability=0;\nend\nif answers{10}=='y' | answers{10}=='Y'\n    tcUI=1;\nelse\n    tcUI=0;\nend\nroiName=view.ROIs(selRoi).name;\n\nh = mrvWaitbar(0,'Chopping tSeries...');\nanal = er_chopTSeries3D(tSeries,trials,roiName,...\n              'peakPeriod',peakPeriod,...\n              'bslPeriod',bslPeriod,...\n              'timeWindow',timeWindow,...\n              'alpha',alpha,...\n              'onsetDelta',onsetDelta,...\n              'whichconds',whichconds,...\n              'normBsl',normBsl,...\n              'plotampsmat',plotampsmat);         \nclose(h)\n% save data \nnewdir=view.viewType;\ncd (newdir)\ndataTypedir=getDataTypeName(view);\ncd (dataTypedir)\n\nif ~exist('ROI4D')\n        mkdir 'ROI4D'\nend\ncd ..    % newdir\ncd ..    % data dir\n\nanal.roiName=view.ROIs(selRoi).name;\nwhichconds\nif reliability\n    [rc,pc,rcov, pcov, odd, even]=pattern_analysis(anal.allamps(:,whichconds,:),anal.allampsminusDC(:,whichconds,:),anal.labels(whichconds),anal.roiName);\n    anal.pc=pc;\n    anal.rc=rc;\n    anal.rcov=rcov;\n    anal.pcov=pcov;\nend\n\n% too long but makes it platform insensitive\ncd (newdir) \ncd (dataTypedir)\ncd ('ROI4D')\nfilename=view.ROIs(selRoi).name;\neval (['save ' filename ' anal']);\nfprintf(1, 'saved anal to %s/%s/ROI4D/%s.mat \\n ', newdir,dataTypedir,filename);\ncd ..\ncd ..\ncd ..\nif tcUI\n    fprintf(1, 'Loading mean ROI timecourse UI..........')\n    tc = timeCourseUI(view,view.ROIs(selRoi).name,scans,dt);\nend\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/er_chopTSeriesMulti3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2466893610163558}}
{"text": "report_this_filefun(mfilename('fullpath'));\n\n% TODO delete this, probably. -CGR\n% Now lets plot the color-map of the z-value\n%\nfigure\n\nset(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n    'FontWeight','bold','LineWidth',1.5,...\n    'Box','on','SortMethod','childorder')\n\nrect = [0.18,  0.10, 0.7, 0.75];\nrect1 = rect;\n\n% set values greater tresh = nan\n%\nre4 = ret;l = r > tresh; re4(l) = zeros(1,length(find(l)))*nan;\n\n% plot image\n%\norient portrait\nset(gcf,'PaperPosition', [2. 1 7.0 5.0])\n\nl = isnan(re4);\n\naxes('position',rect);hold on\n\npco1 = pcolor(gx,gy,(re4))\ncaxis([ 25 150]);\nshading interp\naxis([ min(gx) max(gx) min(gy) max(gy)]);\naxis image;\nhold on\nh = cool(64);h = [  h]; colormap(h)\n\nset(gca,'Color',[0.9 0.9 0.9])\nset(gca,'YTickLabels',[  10 8  6 4  2])\n\n%xlabel('Distance in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n%ylabel('depth in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n\nif exist('maex', 'var')\n    pl = plot(maex,-maey,'*y');\n    set(pl,'MarkerSize',6,'LineWidth',2)\nend\noverlay\n\nset(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n    'FontWeight','normal','LineWidth',1.5,...\n    'Box','on','TickDir','out')\nh1 = gca;hzma = gca;\n\n% Create a colobar\n%\n% h5 = colorbar('horiz');\n%set(h5,'Pos',[0.25 0.05 0.5 0.05],...\n%'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n\n% Make the figure visible\n%\nset(gca,'visible','on','FontSize',10,'FontWeight','bold',...\n    'FontWeight','normal','LineWidth',1.0,...\n    'Box','on','TickDir','out')\n\naxes(h1)\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/plcros2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24668935418052157}}
{"text": "%% t_installSegmentation\n%\n% Illustrates how to align the inplane volume from an fMRI session to the\n% 3D volume anatomy using sample data set <erniePRF>\n%\n% Dependencies: \n%   Remote Data Toolbox\n%\n% This tutorial is part of a sequence. Run \n%   t_initAnatomyFromFreesurfer\n%   t_initVistaSession\n%   t_alignInplaneToVolume\n% prior to running this tutorial. \n%\n% Summary\n%\n% - Specify alignment matrix linking inplane anatomy to volume anatomy\n% - Save mrSESSION with alignment matrix\n%\n% Tested 07/21/2016 - MATLAB r2015a, Mac OS 10.11.6 \n%\n%  See also: t_initAnatomyFromFreesurfer t_initVistaSession t_alignInplaneToVolume\n%\n% Winawer lab (NYU)\n\n%% Start\n% Clean start in case we have a vista session open\nmrvCleanWorkspace();\n\n% Remember where we are\ncurdir = pwd();\n\n%% Organize functional data\n\n% Find ernie PRF session in scratch directory\nerniePathTemp      = fullfile(vistaRootPath, 'local', 'scratch', 'erniePRF');\n\nif ~exist(erniePathTemp, 'dir')\n    help(mfilename)\n    error('Please run  pre-requisite tutorials')\nend\n\n% Navigate and create a directory\ncd(erniePathTemp)\n\n%% Align inplane to t1 and install Gray/white segmentation\n\n% Open a hidden view\nvw = initHiddenInplane();\n\n% Segmentation inputs\n%   use command line, not dialog\nquery = false;       \n\n%   keep all gray nodes, including those outside functional FOV\nkeepAllNodes = true; \n\n%   path to class file\nfilePaths = fullfile('3DAnatomy', 't1_class.nii.gz');\n\n%   number of layers in gray graph along surface (3 layers for 1 mm voxels)\nnumGrayLayers = 3;\n\n% Do it\ninstallSegmentation(query, keepAllNodes, filePaths, numGrayLayers);\n\n\n%% Visualize\n\n% open a UI\nvw = mrVista;\n\n% Define an ROI that is the entire functional slab\nvw = makeGrayROI(vw); \nvw = refreshScreen(vw,0);\n\n% add the local variable, vw, to the UI in case you would like to interact\n% with the GUI\nupdateGlobal(vw)\n\n%% Clean up\nclose(viewGet(vw, 'figure number')); \nmrvCleanWorkspace\ncd(curdir)", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/tutorials/bold/session/t_installSegmentation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24668935418052157}}
{"text": "function [OMNISol,bilevelMILPProblem] = OMNI(model, selectedRxnList, options, constrOpt, measOpt, prevSolutions, verbFlag)\n%\n%% ***********************NOT WORKING**************************************\n%\n\n%function [OMNISol,bilevelMILPProblem] = OMNI(model,selectedRxnList,options,constrOpt,prevSolutions,verbFlag,solutionFileNameTmp)\n\n%OMNI Run OMNI in the most general form\n%\n% OMNI(model,selectedRxnList,options,constrOpt,prevSolutions,verbFlag,solutionFileName)\n%\n%INPUTS\n% model                 Structure containing all necessary variables to \n%                       describe a stoichiometric model\n%   rxns                  Rxns in the model\n%   mets                  Metabolites in the model\n%   S                     Stoichiometric matrix (sparse)\n%   b                     RHS of Sv = b (usually zeros)\n%   c                     Objective coefficients\n%   lb                    Lower bounds for fluxes\n%   ub                    Upper bounds for fluxes\n%   rev                    Reversibility of fluxes\n% selectedRxnList       List of reactions that can be knocked-out in OMNI\n% options               OMNI options\n%   numDel                # of bottlenecks\n%   numDelSense           Direction of # of bottleneck constraint (G/E/L)\n%   vMax                  Max flux\n%   solveOMNI             Solve problem within Matlab\n%   createGams            Create GAMS input file\n%   gamsFile              GAMS input file name\n% constrOpt             Explicitly constrained reaction options\n%   rxnList               Reaction list\n%   values                Values for constrained reactions\n%   sense                 Constraint senses for constrained reactions\n%                         (G/E/L)\n% measOpt               Measured flux options\n%   rxnSel                Names of measured reactions\n%   values                Flux values of measured reactions\n%   weights               Weights for measured fluxes\n%\n%OPTIONAL INPUTS\n% prevSolutions         Previous solutions\n% verbFlag              Verbose flag\n% solutionFileName      File name for storing temporary solutions\n%\n%OUTPUTS\n% OMNISol               OMNI solution structure\n% bilevelMILPProblem    bi-level MILP problem structure used\n%\n% Markus Herrgard 3/28/05\n\n% Set these for MILP callbacks\nglobal MILPproblemType;\nglobal selectedRxnIndIrrev;\n%global rxnList;\nglobal irrev2rev;\n%global solutionFileName;\n%global biomassRxnID;\n%global OMNIKOrxnList;\n%global OMNIObjective;\n%global OMNIGrowth;\n%global solID;\n\nif (nargin < 5)\n    prevSolutions = [];\nend\nif (nargin < 6)\n    verbFlag = false;\nend\n% if (nargin < 7)\n%     solutionFileName = 'OMNISolutions.mat';\n% else\n%     solutionFileName = solutionFileNameTmp;\n% end\n\n% Convert to irreversible rxns\n[modelIrrev,matchRev,rev2irrev,irrev2rev] = convertToIrreversible(model);\n\n% Create the index of the previous KO's suggested by OMNI to avoid obtaining the same\n% solution again\nselPrevSolIrrev = [];\nfor i = 1:size(prevSolutions,2)\n    prevSolRxnList = model.rxns(prevSolutions(:,i)==1);\n    selPrevSol = ismember(model.rxns,prevSolRxnList);\n    selPrevSolIrrev(:,i) = selPrevSol(irrev2rev);\nend\n\n[nMets,nRxns] = size(modelIrrev.S);\n\n% Create matchings for reversible reactions in the set selected for KOs \n% This is to ensure that both directions of the reaction are knocked out\nselSelectedRxn = ismember(model.rxns,selectedRxnList);\nselSelectedRxnIrrev = selSelectedRxn(irrev2rev);\nselectedRxnIndIrrev = find(selSelectedRxnIrrev);\ncnt = 0;\n%prevRxnID = -10;\nnSelected = length(selectedRxnIndIrrev);\nselRxnCnt = 1;\nwhile selRxnCnt <= nSelected\n    rxnID = selectedRxnIndIrrev(selRxnCnt);\n    if (matchRev(rxnID)>0)\n        cnt = cnt + 1;\n        selectedRxnMatch(cnt,1) = selRxnCnt;\n        selectedRxnMatch(cnt,2) = selRxnCnt+1;\n        selRxnCnt = selRxnCnt + 1;\n    end\n    selRxnCnt = selRxnCnt + 1;\nend\n\n% Set inner constraints for the LP\nconstrOptIrrev = setConstraintsIrrevModel(constrOpt,model,modelIrrev,rev2irrev);\n% constrOptIrrev = model; \n% constrOptIrrev = []; \n    \n% Set objectives for linear and integer parts\ncLinear = zeros(nRxns,1);\ncInteger = zeros(sum(selSelectedRxnIrrev),1);\n\n% Set the correct objective coefficient (not necessary for OMNI)\n% targetRxnID = find(ismember(model.rxns,options.targetRxn));\n% targetRxnIDirrev = rev2irrev{targetRxnID}(1);\n% cLinear(targetRxnIDirrev) = 1;\n\n% Set measured reaction in objective\nsel_meas_rxn = measOpt.rxnSel';\nb_meas_rxn = measOpt.values';\nwt_meas_rxn = measOpt.weights';\nn_m = length(sel_meas_rxn);\n\n% Create selection vector in the decoupled representation\n% This is to ensure that the objective function for measured reversible\n% reactions is constructed correctly\nsel_m = zeros(nRxns,1);\nord_ir = [];\nb_meas_tmp = [];\nwt_meas_tmp = [];\nfor i = 1:n_m\n    rxn_name = sel_meas_rxn{i};\n    rxn_id = find(strcmp(model.rxns,rxn_name));\n    if (~isempty(rxn_id)) % Protect against measured fluxes that are not part of the model\n        b_meas_tmp = [b_meas_tmp;b_meas_rxn(i)];\n        wt_meas_tmp = [wt_meas_tmp;wt_meas_rxn(i)];\n        % Reversible rxns\n        if (model.rev(rxn_id))\n            rxn_id_ir = rev2irrev{rxn_id}(1);\n            sel_m(rxn_id_ir) = 1;\n            sel_m(rxn_id_ir+1) = -1;\n        else\n            % Irrev rxns\n            rxn_id_ir = rev2irrev{rxn_id};\n            sel_m(rxn_id_ir) = 1;\n        end\n        % Figure out ordering in decoupled representation\n        ord_ir = [ord_ir rxn_id_ir];\n    end\nend\n% Get ordering indices\n[tmp,ord_ind] = sort(ord_ir);\n% Reorder or create weights\nif (sum(wt_meas_rxn) == 0)\n    measOpts.weights = ones(n_m,1);\nelse\n    measOpts.weights = wt_meas_tmp(ord_ind);\nend\n% Reorder measured flux values\nmeasOpts.values = b_meas_tmp(ord_ind);\n\nmeasOpts.rxnSel = sel_m;\n\n% Create the constraint matrices for the bilevel MILP\nbilevelMILPProblem = createBilevelMILPproblem(modelIrrev,cLinear,cInteger,selSelectedRxnIrrev,...\n    selectedRxnMatch,constrOptIrrev,measOpts,options,selPrevSolIrrev);\n\n% Initial guess (random)\n%bilevelMILPProblem.x0 = round(rand(length(bilevelMILPProblem.c),1));\nif isfield(options,'initSolution')\n    if (length(options.initSolution) > options.numDel | ~all(ismember(options.initSolution,selectedRxnList)))\n        warning('Initial solution not valid - starting from a random initial solution')\n        bilevelMILPProblem.x0 = [];\n    else\n        % Set initial integer solution\n        selInitRxn = ismember(model.rxns,options.initSolution);\n        selInitRxnIrrev = selInitRxn(irrev2rev);\n        initRxnIndIrrev = find(selInitRxnIrrev);\n        initIntegerSol = ~ismember(selectedRxnIndIrrev,initRxnIndIrrev);\n        selInteger = bilevelMILPProblem.vartype == 'B';\n        [nConstr,nVar] = size(bilevelMILPProblem.A);\n        bilevelMILPProblem.x0 = nan(nVar,1);\n        bilevelMILPProblem.x0(selInteger) = initIntegerSol;    \n        \n%         LPproblem.b = bilevelMILPProblem.b - bilevelMILPProblem.A(:,selInteger)*initIntegerSol;\n%         LPproblem.A = bilevelMILPProblem.A(:,bilevelMILPProblem.vartype == 'C');\n%         LPproblem.c = bilevelMILPProblem.c(bilevelMILPProblem.vartype == 'C');\n%         LPproblem.lb = bilevelMILPProblem.lb(bilevelMILPProblem.vartype == 'C');\n%         LPproblem.ub = bilevelMILPProblem.ub(bilevelMILPProblem.vartype == 'C');\n%         LPproblem.osense = -1;\n%         LPproblem.csense = bilevelMILPProblem.csense;\n%         LPsol = solveCobraLP(LPproblem);\n%         \n%         bilevelMILPProblem.x0(~selInteger) = LPsol.full;\n    end\nelse\n    bilevelMILPProblem.x0 = [];\nend\n\n% Minimize\nbilevelMILPProblem.osense = 1;\n\nif (verbFlag) \n    [nConstr,nVar] = size(bilevelMILPProblem.A);\n    nInt = length(bilevelMILPProblem.intSolInd);\n    fprintf('MILP problem with %d constraints %d integer variables and %d continuous variables\\n',...\n        nConstr,nInt,nVar);\nend\n\nbilevelMILPProblem.model = modelIrrev;\n\n% Set these for CPLEX callbacks\nMILPproblemType = 'OMNI';\n% rxnList = model.rxns;\n% biomassRxnID = find(modelIrrev.c==1);\n% solID = 0;\n% OMNIObjective = [];\n% OMNIGrowth = [];\n% OMNIKOrxnList = {};\n\n% Solve problem\nif (options.solveOMNI)\n    OMNISol = solveCobraMILP(bilevelMILPProblem,'printLevel',0);\n    if OMNISol.stat~=0\n        if (~isempty(OMNISol.cont))\n            OMNISol.fluxes = convertIrrevFluxDistribution(OMNISol.cont(1:length(matchRev)),matchRev);\n        end\n        if (~isempty(OMNISol.int))\n            % Figure out the KO reactions\n            OMNIRxnInd = selectedRxnIndIrrev(OMNISol.int < 1e-4);\n            OMNISol.kos = model.rxns(unique(irrev2rev(OMNIRxnInd)));\n            \n%             %sanity check\n%             modelTemp = changeRxnBounds(model,OMNISol.kos,0,'b');\n%             solTemp = optimizeCbModel(modelTemp);\n%             if abs(solTemp.f - OMNISol.obj) > 1e-4\n%                 [OMNISol,bilevelMILPProblem] = OMNI(model, selectedRxnList, options, constrOpt, measOpt, prevSolutions, verbFlag);\n%                 previous_solutions(:,end+1) = zeros(length(model.rxns),1);\n%             end\n        end\n    else\n        OMNISol.fluxes=[];\n        OMNISol.kos={};\n    end\nelse \n    OMNISol.rxnList = {};\n    OMNISol.fluxes = [];\nend\n\n\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/deprecated/OMNI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2465979682236806}}
{"text": "function XY = rl_reward_firepit( type )\n%RL_REWARD_FIREPITE \n%\n%   intput-----------------------------------------------------------------\n%\n%           o type : string, type of fire pit.\n%\n%   output----------------------------------------------------------------- \n%\n%           o XY   : (N x 2)\n%\n%\n\n\nXY = [];\n\nif strcmp(type,'central_pit')\n    \n    [X,Y] = meshgrid(linspace(3,7,20),linspace(3,7,20));\n    XY    = [X(:),Y(:)];\n    \nelse\n    \nend\n\n\n\n\n\n\n\n\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/reinforcement_learning/rl_2D_gworld_functions/rewards/rl_reward_firepit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24659796822368055}}
{"text": "classdef ParamMPCGCBF < handle\n    properties\n        horizon\n        gamma\n        P % weight for terminal cost (CLF)\n        xWeight\n        uWeight\n    end\n    methods\n        function self = ParamMPCGCBF(horizon, gamma, P, x_weight, u_weight)\n            self.horizon = horizon;\n            self.gamma = gamma;\n            self.P = P;\n            self.xWeight = x_weight;\n            self.uWeight = u_weight;\n        end\n    end\nend", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/cdc2021/ParamMPCGCBF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2465979552399218}}
{"text": "% EEG_TOPOPLOT - plot scalp map\n%\n% eeg_topoplot( vals, chanlocs, 'key', 'val');\n%\n% Input:\n%   vals     - values, one per channel\n%   chanlocs - channel structure, same size as vals\n%\n% Optional inputs:\n%   'colormap'   - colormap. Possible colormaps are 'blueredyellow', ...\n%                'yellowredblue', 'bluered' or any Matlab colormap ('cool',\n%                'jet', 'hsv', ...). It can also be a text file 'xxx.txt'. \n%                The text file must contain 3 columns and idealy 64 rows \n%                defining the colors in RGB format.\n%   'maplimits'  - can be [min max]. This help defines the color scale for\n%                maps.\n%   'electrodes' - can be 'on' to show electrode dots, 'off', or \n%               'labels' to show electrode labels. Default is 'on'\n%   'dotsize'    - size of electrode dots. Default is 5.\n%   'shading'    - 'flat','interp'  {default: 'interp'}\n%   'exclude'    - labels or indices of electrodes not to be plotted. From the\n%                compiled files, these must be entered using underscores\n%                for separators (e.g., \"cz_pz\").\n%   'sphspline'  - can be 'on' or 'off'. If 'on' spherical splines are used\n%                for interpolation of the scalp map. If 'off' standard \n%                planar inverse distance interpolation is used.\n%   'shrink'     - shrink electrode positions (default is 0.75 to be able to\n%                plot electrode at the head limit if spherical interpolation\n%                is set and 0.95 for planar 2-D interpolation).\n%\n% References for spline interpolation:\n%   [1] Perrin, F., Pernier, J., Bertrand, O., & Echallier, J. F.\n%       (1989). Spherical splines for scalp potential and current\n%       density mapping. Electroencephalography and Clinical\n%       Neurophysiology, 72, 184-187\n%   [2] Ferree, T. C. (2000). Spline Interpolation of the Scalp EEG.\n%       Retrieved March 26, 2006, from\n%       www.egi.com/Technotes/SplineInterpolation.pdf\n%\n% limitation: does not plot anything below the upper part of the head\n\n% Copyright (C) Arnaud Delorme, SCCN, INC, 2010\n%                                          \n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction eeg_topoplot(values, chanlocs, varargin);\n\ng = [];\nfor index = 1:2:length(varargin)\n    g = setfield(g, varargin{index}, varargin{index+1});\nend\nif ~isfield(g, 'electrodes'), g.electrodes = 'on'; end\nif ~isfield(g, 'colormap'),   g.colormap   = jet;  end\nif ~isfield(g, 'maplimits'),  g.maplimits  = [];   end\nif ~isfield(g, 'headrad'),    g.headrad    = [];   end\nif ~isfield(g, 'sphspline'),  g.sphspline  = 'on'; end\nif ~isfield(g, 'shading'),    g.shading    = 'interp'; end\nif ~isfield(g, 'contour'),    g.contour    = 'on'; end\nif ~isfield(g, 'dotsize'),    g.dotsize    = 5;    end\nif ~isfield(g, 'mark'),       g.mark       = [];   end\nif ~isfield(g, 'exclude'),    g.exclude    = [];   end\nif ~isfield(g, 'linewidth'),  g.linewidth  = 2;    end\nif ~isfield(g, 'shrink'),     g.shrink     = 1;    end\nif ischar(g.dotsize), g.dotsize = str2num(g.dotsize); end\nif any(values == 0)\n    inds = find(values == 0);\n    if ~isempty( [ chanlocs(inds).theta ])\n        g.contour = 'off';\n        g.sphspline = 'off';\n    end\nend\n\n% exclude electrodes\n% ------------------\nif ~isempty(g.exclude)\n    chanlocs(g.exclude) = [];\n    values(g.exclude)   = [];\nend\n\n% find channel coordinates\n% ------------------------\nemptyvals = cellfun('isempty', { chanlocs.theta }); \nth = [ chanlocs.theta ];\nrd = [ chanlocs.radius ];\n[y x] = pol2cart(th/180*pi, rd); x=-x;\nx = x*g.shrink;\ny = y*g.shrink;\nnewvalues            = values;\nnewvalues(emptyvals) = [];\nlabls = { chanlocs.labels }; \nlabls(emptyvals) = [];\n\nif strcmpi(g.sphspline, 'on')\n    % default head radius\n    % -------------------\n    g.headrad = 0.5;\n    \n    % spherical plotting\n    % ------------------\n    xelec = [ chanlocs.X ];\n\tyelec = [ chanlocs.Y ];\n\tzelec = [ chanlocs.Z ];\n\n    dist = sqrt(xelec.^2+yelec.^2+zelec.^2);\n\txelec = xelec./dist;\n\tyelec = yelec./dist;\n\tzelec = zelec./dist;\n    \n    if g.shrink ~= 1\n        [th phi rad] = cart2sph(xelec, yelec, zelec);\n        phi = (phi-pi/2)*g.shrink+pi/2;\n        [xelec, yelec, zelec] = sph2cart(th, phi, rad);\n    end;        \n    \n\t[xsph, ysph, zsph, valsph] = spheric_spline(xelec,yelec,zelec,newvalues); \n    surf(-ysph/2,xsph/2,zsph/2,double(valsph), 'edgecolor', 'none'); view([0 0 1]);hold on;\n    shading(g.shading);\n    top = max(abs(valsph(:)))*1000;\n    \n    if strcmpi(g.contour, 'on')\n    \t[c h] = contour3(-ysph/2, xsph/2, valsph+top/10, 5); view([0 0 1]);\n        set(h, 'cdata', [], 'edgecolor', 'k')\n    end\n    \n\t% coordinates for electrodes\n\t% --------------------------\n    xelec(find(zelec < 0)) = [];\n    yelec(find(zelec < 0)) = [];\n    x = yelec/2;\n    y = xelec/2;\n    \nelse\n    % default head radius\n    % -------------------\n    if isempty(g.headrad);\n        g.headrad = max(sqrt(x.^2+y.^2));\n    end\n    \n    % data points for 2-D data plot\n    % -----------------------------\n    pnts = linspace(0,2*pi,200/0.25*(g.headrad.^2));\n    xx = sin(pnts)*g.headrad;\n    yy = cos(pnts)*g.headrad;\n\n\t% make grid and add circle\n\t% ------------------------\n    gridres = 30;\n\tcoords = linspace(-g.headrad, g.headrad, gridres);\n\tay = repmat(coords,  [gridres 1]);\n\tax = repmat(coords', [1 gridres]);\n\tfor ind=1:length(xx)\n        [tmp closex] = min(abs(xx(ind)-coords));\n        [tmp closey] = min(abs(yy(ind)-coords));\n        ax(closex,closey) = xx(ind);\n        ay(closex,closey) = yy(ind);\n\tend\n\txx2 = sin(pnts)*(g.headrad-0.01);\n\tyy2 = cos(pnts)*(g.headrad-0.01);\n\tfor ind=1:length(xx)\n        [tmp closex] = min(abs(xx2(ind)-coords));\n        [tmp closey] = min(abs(yy2(ind)-coords));\n        ax(closex,closey) = xx(ind);\n        ay(closex,closey) = yy(ind);\n\tend\n\t\n\t% linear interpolation and removal of values outside circle\n\t% ---------------------------------------------------------\n    a = griddata(x, y, newvalues, -ay, ax, 'v4');\n\taradius = sqrt(ax.^2 + ay.^2);\n\tindoutcircle = find(aradius(:) > g.headrad+0.01);\n\ta(indoutcircle) = NaN;\n\tsurf(ay, ax, a, 'edgecolor', 'none'); view([0 0 1]); hold on;\n    shading(g.shading);\n    top = max(values)*1.5;\n\n\t% plot level lines\n\t% ----------------\n    if strcmpi(g.contour, 'on')\n        [c h] = contour3(ay, ax, a, 5);\n        set(h, 'cdata', [], 'edgecolor', 'k')\n    end\nend\n\n% plot electrodes as dots\n% -----------------------\nif strcmpi(g.electrodes, 'on') || strcmpi(g.electrodes, 'labels')\n    rad = sqrt(x.^2 + y.^2);\n    x(find(rad > g.headrad)) = [];\n    y(find(rad > g.headrad)) = [];\n    plot3( -x, y, ones(size(x))*top, 'k.', 'markersize', g.dotsize);\n    for i = g.mark,      plot3( -x(i), y(i), double(top), 'y.', 'markersize', 4*g.dotsize); plot3( -x(i), y(i), double(top), 'r.', 'markersize', 2*g.dotsize); end\n    if strcmpi(g.electrodes, 'labels')\n        for index = 1:length(x)\n            text( -x(index)+0.02, y(index), double(top), labls{index});\n        end\n    end\nelse\n    % invisible electrode that avoid plotting problem (no surface, only\n    % contours)\n    plot3( -x, y, -ones(size(x))*top, 'k.', 'markersize', 0.001); \nend\n\n% plot dipoles if any\n% -------------------\nif ~isempty(g.dipole)  \n    hold on;\n    for index = 1:size(g.dipole,1)\n        g.dipole(index,:)   = g.dipole(index,:)*0.5;\n        g.dipole(index,3:5) = g.dipole(index,3:5)/norm(g.dipole(index,3:end))*0.2;\n        if ~any(g.dipole(index,:))\n            fprintf('Note: dipole contains 0 - not plotted\\n')\n        elseif sum(g.dipole(index,3:4).^2) <= 0.00001 \n            fprintf('Note: dipole is length 0 - not plotted\\n')\n        elseif sum(g.dipole(index,1:2).^2) > g.headrad\n            fprintf('Note: dipole is outside plotting area - not plotted\\n')\n        else\n            hh = plot3( -g.dipole(index, 2), g.dipole(index, 1), top, '.');\n            set(hh, 'color', 'k', 'markersize', 30);\n            hh = line( -[g.dipole(index, 2) g.dipole(index, 2)+g.dipole(index, 4)]', ...\n                [g.dipole(index, 1) g.dipole(index, 1)+g.dipole(index, 3)]',[top top]);\n            set(hh, 'color', 'k', 'linewidth', 30/7);\n        end\n    end\nend\n\n% special colormaps\n% -----------------\nif ischar(g.colormap) \n    if ~isempty(strmatch(g.colormap, { 'hsv' 'jet' 'gray' 'hot' 'cool' 'bone' ...\n            'copper', 'pink' 'flag' 'prism' }, 'exact'))\n    else % read text file\n        g.colormap = load('-ascii', g.colormap);\n    end\nend;    \ncolormap(g.colormap);\n\nif ~isempty(g.maplimits)\n    if ~ischar(g.maplimits) && ~isempty(g.maplimits) && ~isnan(g.maplimits(1))\n        caxis(g.maplimits);\n    end\nend\n\n% main circle\n% -----------\nradiuscircle = 0.5;\npnts   = linspace(0,2*pi,200);\nxc     = sin(pnts)*radiuscircle;\nyc     = cos(pnts)*radiuscircle;\nsf     = 1; % scaling factor\nplot3(xc*sf,yc*sf,ones(size(xc))*top, 'k', 'linewidth', g.linewidth); hold on;\n\n% ears & nose\n% -----------\nrmax  = 0.5;\nbase  = rmax-.0046;\nbasex = 0.18*rmax;                   % nose width\ntip   = 1.15*rmax; \ntiphw = .04*rmax;                    % nose tip half width\ntipr  = .01*rmax;                    % nose tip rounding\nq = .04; % ear lengthening\nEarX  = [.497-.005  .510  .518  .5299 .5419  .54    .547   .532   .510   .489-.005]; % rmax = 0.5\nEarY  = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199];\n\nplot3(EarX*sf,EarY*sf,ones(size(EarX))*top,'color','k','LineWidth',g.linewidth)    % plot left ear\nplot3(-EarX*sf,EarY*sf,ones(size(EarY))*top,'color','k','LineWidth',g.linewidth)   % plot right ear\nplot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,top*ones(size([basex;tiphw;0;-tiphw;-basex])),'color','k','LineWidth',g.linewidth);\n\n% axis limits\n% -----------\naxis off;\nset(gca, 'ydir', 'normal');\naxis equal\nylimtmp = max(g.headrad, 0.58);\nylim([-ylimtmp ylimtmp]);\n\n% ----------------\n% spherical spline\n% ----------------\nfunction [x, y, z, Res] = spheric_spline( xelec, yelec, zelec, values);\n\nSPHERERES = 40;\n[x,y,z] = sphere(SPHERERES);\nx(1:(length(x)-1)/2,:) = [];\ny(1:(length(x)-1)/2,:) = [];\nz(1:(length(x)-1)/2,:) = [];\n\nGelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec);\nGsph  = computeg(x,y,z,xelec,yelec,zelec);\n\n% equations are \n% Gelec*C + C0  = Potential (C unknown)\n% Sum(c_i) = 0\n% so \n%             [c_1]\n%      *      [c_2]\n%             [c_ ]\n%    xelec    [c_n]\n% [x x x x x]         [potential_1]\n% [x x x x x]         [potential_ ]\n% [x x x x x]       = [potential_ ]\n% [x x x x x]         [potential_4]\n% [1 1 1 1 1]         [0]\n\n% compute solution for parameters C\n% ---------------------------------\nmeanvalues = mean(values); \nvalues = values - meanvalues; % make mean zero\nC = pinv([Gelec;ones(1,length(Gelec))]) * [values(:);0];\n\n% apply results\n% -------------\nRes = zeros(1,size(Gsph,1));\nfor j = 1:size(Gsph,1)\n    Res(j) = sum(C .* Gsph(j,:)');\nend\nRes = Res + meanvalues;\nRes = reshape(Res, size(x));\n\n% compute G function\n% ------------------\nfunction g = computeg(x,y,z,xelec,yelec,zelec)\n\nunitmat = ones(length(x(:)),length(xelec));\nEI = unitmat - ((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +... \n                (repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +...\n                (repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2)/2;\n\ng = zeros(length(x(:)),length(xelec));\nm = 4; % 3 is linear, 4 is best according to Perrin's curve\nfor n = 1:7\n    L = legendre(n,EI);\n    g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:));\nend\ng = g/(4*pi);    \n\n% find electrode indices\n% ----------------------\nfunction allinds = elecind( str, chanlocs, values );\n\n    findmax = 0;\n    findmin = 0;\n    if ~iscell(str)\n         if strmatch(str, 'max', 'exact'), findmax = 1; end\n         if strmatch(str, 'min', 'exact'), findmin = 1; end;         \n         indunderscore = [ 0 find( str == '_' ) length(str)+1 ];\n    else indunderscore = [1:length(str)+1];\n    end\n     \n    % find maximum or minimum\n    % -----------------------\n    if findmax, [tmp allinds] = max(values); return; end\n    if findmin, [tmp allinds] = min(values); return; end\n    \n    % find indices for labels\n    % -----------------------\n    labels = lower({ chanlocs.labels });\n    for i = 1:length(indunderscore)-1\n        if ~iscell(str)\n             tmpstr = str(indunderscore(i)+1:indunderscore(i+1)-1);\n        else tmpstr = str{i};\n        end\n        tmpind = strmatch(lower(tmpstr), labels, 'exact');\n        if isempty(tmpind)\n            if str2num(tmpstr) > 0\n                tmpind = str2num(tmpstr);\n            else\n                error(sprintf('Could not find channel \"%s\"', tmpstr));\n            end\n        end\n        allinds(i) = tmpind;\n    end\n    \n        \n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/popfunc/eeg_topoplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2465660590056481}}
{"text": "function proposals = gen_proposals(img, map, resizeRatio, minmaxRF)\n    global param\n    global globalVar\n    \n    %% bw prob map\n    f = fspecial('gaussian',[5 5],7);\n    map = imfilter(map,f,'same');\n    \n    bwmap = map > param.minRegionProb;\n    \n    SE1=strel('disk',3);\n    bwmap = imerode(bwmap,SE1);\n    bwmap = imdilate(bwmap,SE1);\n    bwmap = bwmap>0;\n    bwmap = imfill(bwmap,'holes');\n\n    \n    %% process each region\n    [L, L_num] = bwlabel(bwmap, 8);\n    proposals = cell(L_num, 1);\n    estimated_orientations = zeros(L_num, 1);\n    regions = cell(L_num, 1);\n    regionPerims = cell(L_num, 1);\n    totalTimeOfGetCompOfRegion = 0;\n    totalTimeOfEstimateOrientation = 0;\n    totalTimeOfGenProposalsByOrientation = 0;\n    for i = 1 : L_num\n        regionMap = L == i;\n        \n        %% construct regions\n        [y, x] = find(regionMap);\n        regions{i} = [y, x];\n        \n        %% Substruct sub img and sub region map by regions\n        regionMinX= min(x);\n        regionMaxX = max(x);\n        regionMinY = min(y);\n        regionMaxY = max(y);\n        regionHeight = regionMaxY - regionMinY + 1;\n        regionWidth = regionMaxX - regionMinX + 1;\n        \n        extendRegionMinX = max(1, regionMinX - regionWidth * 0.005);\n        extendRegionMaxX = min(size(img, 2), regionMaxX + regionWidth * 0.005);\n        extendRegionMinY = max(1, regionMinY - regionHeight * 0.005);\n        extendRegionMaxY = min(size(img, 1), regionMaxY + regionHeight * 0.005);\n        \n        subImg = img(extendRegionMinY : extendRegionMaxY, extendRegionMinX : extendRegionMaxX, :);\n        subRegionMap = regionMap(extendRegionMinY : extendRegionMaxY, extendRegionMinX : extendRegionMaxX);\n        [subY, subX] = find(subRegionMap);\n        subRegions = [subY, subX];\n        \n        %% Get comp info from subImg\n        %comp_infos = normal_mser3(subImg, param.mser_info, resizeRatio, minmaxRF);\n        comp_infos = normal_mser(subImg, resizeRatio, minmaxRF, [globalVar.imgName, '_', num2str(i)]);\n        \n        %% ---- for debug ----\n        if(param.debug)\n            boxes = zeros(length(comp_infos), 4);\n            for n = 1 : length(comp_infos)\n                boxes(n,:) = comp_infos{n}.box; \n            end\n            show_bbox(subImg, boxes);\n        end\n        \n        %% construct regionPerims\n        subRegionMap = imfill(subRegionMap, 'holes');\n        perimMap = bwperim(subRegionMap);\n        [y, x] = find(perimMap);\n        subRegionPerims = [y, x];\n        \n        tic;\n        [region_comp_infos] = getCompOfRegion(subImg, subRegions, comp_infos, param.minRegionCompCoveredArea, param.maxRegionCompArea);\n        tmpTime = toc;\n        totalTimeOfGetCompOfRegion = totalTimeOfGetCompOfRegion + tmpTime;\n        \n        %% generate secondary_region_comp_infos\n%         [~, secondary_region_comp_idx] = getCompOfRegion(img, regions{i}, comp_infos, param.secondaryMinRegionCompArea);\n%         secondary_region_comp_flags = false(length(comp_infos), 1);\n%         secondary_region_comp_flags(secondary_region_comp_idx) = true;\n%         secondary_region_comp_flags(region_comp_idx) = false;\n%         secondary_region_comp_infos = num2cell(comp_infos(secondary_region_comp_flags));\n        \n        if(param.debug)\n            debug_bbox = zeros(length(region_comp_infos), 4);\n            for d_i = 1 : length(region_comp_infos)\n                debug_bbox(d_i,:) = region_comp_infos{d_i}.box;\n            end\n            show_bbox(subImg, debug_bbox);\n        end\n        \n        if(false && param.debug)\n            debug_bbox = zeros(length(secondary_region_comp_infos), 4);\n            for d_i = 1 : length(secondary_region_comp_infos)\n                debug_bbox(d_i,:) = secondary_region_comp_infos{d_i}.box;\n            end\n            show_bbox(subImg, debug_bbox);\n        end\n        \n        tic;\n        estimated_orientations(i) = estimateOrientation(subImg, subRegions, region_comp_infos, param.orient_param);\n        tmpTime = toc;\n        totalTimeOfEstimateOrientation = totalTimeOfEstimateOrientation + tmpTime;\n        \n        tic;\n        proposals{i} = genProposalsByOrientation(subImg, subRegions, subRegionPerims, estimated_orientations(i), region_comp_infos);\n        tmpTime = toc;\n        totalTimeOfGenProposalsByOrientation = totalTimeOfGenProposalsByOrientation + tmpTime;\n        \n        proposals{i}(:, 1 : 2 : 8) = proposals{i}(:, 1 : 2 : 8) + extendRegionMinX;\n        proposals{i}(:, 2 : 2 : 8) = proposals{i}(:, 2 : 2 : 8) + extendRegionMinY;\n    end\n    \n    if(false)\n        fprintf('TotalTime: %.2f, %.2f, %.2f\\n', ...\n            totalTimeOfGetCompOfRegion, ... \n            totalTimeOfEstimateOrientation, ... \n            totalTimeOfGenProposalsByOrientation);\n    end\n    \n    proposals = cell2mat(proposals);\nend\n\n", "meta": {"author": "stupidZZ", "repo": "FCN_Text", "sha": "4bfa6736adf59924f766c3825bb145054ddc439d", "save_path": "github-repos/MATLAB/stupidZZ-FCN_Text", "path": "github-repos/MATLAB/stupidZZ-FCN_Text/FCN_Text-4bfa6736adf59924f766c3825bb145054ddc439d/ProposalGeneration/gen_proposals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.2465363314371356}}
{"text": "function SO3F = rotate_outer(SO3F,varargin)\n% rotate ODF\n%\n% Syntax\n%   SO3F = rotate_outer(SO3F,rot)\n%\n% Input\n%  SO3F - @SO3Fun\n%  rot  - @rotation\n%\n% Output\n%  SO3F - @SO3FunHandle\n\nSO3F = SO3FunHandle(@(rot) SO3F.eval(rot));\n\nSO3F = rotate_outer(SO3F,varargin{:});", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3Fun/rotate_outer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24653632588928492}}
{"text": "function [sys,x0,str,ts]=NonlinearPD(t,x,u,flag,Beta1,Beta2,Delta,A1,A2,SampleTime)\n\nif flag==0\n\n    sys = [0;1;1;2;0;1;1];\n     x0 = [0 ];                       \n    str = [ ];\n     ts = [SampleTime 0];\n           \n   \nelseif flag==2\n    \n    Bili=fal(u(1),A1,Delta);\n    Weifen=fal(u(2),A2,Delta);\n    sys=Beta1*Bili+Beta2*Weifen;    \n    \nelseif flag==3\n    sys=x;\n    \nelseif flag==4\n    sys=sys+SampleTime;\n    \n    \nelse \n    sys=[];\nend", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/ADRC TANKS/adrc2/NonlinearPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.24650563490774957}}
{"text": "function data = LoadBinary(filename,varargin)\n\n%LoadBinary - Load data from a multiplexed binary file.\n%\n%  Reading a subset of the data can be done in two different manners: either\n%  by specifying start time and duration (more intuitive), or by indicating\n%  the position and size of the subset in terms of number of samples per\n%  channel (more accurate).\n%\n%  USAGE\n%\n%    data = LoadBinary(filename,<options>)\n%\n%    filename       file to read\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'frequency'   sampling rate (in Hz, default = 20kHz)\n%     'start'       position to start reading (in s, default = 0)\n%     'duration'    duration to read (in s, default = Inf)\n%     'offset'      position to start reading (in samples per channel,\n%                   default = 0)\n%     'samples'     number of samples (per channel) to read (default = Inf)\n%     'nChannels'   number of data channels in the file (default = 1)\n%     'channels'    channels to read (default = all)\n%     'precision'   sample precision (default = 'int16')\n%     'skip'        number of bytes to skip after each value is read\n%                   (default = 0)\n%     'downsample'  factor by which to downample by (default = 1)\n%    =========================================================================\n\n% Copyright (C) 2004-2011 by Micha\u00ebl Zugaro\n%Modified by DLevenstein 2016 to include downsampling\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Default values\nnChannels = 1;\nprecision = 'int16';\n%error('this function is now deprecated, use bz_LoadBinary.m')\n%warning(['this function assumes int16 precision, if your file is not int16 use load/resample.m'])\nskip = 0;\nfrequency = 20000;\nchannels = [];\nstart = 0;\nduration = Inf;\noffset = 0;\nnSamplesPerChannel = Inf;\ntime = false;\nsamples = false;\ndownsamplefactor = 1;\n\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n  error('Incorrect number of parameters (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\nend\n\n% Parse options\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\terror(['Parameter ' num2str(i+3) ' is not a property (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'frequency',\n\t\t\tfrequency = varargin{i+1};\n\t\t\tif ~isdscalar(frequency,'>0'),\n\t\t\t\terror('Incorrect value for property ''frequency'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\tcase 'start',\n\t\t\tstart = varargin{i+1};\n\t\t\tif ~isdscalar(start),\n\t\t\t\terror('Incorrect value for property ''start'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\t\tif start < 0, start = 0; end\n\t\t\ttime = true;\n\t\tcase 'duration',\n\t\t\tduration = varargin{i+1};\n\t\t\tif ~isdscalar(duration,'>=0'),\n\t\t\t\terror('Incorrect value for property ''duration'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\t\ttime = true;\n\t\tcase 'offset',\n\t\t\toffset = varargin{i+1};\n\t\t\tif ~isiscalar(offset),\n\t\t\t\terror('Incorrect value for property ''offset'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\t\tif offset < 0, offset = 0; end\n\t\t\tsamples = true;\n\t\tcase 'samples',\n\t\t\tnSamplesPerChannel = varargin{i+1};\n\t\t\tif ~isdscalar(nSamplesPerChannel,'>=0'),\n\t\t\t\terror('Incorrect value for property ''samples'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\t\tsamples = true;\n\t\tcase 'nchannels',\n\t\t\tnChannels = varargin{i+1};\n\t\t\tif ~isiscalar(nChannels,'>0'),\n\t\t\t\terror('Incorrect value for property ''nChannels'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\tcase 'channels',\n\t\t\tchannels = varargin{i+1};\n\t\t\tif ~isivector(channels,'>0'),\n\t\t\t\terror('Incorrect value for property ''channels'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\tcase 'precision',\n\t\t\tprecision = varargin{i+1};\n\t\t\tif ~isa(precision,'char'),\n\t\t\t\terror('Incorrect value for property ''precision'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\tcase 'skip',\n\t\t\tskip = varargin{i+1};\n\t\t\tif ~isiscalar(skip,'>=0'),\n\t\t\t\terror('Incorrect value for property ''skip'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n            end\n\t\tcase 'downsample',\n\t\t\tdownsamplefactor = varargin{i+1};\n\t\t\tif ~isiscalar(downsamplefactor,'>=0'),\n\t\t\t\terror('Incorrect value for property ''downsample'' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).');\n\t\t\tend\n\t\totherwise,\n\t\t\terror(['Unknown property ''' num2str(varargin{i}) ''' (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).']);\n\tend\nend\n\n% Either start+duration, or offset+size\nif time && samples,\n\terror(['Data subset can be specified either in time or in samples, but not both (type ''help <a href=\"matlab:help LoadBinary\">LoadBinary</a>'' for details).']);\nend\n\n% By default, load all channels\nif isempty(channels),\n\tchannels = 1:nChannels;\nend\n\n% Check consistency between channel IDs and number of channels\nif any(channels>nChannels),\n\terror('Cannot load specified channels (listed channel IDs inconsistent with total number of channels).');\nend\n\n% Open file\nif ~exist(filename),\n\terror(['File ''' filename ''' not found.']);\nend\nf = fopen(filename,'r');\nif f == -1,\n\terror(['Cannot read ' filename ' (insufficient access rights?).']);\nend\n\n% Size of one data point (in bytes)\nsampleSize = 0;\nswitch precision,\n\tcase {'uchar','unsigned char','schar','signed char','int8','integer*1','uint8','integer*1'},\n\t\tsampleSize = 1;\n\tcase {'int16','integer*2','uint16','integer*2'},\n\t\tsampleSize = 2;\n\tcase {'int32','integer*4','uint32','integer*4','single','real*4','float32','real*4'},\n\t\tsampleSize = 4;\n\tcase {'int64','integer*8','uint64','integer*8','double','real*8','float64','real*8'},\n\t\tsampleSize = 8;\nend\n\n% Position and number of samples (per channel) of the data subset\nif time,\n\tdataOffset = floor(start*frequency)*nChannels*sampleSize;\n\tnSamplesPerChannel = floor((duration*frequency));\nelse\n\tdataOffset = offset*nChannels*sampleSize;\nend\n\n% Position file index for reading\nstatus = fseek(f,dataOffset,'bof');\nif status ~= 0,\n\tfclose(f);\n\terror('Could not start reading (possible reasons include trying to read past the end of the file).');\nend\n\n% Determine total number of samples in file\nfileStart = ftell(f);\nstatus = fseek(f,0,'eof');\nif status ~= 0,\n\tfclose(f);\n\terror('Error reading the data file (possible reasons include trying to read past the end of the file).');\nend\nfileStop = ftell(f);\n% (floor in case all channels do not have the same number of samples)\nmaxNSamplesPerChannel = floor(((fileStop-fileStart)/nChannels/sampleSize));\nfrewind(f);\nstatus = fseek(f,dataOffset,'bof');\nif status ~= 0,\n\tfclose(f);\n\terror('Could not start reading (possible reasons include trying to read past the end of the file).');\nend\n\nif isinf(nSamplesPerChannel) || nSamplesPerChannel > maxNSamplesPerChannel,\n\tnSamplesPerChannel = maxNSamplesPerChannel;\nend\n\nif downsamplefactor>1\n%     precision = [num2str(nChannels),'*',precision]; % this line is\n%     incorrect, the precision variable is a string that does not depend on\n%     the number of channels\n    skip = nChannels*(downsamplefactor-1)*sampleSize;\n    nSamplesPerChannel = floor(nSamplesPerChannel./downsamplefactor);\nend\n\n\n% For large amounts of data, read chunk by chunk\nmaxSamplesPerChunk = 10000;\nnSamples = nSamplesPerChannel*nChannels;\nif nSamples <= maxSamplesPerChunk,\n\tdata = LoadChunk(f,nChannels,channels,nSamples/nChannels,precision,skip);\nelse\n\t% Determine chunk duration and number of chunks\n\tnSamplesPerChunk = floor(maxSamplesPerChunk/nChannels)*nChannels;\n\tnChunks = floor(nSamples/nSamplesPerChunk);\n\t% Preallocate memory\n\tdata = zeros(nSamplesPerChannel,length(channels),precision);\n\t% Read all chunks\n\ti = 1;\n\tfor j = 1:nChunks,\n\t\td = LoadChunk(f,nChannels,channels,nSamplesPerChunk/nChannels,precision,skip);\n\t\t[m,n] = size(d);\n\t\tif m == 0, break; end\n\t\tdata(i:i+m-1,:) = d;\n\t\ti = i+m;\n\tend\n\t% If the data size is not a multiple of the chunk size, read the remainder\n\tremainder = nSamples - nChunks*nSamplesPerChunk;\n\tif remainder ~= 0,\n\t\td = LoadChunk(f,nChannels,channels,remainder/nChannels,precision,skip);\n\t\t[m,n] = size(d);\n\t\tif m ~= 0,\n\t\t\tdata(i:i+m-1,:) = d;\n\t\tend\n\tend\nend\n\nfclose(f);\n\n% ---------------------------------------------------------------------------------------------------------\n\nfunction data = LoadChunk(fid,nChannels,channels,nSamples,precision,skip)\n\nif skip ~= 0,\n\tdata = fread(fid,[nChannels nSamples],[num2str(nChannels),'*',precision '=>' precision],skip);\n    %data = fread(fid,[nChannels nSamples],[num2str(nChannels),'*',precision],nChannels*skip);\nelse\n\tdata = fread(fid,[nChannels nSamples],[precision '=>' precision]);\nend\ndata=data';\n\nif isempty(data),\n\twarning('No data read (trying to read past file end?)');\nelseif ~isempty(channels),\n\tdata = data(:,channels);\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/IO/LoadBinary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901993027698}}
{"text": "% ------------------------------------------------------------------------ \n%  Copyright (C)\n%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n%  University of California Berkeley (UCB) - USA\n% \n%  Jordi Pont-Tuset <jordi.pont@upc.edu>\n%  Pablo Arbelaez <arbelaez@berkeley.edu>\n%  June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n%    \"Multiscale Combinatorial Grouping,\"\n%    Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------ \n\n% This function defines all parameters to tune in the training of MCG\n% params = nyud_params(); %sf_mUCM_multi_3sc_u_4r_12k_params();\n\n%% Compute all points from combining these base hierarchies\n% The order of combination is hard-coded, see pareto_learning to change it\n% The result will be loaded if already computed\nfunction pareto_chose_point(params, num_regions)\n  pareto = pareto_learning(params);\n\n  %% Plot pareto front results\n\n  % Play with the following two number to get the desired point\n\n  % Which measure used to get the Pareto\n  pareto_meas = 2;  % Jaccard at class level\n\n  % Which particular point in the curve we choose\n  pareto_id = -1;   % Around 14k candidates\n\n  if(pareto_id == -1)\n    pareto_id = find( pareto.st{pareto_meas}{params.n_r_cand}.mean_n_masks > num_regions, 1, 'first');\n  end\n\n  figure;\n  x_limit = 1e6;\n  titles{1} = {'Maximum achievable quality',['(Pascal segvoc ' params.gt_set_pareto ')'], 'Jaccard at instance level (Ji)'};\n  titles{2} = {'Maximum achievable quality',['(Pascal segvoc ' params.gt_set_pareto ')'], 'Jaccard at class level (Jc)'};\n  measures  = {'jaccard_object', 'jaccard_class'};\n  colors = {'r','g','b','k','m','c'};\n  for jj=1:length(measures)\n      subplot(1,2,jj); hold on;\n\n      % Singletons, pairs, and triplets\n      % Pareto on the same measure that evaluated\n      for ii=1:params.n_r_cand\n          plot(pareto.st{jj}{ii}.mean_n_masks,pareto.st{jj}{ii}.(measures{jj}),[colors{ii} '-'])\n      end\n      \n      for ii=1:params.n_r_cand\n          % Pareto on one measure, evaluated on the other\n          kk = setdiff([1 2],jj);\n          plot(pareto.st{kk}{ii}.mean_n_masks,pareto.st{kk}{ii}.(measures{jj}),[colors{ii} '--'])\n      end\n      \n      % Plot working point\n      tmp = pareto.st{pareto_meas}{params.n_r_cand}.(measures{jj});\n      plot(pareto.st{pareto_meas}{params.n_r_cand}.mean_n_masks(pareto_id),tmp(pareto_id),'k*')\n      text(70,0.85,{[num2str(pareto.st{pareto_meas}{params.n_r_cand}.mean_n_masks(pareto_id)) ' c/i'],...\n                    ['J=' num2str(tmp(pareto_id))]})\n      \n      % Make plot nicer\n      title(strrep(titles{jj},'_','\\_'))\n      if (params.n_r_cand==3)\n          legend({'Singletons same','Pairs same','Triplets same','Singletons diff','Pairs diff','Triplets diff'},4)\n      elseif (params.n_r_cand==4)\n          legend({'Singletons same','Pairs same','Triplets same','4-tuples','Singletons diff','Pairs diff','Triplets diff','4-tuples diff'},4)\n      end\n      grid minor\n      grid on\n      axis([10,x_limit,0.3,0.9])\n      set(gca,'XScale','log')\n  end\n\n  %% Once you have found the desired point, save the parameters to file, i.e.,\n  % the number of candidates from each hierarchy and for singletons, pairs, etc.\n  sel_parameters  = pareto.pars{pareto_meas}{params.n_r_cand}(:,pareto_id);\n  sampled_cands = pareto.base_stats{pareto_meas}.n_cands;\n  total_cands = 0;\n  clear n_cands;\n  for ii=1:length(sel_parameters)\n      if sel_parameters(ii)==0\n          n_cands(ii) = 0; %#ok<*SAGROW>\n      else\n          n_cands(ii) = sampled_cands(sel_parameters(ii));\n          total_cands = total_cands + pareto.base_stats{ii}.mean_n_masks(sel_parameters(ii));\n      end\n  end\n  assert(abs(total_cands-pareto.st{pareto_meas}{params.n_r_cand}.mean_n_masks(pareto_id))<1e-5)\n  n_cands = reshape(n_cands,length(params.hiers),params.n_r_cand)';\n  n_cands\n\n  save(params.files.pareto_point,'n_cands','pareto_id');\n  disp(['Saved: ' params.files.pareto_point])\nend\n%% Write the curves to file (to put them in the paper)\n% out_dir = '/Users/jpont/Publications/2014_CVPR/LaTeX/data/obj_cands/';\n% \n% % Write up to singletons, pairs, and triplets (w.r.t pareto_meas)\n% write_jaccard_to_file(pareto.st{pareto_meas}{1},fullfile(out_dir,[params.gt_set_pareto '_' params.hiers_id '_pareto_singletons.txt']));\n% write_jaccard_to_file(pareto.st{pareto_meas}{2},fullfile(out_dir,[params.gt_set_pareto '_' params.hiers_id '_pareto_pairs.txt']));\n% write_jaccard_to_file(pareto.st{pareto_meas}{3},fullfile(out_dir,[params.gt_set_pareto '_' params.hiers_id '_pareto_triplets.txt']));\n% write_jaccard_to_file(pareto.st{pareto_meas}{4},fullfile(out_dir,[params.gt_set_pareto '_' params.hiers_id '_pareto_4tuples.txt']));\n% \n% % Write selected pareto point\n% % params = sf_mUCM_sub_params('sub1');\n% load(params.files.pareto_point)\n% fid = fopen(fullfile(out_dir,[params.gt_set_pareto '_' params.hiers_id '_pareto_selected_point.txt']),'w');\n% fprintf(fid, 'ncands\\tjac_class\\tjac_instance\\n');\n% fprintf(fid, '%d\\t%f\\t%f\\n', [pareto.st{pareto_meas}{4}.mean_n_masks(pareto_id); pareto.st{pareto_meas}{4}.jaccard_class(pareto_id); pareto.st{pareto_meas}{4}.jaccard_object(pareto_id)]);\n% fclose(fid);\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/mcg/scripts_training/pareto_choose_point.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901315981682}}
{"text": "function test_plotMeanTSeries\n%Validate getting plotting the mean TSeries from an INPLANE ROI\n%\n%  test_plotMeanTSeries()\n% \n% Tests: meanTSeries, plotMeanTSeries\n%\n% INPUTS\n%  No inputs\n%\n% RETURNS\n%  No returns\n%\n% Example: test_plotMeanTSeries()\n%\n% See also MRVTEST\n%\n% Copyright Stanford team, mrVista, 2011\n\n%% Initialize the key variables and data path\n% Data directory (where the mrSession file is located)\ndataDir = mrtInstallSampleData('functional','mrBOLD_01');\n\n% This is the validation file\nval = mrtGetValididationData('plotMeanTSeriesFromINPLANE');\n\n% These are the items we stored in the validation file\n%\n% val.detrendDim  = size(d.detrend.frameNumbers);\n% val.rawDim      = size(d.raw.frameNumbers);\n% val.detrendMn   = mean(d.detrend.tSeries);\n% val.detrendMd   = median(d.detrend.tSeries);\n% val.detrendMx   = max(d.detrend.tSeries);\n% val.detrendMin  = min(d.detrend.tSeries);\n% val.rawMn       = mean(d.raw.tSeries);\n% val.rawMd       = median(d.raw.tSeries);\n% val.rawMx       = max(d.raw.tSeries);\n% val.rawMin      = min(d.raw.tSeries);\n% \n% save(vFile, '-struct', 'val')\n\n%% Retain original directory, change to data directory\ncurDir = pwd;\ncd(dataDir);\n\n% There can be several data types - name the one you want to probe\ndataType = 'Original';\n\n% Which scan number from that data type?\nscan = 1;\n\n%% Get data structure:\nvw = initHiddenInplane(); % Foregoes interface - loads data silently\n\n%% Set dataTYPE:\nvw = viewSet(vw, 'Current DataType', dataType); % Data type\n\n%% Load an ROI and coranal\nvw = loadROI(vw, 'LV1.mat');\n\ndetrend = true;\n\n% open a plot figure\nnewGraphWin;\n\n% load both raw and detrended tSeries so we can validate both\nd.detrend = plotMeanTSeries(vw, scan, [], ~detrend);\nd.raw     = plotMeanTSeries(vw, scan, [], detrend);\n\n% close it\ncloseGraphWin;\n\n%% Go home\ncd(curDir)\n\n%% Validate..\n\n% check the number of time points \nassertEqual(val.detrendDim, size(d.detrend.frameNumbers));\nassertEqual(val.rawDim,     size(d.raw.frameNumbers));\n\n% check detrended t-series\nassertElementsAlmostEqual(val.detrendMn,mean(d.detrend.tSeries));\nassertElementsAlmostEqual(val.detrendMd,median(d.detrend.tSeries));\nassertElementsAlmostEqual(val.detrendMx,max(d.detrend.tSeries));\nassertElementsAlmostEqual(val.detrendMin,min(d.detrend.tSeries));\n\n% check raw t-series\nassertElementsAlmostEqual(val.rawMn,mean(d.raw.tSeries));\nassertElementsAlmostEqual(val.rawMd,median(d.raw.tSeries));\nassertElementsAlmostEqual(val.rawMx,max(d.raw.tSeries));\nassertElementsAlmostEqual(val.rawMin,min(d.raw.tSeries));\n\n%% Clear workspace\n\nmrvCleanWorkspace;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrTest/bold/core/test_plotMeanTSeries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901315981676}}
{"text": "function [cleanedData, metToKeepSummary] = metsToKeep(dataOrg, metRep, calRelErr, param)\n%\n% removes the metabolomics measurements from the \n% dataOrg table that have low measurement quality based on the relative SD \n% of technical replicate sample (RSDqc provided in the metRep variable) \n% and/or the average relative error (measured vs actual concentration) of \n% the calibration line samples (RE provided in the calRelErr variable)\n%\n% USAGE:\n%   [cleanedData, metToKeepSummary] = metsToKeep(dataOrg, metRep, calRelErr, param)\n%\n% INPUTS:\n%  dataOrg:     A table with original metabolomics data in a long format \n%               with information about measured samples, compounds, \n%               retention times (RT), area(s), concentrations, etc. \n%               the following column is required for the analysis:\n%\n%                     * .compound - compound (metabolite names) identical\n%                                   to the names used in the metRep and \n%                                   calRE variables       \n%  metRep:      A table with quality information based on the dataOrg \n%               in a long format (output from mzQuality tool).\n%               The following columns are required for the analysis:\n%\n%                     * .compound - compound (metabolite names) identical\n%                                   to the names used in the dataOrg and \n%                                   calRE variables \n%                     * .RSDqc_* - one or more columns specifying the\n%                                  relative standard deviation of the \n%                                  repeated measurement of a (quality) \n%                                  sample (per batch) per metabolite         \n%  calRelErr:   A table with quality information about the relative \n%               error (RE) of the concentration estimation of the \n%               calibration line samples based on the dataOrg \n%               in a long format with information about measured samples, \n%               compounds, retention times (RT), known concentrations, \n%               estimated concentrations, and relative error etc. \n%               The following columns are required for the analysis:\n%\n%                     * .compound - compound (metabolite names) identical\n%                                   to the names used in the dataOrg and \n%                                   calRE variables \n%                     * .RE* - a columns specifying the relative error of \n%                              the concentration estimation of the\n%                              calibration line samples\n%  param.tresholdRSDqc: the treshold value for the relative SD of the repeated \n%                       measurement of sample (default = 25 (%); based on \n%                       the based on the \"Guidelines and considerations for \n%                       the use of system suitability and quality control \n%                       samples in mass spectrometry assays applied in \n%                       untargeted clinical metabolomic studies\")\n%  param.tresholdCalRE: the treshold value for the relative error of the \n%                       concentration estimation of the calibration line \n%                       samples (default = 25 (%)\n%\n% OUTPUTS:\n%  cleanedData:         table in the same format as dataOrg without the \n%                       metabolites of low quality (above set tresholds)\n%  metToKeepSummary:    table in the same format as metRep variable with an\n%                       added columns: \n%                     \n%                     * .keep -     specifies whether a metabolite is to be \n%                                   kept (1) or removed (0) from the further \n%                                   analysis\n%                     * .REcheck - specifies whether a metabolite passed\n%                                   (1) or failed (0) the check based on \n%                                   the relative error of the concentration \n%                                   estimation of the calibration line sample \n%                     * .RSDqcCheck - specifies whether a metabolite passed\n%                                     (1) or failed (0) the check based on \n%                                     the relative standard deviation of \n%                                     the repeated measurement of a (QC) sample\n%                     * .sumRE -    shows the average relative error of the \n%                                   concentration estimation of the \n%                                   calibration line sample per metabolite\n%\n% EXAMPLE:\n%\n% NOTE:\n%\n% Author(s): Agnieszka Wegrzyn (2021)\n\n\nif exist('param', 'var')\n    if isfield(param, \"tresholdRSDqc\")\n        tresholdRSDqc = param.tresholdRSDqc;\n    else\n        tresholdRSDqc = 25;\n    end\n    if isfield(param, \"tresholdCalRE\")\n        tresholdCalRE = param.tresholdCalRE;\n    else\n        tresholdCalRE = 25;\n    end\nelse\n    tresholdRSDqc = 25;\n    tresholdCalRE = 25;\nend\n\nmetToKeep = metRep;\ncalRE = calRelErr;\ncalRE.RE(isnan(calRE.RE)) = 0;\ncalRE.RE(isinf(calRE.RE)) = NaN;\nmetToKeep.REcheck = zeros(length(metToKeep.compound),1);\nmetToKeep.RSDqcCheck = zeros(length(metToKeep.compound),1);\nfor i=1:length(metToKeep.compound)\n    if sum(ismember(calRE.compound,metToKeep.compound(i))) ~= 0\n        avrCalRE = mean(calRE.RE(ismember(calRE.compound,metToKeep.compound(i))),'omitnan');\n        sdCalRE = std(calRE.RE(ismember(calRE.compound,metToKeep.compound(i))),'omitnan');\n        metToKeep.sumRE(i) = avrCalRE;\n        %check if average + 1SD (to account for an outlier) of RE is below the set treshold\n        if (avrCalRE + sdCalRE) > tresholdCalRE\n            metToKeep.REcheck(i) = 0;\n        else\n            metToKeep.REcheck(i) = 1;\n        end\n    else\n        metToKeep.sumRE(i) = NaN;\n    end\n    if all(table2array(metToKeep(i,contains(metToKeep.Properties.VariableNames, 'RSDqc_'))) <= tresholdRSDqc)\n        metToKeep.RSDqcCheck(i) = 1;\n    else\n        metToKeep.RSDqcCheck(i) = 0;\n    end\n    if metToKeep.RSDqcCheck(i) == 1 && metToKeep.REcheck(i) == 1\n        metToKeep.Var1(i) = 1;\n    else\n        metToKeep.Var1(i) = 0;\n    end\nend\nmetToKeepSummary = metToKeep;\nmetToKeepSummary.Properties.VariableNames(1) = \"keep\";\ncleanedData = dataOrg;\ncleanedData(contains(cleanedData.compound,metToKeepSummary.compound(metToKeepSummary.keep == 0)),:)= [];\ncleanedData(:,1)= [];\ndisp(' ')\ndisp('--------------------------------------------------------------')\ndisp(['Number of metabolites in the dataset: ' num2str(numel(metToKeepSummary.compound))])\ndisp(['Number of metabolites left after quality check: ' num2str(sum(metToKeepSummary.keep))])\ndisp(' ')\n\n\n\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/XomicsToModel/metabolomics/metsToKeep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.24627863927775234}}
{"text": "function updateScatterPolar(obj, plotIndex)\n\n    %-AXIS INDEX-%\n    axIndex = obj.getAxisIndex(obj.State.Plot(plotIndex).AssociatedAxis);\n\n    %-PLOT DATA STRUCTURE- %\n    plotData = get(obj.State.Plot(plotIndex).Handle);\n\n    %-CHECK FOR MULTIPLE AXES-%\n    [xsource, ysource] = findSourceAxis(obj, axIndex);\n\n    %-ASSOCIATE POLAR-AXES LAYOUT-%\n    obj.data{plotIndex}.subplot = sprintf('polar%d', xsource+1);\n\n    %-------------------------------------------------------------------------%\n\n    %-parse plot data-%\n    rData = plotData.RData;\n    thetaData = rad2deg(plotData.ThetaData);\n\n    thetaData(rData<0) = mod(thetaData(rData<0)+180, 360);\n    rData = abs(rData);\n\n    %-------------------------------------------------------------------------%\n\n    %-scatterpolar trace setting-%\n    obj.data{plotIndex}.type = 'scatterpolar';\n    obj.data{plotIndex}.mode = 'markers';\n    obj.data{plotIndex}.visible = strcmp(plotData.Visible,'on');\n    obj.data{plotIndex}.name = plotData.DisplayName;\n\n    %-------------------------------------------------------------------------%\n\n    %-set scatterpolar data-%\n    obj.data{plotIndex}.r = rData;\n    obj.data{plotIndex}.theta = thetaData;\n\n    %-------------------------------------------------------------------------%\n\n    %-trace settings-%\n    markerStruct = extractScatterMarker(plotData);\n\n    obj.data{plotIndex}.marker = markerStruct;\n\n    if length(markerStruct.size) == 1\n        obj.data{plotIndex}.marker.size = markerStruct.size * 0.2;\n    end\n\n    if length(markerStruct.line.color) > 1\n        obj.data{plotIndex}.marker.line.color = markerStruct.line.color{1};\n    end\n\n    %-------------------------------------------------------------------------%\n\n    %-legend setting-%\n    leg = get(plotData.Annotation);\n    legInfo = get(leg.LegendInformation);\n\n    switch legInfo.IconDisplayStyle\n        case 'on'\n            obj.data{plotIndex}.showlegend = true;\n        case 'off'\n            obj.data{plotIndex}.showlegend = false;\n    end\n\n    %-------------------------------------------------------------------------%\n\n    %-set polar axes-%\n    updatePolaraxes(obj, plotIndex);\n\n    %-------------------------------------------------------------------------%\nend\n\n%-------------------------------------------------------------------------%\n%\n%-SET POLAR AXIS-%\n%\n%-------------------------------------------------------------------------%\n\nfunction updatePolaraxes(obj, plotIndex)\n\n    %-------------------------------------------------------------------------%\n\n    %-AXIS INDEX-%\n    axIndex = obj.getAxisIndex(obj.State.Plot(plotIndex).AssociatedAxis);\n\n    %-CHECK FOR MULTIPLE AXES-%\n    [xsource, ysource] = findSourceAxis(obj, axIndex);\n        \n    %-GET DATA STRUCTURES-%\n    plotData = get(obj.State.Plot(plotIndex).Handle);\n    axisData = get(plotData.Parent);\n    thetaAxis = get(axisData.ThetaAxis);\n    rAxis = get(axisData.RAxis);\n\n    %-------------------------------------------------------------------------%\n\n    %-set domain plot-%\n    xo = axisData.Position(1);\n    yo = axisData.Position(2);\n    w = axisData.Position(3);\n    h = axisData.Position(4);\n\n    polarAxis.domain.x = min([xo xo + w], 1);\n    polarAxis.domain.y = min([yo yo + h], 1);\n\n    %-------------------------------------------------------------------------%\n        \n    %-setting angular axis-%\n    gridColor = sprintf('rgba(%f,%f,%f,%f)', 255*axisData.GridColor, ...\n        axisData.GridAlpha);\n    gridWidth = axisData.LineWidth;\n    thetaLim = thetaAxis.Limits;\n    \n    polarAxis.angularaxis.linecolor = gridColor;\n    polarAxis.angularaxis.ticklen = mean(thetaAxis.TickLength);\n\n    if isnumeric(thetaLim)\n        polarAxis.angularaxis.range = thetaLim;\n    else\n        polarAxis.angularaxis.autorange = true;\n    end\n\n    if strcmp(axisData.ThetaGrid, 'on')\n        polarAxis.angularaxis.gridwidth = gridWidth;\n        polarAxis.angularaxis.gridcolor = gridColor;\n    end\n\n    %-------------------------------------------------------------------------%\n\n    %-set angular axis label-%\n    thetaLabel = thetaAxis.Label;\n\n    polarAxis.angularaxis.title.text = thetaLabel.String;\n    polarAxis.radialaxis.title.font.family = matlab2plotlyfont(...\n        thetaLabel.FontName);\n    polarAxis.radialaxis.title.font.size = thetaLabel.FontSize;\n    polarAxis.radialaxis.title.font.color = sprintf('rgb(%f,%f,%f)', ...\n        255*thetaLabel.Color);\n\n    %-------------------------------------------------------------------------%\n        \n    %-setting radial axis-%\n    rLim = rAxis.Limits;\n\n    polarAxis.radialaxis.showline = false;\n    polarAxis.radialaxis.angle = axisData.RAxisLocation+6;\n    polarAxis.radialaxis.tickangle = 90-rAxis.TickLabelRotation;\n    polarAxis.radialaxis.ticklen = mean(rAxis.TickLength);\n\n    if isnumeric(rLim)\n        polarAxis.radialaxis.range = rLim;\n    else\n        polarAxis.radialaxis.autorange = true;\n    end\n\n    if strcmp(axisData.RGrid, 'on')\n        polarAxis.radialaxis.gridwidth = gridWidth;\n        polarAxis.radialaxis.gridcolor = gridColor;\n    end\n\n    %-------------------------------------------------------------------------%\n\n    %-set radial axis label-%\n    rLabel = thetaAxis.Label;\n\n    polarAxis.angularaxis.title.text = 'label';%rLabel.String;\n    polarAxis.angularaxis.title.font.family = matlab2plotlyfont(...\n        rLabel.FontName);\n    polarAxis.angularaxis.title.font.size = rLabel.FontSize;\n    polarAxis.angularaxis.title.font.color = sprintf('rgb(%f,%f,%f)', ...\n        255*rLabel.Color);\n\n    %-------------------------------------------------------------------------%\n\n    %-angular tick labels settings-%\n    tickValues = axisData.ThetaTick; \n    tickLabels = axisData.ThetaTickLabel;\n    showTickLabels = true;\n\n    try\n        if tickValues(1) == 0 && tickValues(end) == 360\n            tickValues = tickValues(1:end-1);\n        end\n    catch\n        tickValues = tickValues;\n    end\n\n    if isempty(tickValues) \n        showTickLabels = false;\n        polarAxis.angularaxis.showticklabels = showTickLabels;\n        polarAxis.angularaxis.ticks = '';\n\n    elseif isempty(tickLabels)\n        polarAxis.angularaxis.tickvals = tickValues;\n\n    else\n        polarAxis.angularaxis.tickvals = tickValues;\n        polarAxis.angularaxis.ticktext = tickLabels;\n\n    end\n\n    if showTickLabels\n        switch thetaAxis.TickDirection\n            case 'in'\n                polarAxis.angularaxis.ticks = 'inside';\n            case 'out'\n                polarAxis.angularaxis.ticks = 'outside';\n        end\n\n        %-tick font-%\n        polarAxis.angularaxis.tickfont.family = matlab2plotlyfont(...\n            thetaAxis.FontName);\n        polarAxis.angularaxis.tickfont.size = thetaAxis.FontSize;\n        polarAxis.angularaxis.tickfont.color = sprintf('rgb(%f,%f,%f)', ...\n            255*thetaAxis.Color);\n    end\n\n\n    %-------------------------------------------------------------------------%\n\n    %-radial tick labels settings-%\n    tickValues = axisData.RTick;\n    tickLabels = axisData.RTickLabel;\n    showTickLabels = true;\n\n    if isempty(tickValues) \n        showTickLabels = false;\n        polarAxis.radialaxis.showticklabels = showTickLabels;\n        polarAxis.radialaxis.ticks = '';\n\n    elseif isempty(tickLabels)\n        polarAxis.radialaxis.tickvals = tickValues;\n\n    else\n        polarAxis.radialaxis.tickvals = tickValues;\n        polarAxis.radialaxis.ticktext = tickLabels;\n    end\n\n    if showTickLabels\n        switch rAxis.TickDirection\n            case 'in'\n                polarAxis.radialaxis.ticks = 'inside';\n            case 'out'\n                polarAxis.radialaxis.ticks = 'outside';\n        end\n\n        %-tick font-%\n        polarAxis.radialaxis.tickfont.family = matlab2plotlyfont(...\n            rAxis.FontName);\n        polarAxis.radialaxis.tickfont.size = rAxis.FontSize;\n        polarAxis.radialaxis.tickfont.color = sprintf('rgb(%f,%f,%f)', ...\n            255*rAxis.Color);\n    end\n\n\n    %-------------------------------------------------------------------------%\n\n    %-set polaraxes to layout-%\n    obj.layout = setfield(obj.layout, sprintf('polar%d', xsource+1), polarAxis);\n\n    %-------------------------------------------------------------------------%\nend\n\n\n", "meta": {"author": "plotly", "repo": "plotly_matlab", "sha": "a5595260ef2b165f24740838ea397ffd82a12623", "save_path": "github-repos/MATLAB/plotly-plotly_matlab", "path": "github-repos/MATLAB/plotly-plotly_matlab/plotly_matlab-a5595260ef2b165f24740838ea397ffd82a12623/plotly/plotlyfig_aux/handlegraphics/updateScatterPolar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24613408273759835}}
{"text": "function f = vis_derived_filter(model, tree)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nconf = voc_config();\n\n% indexes into info from get_detection_trees.cc\n% replace with tree_mat_to_struct\nN_PARENT      = 1;\nN_IS_LEAF     = 2;\nN_SYMBOL      = 3;\nN_RULE_INDEX  = 4;\nN_RHS_INDEX   = 5;\nN_X           = 6;\nN_Y           = 7;\nN_L           = 8;\nN_DS          = 9;\nN_DX          = 10;\nN_DY          = 11;\nN_SCORE       = 12;\nN_LOSS        = 13;\nN_SZ          = 14;\n\nrx = tree(N_X, 1);\nry = tree(N_Y, 1);\nrl = tree(N_L, 1);\n\nf = zeros([0 0 conf.features.dim]);\noff_x = 0;\noff_y = 0;\n\nfor i = 2:size(tree,2)\n  s = tree(N_SYMBOL, i);\n  if model.symbols(s).type == 'T'\n    x = off_x + tree(N_X, i) - rx;\n    y = off_y + tree(N_Y, i) - ry;\n    l = tree(N_L, i) - rl;\n\n    pad = [abs(min(0, [y x])) 0];\n    f = padarray(f, pad, 0, 'pre');\n    if pad(1) > 0\n      off_y = off_y + pad(1);\n    end\n    if pad(2) > 0\n      off_x = off_x + pad(2);\n    end\n\n    w = model_get_block(model, model.filters(model.symbols(s).filter));\n    wsz = size(w);\n    fsz = size(f);\n    req_fsz = [off_y + y + wsz(1), off_x + x + wsz(2), wsz(3)];\n    pad = max(0, req_fsz - fsz);\n    f = padarray(f, pad, 0, 'post');\n    f(off_y+1+y:off_y+1+y+wsz(1)-1, off_x+1+x:off_x+1+x+wsz(2)-1, :) = ...\n      f(off_y+1+y:off_y+1+y+wsz(1)-1, off_x+1+x:off_x+1+x+wsz(2)-1, :) + w;\n  end\nend\n\nvisualizeHOG(max(0, f));\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/vis/vis_derived_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24613408273759832}}
{"text": "\n%1. Load the image, for example\n    image        = imread('img.bmp');\n    \n%2. Call this function to calculate the quality score:\n    qualityscore = SSEQ(image)", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/qualityMeasures/SSEQ/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24613408273759832}}
{"text": "function [broadcast_obs,precise_obs]=createObs(TOW,satOrbits)\n\nprecise_obs = 0;\n\nindex=find(satOrbits(1).TOW==TOW);\nPRNlist=[];\n\nfor ii=1:32\n    if satOrbits(ii).C1(index)~=0 && satOrbits(ii).L1(index)~=0 ...\n            &&satOrbits(ii).L2(index)~=0 &&satOrbits(ii).P2(index)~=0 \n        PRNlist=[PRNlist,ii];\n    end\nend\n\nbroadcast_obs.col.XS=1;\nbroadcast_obs.col.YS=2;\nbroadcast_obs.col.ZS=3;\nbroadcast_obs.col.CorrP=4;\nbroadcast_obs.col.TOW=5;\nbroadcast_obs.col.PRN=6;\n\nbroadcast_obs.data=zeros(length(PRNlist),5);\n\nfor ii=1:length(PRNlist)\n    broadcast_obs.data(ii,broadcast_obs.col.XS)=satOrbits(PRNlist(ii)).XS(index);\n    broadcast_obs.data(ii,broadcast_obs.col.YS)=satOrbits(PRNlist(ii)).YS(index);\n    broadcast_obs.data(ii,broadcast_obs.col.ZS)=satOrbits(PRNlist(ii)).ZS(index);\n    broadcast_obs.data(ii,broadcast_obs.col.CorrP)=satOrbits(PRNlist(ii)).CorrP1(index);\n    broadcast_obs.data(ii,broadcast_obs.col.PRN)=satOrbits(PRNlist(ii)).PRN;\n    broadcast_obs.data(ii,broadcast_obs.col.TOW)=TOW;    \nend\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/matlab/createObs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.246134076314406}}
{"text": "function F = filmStrip( I, overlap, delta, border )\n% Used to display R stacks of T images as a \"filmstrip\".\n%\n% See examples below to see what is meant by \"filmstrip\".\n%\n% USAGE\n%  F = filmStrip( I, overlap, delta, border )\n%\n% INPUTS\n%  I          - MxNxTxR or MxNx1xTxR or MxNx3xTxR array\n%               (of bw or color images). R can equal 1.\n%  overlap    - amount of overlap between successive frames\n%  delta      - amount to shift each successive frame upward\n%  border     - width of black border around each frame\n%\n% OUTPUTS\n%  F       - filmstrip\n%\n% EXAMPLE - one filmstrip\n%  load images;\n%  F1 = filmStrip( video(:,:,1:15), 10, 2, 5 );   figure(1); im(F1); % one\n%  F2 = filmStrip( videos(:,:,:,1:10), 5, 2, 3 ); figure(2); im(F2); % many\n%\n% See also MONTAGE2\n%\n% Piotr's Computer Vision Matlab Toolbox      Version 2.0\n% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\n% convert I to be of type double, and have dimensions MxNxCxTxR\nI = double(I); I = I/max(I(:)); sizI = size(I);\nif(~any(sizI(3)==[1 3])); I=reshape(I,[sizI(1:2),1,sizI(3:end)]); end\nI = padarray( I, [border border 0 0 0], 0, 'both' );\n[mRows, nCols, nColor, nFrame, nStrip] = size(I);\n\n% size of final filmstip object\nsizF1 = [mRows+delta*(nFrame-1), nFrame*nCols-overlap*(nFrame-1), nColor];\nsizF=sizF1;  sizF(1)=sizF1(1)*nStrip - ((nFrame-1-2)*delta)*(nStrip-1);\nmRowsF1 = sizF1(1);\n\nfor i=1:nStrip\n\n  % Create i-th film strip\n  Fi = -ones( sizF1 );  row = 1;  col = sizF1(2);\n  for f=nFrame:-1:1\n    Fi( row:(row+mRows-1), (col-nCols+1):col, : ) = I(:,:,:,f,i);\n    row = row + delta;  col = col - nCols + overlap;\n  end\n\n  % stop if creating single filmstrip\n  if( nStrip==1 ); F=Fi; break; end\n\n  % merge with the previous film strips\n  if( i==1 ); F = -ones( sizF );  row2=1;  end\n  Fc = F( row2:(row2+mRowsF1-1), : );\n  locs=(Fc<0);  Fc(locs) = Fi(locs);\n  F( row2:(row2+mRowsF1-1), :  ) = Fc;\n  row2 = row2 + mRowsF1 - ((nFrame-1-2)*delta);\nend\nF(F<0)=1;\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/images/filmStrip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2460592149504696}}
{"text": "%% NLOPT Install for OPTI Toolbox\n% Copyright (C) 2012 Jonathan Currie (I2C2)\n\n% This file will help you compile NonLinear OPTimization (NLOPT) for use \n% with MATLAB. \n\n% My build platform:\n% - Windows 8 SP1 x64\n% - Visual Studio 2012\n\n% To recompile you will need to get / do the following:\n\n% 1) Get NLOPT\n% NLOPT is available from http://ab-initio.mit.edu/wiki/index.php/NLopt. \n% Download the source.\n\n% 2) Compile NLOPT\n% The easiest way to compile NLOPT is to use the Visual Studio Project\n% Builder included with OPTI. Use the following commands, substituting the \n% required path on your computer:\n%\n% %% Visual Studio Builder Commands\n% path = 'full path to NLOPT here'; %e.g. 'C:\\Solvers\\NLOPT'\n% sdir = path;\n% name = 'libnlopt';\n% opts.exPP = {'_CRT_SECURE_NO_WARNINGS'};\n% opts.exclude = {'testfuncs.c','tst.cc','tstc.c','testros.cc','prog.cc','redblack_test.c','DIRparallel.c'};\n% opts.exFolder = {'octave','swig','test'};\n% VS_WriteProj(sdir,name,[],opts)\n% %%\n%\n% Once complete, you will have a directory called NLOPT\\libnlopt. Open the\n% Visual Studio 2012 project file, then complete the following steps:\n%   a) A default config.h has not been supplied (and I'm guessing only gets\n%   made in Linux versions) so I've made one up based on the template. Copy\n%   the supplied config.h from:\n%       OPTI/Solvers/nlopt/Source/Include\n%   To the project directory.\n%   b) Build a Win32 or x64 Release to compile the code.\n%   c) Copy the generated .lib file to the following folder:\n%\n%   OPTI/Solvers/nlopt/Source/lib/win32 or win64\n%\n%   You will also need to copy nlopt.h to the following folder:\n%\n%   OPTI/Solvers/nlopt/Source/Include\n% \n%   Note with Global Optimization turned on in VS it will take a long time\n%   to link the MEX file.\n\n% 3) NLOPT MEX Interface\n% The NLOPT MEX Interface was written by Steven Johnson and is located in\n% the octave folder (nlopt_optimize-mex.c) HOWEVER in its original form it\n% was not compatible with OPTI (due to the method of adding nonlinear\n% constraints cell by cell), as well as the file name caused compile\n% problems (no '-' allowed for MEX). Therefore I have modified the\n% MEX interface and included is nlopt_optimize_mex.c which you will need to\n% use for compatibility with OPTI. You will need to however copy\n% nlopt_optimize_usage.h from nlopt-xxx/octave to:\n%\n%   OPTI/Solvers/nlopt/Source/Include\n\n% 4) Compile the MEX File\n% The code below will automatically include all required libraries and\n% directories to build the NLOPT MEX file. Once you have completed all \n% the above steps, simply run this file to compile NLOPT! You MUST BE in \n% the base directory of OPTI!\n\nclear nlopt\n\n% Get Arch Dependent Library Path\nlibdir = opti_GetLibPath();\n\nfprintf('\\n------------------------------------------------\\n');\nfprintf('NLOPT MEX FILE INSTALL\\n\\n');\n\n%Get NLOPT Libraries\npost = [' -IInclude -L' libdir ' -llibnlopt -llibut -output nlopt'];\n\n%CD to Source Directory\ncdir = cd;\ncd 'Solvers/nlopt/Source';\n\n%Compile & Move\npre = 'mex -v -largeArrayDims nloptmex.c';\ntry\n    eval([pre post])\n    movefile(['nlopt.' mexext],'../','f')\n    fprintf('Done!\\n');\ncatch ME\n    cd(cdir);\n    error('opti:nlopt','Error Compiling NLOPT!\\n%s',ME.message);\nend\ncd(cdir);\nfprintf('------------------------------------------------\\n');\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/nlopt/opti_NLOPT_Install.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2460490158564613}}
{"text": "function this = set_from_affine_geometry(this, affineTransformation, nVoxels, TR_s)\n% Sets dimInfo from affine affineTransformation, assuming 4D nifti data\n%\n%   Y = MrDimInfo()\n%   Y.set_from_affine_geometry(affineTransformation, nVoxels, TR_s)\n%\n% This is a method of class MrDimInfo.\n%\n% IN\n%\n% OUT\n%\n% EXAMPLE\n%   set_from_affine_geometry\n%\n%   See also MrDimInfo\n\n% Author:   Lars Kasper\n% Created:  2017-11-07\n% Copyright (C) 2017 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public License (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\n\nif nargin < 3\n    nVoxels = [1 1 1 1];\nend\n\nif nargin < 4\n    TR_s = 1;\nend\n\n% or add them...\ndimLabelsGeom = {'x','y','z', 't'};\nunits = {'mm', 'mm', 'mm', 's'};\niDimGeom = 1:4;\n% update existing geom dimensions, add new ones for\n% non-existing\niValidDimLabels = this.get_dim_index(dimLabelsGeom);\niDimGeomExisting = find(iValidDimLabels);\niDimGeomAdd = setdiff(iDimGeom, iDimGeomExisting);\n\n% need nifti to reference first sampling point as offcenter\nresolutions = [affineTransformation.scaling TR_s];\n\n% voxel position by voxel center, time starts at 0 \nfirstSamplingPoint = [affineTransformation.scaling 0]/2; \n\n% if dimension labels exist, just update values\nthis.set_dims(dimLabelsGeom(iDimGeomExisting), ...\n    'resolutions', resolutions(iDimGeomExisting), ...\n    'nSamples', nVoxels(iDimGeomExisting), ...\n    'firstSamplingPoint', firstSamplingPoint(iDimGeomExisting), ...\n    'units', units(iDimGeomExisting));\n\n% if they do not exist, create dims\nthis.add_dims(dimLabelsGeom(iDimGeomAdd), ...\n    'resolutions', resolutions(iDimGeomAdd), ...\n    'nSamples', nVoxels(iDimGeomAdd), ...\n    'firstSamplingPoint', firstSamplingPoint(iDimGeomAdd), ...\n    'units', units(iDimGeomAdd));", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDimInfo/set_from_affine_geometry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2460490158564613}}
{"text": "% ijcvMultiSegScript\n \nimdir = '../images/stanford';\noutdir = '../data';\nncv = 5;\n\nif 1\n    load '../data/stanford_imsegs2.mat';\n    ijcv = load('../data/ijcv06/ijcvClassifier.mat');\n    %load '../data/bsdsdata.mat';\nend\n\ncv_images = [1:numel(imsegs)];\nnsegments = [5 10 15 20 25 30 35 40 45 50 60 70 80 90 100];\n\nif ~exist('spfeatures')\n    spfeatures = mcmcGetAllSuperpixelData(imdir, imsegs);\n    [efeatures, adjlist] = mcmcGetAllEdgeData(spfeatures, imsegs);\n    for f = 1:numel(imsegs)\n        fprintf(1, '.', int32(f))\n        if mod(f, 25)==0, fprintf(1, '\\n'); end\n        \n        [pvSP{f}, phSP{f}, pE{f}] = mcmcInitialize(spfeatures{f}, efeatures{f}, ...\n            adjlist{f}, imsegs(f), ijcv.vclassifierSP, ijcv.hclassifierSP, ijcv.eclassifier, ijcv.ecal, 'none');\n        smaps{f} = generateMultipleSegmentations2(pE{f}, adjlist{f}, imsegs(f).nseg, nsegments);\n\n        im = im2double(imread([imdir '/' imsegs(f).imname]));\n        imdata = mcmcComputeImageData(im, imsegs(f));\n\n        for k = 1:numel(nsegments)\n            labdata{f, k} = mcmcGetSegmentFeatures(imsegs(f), spfeatures{f}, imdata, smaps{f}(:, k), (1:max(smaps{f}(:, k))));            \n            [mclab{f, k}, mcprc{f, k}, allprc{f, k}, trainw{f, k}] = segmentation2labels(imsegs(f), smaps{f}(:, k));\n            unilabel{f, k} = mclab{f, k}.*(mcprc{f, k}>0.95);\n            seglabel{f,k} =  1*(mcprc{f, k}>0.95) + (-1)*(mcprc{f, k}<0.95);                                  \n        end        \n    end\n    \n    save([outdir '/indoordata.mat'], 'spfeatures', 'efeatures', 'adjlist', ...\n        'pvSP', 'phSP', 'pE', 'smaps', 'labdata', ...\n        'mclab', 'mcprc', 'allprc', 'seglabel', 'unilabel', ...\n        'trainw');\nend\n%nsegments = [3 5 6 6 7 8 9 10 11 12 13 14 15 17 18 20 23 27 32 45 50 75 100];\n%nsegments = [3 4 5 6 7 7 8 8 9 9 10 11 11 12 12 13 13 14 14 15 16 16 17 19 20 21 23 25 28 31 37 51];\n\n[vacc, hacc, vcm, hcm, pg] = testMultipleSegmentationsCV2(imsegs, ...\n    labdata, labdata, smaps, ijcv.vclassifier, ijcv.hclassifier, ijcv.sclassifier, ...\n    pvSP, phSP, 1);\nsave([outdir '/indoorResults_trainOutdoor.mat'], 'vacc', 'hacc', 'vcm', 'hcm', 'pg');\ndisp(num2str([vacc hacc]))\ndisp(num2str(vcm))\ndisp(num2str(hcm))\n\nif ~exist('vclassifier')\n    for k = 1:ncv\n        disp(['Iteration: ' num2str(k)]);\n        testind{k} = (floor((k-1)*numel(cv_images)/ncv)+1):(floor(k*numel(cv_images)/ncv));\n        trainind{k} = setdiff([1:numel(cv_images)], testind{k});\n        sclassifier(k) = mcmcTrainSegmentationClassifier2(...\n            [labdata(trainind{k}, :) ; labdata], ...\n            [seglabel(trainind{k}, :) ; seglabel], ...\n            [trainw(trainind{k}, :) ; trainw]); \n        [vclassifier(k), hclassifier(k)] = ...\n            mcmcTrainSegmentClassifier2(...\n            [labdata(trainind{k}, :) ; labdata], ...\n            [unilabel(trainind{k}, :) ; unilabel], ...\n            [trainw(trainind{k}, :) ; trainw], 100000);       \n    end\nend\n[vacc, hacc, vcm, hcm, pg] = testMultipleSegmentationsCV2(imsegs, ...\n    labdata, labdata, smaps, vclassifier, hclassifier, sclassifier, [], [], ncv);  \ndisp(num2str([vacc hacc]))\ndisp(num2str(vcm))\ndisp(num2str(hcm))\n\nsave([outdir '/indoorResults.mat'], 'vclassifier', 'hclassifier', 'sclassifier', 'vacc', 'hacc', 'vcm', 'hcm', 'pg');", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/GeometricContext/ijcv06/ijcvTestIndoorScript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.246001607227568}}
{"text": "function printModelStats(model, printModelIssues, printDetails)\n% printModelStats\n%   prints some statistics about a model to the screen\n%\n%   model               a model structure\n%   printModelIssues    true if information about unconnected\n%                       reactions/metabolites and elemental balancing\n%                       should be printed (opt, default false)\n%   printDetails        true if detailed information should be printed\n%                       about model issues. Only used if printModelIssues\n%                       is true (opt, default true)\n%\n%   Usage: printModelStats(model,printModelIssues, printDetails)\n\nif nargin<2\n    printModelIssues=false;\nend\nif nargin<3\n    printDetails=true;\nend\n\nfprintf(['Network statistics for ' model.id ': ' model.name '\\n']);\n\n%Get which reactions are present in each compartment\nrxnComps=sparse(numel(model.rxns),numel(model.comps));\n\n%For each compartment, find the metabolites that are present in that\n%compartment and then the reactions they are involved in\nfor i=1:numel(model.comps)\n    [~, I]=find(model.S(model.metComps==i,:));\n    rxnComps(I,i)=1;\nend\n\nif isfield(model,'eccodes')\n    fprintf(['EC-numbers\\t\\t\\t' num2str(numel(unique(model.eccodes))) '\\n']);\nend\n\n%Print information about genes\nif isfield(model,'genes')\n    fprintf(['Genes*\\t\\t\\t\\t' num2str(numel(model.genes)) '\\n']);\n    %Find the genes in each compartment\n    for i=1:numel(model.comps)\n        [~, I]=find(model.rxnGeneMat(rxnComps(:,i)==1,:));\n        fprintf(['\\t' model.compNames{i} '\\t' num2str(numel(unique(I))) '\\n']);\n    end\nend\n\n%Print information about reactions\nfprintf(['\\nReactions*\\t\\t\\t' num2str(numel(model.rxns)) '\\n']);\nfor i=1:numel(model.comps)\n    fprintf(['\\t' model.compNames{i} '\\t' num2str(sum(rxnComps(:,i))) '\\n']);\nend\n\n%Removes the effect of compartments and removes duplicate reactions\ntemp=model;\ntemp.comps(:)={'s'}; %Set all compartments to be the same\nequ=constructEquations(sortModel(temp,true,true),temp.rxns,false);\n\nfprintf(['Unique reactions**\\t' num2str(numel(unique(equ))) '\\n']);\n\n%Print information about metabolites\nfprintf(['\\nMetabolites\\t\\t\\t' num2str(numel(model.mets)) '\\n']);\nfor i=1:numel(model.comps)\n    fprintf(['\\t' model.compNames{i} '\\t' num2str(sum(model.metComps==i)) '\\n']);\nend\n\nfprintf(['Unique metabolites\\t' num2str(numel(unique(model.metNames))) '\\n']);\n\nfprintf('\\n* Genes and reactions are counted for each compartment if any of the corresponding metabolites are in that compartment. The sum may therefore not add up to the total number.\\n');\nfprintf('** Unique reactions are defined as being biochemically unique (no compartmentalization)\\n');\n\n%Also print some potential problems if there are any\nif printModelIssues==true\n    fprintf(['\\nShort model quality summary for ' model.id ': ' model.name '\\n']);\n    \n    %Check that all the metabolites are being used\n    involvedMat=model.S;\n    involvedMat(involvedMat~=0)=1;\n    usedMets=sum(involvedMat,2);\n    notPresent=find(usedMets==0);\n    if ~isempty(notPresent)\n        errorText=['Non-used metabolites\\t' num2str(numel(notPresent)) '\\n'];\n        if printDetails==true\n            for i=1:numel(notPresent)\n                errorText=[errorText '\\t(' model.mets{notPresent(i)} ') ' model.metNames{notPresent(i)} '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\n    \n    %Check if there are empty reactions\n    usedRxns=sum(involvedMat,1);\n    notUsed=find(usedRxns==0);\n    if ~isempty(notUsed)\n        errorText=['Empty reactions\\t' num2str(numel(notUsed)) '\\n'];\n        if printDetails==true\n            for i=1:numel(notUsed)\n                errorText=[errorText '\\t' model.rxns{notUsed(i)} '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\n    \n    %Check if there are dead-end reactions/metabolites\n    [~, deletedReactions, deletedMetabolites]=simplifyModel(model,true,false,false,true);\n    \n    if ~isempty(deletedReactions)\n        errorText=['Dead-end reactions\\t' num2str(numel(deletedReactions)) '\\n'];\n        if printDetails==true\n            for i=1:numel(deletedReactions)\n                errorText=[errorText '\\t' deletedReactions{i} '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\n    \n    %Ignore non-used metabolites\n    deletedMetabolites=setdiff(deletedMetabolites,model.mets(notPresent));\n    %Must map to indexes in order to print names\n    deletedMetabolites=find(ismember(model.mets,deletedMetabolites));\n    if ~isempty(deletedMetabolites)\n        errorText=['Dead-end metabolites\\t' num2str(numel(deletedMetabolites)) '\\n'];\n        if printDetails==true\n            for i=1:numel(deletedMetabolites)\n                errorText=[errorText '\\t(' model.mets{deletedMetabolites(i)} ') ' model.metNames{deletedMetabolites(i)} '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\n    \n    balanceStructure=getElementalBalance(model);\n    \n    notParsed=find(balanceStructure.balanceStatus<0);\n    notBalanced=find(balanceStructure.balanceStatus==0);\n    \n    if ~isempty(notParsed)\n        errorText=['Reactions which could not be elementally balanced\\t' num2str(numel(notParsed)) '\\n'];\n        if printDetails==true\n            for i=1:numel(notParsed)\n                errorText=[errorText '\\t' model.rxns{notParsed(i)} '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\n    if ~isempty(notBalanced)\n        errorText=['Reactions which are elementally unbalanced\\t' num2str(numel(notBalanced)) '\\n'];\n        if printDetails==true\n            names=strcat(balanceStructure.elements.names,{', '});\n            for i=1:numel(notBalanced)\n                badOnes=sprintf('%s', names{abs(balanceStructure.leftComp(notBalanced(i),:)-balanceStructure.rightComp(notBalanced(i),:))>10^-7});\n                errorText=[errorText '\\t' model.rxns{notBalanced(i)} '\\t' badOnes(1:end-2) '\\n'];\n            end\n            errorText=[errorText '\\n'];\n        end\n        fprintf(errorText);\n    end\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/core/printModelStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.24591929035501642}}
{"text": "function [d_out] = qpsk_srrc(d_in)\n\n    persistent buf\n\n    OS_RATE = 8;\n    f = SRRC;\n\n    if isempty(buf)\n        buf = complex(zeros(1,OS_RATE*2+1),zeros(1,OS_RATE*2+1));\n    end\n\n    buf = [buf(2:end) d_in];\n\n    d_out = buf*f;\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42233-qpsk-example-with-matlab-entry-for-hdl-coder/Chilipepper Labs/Lab_3/MATLAB/qpsk_srrc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24591928471300054}}
{"text": "function cls = spm_mars_newSeg(res,tc,bf,df,mode,tcm)\n% FORMAT cls = spm_mars_newSeg(res,tc,bf,df,mode,tcm)\n%\n% Write out the results from toolbox 'New Segment'. This function is only for\n% the purpose of making toolbox 'MARS' backwards compatible with 'New Segment'.\n%\n% Adapted from spm_preproc_write8 by John Ashburner\n% $Id: spm_preproc_write8.m 4337 2011-05-31 16:59:44Z john $\n% Copyright (C) 2008 Wellcome Department of Imaging Neuroscience\n%\n% Modified by Yu (Andy) Huang\n% $Id: spm_mars_newSeg.m 2015-07-27 andy$\n% Neural Engineering Lab, Dept. of Biomedical Engineering, City College of New York\n% yhuang16@citymail.cuny.edu\n\n% Read essentials from tpm (it will be cleared later)\ntpm = res.tpm;\nif ~isstruct(tpm) || ~isfield(tpm, 'bg1'),\n    tpm = spm_load_priors8(tpm);\nend\nd1        = size(tpm.dat{1});\nd1        = d1(1:3);\nM1        = tpm.M;\n[bb1 vx1] = spm_get_bbox(tpm.V(1), 'old');\n\nif isfield(res,'mg'),\n    lkp = res.lkp;\n    Kb  = max(lkp);\nelse\n    Kb  = size(res.intensity(1).lik,2);\nend\n\nN   = numel(res.image);\nif nargin<2, tc = true(Kb,4); end % native, import, warped, warped-mod\nif nargin<3, bf = true(N,2);  end % field, corrected\nif nargin<4, df = true(1,2);  end % inverse, forward\n% if nargin<5, mrf= 2;          end % MRF parameter  % andy 2013-05-03\n\n[pth,nam]=fileparts(res.image(1).fname);\nind  = res.image(1).n;\nd    = res.image(1).dim(1:3);\n\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3  = 1:d(3);\n\nchan(N) = struct('B1',[],'B2',[],'B3',[],'T',[],'Nc',[],'Nf',[],'ind',[]);\nfor n=1:N,\n    d3         = [size(res.Tbias{n}) 1];\n    chan(n).B3 = spm_dctmtx(d(3),d3(3),x3);\n    chan(n).B2 = spm_dctmtx(d(2),d3(2),x2(1,:)');\n    chan(n).B1 = spm_dctmtx(d(1),d3(1),x1(:,1));\n    chan(n).T  = res.Tbias{n};\n\n    [pth1,nam1,ext1] = fileparts(res.image(n).fname);\n    chan(n).ind      = res.image(n).n;\n\n    if bf(n,2),\n        chan(n).Nc      = nifti;\n        chan(n).Nc.dat  = file_array(fullfile(pth1,['m', nam1, '.nii']),...\n                                     res.image(n).dim(1:3),...\n                                     [spm_type('float32') spm_platform('bigend')],...\n                                     0,1,0);\n        chan(n).Nc.mat  = res.image(n).mat;\n        chan(n).Nc.mat0 = res.image(n).mat;\n        chan(n).Nc.descrip = 'Bias corrected';\n        create(chan(n).Nc);\n    end\n\n    if bf(n,1),\n        chan(n).Nf      = nifti;\n        chan(n).Nf.dat  = file_array(fullfile(pth1,['BiasField_', nam1, '.nii']),...\n                                     res.image(n).dim(1:3),...\n                                     [spm_type('float32') spm_platform('bigend')],...\n                                     0,1,0);\n        chan(n).Nf.mat  = res.image(n).mat;\n        chan(n).Nf.mat0 = res.image(n).mat;\n        chan(n).Nf.descrip = 'Estimated Bias Field';\n        create(chan(n).Nf);\n    end\nend\n\ndo_cls   = any(tc(:)) || nargout>1;\ntiss(Kb) = struct('Nt',[]);\nfor k1=1:Kb,\n    if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1,\n        do_cls  = true;\n    end\n    if tc(k1,1),\n        tiss(k1).Nt      = nifti;\n        tiss(k1).Nt.dat  = file_array(fullfile(pth,['c', num2str(k1), nam, '.nii']),...\n                                      res.image(n).dim(1:3),...\n                                      [spm_type('uint8') spm_platform('bigend')],...\n                                      0,1/255,0);\n        tiss(k1).Nt.mat  = res.image(n).mat;\n        tiss(k1).Nt.mat0 = res.image(n).mat;\n        tiss(k1).Nt.descrip = ['Tissue class ' num2str(k1)];\n        create(tiss(k1).Nt);\n        do_cls = true;\n    end;\nend\n\nprm     = [3 3 3 0 0 0];\nCoef    = cell(1,3);\nCoef{1} = spm_bsplinc(res.Twarp(:,:,:,1),prm);\nCoef{2} = spm_bsplinc(res.Twarp(:,:,:,2),prm);\nCoef{3} = spm_bsplinc(res.Twarp(:,:,:,3),prm);\n\ndo_defs = any(df);\ndo_defs = do_cls | do_defs;\nif do_defs,\n    if df(1),\n        [pth,nam,ext1]=fileparts(res.image(1).fname);\n        Ndef      = nifti;\n        Ndef.dat  = file_array(fullfile(pth,['iy_', nam1, '.nii']),...\n                               [res.image(1).dim(1:3),1,3],...\n                               [spm_type('float32') spm_platform('bigend')],...\n                               0,1,0);\n        Ndef.mat  = res.image(1).mat;\n        Ndef.mat0 = res.image(1).mat;\n        Ndef.descrip = 'Inverse Deformation';\n        create(Ndef);\n    end\n    if df(2) || any(any(tc(:,[2,3,4]))) || nargout>=1,\n        y = zeros([res.image(1).dim(1:3),3],'single');\n    end\nend\n\nspm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');\nM = M1\\res.Affine*res.image(1).mat;\n\nif do_cls\n    Q = zeros([d(1:3),Kb],'single');\nend\n\nfor z=1:length(x3),\n\n    % Bias corrected image\n    cr = cell(1,N);\n    for n=1:N,\n        f          = spm_sample_vol(res.image(n),x1,x2,o*x3(z),0);\n        bf         = exp(transf(chan(n).B1,chan(n).B2,chan(n).B3(z,:),chan(n).T));\n        cr{n}      = bf.*f;\n        if ~isempty(chan(n).Nc),\n            % Write a plane of bias corrected data\n            chan(n).Nc.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = cr{n};\n        end;\n        if ~isempty(chan(n).Nf),\n            % Write a plane of bias field\n            chan(n).Nf.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = bf;\n        end;\n    end\n\n\n    if do_defs,\n        [t1,t2,t3] = defs(Coef,z,res.MT,prm,x1,x2,x3,M);\n        if exist('Ndef','var'),\n            tmp = M1(1,1)*t1 + M1(1,2)*t2 + M1(1,3)*t3 + M1(1,4);\n            Ndef.dat(:,:,z,1,1) = tmp;\n            tmp = M1(2,1)*t1 + M1(2,2)*t2 + M1(2,3)*t3 + M1(2,4);\n            Ndef.dat(:,:,z,1,2) = tmp;\n            tmp = M1(3,1)*t1 + M1(3,2)*t2 + M1(3,3)*t3 + M1(3,4);\n            Ndef.dat(:,:,z,1,3) = tmp;\n        end\n\n        if exist('y','var'),\n            y(:,:,z,1) = t1;\n            y(:,:,z,2) = t2;\n            y(:,:,z,3) = t3;\n        end\n\n        if do_cls,\n            msk = (f==0) | ~isfinite(f);\n\n            if isfield(res,'mg'),\n                q   = zeros([d(1:2) Kb]);\n                q1  = likelihoods(cr,[],res.mg,res.mn,res.vr);\n                q1  = reshape(q1,[d(1:2),numel(res.mg)]);\n                b   = spm_sample_priors8(tpm,t1,t2,t3);\n                for k1=1:Kb,\n                    q(:,:,k1) = sum(q1(:,:,lkp==k1),3).*b{k1};\n                end\n            else\n                q   = spm_sample_priors8(tpm,t1,t2,t3);\n                q   = cat(3,q{:});\n                for n=1:N,\n                    tmp = round(cr{n}*res.intensity(n).interscal(2) + res.intensity(n).interscal(1));\n                    tmp = min(max(tmp,1),size(res.intensity(n).lik,1));\n                    for k1=1:Kb,\n                        likelihood = res.intensity(n).lik(:,k1);\n                        q(:,:,k1)  = q(:,:,k1).*likelihood(tmp);\n                    end\n                end\n            end\n            Q(:,:,z,:) = reshape(q,[d(1:2),1,Kb]); % final probabilities not normalized\n\n        end\n    end\n    spm_progress_bar('set',z);\nend\nspm_progress_bar('clear');\n\ncls   = cell(1,Kb);\nif do_cls\n    P = zeros([d(1:3),Kb],'uint8');\n    for z=1:length(x3),\n        sq = sum(Q(:,:,z,:),4) + eps^2;\n        for k1=1:Kb\n            P(:,:,z,k1) = uint8(round(255 * Q(:,:,z,k1)./sq)); % nomalized probabilities\n        end\n    end\n%     if mrf~=0, nmrf_its = 10; else nmrf_its = 1; end % andy 2013-05-03\n\n%     if mrf==0, % Done this way as spm_mrf is not compiled for all platforms yet\n    if mode == 0  % andy 2013-05-03\n        sQ = (sum(Q,4)+eps)/255;\n        for k1=1:size(Q,4)\n            P(:,:,:,k1) = uint8(round(Q(:,:,:,k1)./sQ));\n        end\n        clear sQ\n    else\n        nmrf_its = 10; % andy 2013-05-03\n        spm_progress_bar('init',nmrf_its,['MRF: Working on ' nam],'Iterations completed');\n        vx2 = single(sum(res.image(1).mat(1:3,1:3).^2));\n        if iscellstr(tcm) % if user specifies TCM, load it  % andy 2013-05-03\n            load(tcm{1},'C');\n            if ndims(C)~=2\n                warning('Warn:convert',...\n                    'Local or regional TCM detected. For MRF-based clean-up provided by SPM8, user-provided TCM must be a global TCM!\\nSPM8 default config is used instead...\\n');\n                G   = ones([Kb,1],'single')*2;\n            else\n            G = single(C);  % andy 2013-04-22\n            end\n        else\n            G   = ones([Kb,1],'single')*2; % andy 2013-05-03\n            %save PQG P Q G tiss Kb x3 ind\n        end\n        \n        for iter=1:nmrf_its,\n            spm_mrf(P,Q,G,vx2);\n            spm_progress_bar('set',iter);\n        end\n    end\n\n    clear Q\n\n    for k1=1:Kb,\n        if ~isempty(tiss(k1).Nt),\n            for z=1:length(x3),\n                tmp = double(P(:,:,z,k1))/255;\n                tiss(k1).Nt.dat(:,:,z,ind(1),ind(2)) = tmp;\n            end\n        end\n    end\n    spm_progress_bar('clear');\n\n    for k1=1:Kb,\n        if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1,\n            cls{k1} = P(:,:,:,k1);\n        end\n    end\n    clear P\nend\n\nclear tpm\nM0 = res.image(1).mat;\n\nif any(tc(:,2)),\n\n    bb = nan(2,3);\n    vx = 1.5;\n    % Sort out bounding box etc\n    bb(~isfinite(bb)) = bb1(~isfinite(bb));\n    if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end;\n    bb(1,:) = vx*round(bb(1,:)/vx);\n    bb(2,:) = vx*round(bb(2,:)/vx);\n\n    % Figure out the mapping from the volumes to create to the original\n    mm = [[\n        bb(1,1) bb(1,2) bb(1,3)\n        bb(2,1) bb(1,2) bb(1,3)\n        bb(1,1) bb(2,2) bb(1,3)\n        bb(2,1) bb(2,2) bb(1,3)\n        bb(1,1) bb(1,2) bb(2,3)\n        bb(2,1) bb(1,2) bb(2,3)\n        bb(1,1) bb(2,2) bb(2,3)\n        bb(2,1) bb(2,2) bb(2,3)]'; ones(1,8)];\n\n    vx2  = M1\\mm;\n    odim = abs(round((bb(2,1:3)-bb(1,1:3))/vx))+1;\n    vx3  = [[\n        1       1       1\n        odim(1) 1       1\n        1       odim(2) 1\n        odim(1) odim(2) 1\n        1       1       odim(3)\n        odim(1) 1       odim(3)\n        1       odim(2) odim(3)\n        odim(1) odim(2) odim(3)]'; ones(1,8)];\n\n    x      = affind(rgrid(d),M0);\n    y1     = affind(y,M1);\n    ind    = find(tc(:,2));\n    [M,R]  = spm_get_closest_affine(x,y1,single(cls{ind(1)})/255);\n    clear x y1\n\n    M      = M0\\inv(R)*M1*vx2/vx3;\n    mat0   =         R\\M1*vx2/vx3;\n    mat    = mm/vx3;\n\n    fwhm = max(vx./sqrt(sum(res.image(1).mat(1:3,1:3).^2))-1,0.01);\n    for k1=1:size(tc,1),\n        if tc(k1,2),\n            tmp1     = decimate(single(cls{k1}),fwhm);\n            [pth,nam,ext1]=fileparts(res.image(1).fname);\n            VT      = struct('fname',fullfile(pth,['rc', num2str(k1), nam, '.nii']),...\n                'dim',  odim,...\n                'dt',   [spm_type('float32') spm_platform('bigend')],...\n                'pinfo',[1.0 0]',...\n                'mat',mat);\n            VT = spm_create_vol(VT);\n\n            Ni             = nifti(VT.fname);\n            Ni.mat0        = mat0;\n            Ni.mat_intent  = 'Aligned';\n            Ni.mat0_intent = 'Aligned';\n            create(Ni);\n\n            for i=1:odim(3),\n                tmp = spm_slice_vol(tmp1,M*spm_matrix([0 0 i]),odim(1:2),[1,NaN])/255;\n                VT  = spm_write_plane(VT,tmp,i);\n            end\n            clear tmp1\n        end\n    end\nend\n\nif any(tc(:,3)),\n    C = zeros([d1,Kb],'single');\nend\n\nif any(tc(:,3)) || any(tc(:,4)) || nargout>=1,\n    spm_progress_bar('init',Kb,'Warped Tissue Classes','Classes completed');\n    for k1 = 1:Kb,\n        if ~isempty(cls{k1}),\n            c = single(cls{k1})/255;\n            if any(tc(:,3)),\n                [c,w]  = dartel3('push',c,y,d1(1:3));\n                vx          = sqrt(sum(M1(1:3,1:3).^2));\n                C(:,:,:,k1) = optimNn(w,c,[1  vx  1e-4 1e-6 0  3 2]);\n                clear w\n            else\n                c      = dartel3('push',c,y,d1(1:3));\n            end\n            if nargout>=1,\n                cls{k1} = c;\n            end\n            if tc(k1,4),\n                N      = nifti;\n                N.dat  = file_array(fullfile(pth,['mwc', num2str(k1), nam, '.nii']),...\n                                    d1,...\n                                    [spm_type('float32') spm_platform('bigend')],...\n                                    0,1,0);\n                N.mat  = M1;\n                N.mat0 = M1;\n                N.descrip = ['Jac. sc. warped tissue class ' num2str(k1)];\n                create(N);\n                N.dat(:,:,:) = c*abs(det(M0(1:3,1:3))/det(M1(1:3,1:3)));\n            end\n            spm_progress_bar('set',k1);\n        end\n    end\n    spm_progress_bar('Clear');\nend\n\nif any(tc(:,3)),\n    spm_progress_bar('init',Kb,'Writing Warped Tis Cls','Classes completed');\n    C = max(C,eps);\n    s = sum(C,4);\n    for k1=1:Kb,\n        if tc(k1,3),\n            N      = nifti;\n            N.dat  = file_array(fullfile(pth,['wc', num2str(k1), nam, '.nii']),...\n                                d1,'uint8',0,1/255,0);\n            N.mat  = M1;\n            N.mat0 = M1;\n            N.descrip = ['Warped tissue class ' num2str(k1)];\n            create(N);\n            N.dat(:,:,:) = C(:,:,:,k1)./s;\n        end\n        spm_progress_bar('set',k1);\n    end\n    spm_progress_bar('Clear');\n    clear C s\nend\n\nif df(2),\n    y         = spm_invert_def(y,M1,d1,M0,[1 0]);\n    N         = nifti;\n    N.dat     = file_array(fullfile(pth,['y_', nam1, '.nii']),...\n                           [d1,1,3],'float32',0,1,0);\n    N.mat     = M1;\n    N.mat0    = M1;\n    N.descrip = 'Deformation';\n    create(N);\n    N.dat(:,:,:,:,:) = reshape(y,[d1,1,3]);\nend\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(sol,z,MT,prm,x0,y0,z0,M)\niMT = inv(MT);\nx1  = x0*iMT(1,1)+iMT(1,4);\ny1  = y0*iMT(2,2)+iMT(2,4);\nz1  = (z0(z)*iMT(3,3)+iMT(3,4))*ones(size(x1));\nx1a = x0    + spm_bsplins(sol{1},x1,y1,z1,prm);\ny1a = y0    + spm_bsplins(sol{2},x1,y1,z1,prm);\nz1a = z0(z) + spm_bsplins(sol{3},x1,y1,z1,prm);\nx1  = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1  = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1  = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nif ~isempty(T)\n    d2 = [size(T) 1];\n    t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\n    t  = B1*t1*B2';\nelse\n    t = zeros(size(B1,1),size(B2,1),size(B3,1));\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction p = likelihoods(f,bf,mg,mn,vr)\nK  = numel(mg);\nN  = numel(f);\nM  = numel(f{1});\ncr = zeros(M,N);\nfor n=1:N,\n    if isempty(bf),\n        cr(:,n) = double(f{n}(:));\n    else\n        cr(:,n) = double(f{n}(:).*bf{n}(:));\n    end\nend\np  = ones(numel(f{1}),K);\nfor k=1:K,\n    amp    = mg(k)/sqrt((2*pi)^N * det(vr(:,:,k)));\n    d      = cr - repmat(mn(:,k)',M,1);\n    p(:,k) = amp * exp(-0.5* sum(d.*(d/vr(:,:,k)),2));\nend\n%=======================================================================\n\n%=======================================================================\nfunction dat = decimate(dat,fwhm)\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\nx  = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x  = x/sum(x);\ny  = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y  = y/sum(y);\nz  = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z  = z/sum(z);\ni  = (length(x) - 1)/2;\nj  = (length(y) - 1)/2;\nk  = (length(z) - 1)/2;\nspm_conv_vol(dat,dat,x,y,z,-[i j k]);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction y1 = affind(y0,M)\ny1 = zeros(size(y0),'single');\nfor d=1:3,\n    y1(:,:,:,d) = y0(:,:,:,1)*M(d,1) + y0(:,:,:,2)*M(d,2) + y0(:,:,:,3)*M(d,3) + M(d,4);\nend\n%=======================================================================\n\n%=======================================================================\nfunction x = rgrid(d)\nx = zeros([d(1:3) 3],'single');\n[x1,x2] = ndgrid(single(1:d(1)),single(1:d(2)));\nfor i=1:d(3),\n    x(:,:,i,1) = x1;\n    x(:,:,i,2) = x2;\n    x(:,:,i,3) = single(i);\nend\n%=======================================================================\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/mars/spm_mars_newSeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24591928471300054}}
{"text": "classdef Server < handle\n  properties(SetAccess=private, GetAccess=private)\n    heightmaps=containers.Map('KeyType', 'uint32', 'ValueType', 'any');\n    map_id_last_used=[];\n    map_id_last_added=[];\n    max_stored_maps=5;\n  end\n\n  methods\n    function obj = Server()\n    end\n\n    function region = getCSpaceRegionAtIndex(obj, i0, yaw, collision_model, varargin)\n      p = inputParser();\n      p.addRequired('i0', @isnumeric);\n      p.addRequired('yaw', @isnumeric);\n      p.addRequired('collision_model', @(x) isa(x, 'iris.terrain_grid.CollisionModel'));\n      p.addParamValue('map_id', -1, @isnumeric);\n      p.addParamValue('xy_bounds', iris.Polyhedron(zeros(0,2),zeros(0,1)), @(x) isa(x, 'iris.Polyhedron'));\n      p.addParamValue('plane_distance_tolerance', 0.025, @isnumeric);\n      p.addParamValue('plane_angle_tolerance', 10 * pi/180, @isnumeric);\n      p.addParamValue('excluded_grid', []);\n      p.addParamValue('debug', false);\n      p.addParamValue('error_on_infeasible_start', true);\n      p.parse(i0, yaw, collision_model, varargin{:});\n      options = p.Results;\n\n      if options.map_id == -1\n        heightmap = obj.getHeightmap(obj.map_id_last_added(end));\n      else\n        heightmap = obj.getHeightmap(options.map_id);\n      end\n\n      x0 = heightmap.X(i0);\n      y0 = heightmap.Y(i0);\n      z0 = heightmap.Z(i0);\n      p0 = [x0;y0;z0];\n      n0 = heightmap.normals(:,i0);\n\n      sz = size(heightmap.X);\n\n\n      dist_to_plane = abs(n0'*[reshape(heightmap.X, 1, []); reshape(heightmap.Y, 1, []); reshape(heightmap.Z, 1, [])] - n0'*p0);\n      dist_to_plane = reshape(dist_to_plane, sz);\n      dist_mask = abs(dist_to_plane < options.plane_distance_tolerance);\n\n      normal_product = n0' * heightmap.normals;\n      normal_product = reshape(normal_product, sz);\n      normal_angle_mask = normal_product > cos(options.plane_angle_tolerance);\n\n      plane_mask = dist_mask & normal_angle_mask;\n      if ~isempty(options.excluded_grid)\n        if ~options.excluded_grid(i0)\n          error('IRIS:TerrainSegmentation:BadSeed', 'the seed point is marked as infeasible in the excluded_grid option');\n        end\n        plane_mask = plane_mask & options.excluded_grid;\n      end\n\n      if ~plane_mask(i0)\n        error('IRIS:TerrainSegmentation:SelectedPointInfeasible', 'cannot create a region around this point.');\n      end\n\n      boundary_mask = logical(iris.terrain_grid.component_boundary(plane_mask, i0));\n\n      if options.debug\n        figure(4)\n        clf\n        subplot(321)\n        imshow(dist_mask, 'InitialMagnification', 'fit');\n        title('dist')\n        subplot(323)\n        imshow(normal_angle_mask, 'InitialMagnification', 'fit');\n        title('normal');\n        subplot(325)\n        imshow(options.excluded_grid, 'InitialMagnification', 'fit');\n        title('existing');\n        subplot(322)\n        imshow(plane_mask, 'InitialMagnification', 'fit');\n        title('combined');\n        subplot(324)\n        imshow(~boundary_mask, 'InitialMagnification', 'fit');\n        title('boundary');\n      end\n\n      obs_x = heightmap.X(boundary_mask);\n      obs_y = heightmap.Y(boundary_mask);\n      obstacle_pts = reshape([reshape(obs_x, 1, []); reshape(obs_y, 1, [])], 2, 1, []);\n      theta_steps = yaw + (-pi:pi/4:pi);\n\n      %% Get obstacles for the foot shape\n      % Reorient the foot onto the terrain plane\n      c = cross([0;0;1], n0);\n      if norm(c) >= 1e-6\n        ax = c / norm(c);\n        angle = asin(norm(c));\n        Rplane = axis2rotmat([ax; angle]);\n      else\n        Rplane = eye(3);\n      end\n\n      c_obs = iris.cspace.cspace3(obstacle_pts, collision_model.foot_shape, theta_steps, Rplane(1:2,1:2));\n\n\n      %% Get obstacles for the upper body collision model\n      % compute distance from the heightmap Z to the current plane\n      % n' * [x;y;z] = n' * point\n      % z = (n'*point - n(1:2)'*[x;y])/n(3)\n      dZ = heightmap.Z - reshape((n0'*p0 - n0(1:2)'*[reshape(heightmap.X,1,[]);reshape(heightmap.Y,1,[])])/n0(3), sz);\n      for j = 1:length(collision_model.body_slices.z)\n        zmin = collision_model.body_slices.z(j);\n        if j < length(collision_model.body_slices.z)\n          zmax = collision_model.body_slices.z(j+1);\n        else\n          zmax = inf;\n        end\n        z_range_mask = dZ >= zmin & dZ <= zmax;\n        boundary_mask = logical(iris.terrain_grid.component_boundary(~z_range_mask, i0));\n        obs_x = heightmap.X(boundary_mask);\n        obs_y = heightmap.Y(boundary_mask);\n        if ~isempty(obs_x)\n          obstacle_pts = reshape([reshape(obs_x, 1, []); reshape(obs_y, 1, [])], 2, 1, []);\n          c_obs = cat(3, c_obs, iris.cspace.cspace3(obstacle_pts, collision_model.body_slices.xy(:,:,j), theta_steps ));\n        end\n      end\n\n      %% Add a bounding polyhedron\n      bounds = iris.Polyhedron.from2DVertices([heightmap.X(end,1), heightmap.X(end,end), heightmap.X(1,end), heightmap.X(1,1); \n                                             heightmap.Y(end,1), heightmap.Y(end,end), heightmap.Y(1,end), heightmap.Y(1,1)]);\n      % Add bounds on yaw angle\n      bounds.A = [bounds.A, zeros(size(bounds.A, 1), 1); \n                  zeros(2, size(bounds.A, 2)), [-1; 1]];\n      bounds.b = [bounds.b; -theta_steps(1); theta_steps(end)];\n      if size(options.xy_bounds.A, 2) == 2\n        options.xy_bounds.A(:,end+1:3) = 0;\n      end\n      bounds.A = [bounds.A; options.xy_bounds.A];\n      bounds.b = [bounds.b; options.xy_bounds.b];\n      [A, b, C, d] = iris.inflate_region(c_obs, bounds.A, bounds.b, [x0; y0; yaw], 'require_containment', true, 'error_on_infeasible_start', options.error_on_infeasible_start);\n\n      [A, iA] = unique(A, 'rows');\n      b = b(iA);\n      region = iris.TerrainRegion(A, b, C, d, p0, n0);\n\n      if options.debug\n        figure(12)\n        clf\n        iris.drawing.drawPolyFromVertices(iris.thirdParty.polytopes.lcon2vert(A, b)', 'r');\n      end\n      \n    end\n\n    function regions = findSafeTerrainRegions(obj, map_id, collision_model, varargin)\n      p = inputParser();\n      p.KeepUnmatched = true;\n      p.addRequired('map_id', @isnumeric);\n      p.addRequired('collision_model', @(x) isa(x, 'iris.terrain_grid.CollisionModel'));\n      p.addParamValue('seeds', []);\n      p.addParamValue('default_yaw', 0, @isnumeric);\n      p.addParamValue('max_slope_angle', 40 * pi/180, @isnumeric);\n      p.addParamValue('max_height_variation', 0.05, @isnumeric);\n      p.addParamValue('xy_bounds', iris.Polyhedron(zeros(0,2),zeros(0,1)), @(x) isa(x, 'iris.Polyhedron'));\n      p.addParamValue('max_num_regions', inf, @(x) x > 0);\n      p.addParamValue('debug', false);\n      p.parse(map_id, collision_model, varargin{:});\n      options = p.Results;\n\n      region_options = p.Unmatched;\n      region_options.map_id = map_id;\n      region_options.xy_bounds = options.xy_bounds;\n      region_options.debug = options.debug;\n\n      regions = iris.TerrainRegion.empty();\n\n      foot_length = max(collision_model.foot_shape(1,:)) - min(collision_model.foot_shape(1,:));\n\n      heightmap = obj.getHeightmap(map_id);\n      slope_angles = heightmap.getSlopeAngles();\n      potential_safe_grid = slope_angles < options.max_slope_angle;\n      sz = size(potential_safe_grid);\n      \n      within_bounds = all(bsxfun(@le, options.xy_bounds.A * [reshape(heightmap.X, 1, []); reshape(heightmap.Y, 1, [])], options.xy_bounds.b), 1);\n      potential_safe_grid = potential_safe_grid & reshape(within_bounds,sz);\n      for dx = -1:1\n        for dy = -1:1\n          dZ = heightmap.Z(2:end-1,2:end-1) - heightmap.Z((2+dx):(end-1+dx),(2+dy):(end-1+dy));\n          potential_safe_grid(2:end-1,2:end-1) = potential_safe_grid(2:end-1,2:end-1) & abs(dZ) < options.max_height_variation;\n        end\n      end\n\n      excluded_grid = true(sz);\n      seed_ind = 1;\n\n      while length(regions) < options.max_num_regions\n\n        if options.debug\n          figure(3)\n          clf\n          imshow(potential_safe_grid, 'InitialMagnification', 'fit');\n        end\n\n        if seed_ind <= size(options.seeds, 2)\n          seed = options.seeds([1,2,6], seed_ind);\n          yaw = seed(3);\n          seed_ind = seed_ind + 1;\n          i0 = obj.xy2ind(map_id, seed(1:2));\n          % seed\n          % heightmap.X(i0)\n          % heightmap.Y(i0)\n          % disp('here')\n        else\n          obs_dists = iris.terrain_grid.obs_dist(potential_safe_grid);\n          [max_dist, i0] = max(obs_dists(:));\n          yaw = options.default_yaw;\n          if max_dist < 0.5 * foot_length / mean(heightmap.resolution);\n            break;\n          end\n        end\n\n        try\n          region = obj.getCSpaceRegionAtIndex(i0, yaw, collision_model, region_options, 'excluded_grid', excluded_grid, 'error_on_infeasible_start', true);\n        catch e\n          if strcmp(e.identifier, 'IRIS:InfeasibleStart')\n            excluded_grid(i0) = false;\n            potential_safe_grid(i0) = false;\n            continue\n          else\n            rethrow(e);\n          end\n        end\n        regions(end+1) = region;\n        % excluded_grid(i0) = false;\n        potential_safe_grid(i0) = false;\n\n        inpoly = all(bsxfun(@minus, region.A * [reshape(heightmap.X, 1, []); reshape(heightmap.Y, 1, []); yaw + zeros(1, numel(heightmap.X))], region.b) <= foot_length / 2, 1);\n        inpoly = reshape(inpoly, sz);\n        potential_safe_grid = potential_safe_grid & ~inpoly;\n      end\n    end\n\n    function i0 = xy2ind(obj, map_id, xy)\n      heightmap = obj.getHeightmap(map_id);\n      sz = size(heightmap.X);\n      [~, m0] = min(abs(heightmap.Y(:,1) - xy(2)));\n      [~, n0] = min(abs(heightmap.X(1,:) - xy(1)));\n      i0 = sub2ind(sz, m0, n0);\n    end\n\n    function obj = addHeightmap(obj, id, heightmap)\n      if isa(heightmap, 'RigidBodyHeightMapTerrain')\n        [X, Y] = meshgrid(heightmap.x, heightmap.y);\n        [Z, normals] = heightmap.getHeight([reshape(X, 1, []); reshape(Y, 1, [])]);\n        heightmap = iris.terrain_grid.Heightmap(X, Y, reshape(Z, size(X)), normals);\n      elseif isa(heightmap, 'iris.terrain_grid.Heightmap')\n      else\n        error('IRIS:TerrainSegmentation:BadHeightmap', 'unrecognized heightmap class: %s', class(heightmap));\n      end\n      obj.heightmaps(id) = heightmap;\n      obj.map_id_last_added(end+1) = id;\n      obj.cleanup();\n    end\n\n    function b = hasHeightmap(obj, id)\n       b = obj.heightmaps.isKey(id);\n     end\n\n    function heightmap = getHeightmap(obj, id)\n      heightmap = obj.heightmaps(id);\n      obj.map_id_last_used(obj.map_id_last_used == id) = [];\n      obj.map_id_last_used(end+1) = id;\n      obj.cleanup();\n    end\n\n    function cleanup(obj)\n      if length(obj.map_id_last_added) >= 2 * obj.max_stored_maps || length(obj.map_id_last_used) >= 2 * obj.max_stored_maps\n        last_used = obj.map_id_last_used(max(1, end-(obj.max_stored_maps-1)):end);\n        last_added = obj.map_id_last_added(max(1, end-(obj.max_stored_maps-1)):end);\n        ids = num2cell(union(last_added, last_used));\n        obj.heightmaps = containers.Map(ids, obj.heightmaps.values(ids));\n      end\n    end\n  end\nend\n\n\n\n\n\n    ", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/+terrain_grid/Server.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.24591927907098454}}
{"text": "function [signalPeaks, signalPeaksArray, signalSigmas, signalStruct] = computeSignalPeaks(signalMatrix, varargin)\n\t% [signalPeaks, signalPeaksArray, signalSigmas] = computeSignalPeaks(signalMatrix, varargin)\n\t% \n\t% Binarize [0,1] input analog signals based on peaks in the signal.\n\t% \n\t% Biafra Ahanonu\n\t% started: 2013.10.28\n\t% \n\t% inputs\n\t% \tsignalMatrix: [nSignals frame] matrix containing analog input signals.\n\t% outputs\n\t% \tsignalPeaks: [nSignals frame] matrix. Binary matrix with 1 = peaks, 0 = non-peaks.\n\t% \tsignalPeaksArray: {1 nSignals} cell array. Each cell contains [1 nPeaks] vector that stores the frame locations of each peak.\n\t% \tsignalSigmas: [nSignals 1] - std of each signal.\n\t% \tsignalStruct: structure containing signalPeaks and signalPeaksArray if multiple thresholds requested.\n\t% options\n\t% \tSee below.\n\t% \t% make a plot?\n\t% \toptions.makePlots = 0;\n\t% \t% show waitbar?\n\t% \toptions.waitbarOn = 1;\n\t% \t% make summary plots of spike information\n\t% \toptions.makeSummaryPlots = 0;\n\t% \t% number of standard deviations above the threshold to count as spike\n\t% \toptions.numStdsForThresh = 3;\n\t% \t% minimum number of time units between events\n\t% \toptions.minTimeBtEvents = 8;\n\t% \t% shift peak detection\n\t% \toptions.nFramesShift = 0;\n\t% \t% should diff and fast oopsi be done?\n\t% \toptions.addedAnalysis = 0;\n\t% \t% use simulated oopsi data\n\t% \toptions.oopsiSimulated = 0;\n\t% changelog\n\t\t% 2015.10.06 [00:14:09] Changed computePeakForSignal to shift the signal to the actual nearby peak since findpeak is sometimes off by a frame or two, should also improve the S-ratio.\n\t\t% 2016.07.05 [14:52:43] Made changes to computePeakForSignal to improve diff based peak detection.\n\t\t% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.\n\t\t% 2022.04.20 [21:29:09] - Better comments for options.\n\t% TODO:\n\t\t% Add option to obtain multiple signal peak outputs from different thresholds in the same run, would save time.\n\t\t% allow input of options file (e.g. for different GCaMP variants, brain regions, etc.)\n\t\t% integrate nearest neighbor into analysis if there is a lot of cross-talk\n\t\t% possibly integrate into identifySpikes?\n\t\t% TODO: convert main loop to parfor, convert signalMatrix to cell array to allow this. Normally fast enough that this won't provide a speed-up.\n\n\t% add controller directory and subdirectories to path\n\t% addpath(genpath(pwd));\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\t%========================\n\t% Binary: 1 = show plots with found events and other information for each signal. 0 = do not show signal plot GUI.\n\toptions.makePlots = 0;\n\t% Binary: 1 = show wait bar, 0 = do not show wait bar.\n\toptions.waitbarOn = 1;\n\t% Binary: 1 = make summary plots of spike information, 0 = no summary plots.\n\toptions.makeSummaryPlots = 0;\n\t% ===\n\t% Int: number of standard deviations above the threshold to count as spike\n\toptions.numStdsForThresh = 3; % 0.5\n\t% DEPRECIATED - Int: alternative to options.numStdsForThresh for display purposes \n\toptions.numStdsForThreshTwo = 2;\n\t% Int: minimum number of time units between events.\n\toptions.minTimeBtEvents = 8;\n\t% Str: detect on differential ('diff') or raw ('raw') trace\n\toptions.detectMethod = 'diff'; % 'raw'\n\t% Int: the size of the window to use to ignore smaller peaks near larger peaks.\n\toptions.movAvgReqSize = 2;\n\t% Int: the size of the moving average to use on the input signals, to smooth out noise.\n\toptions.movAvgFiltSize = 3;\n\t% Binary: 1 = use moving average as specified in options.movAvgFiltSize.\n\toptions.doMovAvg = 1;\n\t% Binary: 1 = subtract median calculated over a filter of some range.\n\toptions.doMedianFilter = 1;\n\t% Int: number of frames to calculate rolling median filter.\n\toptions.medianFilterLength = 201;\n\t% Binary: 1 = leave report peaks as determined by findpeaks (e.g. normally midpoint of the peak rise if using 'diff'). 0 = adjust peak location to the maximum value found within a options.peakMaxLook window.\n\toptions.reportMidpoint = 0;\n\t% Int vector: frames before and after region around each peak to look for a maximum to adjust the test peak by.\n\toptions.peakMaxLook = -6:6;\n\t% Int: number of frames to shift detected peaks.\n\toptions.nFramesShift = 0;\n\t% ===\n\t% Binary: 1 = perform diff and fast oopsi.\n\toptions.addedAnalysis = 0;\n\t% Binary: 1 = use simulated oopsi data.\n\toptions.oopsiSimulated = 0;\n\t% Binary: 1 = open workers, 0 = do not open workers\n\toptions.parallel = 1;\n\t% Binary: 1 = display output information. 0 = suppress most output (e.g. when running in batch for certain applications).\n\toptions.outputInfo = 1;\n\t% Binary: 1 = convert input inputSignals matrix to cell array\n\toptions.convertSignalsToCell = 1;\n\t% get user inputs\n\toptions = getOptions(options,varargin);\n\t% unpack options into current workspace\n\t% fn=fieldnames(options);\n\t% for i=1:length(fn)\n\t%     eval([fn{i} '=options.' fn{i} ';']);\n\t% end\n\t%========================\n\ttry\n\t\t% make sure matrix is double\n\t\t% if ~strcmp(class(signalMatrix),'double')\n\t\tif ~isa(signalMatrix,'double')\n\t\t\tif options.outputInfo==1\n\t\t\t\tdisp('converting signalMatrix to double');\n\t\t\tend\n\t\t\tsignalMatrix = double(signalMatrix);\n\t\tend\n\t\tif options.outputInfo==1\n\t\t\tdisp('calculating signal peaks...')\n\t\tend\n\t\tnSignals = size(signalMatrix,1);\n\t\tnFrames = size(signalMatrix,2);\n\n\t\t% Remove any NaN signals, set to the mean\n\t\tif sum(isnan(signalMatrix(:)))>0\n\t\t\tif options.outputInfo==1\n\t\t\t\tdisp('Removing NaNs from matrix');\n\t\t\tend\n\t\t\tfor signalNo = 1:nSignals\n\t\t\t\trepIdx = isnan(signalMatrix(signalNo,:));\n\t\t\t\tsignalMatrix(signalNo,repIdx) = nanmean(signalMatrix(signalNo,:));\n\t\t\tend\n\t\tend\n\n\t\tsignalStruct = struct;\n\n\t\t% this matrix will contain binarized version of signalMatrix\n\t\tsignalPeaks = zeros(size(signalMatrix));\n\t\t% contains a list for each signal of locations of peaks\n\t\tsignalPeaksArray = cell([1 nSignals]);\n\t\t% open waitbar\n\t\t% if options.waitbarOn==1 waitbarHandle = waitbar(0, 'detecting traces...'); end\n\t\t% loop over all signals.\n\t\t% reverseStr = '';\n\t\tmanageParallelWorkers('parallel',options.parallel);\n\t\tsignalPeaksArrayTmp = cell([1 nSignals]);\n\t\tsignalSigmas = repmat([],[1 nSignals]);\n\t\t% try;[percent progress] = parfor_progress(nSignals);catch;end; dispStepSize = round(nSignals/20); dispstat('','init');\n\n\t\t% Convert to cell array to reduce memory transfer during parallelization\n\t\tif options.convertSignalsToCell==1\n\t\t\t% signalMatrix = squeeze(mat2cell(signalMatrix,ones(1,size(signalMatrix,1)),size(signalMatrix,2)));\n\t\tend\n\n\t\t[optionsOut] = computePeakForSignalOptions('options', options);\n\n\t\t% Only implement in Matlab 2017a and above\n\t\tif ~verLessThan('matlab', '9.2')\n\t\t\tD = parallel.pool.DataQueue;\n\t\t\tafterEach(D, @nUpdateParforProgress);\n\t\t\tp = 1;\n\t\t\tN = nSignals;\n\t\t\tnInterval = round(nSignals/30);%25\n\t\t\toptions_waitbarOn = options.waitbarOn;\n\t\tend\n\n\t\t% signalIdxAll = {};\n\t\t% if options.convertSignalsToCell==1\n\t\t%     parfor signalNum3 = 1:nSignals\n\t\t%         signalIdxAll{signalNum3} = signalNum3;\n\t\t%     end\n\t\t% else\n\t\t%     parfor signalNum3 = 1:nSignals\n\t\t%         signalIdxAll{signalNum3} = sub2ind(size(signalMatrix), repmat(signalNum3,[nFrames 1]), [1:nFrames]');\n\t\t%     end\n\t\t% end\n\n\t\t% startState = ticBytes(gcp);\n\t\tif isempty(gcp)\n\t\t\toptsConstant.Value = optionsOut;\n\t\telse\n\t\t\toptsConstant = parallel.pool.Constant(optionsOut);\n\t\tend\n\t\toptionsCopy_addedAnalysis = options.addedAnalysis;\n\t\toptionsCopy_convertSignalsToCell = options.convertSignalsToCell;\n\t\tparfor signalNum = 1:nSignals\n\t\t\toptionsOutCopy = optsConstant.Value;\n\t\t\t% [percent progress] = parfor_progress;if mod(progress,dispStepSize) == 0;dispstat(sprintf('progress %0.1f %',percent));else;end\n\t\t\t% get the current signal and find its peaks\n\t\t\t% if options.convertSignalsToCell==1\n\t\t\t%     thisSignal = signalMatrix{signalNum2};\n\t\t\t%     signalNum = signalNum2;\n\t\t\t%     signalNum3 = signalNum2;\n\t\t\t%     signalSigmas(signalNum2) = std(thisSignal);\n\t\t\t%     signalPeaksArray{signalNum2} = computePeakForSignal(thisSignal,optionsOutCopy);\n\t\t\t% else\n\t\t\t%     signalNum = find(cellfun(@(x) sum(signalNum2==x),signalIdxAll));\n\t\t\t%     % signalIdx = sub2ind(size(signalMatrix), repmat(signalNum,[nFrames 1]), [1:nFrames]');\n\t\t\t%     % signalIdx = signalIdxAll{signalNum};\n\t\t\t%     thisSignal = signalMatrix(signalNum2);\n\t\t\t%     signalSigmas(signalNum) = std(thisSignal);\n\t\t\t%     signalPeaksArray{signalNum} = computePeakForSignal(thisSignal,optionsOutCopy);\n\t\t\t% end\n\n\t\t\tthisSignal = signalMatrix(signalNum,:);\n\n\t\t\t% if iscell(signalMatrix)==1\n\t\t\t%     thisSignal = signalMatrix{signalNum};\n\t\t\t% else\n\t\t\t%     thisSignal = signalMatrix(signalNum,:);\n\t\t\t%     % signalSigmas(signalNum) = std(thisSignal);\n\t\t\t%     % signalPeaksArray{signalNum} = computePeakForSignal(thisSignal,optionsOutCopy);\n\t\t\t% end\n\n\t\t\t%\n\t\t\tsignalSigmas(signalNum) = std(thisSignal);\n\t\t\tsignalPeaksArray{signalNum} = computePeakForSignal(thisSignal,optionsOutCopy);\n\n\t\t\t% [~] = viewComputePeaksPlot(thisSignal,signalPeaksArray{signalNum},[0 0 0],options.makePlots,50,2,'on')\n\t\t\t% ===\n\t\t\tif optionsCopy_addedAnalysis==1\n\t\t\t\t% using diff\n\t\t\t\tdetectOld = optionsOutCopy.detectMethod;\n\t\t\t\toptionsOutCopy.detectMethod = 'diff';\n\t\t\t\toptionsOutCopy.detectMethod = detectOld;\n\n\t\t\t\tsignalPeaksArrayTmp{signalNum} = computePeakForSignal(thisSignal,optionsOutCopy);\n\t\t\t\t% plot the resulting peaks overlayed\n\t\t\t\t[~] = viewComputePeaksPlot(thisSignal,signalPeaksArrayTmp{signalNum},[0 0 1],options.makePlots,20,0.1,'off',options)\n\t\t\t\tlegend('signal','raw','signal','diff')\n\t\t\t\ttitle(['raw: ' num2str(length(signalPeaksArray{signalNum})) ' | diff: ' num2str(length(signalPeaksArrayTmp{signalNum}))]);\n\t\t\t\t[~,~,~]=ginput(1);\n\t\t\t\t% fast oopsi\n\t\t\t\t[Nhat] = computePeakForSignalOopsi(thisSignal,signalPeaksArray{signalNum},options);\n\t\t\t\t[~,~,~]=ginput(1);\n\t\t\t\t% if options.convertSignalsToCell==1\n\t\t\t\t% else\n\t\t\t\t% end\n\t\t\t\t% ===\n\t\t\tend\n\t\t\t% create matrix of peaks\n\t\t\t% signalPeaks(signalNum,signalPeaksArray{signalNum})=1;\n\n\t\t\t% waitbar access\n\t\t\t% reverseStr = cmdWaitbar(signalNum,nSignals,reverseStr,'inputStr','detecting peaks','waitbarOn',options.waitbarOn,'displayEvery',50);\n\n\t\t\tif ~verLessThan('matlab', '9.2')\n\t\t\t\t% Update\n\t\t\t\tsend(D, signalNum);\n\t\t\tend\n\t\tend\n\t\t% tocBytes(gcp,startState)\n\t\tif options.makePlots==1\n\t\t\tfor signalNum=1:nSignals\n\t\t\t\tif options.convertSignalsToCell==1\n\t\t\t\t\t% thisSignal = signalMatrix{signalNum};\n\t\t\t\t\tthisSignal = signalMatrix(signalNum,:);\n\t\t\t\telse\n\t\t\t\t\tthisSignal = signalMatrix(signalNum,:);\n\t\t\t\tend\n\t\t\t\t\t[~] = viewComputePeaksPlot(thisSignal,signalPeaksArray{signalNum},[0 0 0],options.makePlots,50,2,'on',options,signalNum,nSignals,options.numStdsForThresh);\n\t\t\t\t\tpause\n\t\t\t\t\tkeyIn = get(gcf,'CurrentCharacter');\n\t\t\t\t\tif strcmp(keyIn,'e')\n\t\t\t\t\t\treturn\n\t\t\t\t\tend\n\t\t\t\t% pause\n\t\t\t\t% clf\n\t\t\tend\n\t\tend\n\t\tfor signalNum=1:nSignals\n\t\t\t% create matrix of peaks\n\t\t\tsignalPeaks(signalNum,signalPeaksArray{signalNum})=1;\n\t\tend\n\tcatch err\n\t\tsignalPeaks = [];\n\t\tsignalPeaksArray = {};\n\t\tdisp(repmat('@',1,7))\n\t\tdisp(getReport(err,'extended','hyperlinks','on'));\n\t\tdisp(repmat('@',1,7))\n\tend\n\t% summary of general statistics for this set of IC data\n\ttry\n\t\tif options.makeSummaryPlots==1\n\t\t\tviewSpikeSummary(signalMatrix,signalPeaks);\n\t\tend\n\tcatch err\n\t\tdisp(repmat('@',1,7))\n\t\tdisp(getReport(err,'extended','hyperlinks','on'));\n\t\tdisp(repmat('@',1,7))\n\tend\n\tfunction nUpdateParforProgress(~)\n\t\tif ~verLessThan('matlab', '9.2')\n\t\t\tp = p + 1;\n\t\t\tif (mod(p,nInterval)==0||p==2||p==nSignals)&&options_waitbarOn==1\n\t\t\t\tif p==nSignals\n\t\t\t\t\tfprintf('%d\\n',round(p/nSignals*100))\n\t\t\t\telse\n\t\t\t\t\tfprintf('%d|',round(p/nSignals*100))\n\t\t\t\tend\n\t\t\t\t% cmdWaitbar(p,nSignals,'','inputStr','','waitbarOn',1);\n\t\t\tend\n\t\t\t% [p mod(p,nInterval)==0 (mod(p,nInterval)==0||p==nSignals)&&options_waitbarOn==1]\n\t\tend\n\tend\nend\nfunction [inputSignal] = viewComputePeaksPlot(inputSignal,testpeaks,dotColor,makePlots,markersize,linewidth,holdVal,options,signalNum,nSignals,numStdsForThresh)\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\t% decide whether to plot the peaks with points indicating location of\n\t% chosen peaks\n\tif makePlots==1\n\t\t% setFigureDefaults()\n\t\tfig1 = figure(422); clf;\n\t\tsubplot(4,3,1)\n\t\t\t% hist(inputSignal(testpeaks),20);\n\t\t\thist((inputSignal(testpeaks) - nanmean(inputSignal(:)))/nanstd(inputSignal(:)),20);\n\t\t\thold(holdVal);\n\t\t\ttitle(num2str(nanstd(inputSignal(:))))\n\t\t\txlabel('Peak amplitude (Z-score)');ylabel('Peak count')\n\t\t\tset(gca,'XMinorTick','on','TickDir','out');box off;\n\t\t\t% plot(histBins,histCounts);\n\t\t\t% set(gca,'yscale','log');\n\n\t\tsubplot(4,3,2)\n\t\t\tpeakROI = [-20:20];\n\t\t\textractMatrix = bsxfun(@plus,testpeaks',peakROI);\n\t\t\textractMatrix(extractMatrix<=0)=1;\n\t\t\textractMatrix(extractMatrix>=size(inputSignal,2))=size(inputSignal,2);\n\t\t\tspikeCenterTrace = reshape(inputSignal(extractMatrix),size(extractMatrix));\n\t\t\tplot(repmat(peakROI, [size(spikeCenterTrace,1) 1])', spikeCenterTrace','Color',[4 4 4]/8)\n\t\t\tset(gca,'TickDir','out');box off;\n\t\t\txlabel('Time (frames)');ylabel('Signal amplitude')\n\t\t\ttitle('All peaks')\n\n\t\tsubplot(4,3,3)\n\t\t\tpeakSignalAmplitude = inputSignal(testpeaks(:));\n\t\t\t[peakSignalAmplitude, peakIdx] = sort(spikeCenterTrace(:,round(end/2)+1),'descend');\n\t\t\tspikeCenterTrace = spikeCenterTrace(peakIdx,:);\n\t\t\tif size(spikeCenterTrace,1)>20\n\t\t\t\tspikeCenterTrace = spikeCenterTrace(1:20,:);\n\t\t\tend\n\t\t\t% xlabel('Time (frames)')\n\t\t\tplot(repmat(peakROI, [size(spikeCenterTrace,1) 1])', spikeCenterTrace','Color',[4 4 4]/8)\n\t\t\txlabel('Time (frames)');ylabel('Signal amplitude')\n\t\t\ttitle('Top 20 peaks')\n\t\t\tset(gca,'TickDir','out');box off;\n\n\t\tsubplot(4,3,[4:12])\n\t\t\tset(gcf,'color','w');\n\t\t\t% scnsize = get(0,'ScreenSize');\n\t\t\t% position = get(fig1,'Position');\n\t\t\t% outerpos = get(fig1,'OuterPosition');\n\t\t\t% borders = outerpos - position;\n\t\t\t% edge = -borders(1)/2;\n\t\t\t% %pos1 = [scnsize(3)/2 + edge, 0, scnsize(3)/2 - edge, scnsize(4)];\n\t\t\t% pos1 = [0, 0, scnsize(3), scnsize(4)];\n\t\t\t% set(fig1,'OuterPosition',pos1);\n\n\t\t\tplot(inputSignal, 'r');\n\n\t\t\tinputSignalMedian=medfilt1(inputSignal,options.medianFilterLength,'omitnan','truncate');\n\t\t\tinputSignal = inputSignal - inputSignalMedian;\n\t\t\tinputSignal = filtfilt(ones(1,options.movAvgFiltSize)/options.movAvgFiltSize,1,inputSignal);\n\t\t\thold on;\n\t\t\tplot(inputSignal, 'b');\n\n\t\t\tset(gca,'Color','none'); box off;\n\t\t\tset(gca,'TickDir','out');box off;\n\t\t\thold on;\n\t\t\t% axis([0 length(inputSignal) -0.1 0.5]);\n\t\t\tscatter(testpeaks, inputSignal(testpeaks),markersize, 'LineWidth',linewidth,'MarkerFaceColor',dotColor, 'MarkerEdgeColor',dotColor)\n\t\t\tlegend({'Raw signal','Raw signal minus rolling median filter'},'Location','northoutside')\n\t\t\taxis tight;\n\t\t\txlabel('Time (frames)');ylabel('Signal amplitude')\n\t\t\t% options.numStdsForThresh = options.numStdsForThreshTwo;\n\t\t\t% signalPeaksArray{signalNum} = computePeakForSignal(thisSignal, 'options', options);\n\n\t\t\t% [x,y,reply]=ginput(1);\n\t\t\t% close(fig1);\n\t\t\thold(holdVal);\n\t\t\ttitle(sprintf('%d peaks | Zoom is enabled for closer look at peaks',length(testpeaks)))\n\t\tzoom on\n\t\tciapkg.overloaded.suptitle(sprintf('Right arrow key to move to next signal | press ''e'' to exit | threshold = %0.2f | signal %d/%d',numStdsForThresh,signalNum,nSignals))\n\tend\nend\nfunction [Nhat] = computePeakForSignalOopsi(inputSignal,testpeaks, options, varargin)\n\t% clear, clc,\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\tswitch options.oopsiSimulated\n\t\tcase 1\n\t\t\t% set simulation metadata\n\t\t\tT       = 1000; % # of time steps\n\t\t\tV.dt    = 1/8;  % time step size\n\n\t\t\t% initialize params\n\t\t\tP.a     = 1;    % observation scale\n\t\t\tP.b     = 0;    % observation bias\n\t\t\ttau     = 1.5;    % decay time constant\n\t\t\tP.gam   = 1-V.dt/tau; % C(t) = gam*C(t-1)\n\t\t\tP.lam   = 0.1;  % firing rate = lam*dt\n\t\t\tP.sig   = 0.1;  % standard deviation of observation noise\n\n\t\t\t% simulate data\n\t\t\tN = poissrnd(P.lam*V.dt*ones(T,1)); % simulate spike train\n\t\t\tN(100) = 10;\n\t\t\tP.sig   = std(N);  % standard deviation of observation noise\n\t\tcase 0\n\t\t\t% our data\n\t\t\t% inputSignal = inputSignal(1:1000);\n\t\t\t% testpeaks = testpeaks(testpeaks<1000);\n\t\t\tT = length(inputSignal);\n\t\t\tV.dt    = 1/5;  % time step size\n\t\t\tP.k = 30;\n\t\t\t%\n\t\t\tP.a     = 1;    % observation scale\n\t\t\tP.b     = 0;    % observation bias\n\t\t\ttau     = 1.5;    % decay time constant\n\t\t\tP.gam   = 1-V.dt/tau; % C(t) = gam*C(t-1)\n\t\t\tP.lam   = 0.01;  % firing rate = lam*dt\n\n\t\t\tinputSignalMetric = nanmean(inputSignal(testpeaks));\n\t\t\t% inputSignalMetric = nanmax(inputSignal(testpeaks));\n\t\t\tN = inputSignal(:)/inputSignalMetric;\n\t\t\t% inputSignal = normalizeVector(inputSignal,'normRange','zeroToOne');\n\t\t\t% N = inputSignal(:);\n\t\t\tP.sig = std(inputSignal(:)); % standard deviation of observation noise\n\t\t\tP.sig\n\t\t\tF = N;\n\t\t\t% N = zeros([length(inputSignal) 1]);\n\t\t\t% N(testpeaks) = 1;\n\t\t\t% normalizeVector(inputSignal(:),'normRange','zero')\n\n\t\totherwise\n\t\t\t% body\n\tend\n\tP.sig = 0.1; % standard deviation of observation noise\n\tC = filter(1,[1 -P.gam],N);         % calcium concentration\n\tF = P.a*C+P.b + P.sig*randn(T,1);   % observations\n\t% fast oopsi\n\t[Nhat Phat] = fast_oopsi(F,V,P);\n\n\t% smc-oopsi\n\tV.smc_iter_max = 1;\n\t% [M P V] = smc_oopsi(F,V,P);\n\n\t%% plot results\n\tfigure(1), clf\n\ttvec=0:V.dt:(T-1)*V.dt;\n\ttvec = 1:T;\n\th(1)=subplot(411); plot(tvec,F); axis('tight'), ylabel('F (au)')\n\th(2)=subplot(412); plot(tvec,C); axis('tight'), ylabel('C (au)')\n\tswitch options.oopsiSimulated\n\t\tcase 1\n\t\t\th(3)=subplot(4,1,[3 4]); stem(tvec,N,'.'); hold on, plot(tvec,Nhat,'r','linewidth',1), axis('tight'), ylabel('fast')\n\t\tcase 0\n\t\t\th(3)=subplot(4,1,3); stem(tvec,N,'.'); hold on, plot(tvec,Nhat,'r','linewidth',1), axis('tight'), ylabel('fast')\n\t\t\th(4)=subplot(414);plot(tvec,inputSignal, 'r'); box off; hold on;\n\t\t\tscatter(testpeaks, inputSignal(testpeaks),50, 'LineWidth',2,'MarkerFaceColor',[0 0 1], 'MarkerEdgeColor',[0 0 1]); axis('tight')\n\t\totherwise\n\tend\n\t% Nsmc = M.nbar/max(M.nbar);\n\t% Nsmc(Nsmc<0.1)=0;\n\t% h(4)=subplot(414); stem(tvec,N); hold on, plot(tvec,Nsmc,'k','linewidth',2); axis('tight'), ylabel('smc')\n\t% xlabel('time (sec)')\n\tlinkaxes(h,'x')\nend\nfunction [optionsOut] = computePeakForSignalOptions(varargin)\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\t%========================\n\t% number of standard deviations above the threshold to count as spike\n\toptions.numStdsForThresh = 3;\n\t% minimum number of time units between events\n\toptions.minTimeBtEvents = 10;\n\t% make a plot?\n\toptions.makePlots = 0;\n\t% the size of the moving average\n\toptions.movAvgReqSize = 2;\n\toptions.movAvgFiltSize = 3;\n\t% subtract median calculated over a filter of some range.\n\toptions.doMedianFilter = 1;\n\t% number of frames to calculate median filter\n\toptions.medianFilterLength = 201;\n\t% decide whether to have a moving average\n\toptions.doMovAvg = 1;\n\t% report the midpoint of the rise\n\toptions.reportMidpoint=0;\n\t% shift peak detection\n\toptions.nFramesShift = 0;\n\t% detect on differential ('diff') or raw ('raw') trace\n\toptions.detectMethod = 'raw';\n\t% region around each peak to look for a maximum to adjust the test peak by\n\toptions.peakMaxLook = [-6:6];\n\t% get options\n\toptionsOut = getOptions(options,varargin,'showWarnings',0);\nend\nfunction [testpeaks] = computePeakForSignal(inputSignal, options)\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\t% identifies peaks in an input signal given a particular threshold and other parameters.\n\t% biafra ahanonu\n\t% started: 2013.10.28\n\t% adapted from Lacey Kitch's and Laurie Burns' code\n\t% inputs\n\t\t%\n\t% outputs\n\t\t%\n\t% changelog\n\t\t% 2013.11.18 [20:06:00]\n\t% TODO\n\t\t%\n\n\t%========================\n\t% unpack options into current workspace\n\tfn=fieldnames(options);\n\tfor i=1:length(fn)\n\t\teval([fn{i} '=options.' fn{i} ';']);\n\tend;\n\t%========================\n\n\t% histBins = logspace(1,max(inputSignal));\n\t% [histCounts histBins] = hist(inputSignal(:),100);\n\t% plot(histBins,histCounts);\n\t% set(gca,'yscale','log');\n\n\t% median filter subtract\n\tif doMedianFilter==1\n\t\tinputSignalMedian=medfilt1(inputSignal,options.medianFilterLength,'omitnan','truncate');\n\t\tinputSignal = inputSignal - inputSignalMedian;\n\tend\n\t% moving average of input signal\n\tif doMovAvg==1\n\t\t% class(movAvgFiltSize)\n\t\t% movAvgFiltSize\n\t\t% class(inputSignal)\n\t\t% inputSignal(1:10)\n\t\tinputSignal = filtfilt(ones(1,movAvgFiltSize)/movAvgFiltSize,1,inputSignal);\n\tend\n\n\tswitch options.detectMethod\n\t\tcase 'diff'\n\t\t\trawInputSignalStd = std(inputSignal(:));\n\t\t\trawInputSignal = inputSignal;\n\t\t\t% get the differential\n\t\t\tinputSignal = [0 diff(inputSignal)];\n\t\t\tinputSignal(inputSignal<0) = 0;\n\t\t\t% options.nFramesShift = 0;\n\t\tcase 'raw'\n\t\t\t%\n\t\totherwise\n\t\t\t% body\n\tend\n\n\t% get standard deviation of current signal\n\t% inputSignalStd = std(inputSignal(:));\n\tinputSignalStd = nanstd(inputSignal(:));\n\tthisStdThreshold = inputSignalStd*numStdsForThresh;\n\n\t% =======\n\t% peakIdx = bsxfun(@plus,options.timeSeq',testpeaks);\n\t% tmpTestPeak = testpeaks;\n\t% % remove peaks outside range of signal\n\t% peakIdx(peakIdx>length(loopSignal))=[];\n\t% peakIdx(peakIdx<=0)=[];\n\n\t% % remove signal then add back in noise based on signal statistics\n\t% noiseSignal = loopSignal;\n\t% noiseSignal(peakIdx) = NaN;\n\t% =======\n\n\t% run findpeaks (part of signal), returns maxima above thisStdThreshold\n\t% and ignores smaller peaks around larger maxima within minTimeBtEvents\n\twarning off\n\t[~,testpeaks] = findpeaks(inputSignal,'minpeakheight',thisStdThreshold,'minpeakdistance',minTimeBtEvents);\n\twarning on\n\n\t% ignores smaller peaks around larger maxima within minTimeBtEvents\n\t%[~,testpeaks2] = findpeaks(inputSignal,'minpeakdistance',minTimeBtEvents);\n\t%testpeaks = intersect(testpeaks,testpeaks2);\n\t% extra check\n\ttestpeaks = intersect(testpeaks,...\n\t\tfind(filtfilt(ones(1,movAvgReqSize)/movAvgReqSize,1,inputSignal)>thisStdThreshold)...\n\t\t);\n\n\t% remove non-peaks within some set criteria\n\tswitch options.detectMethod\n\t\tcase 'diff'\n\t\t\t% get the differential\n\t\t\ttestpeaks = testpeaks(rawInputSignal(testpeaks)>(numStdsForThresh*rawInputSignalStd));\n\t\t\t% options.nFramesShift = 0;\n\n\t\t\t% switch back for later analysis\n\t\t\tinputSignal = rawInputSignal;\n\t\tcase 'raw'\n\t\t\t%\n\t\totherwise\n\t\t\t% body\n\tend\n\n\t% check that maximum is at peak, else shift it\n\tif ~isempty(testpeaks)&options.reportMidpoint==0\n\t\tpeakMaxLook = options.peakMaxLook;\n\t\tfor peakNo = 1:length(testpeaks)\n\t\t\t\ttestNewPeakIdx = testpeaks(peakNo)+peakMaxLook;\n\t\t\t\tif min(testNewPeakIdx)<=0|max(testNewPeakIdx)>length(inputSignal)\n\t\t\t\t\tcontinue;\n\t\t\t\tend\n\t\t\t\ttestSignal = inputSignal(testNewPeakIdx);\n\t\t\t\t[~,maxSignal] = max(testSignal);\n\t\t\t\t% [maxSignal testpeaks(peakNo) testpeaks(peakNo)+(maxSignal-round(length(testNewPeakIdx)/2))]\n\t\t\t\ttestpeaks(peakNo) = testpeaks(peakNo)+(maxSignal(1)-round(length(testNewPeakIdx)/2));\n\t\tend\n\telseif options.reportMidpoint==1\n\t\t% peakMaxLook = options.peakMaxLook;\n\t\t% for peakNo = 1:length(testpeaks)\n\t\t%         testNewPeakIdx = testpeaks(peakNo)+peakMaxLook;\n\t\t%         if min(testNewPeakIdx)<=0|max(testNewPeakIdx)>length(inputSignal)\n\t\t%             continue;\n\t\t%         end\n\t\t%         testSignal = inputSignal(testNewPeakIdx);\n\t\t%         [~,maxSignal] = max(testSignal);\n\t\t%         % [maxSignal testpeaks(peakNo) testpeaks(peakNo)+(maxSignal-round(length(testNewPeakIdx)/2))]\n\t\t%         testpeaks(peakNo) = testpeaks(peakNo)+(maxSignal(1)-round(length(testNewPeakIdx)/2));\n\t\t% end\n\tend\n\n\t% shift peaks\n\ttestpeaks = testpeaks + options.nFramesShift;\n\nend\n\nfunction [peakIdx] = subfxnCalcSignalNew(noiseSigmaThreshold,noiseSignal,loopSignal,tmpTestPeak)\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n\tnoiseStd = nanstd(noiseSignal(:));\n\t% noiseStd\n\tnPeaks = length(tmpTestPeak);\n\tpeakIdxTmp1 = cell([1 nPeaks]);\n\tpeakIdxTmp2 = cell([1 nPeaks]);\n\t% noiseSigmaThreshold = options.noiseSigmaThreshold;\n\tloopSignalThresholded = loopSignal>noiseSigmaThreshold*noiseStd;\n\tloopSignalThresholdedDiff = [0 diff(loopSignalThresholded)];\n\tfor peakNo = 1:nPeaks\n\t\ttry\n\t\t\tpeakFrame = tmpTestPeak(peakNo);\n\n\t\t\t% currFrame = peakFrame;\n\t\t\tsignalCriteria = loopSignalThresholdedDiff(1:peakFrame);\n\t\t\tcurrFrame = find(signalCriteria,1,'last');\n\t\t\tif isempty(currFrame)\n\t\t\t\tif sum(loopSignalThresholded(1:peakFrame))==length(loopSignalThresholded(1:peakFrame))\n\t\t\t\t\tcurrFrame = 1;\n\t\t\t\tend\n\t\t\tend\n\t\t\t% currFrame\n\t\t\t% aboveNoise = 1;\n\t\t\t% while aboveNoise==1\n\t\t\t%   aboveNoise = loopSignal(currFrame)>options.noiseSigmaThreshold*noiseStd;\n\t\t\t%   currFrame = currFrame - 1;\n\t\t\t%   if currFrame<1\n\t\t\t%       break\n\t\t\t%   end\n\t\t\t% end\n\t\t\tpeakIdxTmp1{peakNo} = currFrame:peakFrame;\n\n\t\t\t% currFrame = peakFrame;\n\t\t\t% loopSignalThresholded = loopSignal>noiseSigmaThreshold*noiseStd;\n\t\t\tsignalCriteria = abs(loopSignalThresholdedDiff(peakFrame:end));\n\t\t\tcurrFrame = find(signalCriteria,1,'first')+peakFrame;\n\t\t\tif isempty(currFrame)\n\t\t\t\tif sum(loopSignalThresholded(peakFrame:end))==length(loopSignalThresholded(peakFrame:end))\n\t\t\t\t\tcurrFrame = length(loopSignal);\n\t\t\t\tend\n\t\t\tend\n\t\t\t% currFrame\n\t\t\t% aboveNoise = 1;\n\t\t\t% currFrame = peakFrame;\n\t\t\t% while aboveNoise==1\n\t\t\t%   aboveNoise = loopSignal(currFrame)>options.noiseSigmaThreshold*noiseStd;\n\t\t\t%   currFrame = currFrame + 1;\n\t\t\t%   if currFrame>length(loopSignal)\n\t\t\t%       break\n\t\t\t%   end\n\t\t\t% end\n\t\t\tpeakIdxTmp2{peakNo} = peakFrame:currFrame;\n\t\tcatch err\n\t\t\tfprintf('peakFrame = %d\\n',peakFrame);\n\t\t\tdisplay(repmat('@',1,7))\n\t\t\tdisp(getReport(err,'extended','hyperlinks','on'));\n\t\t\tdisplay(repmat('@',1,7))\n\t\tend\n\tend\n\tpeakIdx = [peakIdxTmp1{:} peakIdxTmp2{:}];\n\tpeakIdx = unique(peakIdx(:));\nend", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/+ciapkg/+signal_processing/computeSignalPeaks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24589668826323888}}
{"text": "function b = reduceboxes(model, bs)\n% Eliminate columns for filters that are not used.\n%   b = reduceboxes(model, bs)\n%\n%   E.g., [0 0 0 0 10 20 110 120] -> [10 20 110 120]\n%   Index end-1 is the component label and index end is the \n%   detection score.\n%\n%   This function assumes that model is a mixture model where\n%   each component always places exactly the same number of filters.\n%\n% Return value\n%   b       Filter bounding boxes with unused filter columns removed\n% Arguments\n%   model   Object model\n%   bs      Filter bounding boxes\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% Only reduce boxes for mixtures of star models\nif model.type ~= model_types.MixStar\n  b = bs;\n  return;\nend\n\n% n = #filters per component (assuming all components have\n% the same number of parts)\nn = length(model.rules{model.start}(1).rhs);\n% n*4+2 := 4 coordinates per boxes plus the component index \n% and score\nb = zeros(size(bs, 1), n*4+2);\nmaxc = max(bs(:,end-1));\nfor i = 1:maxc\n  % process boxes for component i\n  I = find(bs(:,end-1) == i);\n  tmp = bs(I,:);\n  del = [];\n  % find unused filters\n  for j = 1:4:size(bs, 2)-2\n    % count # of non-zero coordinates\n    s = sum(sum(tmp(:,j:j+3)~=0));\n    % the filter was not used if all coordinates are zero\n    if s == 0\n      del = [del j:j+3];\n    end\n  end\n  % remove all unused filters\n  tmp(:,del) = [];\n  b(I,:) = tmp;\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/utils/reduceboxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24589668826323885}}
{"text": "%% Copyright 2013 The MathWorks, Inc.\n% Read input image\nI = imread('visionteam.jpg');\nfigure,imshow(I);\n\n%% Detect upright people\npeopleDetector = vision.PeopleDetector;\n[bboxes, scores] = step(peopleDetector,I);\nI_people = insertObjectAnnotation(I,'rectangle',bboxes,scores);\nfigure, imshow(I_people);\n\n%% Try the other model\npeopleDetector = vision.PeopleDetector('ClassificationModel','UprightPeople_128x64');\npeopleDetector.WindowStride = [4 4];\npeopleDetector.MinSize = [256 128];\n[bboxes, scores] = step(peopleDetector,I);\nI_people = insertObjectAnnotation(I,'rectangle',bboxes,scores);\nfigure, imshow(I_people);\n\n%% Use PeopleDetector with video\npeopleDetector = vision.PeopleDetector;\nvideo = vision.VideoFileReader('viptrain.avi');\nviewer = vision.VideoPlayer;\nwhile ~isDone(video)\n    image = step(video);\n    [bboxes, scores] = step(peopleDetector,image);\n    I_people = insertObjectAnnotation(image,'rectangle',bboxes,scores);\n    step(viewer,I_people);\nend\n\n%% Detect Faces in the image\n% Create a detector object\nfaceDetector = vision.CascadeObjectDetector('FrontalFaceCART');   \n\n% Detect faces\nbbox = step(faceDetector, I); \n\n% Draw boxes around detected faces and display results              \nshapeInserter = vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[255 255 0]);\nI_faces = step(shapeInserter, I, int32(bbox));\nimshow(I_faces);\n\n%% Use new object annotation function              \nI_faces = insertObjectAnnotation(I,'rectangle',bbox,[1:size(bbox,1)]);\nimshow(I_faces);\n\n%% Detect Upper Bodies in the image\n% Create a detector object \nbodyDetector = vision.CascadeObjectDetector('UpperBody'); \nbodyDetector.MinSize = [60 60];\nbodyDetector.ScaleFactor = 1.05;\n\nbbox_body = step(bodyDetector, I);\n\n% Draw bounding boxes\nI_body = insertObjectAnnotation(I,'rectangle',bbox_body,1:size(bbox_body,1));\nfigure, imshow(I_body);\n\n%% Remove false detections by looking for face\nbbox_face = zeros(size(bbox_body));\nfor i=1:length(bbox_body)\n    Icrop = imcrop(I,bbox_body(i,:));\n    bbox = step(faceDetector,Icrop);\n    if ~isempty(bbox)\n        bbox_face(i,:) = bbox + [bbox_body(i,1:2)-1 0 0];\n    end\nend\n    \nI_faces2 = insertObjectAnnotation(I,'rectangle',bbox_face,1:size(bbox_face,1));\nfigure, imshow(I_faces2);\n\n%% Extract one face to use\nIcrop = imcrop(I,bbox_body(1,:));\nfigure;imshow(Icrop);\nbbox = step(faceDetector,Icrop);\nhold on;rectangle('Position',bbox,'EdgeColor','y');\n\n%% See how much we can rotate the image with the face still being detected\nx = 10;\nIrotate = imrotate(Icrop,x);\nimshow(Irotate);\nbbox = step(faceDetector, Irotate);\nif bbox > 0\n    hold on;rectangle('Position',bbox,'EdgeColor','y'); hold off;\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40079-january-2013-computer-vision-with-matlab-webinar-demo-files/demos/FacePeopleDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2457339595167568}}
{"text": "%% ASCII Art\n%  The ASCII art is an interesting art of representing images using\n% characters. In the past a great number of powerful libs and tools are\n% develped, the most famous is aalib that allow to paint in real time a\n% stream of images (a video) containing only ASCII characters (on a TTY).\n% So for example the using the mplayer under Linux it is possible to see a\n% DVD film completely in ASCII art, or to play Quake with it's aalib version\n% (tty-quake). Here a simple ASCII art converter function is given using\n% multiple palettes depending on the gradient of the image, something\n% different with respecto to the other AA tools.\n\n%% Reading an image\n%  Reading and preparing an image for the conversion: an image must be\n% gayscale to be used with gabAscii.\n\n% Getting a standard image:\nimg = imread('peppers.png');\n\n% Converting to grayscale:\nimg = rgb2gray(img);\n\n%% Generating the ASCII-Art version of the image\n%  Here the ASCII-Art version of the image is generated using the default\n% parameters, in this tool the size of the axels and the palettes can be\n% defined as parameters.\n\n% Generation of the output:\nasciiImg = gabAscii(img),\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11307-ascii-art-variation/ASCIIArt/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24573395951675675}}
{"text": "% Copyright 2018 Marc Ren\u00e9 Sch\u00e4dler\n%\n% This file is part of the mobile hearing aid prototype project\n% The the mobile hearing aid prototype project 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.\n%\n% The mobile hearing aid prototype project 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.\n%\n% You should have received a copy of the GNU General Public License along with the mobile hearing aid prototype project. If not, see http://www.gnu.org/licenses/.\n\nfunction thresholds = measure_thresholds(freqs, ear)\n  thresholds = nan(size(freqs));\n  for i=1:length(freqs)\n    threshold = measure_sweep(freqs(i), ear);\n    if ~isempty(threshold)\n      thresholds(i) = threshold;\n    end\n  end\nend\n\n", "meta": {"author": "m-r-s", "repo": "hearingaid-prototype", "sha": "973b4c8e793a0ac78e8d1e7bd40e518876fc3c83", "save_path": "github-repos/MATLAB/m-r-s-hearingaid-prototype", "path": "github-repos/MATLAB/m-r-s-hearingaid-prototype/hearingaid-prototype-973b4c8e793a0ac78e8d1e7bd40e518876fc3c83/tools/measure_thresholds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24570009848275978}}
{"text": "function computeAllModelChoice_batchVASARI_LGG(pathExperiments,maxOrder,nBoot,imbalance,nBatch,matlabPATH,seed)\n% -------------------------------------------------------------------------\n% function computeAllModelChoice_batchVASARI_LGG(pathExperiments,maxOrder,nBoot,imbalance,nBatch,matlabPATH,seed)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes feature set selection for all feature set types \n% and for all experiments with different degrees of freedom. See ref. [1]\n% for more details.\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathExperiments: Full path to where all experiments need to be\n%                     performed.\n%                     --> Ex: /myProject/WORKSPACE/VASARI\n% 2. maxOrder: Integer specifying the maximal model order to construct.\n%              --> Ex: 10\n% 3. nBoot: Number of bootstrap samples to use.\n%           --> Ex: 100\n% 4. imbalance: String specifying the type of imbalance-adjustement strategy\n%               employed. Either 'IABR' for imbalance-adjusted bootstrap\n%               resampling (see ref.[1]), or 'IALR' for imbalance-adjusted\n%               logistic regression (formal reference to come).\n%               --> Ex: 'IALR'\n% 5. nBatch: Number of parallel batch.\n%            --> Ex: 8\n% 6. matlabPATH: Full path to the MATLAB executable on the system.\n%                --> 'matlab' if a symbolic link to the matlab executable\n%                     was previously created.\n% 7. seed: Numerical number to use as seed for bootstrapping experiment\n%          --> Ex: 54288\n% -------------------------------------------------------------------------\n% OUTPUTS: Mutivariable models are saved in a folder named 'MODELS' in the\n% corresponding folder of 'pathExperiments'.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\n\n% INITIALIZATON\ntime = 60; % Number of seconds to wait before checking if parallel computations are done\ncd(pathExperiments), load('outcomes')\npathSet = fullfile(pwd,'FSET'); mkdir('MODELS'), cd('MODELS'), pathModels = pwd; \nmkdir('batchLog_Models'), cd('batchLog_Models'), pathBatch = pwd;\nsetNames = {'VASARI'};\n[param] = batchExperiments(setNames,outcomes,nBatch); nBatch = length(param);\n\n% PRODUCE BATCH COMPUTATIONS\nsave('workspace','pathSet','pathModels','outcomes','param','maxOrder','nBoot','imbalance','seed'), pause(5);\nfor i = 1:nBatch\n    nameScript = ['batch',num2str(i),'_script.m'];\n    fid = fopen(nameScript,'w');\n    fprintf(fid,'load(''workspace'')\\n');\n    for j = 1:numel(param{i})\n        fprintf(fid,['computeAllModelChoice_VASARI_LGG(pathSet,pathModels,outcomes,param{',num2str(i),'}{',num2str(j),'},maxOrder,nBoot,imbalance,seed)\\n']);\n    end\n    fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n    fprintf(fid,'clear all');\n    fclose(fid);\n    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nBatch)\ndelete('workspace.mat')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/computeAllModelChoice_batchVASARI_LGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24570009848275975}}
{"text": "function y = gpReversibleDynamicsSamp(model, X);\n\n% GPREVERSIBLEDYNAMICSSAMP Sample from the dynamics for a given input.\n\n% FGPLVM\n\npersistent oldX\nif isempty(oldX)\n  Xp = [X zeros(size(X))];\nelse\n  Xp = [X X-oldX];\nend\noldX = X;\n[mu, var] = gpPosteriorMeanVar(model, Xp);\ny = gsamp(mu, diag(var), 1);\ny = X + y;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/gpReversibleDynamicsSamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2456515695104609}}
{"text": "clear all;\nclose all;\nclc;\nspx.cluster.ssc.util.simulate_subspace_preservation(@ssc_omp, 'ssc_omp');\nspx.cluster.ssc.util.print_subspace_preservation_results('ssc_omp');\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/ssc_subspace_preservation_test/ex_ssc_omp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564155301056112}}
{"text": "function [niiC, scanFileNameC] = scan2nii(planC,scanNumV,tmpDirPath,reorientFlag)\n\nif ~exist('tmpDirPath','var') || isempty(tmpDirPath) || ~exist(tmpDirPath,'dir')\n    tmpDirPath = fullfile(getCERRPath, 'ImageRegistration', 'tmpFiles');\nend\n\nif ~exist('reorientFlag','var') || isempty(reorientFlag)\n    reorientFlag = 1;\nend\n\nfor i = 1:numel(scanNumV)\n    scanNum = scanNumV(i);\n    [scanUniqName, ~] = genScanUniqName(planC,scanNum);\n    [affineMat,scan3M_RAS,voxel_size] = getPlanCAffineMat(planC, scanNum, 1);\n    qOffset = affineMat(1:3,end)';\n    scanFileName = fullfile(tmpDirPath, ['scan_' num2str(scanNumV(i)) '_' scanUniqName '.nii']);\n    niiC{i} = vol2nii(scan3M_RAS,affineMat,qOffset,voxel_size,scanFileName);\n    scanFileNameC{i} = scanFileName;\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Extras/scan2nii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564154665647464}}
{"text": "function gradx = singletrack_gradx_f(in1,in2,in3)\n%SINGLETRACK_GRADX_F\n%    GRADX = SINGLETRACK_GRADX_F(IN1,IN2,IN3)\n\n%    This function was generated by the Symbolic Math Toolbox version 8.3.\n%    09-Jan-2020 11:52:33\n\nI_z = in3(2,:);\nM = in3(1,:);\nT = in2(2,:);\nV_vx = in1(4,:);\nV_vy = in1(5,:);\nc_f = in3(8,:);\nc_r = in3(9,:);\ndelta = in2(1,:);\ndeltamax = in3(5,:);\nl_f = in3(3,:);\nl_r = in3(4,:);\nmaxbrakeWForce = in3(6,:);\npsi_dot = in1(6,:);\nvpsi = in1(3,:);\nt2 = cos(vpsi);\nt3 = sin(vpsi);\nt4 = l_f.*psi_dot;\nt5 = l_r.*psi_dot;\nt6 = V_vx.^2;\nt7 = 1.0./I_z;\nt8 = 1.0./M;\nt9 = T.*5.0e+1;\nt10 = delta.*5.0e+1;\nt11 = deltamax.*5.0e+1;\nt14 = V_vx.*1.0e+2;\nt12 = -t5;\nt13 = -t9;\nt15 = -t10;\nt16 = -t11;\nt17 = V_vy+t4;\nt18 = tanh(t14);\nt19 = t17.^2;\nt20 = V_vy+t12;\nt21 = t13+5.0e+1;\nt22 = t18.^2;\nt23 = t13-5.0e+1;\nt27 = t11+t15;\nt31 = t15+t16;\nt24 = t20.^2;\nt25 = exp(t21);\nt26 = exp(t23);\nt28 = exp(t27);\nt29 = t6+t19;\nt32 = exp(t31);\nt34 = t22.*1.0e+2;\nt30 = t25+1.0;\nt33 = t26+1.0;\nt35 = t6+t24;\nt36 = t28+1.0;\nt38 = t32+1.0;\nt39 = 1.0./t29;\nt44 = t34-1.0e+2;\nt37 = 1.0./t30;\nt40 = 1.0./t33;\nt41 = 1.0./t36;\nt42 = 1.0./t35;\nt43 = 1.0./t38;\nt45 = t37.*5.0e+1;\nt46 = t37-1.0;\nt47 = t40.*5.0e+1;\nt49 = deltamax.*t41;\nt50 = t41-1.0;\nt52 = V_vx.*c_r.*l_r.*t42;\nt53 = t43-1.0;\nt48 = -t45;\nt51 = -t47;\nt54 = deltamax.*t53;\nt55 = T.*t40.*t46;\nt57 = t9.*t40.*t46;\nt58 = delta.*t43.*t50;\nt56 = -t55;\nt59 = -t58;\nt61 = t48+t51+t57+5.0e+1;\nt60 = t40+t46+t56;\nt62 = exp(t61);\nt64 = t49+t54+t59;\nt63 = t62+1.0;\nt65 = sin(t64);\nt67 = cos(t64);\nt66 = 1.0./t63;\nt69 = V_vx.*c_f.*l_f.*t39.*t67;\nt68 = t66-1.0;\ngradx = reshape([0.0,0.0,-V_vx.*t3-V_vy.*t2,t2,-t3,0.0,0.0,0.0,0.0,V_vx.*t2-V_vy.*t3,t3,t2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,t8.*(-c_f.*t17.*t39.*t65+(maxbrakeWForce.*t44.*t60.*t68)./2.0+(maxbrakeWForce.*t44.*t60.*t67.*t68)./2.0),t8.*(psi_dot+V_vx.*c_f.*t39.*t65),t8.*(V_vy+V_vx.*c_f.*l_f.*t39.*t65),0.0,0.0,0.0,0.0,t8.*(c_r.*t20.*t42+c_f.*t17.*t39.*t67+(maxbrakeWForce.*t44.*t60.*t65.*t68)./2.0),-t8.*(psi_dot+V_vx.*c_r.*t42+V_vx.*c_f.*t39.*t67),-t8.*(V_vy-t52+t69),0.0,0.0,0.0,0.0,t7.*(-c_r.*l_r.*t20.*t42+c_f.*l_f.*t17.*t39.*t67+(l_f.*maxbrakeWForce.*t44.*t60.*t65.*t68)./2.0),t7.*(t52-t69),-t7.*(l_f.*t69+l_r.*t52),0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[7,7]);\n", "meta": {"author": "lucasrm25", "repo": "Gaussian-Process-based-Model-Predictive-Control", "sha": "ef00c0df1ff25fb75f6f9c3d9099d47c9cfe1078", "save_path": "github-repos/MATLAB/lucasrm25-Gaussian-Process-based-Model-Predictive-Control", "path": "github-repos/MATLAB/lucasrm25-Gaussian-Process-based-Model-Predictive-Control/Gaussian-Process-based-Model-Predictive-Control-ef00c0df1ff25fb75f6f9c3d9099d47c9cfe1078/CODEGEN/singletrack_gradx_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24560325615837814}}
{"text": "% this code is revised based on ILSVRC 2013 (http://www.image-net.org/challenges/LSVRC/2013/)\n\nfunction  zeroShot = zeroShot_top_recall_Phrase(Nre, tuple_confs_cell, tuple_labels_cell, sub_bboxes_cell, obj_bboxes_cell)\n\nload('gt.mat','gt_tuple_label','gt_obj_bboxes','gt_sub_bboxes');\nload('zeroShot.mat','zeroShot');\n\nfor ii = 1 : 1000 \n    det = find(zeroShot{ii} == 0);\n    gt_tuple_label{ii}(det,:) = [];\n    gt_obj_bboxes{ii}(det,:) = [];\n    gt_sub_bboxes{ii}(det,:) = [];\nend\n\n \n%num_imgs = length(gt_tuple_label);\nnum_imgs = 1000;\nfor i=1:num_imgs\n    [tuple_confs_cell{i}, ind] = sort(tuple_confs_cell{i},'descend');\n    if length(ind) >= Nre\n        tuple_confs_cell{i} = tuple_confs_cell{i}(1:Nre);\n        tuple_labels_cell{i} = tuple_labels_cell{i}(ind(1:Nre),:);\n        obj_bboxes_cell{i} = obj_bboxes_cell{i}(ind(1:Nre),:);\n        sub_bboxes_cell{i} = sub_bboxes_cell{i}(ind(1:Nre),:);\n    else\n        tuple_labels_cell{i} = tuple_labels_cell{i}(ind,:);\n        obj_bboxes_cell{i} = obj_bboxes_cell{i}(ind,:);\n        sub_bboxes_cell{i} = sub_bboxes_cell{i}(ind,:);\n    end\nend\n\nnum_pos_tuple = 0;\nfor ii = 1 : num_imgs\n    num_pos_tuple = num_pos_tuple + size(gt_tuple_label{ii},1);\nend\n \n\ntp_cell = cell(1,num_imgs);\nfp_cell = cell(1,num_imgs);\n\ngt_thr = 0.5;\n% iterate over images\nfor i=1:num_imgs \n \n    gt_tupLabel = gt_tuple_label{i};\n    if ~isempty(gt_obj_bboxes{i})\n        gt_box_entity = [min(gt_obj_bboxes{i}(:,1:2),gt_sub_bboxes{i}(:,1:2)),max(gt_obj_bboxes{i}(:,3:4),gt_sub_bboxes{i}(:,3:4))];\n    else\n        gt_box_entity = [];\n    end\n    \n     \n    num_gt_tuple = size(gt_tupLabel,1);\n    gt_detected = zeros(1,num_gt_tuple);\n   \n    labels = tuple_labels_cell{i};\n    boxObj = obj_bboxes_cell{i};\n    boxSub = sub_bboxes_cell{i};\n    if ~isempty(boxObj)\n        box_entity_our  = [min(boxObj(:,1:2), boxSub(:,1:2)), max(boxObj(:,3:4), boxSub(:,3:4))];\n    else\n        box_entity_our  = [];\n    end\n    \n    num_obj = size(labels,1);\n    tp = zeros(1,num_obj);\n    fp = zeros(1,num_obj);\n    for j=1:num_obj\n\n        bbO = box_entity_our(j,:); \n        ovmax = -inf;\n        kmax = -1;\n        \n        for k=1:num_gt_tuple\n            if norm(labels(j,:) - gt_tupLabel(k,:),2) ~= 0\n                continue;\n            end\n            if gt_detected(k) > 0\n                continue;\n            end\n            \n            bbgtO = gt_box_entity(k,:); \n            \n            biO=[max(bbO(1),bbgtO(1)) ; max(bbO(2),bbgtO(2)) ; min(bbO(3),bbgtO(3)) ; min(bbO(4),bbgtO(4))];\n            iwO=biO(3)-biO(1)+1;\n            ihO=biO(4)-biO(2)+1;\n        \n     \n            if iwO>0 & ihO>0            \n                % compute overlap as area of intersection / area of union\n                uaO=(bbO(3)-bbO(1)+1)*(bbO(4)-bbO(2)+1)+...\n                   (bbgtO(3)-bbgtO(1)+1)*(bbgtO(4)-bbgtO(2)+1)-...\n                   iwO*ihO;\n                ov =iwO*ihO/uaO;\n    \n                \n                % makes sure that this object is detected according\n                % to its individual threshold\n                if ov >= gt_thr && ov > ovmax\n                    ovmax=ov;\n                    kmax=k;\n                end\n            end\n        end\n        \n        if kmax > 0\n            tp(j) = 1;\n            gt_detected(kmax) = 1;\n        else\n            fp(j) = 1;\n        end\n    end\n\n    % put back into global vector\n    tp_cell{i} = tp;\n    fp_cell{i} = fp;\n\n\nend\n\nt = tic;\ntp_all = [];\nfp_all = [];\nconfs = [];\nfor ii = 1 : num_imgs\ntp_all = [tp_all; tp_cell{ii}(:) ];\nfp_all = [fp_all; fp_cell{ii}(:) ];\nconfs = [confs; tuple_confs_cell{ii}(:)];\nend\n\n[confs, ind] = sort(confs,'descend');\ntp_all = tp_all(ind);\nfp_all = fp_all(ind); \n\n \ntp = cumsum(tp_all );\nfp = cumsum(fp_all );\nrecall =(tp/num_pos_tuple);\nzeroShot = recall(end);\n\nend", "meta": {"author": "Prof-Lu-Cewu", "repo": "Visual-Relationship-Detection", "sha": "3f4f51b038aca12db86851a5040d43c65db28e95", "save_path": "github-repos/MATLAB/Prof-Lu-Cewu-Visual-Relationship-Detection", "path": "github-repos/MATLAB/Prof-Lu-Cewu-Visual-Relationship-Detection/Visual-Relationship-Detection-3f4f51b038aca12db86851a5040d43c65db28e95/evaluation/zeroShot_top_recall_Phrase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.2456032500290346}}
{"text": "function out=declus_wintec(mCatalog, eMethod)\n    % DECLUS_WINTEC execute declustering by windowing technique\n    %\n    % DECLUS_WINTEC(catalog, nMethod)\n    %\n    % Incoming variables:\n    % mCatalog : EQ catalog in ZMAP format\n    % eMethod  : a choice from DeclusterWindowingMethods\n    %\n    %\n    % out : struct of declustered details [output from CALC_DECLUSTER]\n    % J. Woessner, woessner@seismo.ifg.ethz.ch\n    % updated: 14.08.02\n    %\n    % see DECLUS_INP, CALC_DECLUSTER\n    \n    \n    report_this_filefun();\n    \n    %%% Decluster catalog using window technique\n    out = struct;\n    % [out.mCatDecluster, out.mCatAfter, out.vCluster, out.vCl, out.vMain] = calc_decluster(mCatalog,eMethod);\n    [out.declusteredCatalog, out.aftershockCatalog, out.aftershockClusterIdx, out.allClusterIdx, out.mainshockClusterIdx] = calc_decluster(mCatalog,eMethod);\n    %vSel = (out.vMain(:,1) > 0); % Selects mainshocks of clusters\n    %mCluster = mCatalog.subset(vSel);\n    out.description = [\"Decluster results have been written to gk_decluster_output with the following fields\";...\n    \t\"  declusteredCatalog: Declustered earthquake catalog (with mainshocks, no fore/aftershocks)\";...\n        \"  aftershockCatalog: Catalog of aftershocks (and foreshocks)\";...\n        \"  aftershockClusterIdx : Vector indicating only aftershocks/foreshocks in cluster using a cluster number (background seismicity == 0)\";...\n        \"  allClusterIdx: Vector indicating all events in clusters using a cluster number (background seismicity == 0)\";...\n        \"  mainshockClusterIdx: index into original catalog, indicating mainshocks, where any non-zero value is the cluster number\"];\n    \n    %%% Plot comparison to window length\n    %[vMags, vClusTime, vDist]= plot_cluscomp(vMain, vCluster, mCatalog, eMethod);\n    % plot_cluscomp(out.mainshockClusterIdx, out.aftershockClusterIdx, mCatalog, eMethod); % output arguments weren't being used\n    return % CGR - Sep 1 2020\n    \n    %%% Plot seismicity map, clusters and mainshocks\n    replaceMainCatalog(out.mCatDecluster);\n    zmap_update_displays();\n    plot(mCluster.Longitude, mCluster.Latitude,'m+');\n    \n    describe_clusters(mCatalog, out)\n    plot_mag_histogram(catalog, mCatAfter)\n    \nend\n\nfunction describe_clusters(mCatalog, out)\n    %%% Calculate moment release [local variables], only used for description\n    [fMomentCluster, vMomentCluster] = calc_moment(out.mCatAfter);\n    \n    [fMomentorg, vMomentorg] = calc_moment(out.mCatalog);\n    \n    fMomentpercentage = 100*fMomentCluster/fMomentorg;\n    \n    fEventpercentage = 100*out.mCatAfter.Count/mCatalog.Count; % Percentage of events in clusters\n    \n    %% Setup message box\n    sInfost1 = sprintf(...\n        [' The declustering found %d clusters of earthquakes, a total of %d (%g\\%) events out of %d. ',...\n        ' The map window now displays the declustered catalog containing %d events as blue dots.', ....\n        ' The individual clusters are displayed as magenta pluses. The seismic moment released by the clusters'...\n        ' is %g Nm which is about %g\\% of the total seismic moment (%g Nm) of the catalog.'],...\n        max(out.vMain) , out.mCatAfter.Count, fEventpercentage, mCatalog.Count,...\n        out.mCatDecluster.Count,...\n        fMomentCluster, fMomentpercentage, fMomentorg);\n    \n    msgbox(sInfost1,'Declustering Information')\nend\n\n\nfunction plot_mag_histogram(origCatalog, declusteredCatalog)\n    %%% Plotting magnitude histogram\n    if exist('hd1_declus_wintec','var') && ishandle(hd1_declus_wintec)\n        set(0,'Currentfigure',hd1_declus_wintec);\n        disp('Figure exists');\n    else\n        hd1_win_fig=figure('tag','fig_declus_wintec','Name','Histogram',...\n            'Units','normalized','Nextplot','add',...\n            'Numbertitle','off','Position',[0.4 0.2 .4 .6],'Menubar','none');\n    end\n    \n    set(gca,'tag','ax_declus_wintec_mag','Nextplot','replace','box','on','Xticklabel', [0 10 100]);\n    axs1=findobj('tag','ax_declus_wintec_mag');\n    axes(axs1(1));\n    maxMagLimit=max(origCatalog.Magnitude);\n    magEdges = 0:0.1:maxMagLimit;\n    histogram(declusteredCatalog.Magnitude, magEdges);\n    xlabel('Magnitude (events of all clusters)');\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/declus_wintec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24560325002903458}}
{"text": "function vot_wrapper(tracker_name, runfile_name, do_cleanup)\n\nif nargin < 3\n    do_cleanup = true;\nend\n\n% *************************************************************\n% VOT: Always call exit command at the end to terminate Matlab!\n% *************************************************************\nif do_cleanup\n    cleanup = onCleanup(@() exit() );\nelse\n    [pathstr, ~, ~] = fileparts(mfilename('fullpath'));\n    cd_ind = strfind(pathstr, filesep());\n    pathstr = pathstr(1:cd_ind(end)-1);\n    cleanup = onCleanup(@() cd(pathstr));\nend\n\ntry\n\n% *************************************************************\n% VOT: Set random seed to a different value every time.\n% *************************************************************\nRandStream.setGlobalStream(RandStream('mt19937ar', 'Seed', sum(clock)));\n\n% **********************************\n% VOT: Get initialization data\n% **********************************\n[images, region] = vot_initialize();\n\nresults = cell(length(images), 1);\n\nbb_scale = 1;\n\n% If the provided region is a polygon ...\nif numel(region) > 4\n    % Init with an axis aligned bounding box with correct area and center\n    % coordinate\n    cx = mean(region(1:2:end));\n    cy = mean(region(2:2:end));\n    x1 = min(region(1:2:end));\n    x2 = max(region(1:2:end));\n    y1 = min(region(2:2:end));\n    y2 = max(region(2:2:end));\n    A1 = norm(region(1:2) - region(3:4)) * norm(region(3:4) - region(5:6));\n    A2 = (x2 - x1) * (y2 - y1);\n    s = sqrt(A1/A2);\n    w = s * (x2 - x1) + 1;\n    h = s * (y2 - y1) + 1;\nelse\n    cx = region(1) + (region(3) - 1)/2;\n    cy = region(2) + (region(4) - 1)/2;\n    w = region(3);\n    h = region(4);\nend\n\ninit_c = [cx cy];\ninit_sz = bb_scale * [w h];\n\nim_size = size(imread(images{1}));\nim_size = im_size([2 1]);\n\ninit_pos = min(max(round(init_c - (init_sz - 1)/2), [1 1]), im_size);\ninit_sz = min(max(round(init_sz), [1 1]), im_size - init_pos + 1);\n\nseq.s_frames = images;\nseq.init_rect = [init_pos, init_sz];\n\n[file_path, file_name_start, file_ext] = fileparts(seq.s_frames{1});\n[~, file_name_end, ~] = fileparts(seq.s_frames{end});\nseq.path = file_path;\nseq.name = 'vot_seq';\nseq.ext = file_ext(2:end);\nseq.len = length(seq.s_frames);\nseq.nz = length(file_name_start);\nseq.startFrame = str2num(file_name_start);\nseq.endFrame = str2num(file_name_end);\n\n% setup_tracker_paths(tracker_name);\n\notb_res = eval([runfile_name '(seq, [], []);']);\n%convert the results to rectangle format\n% otb_res = convert_to_rect(otb_res);\n\n\nnum_frames = numel(images);\n\nfor frame = 1:num_frames\n    bb = otb_res.res(frame,:);\n    sz = bb(3:4);\n    c = bb(1:2) + (sz - 1)/2;\n    new_sz = sz / bb_scale;\n    new_tl = c - (new_sz - 1)/2;\n    results{frame} = round([new_tl, new_sz]);\nend\n\n% **********************************\n% VOT: Output the results\n% **********************************\nvot_quit(results);\n\ncatch err\n    [wrapper_pathstr, ~, ~] = fileparts(mfilename('fullpath'));\n    cd_ind = strfind(wrapper_pathstr, filesep());\n    VOT_path = wrapper_pathstr(1:cd_ind(end));\n    \n    error_report_path = [VOT_path 'error_reports\\'];\n    if ~exist(error_report_path, 'dir')\n        mkdir(error_report_path);\n    end\n    \n    report_file_name = [error_report_path tracker_name '_' runfile_name datestr(now,'_yymmdd_HHMM') '.mat'];\n    \n    save(report_file_name, 'err')\n    \n    rethrow(err);\nend\n", "meta": {"author": "lifeng9472", "repo": "STRCF", "sha": "68c062d4aa7083b8721e37ce19d92497c8dc4de3", "save_path": "github-repos/MATLAB/lifeng9472-STRCF", "path": "github-repos/MATLAB/lifeng9472-STRCF/STRCF-68c062d4aa7083b8721e37ce19d92497c8dc4de3/vot_wrapper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24559122087402285}}
{"text": "function event = read_micromed_event(trcfile)\n\n% reads the events of the Micromed TRC format files\n\nfid=fopen_or_error(trcfile,'r');\n\n%------------------reading patient & recording info----------\nfseek(fid,64,-1);\nsurname=char(fread(fid,22,'char'))';\nname=char(fread(fid,20,'char'))';\n\nfseek(fid,128,-1);\nday=fread(fid,1,'char');\nif length(num2str(day))<2\n    day=['0' num2str(day)];\nelse\n    day=num2str(day);\nend\nmonth=fread(fid,1,'char');\nswitch month\ncase 1 \n    month='JAN';\ncase 2 \n    month='FEB';\ncase 3 \n    month='MAR';\ncase 4 \n    month='APR';\ncase 5 \n    month='MAY';\ncase 6 \n    month='JUN';\ncase 7 \n    month='JUL';\ncase 8 \n    month='AUG';\ncase 9 \n    month='SEP';\ncase 10 \n    month='OCT';\ncase 11 \n    month='NOV';\ncase 12 \n    month='DEC';\nend\nyear=num2str(fread(fid,1,'char')+1900);\n\n%------------------ Reading Header Info ---------\n\nfseek(fid,175,-1);\nHeader_Type=fread(fid,1,'char');\nif Header_Type ~= 4\n    ft_error('*.trc file is not Micromed System98 Header type 4')\nend\n\nfseek(fid,138,-1);\nData_Start_Offset=fread(fid,1,'uint32');\nNum_Chan=fread(fid,1,'uint16');\nMultiplexer=fread(fid,1,'uint16');\nRate_Min=fread(fid,1,'uint16');\nBytes=fread(fid,1,'uint16');\nfseek(fid,176+8,-1);\nCode_Area=fread(fid,1,'uint32');\nCode_Area_Length=fread(fid,1,'uint32');\nfseek(fid,192+8,-1);\nElectrode_Area=fread(fid,1,'uint32');\nElectrode_Area_Length=fread(fid,1,'uint32');\n\nfseek(fid,400+8,-1);\nTrigger_Area=fread(fid,1,'uint32');\nTigger_Area_Length=fread(fid,1,'uint32');\n\n%----------------- Read Trace Data ----------\n\nfseek(fid,Data_Start_Offset,-1);\nswitch Bytes\ncase 1    \n    trace=fread(fid,'uint8');\ncase 2\n    trace=fread(fid,'uint16');\ncase 4\n    trace=fread(fid,'uint32');\nend\nm=length(trace);\nif rem(m,Num_Chan)~=0\n    roundata=floor(m/Num_Chan);\n    trace=trace(1:roundata*Num_Chan);\n    m=length(trace);\nend\ntrace=reshape(trace,Num_Chan,m/Num_Chan);\n\n%---------------- Reading Trigger Data ----------\nfseek(fid,Trigger_Area,-1);\nfor l=1:Tigger_Area_Length/6\n    trigger(1,l)=fread(fid,1,'uint32');\n    trigger(2,l)=fread(fid,1,'uint16');\nend\n\nfirst_trigger=trigger(1,1);\nm=length(trace);\ntl=length(trigger);\nNoTrig=0;\nfor tr=1:tl\n    if ((trigger(1,tr) <= m) && (trigger(1,tr) >= first_trigger))\n        NoTrig=NoTrig+1;\n    end\nend\nif NoTrig > 0\n   \ttrigger=trigger(:,1:NoTrig);\nelse\n\ttrigger=[];\n\tfirst_trigger=[];\nend\n\nfclose(fid);\n\nevent = [];\n\nif ~isempty(trigger)\n  for E=1:length(trigger)\n    event(E).type    = 'MARKER';\n    event(E).sample  = trigger(1,E)+1;\n    event(E).value   = trigger(2,E);\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_micromed_event.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24559121045808874}}
{"text": "function [K] = ku1u0(x, y, xp, yp, hyp, ubarp, vbarp, dt, i)\n\nlogsigma = hyp(1);\nlogthetax = hyp(2);\nlogthetay = hyp(3);\n\na1 = hyp(4);\na2 = hyp(5);\n\nn_x = size(x,1);\nn_y = size(y,1);\nn_xp = size(xp,1);\nn_yp = size(yp,1);\n\nx = repmat(x,1,n_xp);\ny = repmat(y,1,n_yp);\nxp = repmat(xp',n_x,1);\nyp = repmat(yp',n_y,1);\n\nubarp = repmat(ubarp',n_x,1);\nvbarp = repmat(vbarp',n_y,1);\n\nswitch i\n\n\ncase 0\n\nK=exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...\n  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp( ...\n  1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.* ...\n  exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+ ...\n  (-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...\n  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4));\n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...\n  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp( ...\n  1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.* ...\n  exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+ ...\n  (-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...\n  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4));\n\n\ncase 2 % logthetax\n\nK=(1/2).*exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).* ...\n  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...\n  yp).^2).*(exp(1).^((-1).*logthetax).*(x+(-1).*xp).^2.*(exp(1).^(2.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...\n  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...\n  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1) ...\n  .^((-2).*logthetax+2.*logthetay).*(exp(1).^(a2+logthetax)+a1.*exp(1) ...\n  .^logthetax.*ubarp.*(x+(-1).*xp)+(-2).*exp(1).^a2.*(x+(-1).*xp).^2).*( ...\n  exp(1).^logthetay+(-1).*(y+(-1).*yp).^2));\n\n\ncase 3 % logthetay\n\nK=exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...\n  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp( ...\n  1).^(3.*logthetay)+2.*exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*( ...\n  y+(-1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+( ...\n  -1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...\n  -4)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^( ...\n  (-1).*logthetax+2.*logthetay).*(2.*exp(1).^logthetay.*ubarp.*(x+(-1).* ...\n  xp)+3.*exp(1).^logthetax.*vbarp.*(y+(-1).*yp)+(-1).*ubarp.*(x+(-1).*xp) ...\n  .*(y+(-1).*yp).^2)+dt.*exp(1).^(a2+(-2).*logthetax+logthetay).*(6.*exp( ...\n  1).^(2.*logthetax+logthetay)+3.*exp(1).^(logthetax+2.*logthetay)+(-3).* ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax).*( ...\n  y+(-1).*yp).^2+(-2).*exp(1).^(logthetax+logthetay).*(y+(-1).*yp).^2+2.* ...\n  exp(1).^logthetay.*(x+(-1).*xp).^2.*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...\n  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...\n  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3));\n\n\ncase 4 % a1\n\nK=dt.*exp(1).^(logsigma+(-1).*logthetax+(-3).*logthetay+(-1/2).*exp(1).^(( ...\n  -1).*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+( ...\n  -1).*yp).^2).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3);\n\n\ncase 5 % a2\n\nK=dt.*exp(1).^(a2+logsigma+(-2).*logthetax+(-4).*logthetay+(-1/2).*exp(1) ...\n  .^((-1).*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).* ...\n  (y+(-1).*yp).^2).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4);\n\n\notherwise\n        \n        K = zeros(n_x, n_xp);\nend\n\nend\n", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Kernels/Navier_Stokes/+k10/ku1u0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.2455415382302657}}
{"text": "function [inputs, label] = ComputeTestExamples(curImgsLDR, curExpo, curLabel)\n\nglobal param;\n\ncropSize = param.cropSizeTraining;\nborder = param.border;\n\n%%% prepare input features\n[inputs, label] = PrepareInputFeatures(curImgsLDR, curExpo, curLabel, true);\n\n% %%% crop boundaries\n% inputs = CropImg(inputs, cropSize-border);\n% label = CropImg(label, cropSize-border);\n", "meta": {"author": "qingsenyangit", "repo": "AHDRNet", "sha": "03d1329ff0e7dce8151dfbe685ff558110e262da", "save_path": "github-repos/MATLAB/qingsenyangit-AHDRNet", "path": "github-repos/MATLAB/qingsenyangit-AHDRNet/AHDRNet-03d1329ff0e7dce8151dfbe685ff558110e262da/GenerH5Data/Functions/ComputeTestExamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24537455336678649}}
{"text": "function [FS,read] = spm_voice_FS(wfile)\n% Sampling frequency and function handle for handling sound signals\n% FORMAT [FS,read] = spm_voice_FS(wfile)\n%\n% wfile  - .wav file, audio object or (double) timeseries\n%\n% FS     - sampling frequency\n% read   - function handle: Y = read(wfile);\n%\n%  This auxiliary routine finds the sampling frequency and returns a\n%  function handle appropriate for the sound format in question.\n%__________________________________________________________________________\n% Copyright (C) 2019 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_voice_FS.m 7750 2019-12-05 17:54:29Z spm $\n\n\n% get timeseries from audio recorder(or from a file)\n%--------------------------------------------------------------------------\nglobal VOX\n\n% default\n%--------------------------------------------------------------------------\nif ~nargin\n    try\n        FS = get(VOX.audio,'SampleRate');\n    catch\n        FS = 22050;\n    end\n    return\nend\n\n% get source (recorder) and FS\n%--------------------------------------------------------------------------\nif isa(wfile,'audiorecorder')\n    \n    FS     = get(wfile,'SampleRate');\n    read   = @getaudiodata;\n\nelseif isnumeric(wfile)\n    \n    % timeseries\n    %----------------------------------------------------------------------\n    try\n        FS = get(VOX.audio,'SampleRate');\n    catch\n        try\n            FS = VOX.FS;\n        catch\n            FS = 22050;\n        end\n    end\n    read   = @(Y)Y;\n    \nelse\n    \n    % sound file\n    %----------------------------------------------------------------------\n    try\n        xI     = audioinfo(wfile);\n        FS     = xI.SampleRate;\n        read   = @audioread;\n    catch\n        [~,FS] = wavread(wfile,[1 1]);\n        read   = @wavread;\n    end\n    \nend\n\n% place sampling frequency in global VOX structure\n%----------------------------------------------------------------------\n% VOX.FS = FS;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_voice_FS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24537455336678649}}
{"text": "function scaleDoseROE(hObj,hEvt,hFig)\n% Compute TCP/NTCP at scaled fraction size/number.\n%\n% AI 05/12/21\n\nud = guidata(hFig);\nprotS = ud.Protocols;\n\n%Get selected scale\nuserScale = get(hObj,'Value');\nxScale = userScale;\n\n%Get scale & clear any previous markers\nswitch(ud.plotMode)\n    case {1,2}\n        y1PlotAxis = ud.handle.modelsAxis(1); %NTCP axis\n        y2PlotAxis = [];\n        maxDelFrx = round(max([protS.numFractions])/2); %rounded\n    case 3\n        y1PlotAxis = ud.handle.modelsAxis(2); %NTCP axis\n        y2PlotAxis = ud.handle.modelsAxis(3); %TCP/BED axis\n        fxSizScaleV = linspace(0.5,1.5,99);\n        xIdx = abs(fxSizScaleV-userScale) < eps;\n        if isempty(xIdx)\n            return %Invalid scale factor entered\n        end\n    case 4\n        y1PlotAxis = ud.handle.modelsAxis(4); %NTCP axis\n        y2PlotAxis = ud.handle.modelsAxis(5); %TCP/BED axis\n        maxDelFrx = round(max([protS.numFractions])/2);\nend\nhScaled_y1 = findall(y1PlotAxis,'type','line','LineStyle','-.');\ndelete(hScaled_y1);\nif ~isempty(y2PlotAxis)\n    hScaled_y2 = findall(y2PlotAxis,'type','line','LineStyle','-.');\n    delete(hScaled_y2);\nend\n\n%Clear previous readouts\nif isfield(ud,'scaleDisp')\n    set(ud.scaleDisp,'String','');\nend\ny1ReadoutsH = findobj(y1PlotAxis,'tag','NTCPreadout');\ny2ReadoutsH = findobj(y2PlotAxis,'tag','TCPBEDreadout');\nyReadoutsH = [y1ReadoutsH;y2ReadoutsH];\nfor nLabel = length(yReadoutsH):-1:1\n    delete(yReadoutsH(nLabel));\nend\n\nif isfield(ud,'y1Disp')\n    ud.y1Disp = gobjects;\nend\nif isfield(ud,'y2Disp')\n     ud.y2Disp = gobjects;\nend\n\nxLmtV = get(y1PlotAxis,'xLim');\nhDisp_y1 = text(xLmtV(1),0,'','Parent',y1PlotAxis,...\n    'FontSize',8,'Color',[.3 .3 .3],'HitTest','on',...\n    'PickableParts','visible');\nif ~isempty(y2PlotAxis)\n    hDisp_y2 = text(xLmtV(2),0,'','Parent',y2PlotAxis,...\n        'FontSize',8,'Color',[.3 .3 .3],'HitTest','on',...\n        'PickableParts','visible');\nend\n\n\n%Set color order\ncolorM = ud.plotColorOrderM;\n\n%Scale plots as selected\nmodNum = 0;\ny1 = 0;\ny2 = 0;\nfor l = 1:numel(ud.Protocols)\n    \n    nMod = length(ud.Protocols(l).model);\n    if l == ud.foreground\n        pColorM = [colorM,ones(size(colorM,1),1)];\n    else\n        wt = 0.4;\n        pColorM = [colorM,repmat(wt,size(colorM,1),1)];\n    end\n    \n    %Get plan no.\n    planNum = ud.planNum;\n    \n    %Loop over models\n    for k = 1:nMod\n        modNum = modNum+1;\n        \n        % Get params\n        modelsC = ud.Protocols(l).model;\n        paramsS = modelsC{k}.parameters;\n        \n        % Get struct\n        strNum = modelsC{k}.strNum;\n        paramsS.structNum = strNum;\n        \n        % Get plan\n        paramsS.planNum = planNum;\n        paramsS.numFractions.val = ud.Protocols(l).numFractions;\n        paramsS.frxSize.val = ud.Protocols(l).totalDose/ud.Protocols(l).numFractions;\n        if isfield(modelsC{k},'abRatio')\n            paramsS.abRatio.val = modelsC{k}.abRatio;\n        end\n        \n        % Get dose bins\n        if isfield(modelsC{k},'dv')\n            dose0C = modelsC{k}.dv{1};\n            vol0C = modelsC{k}.dv{2};\n            \n            %Scale\n            if ud.plotMode==3\n                scdoseC = cellfun(@(x) x*userScale,dose0C,'un',0);\n                paramsS.frxSize.val = userScale*paramsS.frxSize.val;\n            else\n                nFProtocol = paramsS.numFractions.val;\n                scNumFrx = userScale + nFProtocol;\n                nfrxV = linspace(-maxDelFrx,maxDelFrx,99);\n                [~,xIdx] = min(abs(nfrxV-userScale));\n                if isempty(xIdx)\n                    return %Invalid scale factor entered\n                end\n                paramsS.numFractions.val = scNumFrx;\n                scdoseC = cellfun(@(x) x*scNumFrx/nFProtocol,dose0C,'un',0);\n            end\n            %Apply fractionation correction where required\n            eqScaledDoseC = frxCorrectROE(modelsC{k},strNum,paramsS.numFractions.val,scdoseC);\n            \n            % Pass as vector if nStr==1\n            if numel(strNum) == 1\n                vol0C = vol0C{1};\n                eqScaledDoseC = eqScaledDoseC{1};\n            end\n            \n            % Compute probability\n            cpNew = feval(modelsC{k}.function,paramsS,eqScaledDoseC,vol0C);\n            \n            % Set plot color\n            clrIdx = mod(k,size(pColorM,1))+1;\n            \n            if strcmpi(modelsC{k}.type,'NTCP') %y1 axis\n                currAx = 'y1';\n                loc = hObj.Min;\n                hplotAx = y1PlotAxis;\n                y1 = y1+1;\n                count = y1;\n                hDisp_y1(count) = text(xLmtV(1),0,'','Parent',y1PlotAxis,...\n                   'FontSize',8,'Color',[0 0 0],'BackgroundColor',[1 1 1],...\n                   'EdgeColor',pColorM(clrIdx,:),'LineWidth',1.5,...\n                   'FontWeight','Bold','Tag','NTCPreadout');\n                txtPos = xLmtV(1) - 0.15*abs(xLmtV(1));\n                if ud.plotMode==1 || ud.plotMode==2\n                    xScale = ud.NTCPCurve(k).XData(xIdx);\n                end\n                skip=0;\n            else %y2 axis\n                currAx = 'y2';\n                if ud.plotMode==1 || ud.plotMode==2\n                    %Skip\n                    skip = 1;\n                else\n                    loc = hObj.Max;\n                    hplotAx = y2PlotAxis;\n                    y2 = y2+1;\n                    count = y2;\n                    hDisp_y2(count) = text(xLmtV(2),0,'','Parent',y2PlotAxis,...\n                        'FontSize',8,'Color',[0 0 0],'BackgroundColor',...\n                        [1 1 1],'EdgeColor',pColorM(clrIdx,:),'LineWidth',...\n                        1.5,'FontWeight','Bold','Tag','TCPBEDreadout');\n                    txtPos = xLmtV(2)+.02;\n                    skip=0;\n                end\n            end\n            \n            if ~skip %Error here: TO DO! Check!\n                \n                plot([xScale xScale],[0 cpNew],'Color',pColorM(clrIdx,:),...\n                    'LineStyle','-.','linewidth',1.5,'parent',hplotAx);\n                plot([loc xScale],[cpNew cpNew],'Color',pColorM(clrIdx,:),...\n                    'LineStyle','-.','linewidth',1.5,'parent',hplotAx);\n                \n                if strcmp(currAx,'y1')\n                    set(hDisp_y1(count),'Position',[txtPos,cpNew],'String',sprintf('%.3f',...\n                        cpNew),'Edge',pColorM(clrIdx,:),'LineWidth',2,...\n                        'FontWeight','Bold');\n                    %Make labels draggable\n                    draggable(hDisp_y1(count), \"v\", [0.01 0.1]);\n                else\n                    set(hDisp_y2(count),'Position',[txtPos,cpNew],'String',sprintf('%.3f',...\n                        cpNew),'Edge',pColorM(clrIdx,:),'LineWidth',2,...\n                        'FontWeight','Bold');\n                    %Make labels draggable\n                    draggable(hDisp_y2(count), \"v\", [0.01 0.1]);\n                end\n                \n            end\n            \n        end\n    end\nend\n\nscaleVal = sprintf('%.3f',xScale);\nhXDisp = text(xScale,-.03,scaleVal,'Parent',y1PlotAxis,...\n    'FontSize',8,'Color',[.3 .3 .3]);\nud.scaleDisp = hXDisp;\nud.y1Disp = hDisp_y1;\nif ~isempty(y2PlotAxis)\n    ud.y2Disp = hDisp_y2;\nend\n\n\nguidata(hFig,ud);\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/ROE_support/scaleDoseROE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.24528173560986538}}
{"text": "model = 'resnext50' ; % {'cafferef','resnext50','resnext101'}\ninput = 'rgb' ; % {'rgb','of'}\ndataset = 'ucf101' ; % {'ucf101','hmdb51'}  hmdb51 requires more iterations to train (add more epochs to learning rate)\nopts.train.batchSize = 128 ;\nopts.train.numSubBatches = 32 ; % increase the number (16,32) if it does not fit into gpu mem \nopts.epochFactor = 5 ;\nopts.split = 1 ;\n\nopts.train.gpus = 1 ;\n\nrun matconvnet/matlab/vl_setupnn.m ;\nvl_contrib install mcnExtraLayers ; vl_contrib setup mcnExtraLayers ;\nvl_contrib install autonn ; vl_contrib setup autonn ;\n\n% addpath(fullfile('matconvnet','contrib','mcnExtraLayers','matlab')) ;\n\nopts.expDir = ['exp/' model 'rgb-arpool-split' num2str(opts.split)] ;\nif strcmp(input,'rgb')  \n  opts.DropOutRate = 0.5 ;\n  trainfn = @cnn_dicnn_rgb ;\nelseif strcmp(input,'of')  \n  opts.DropOutRate = 0.8 ;\n  trainfn = @cnn_dicnn_of ;\nend\n\nif strcmp(model,'cafferef')  \n\n  opts.pool1Layer = 'conv1' ;\n  % download from http://www.vlfeat.org/matconvnet/models/imagenet-caffe-ref.mat\n  opts.modelPath = fullfile('models','imagenet-caffe-ref.mat') ;\n  opts.networkFn = @cnn_init_cafferef ;\n  \n  if strcmp(input,'rgb')  \n    opts.train.learningRate = 1e-3 * [ones(1,2) 0.1*ones(1,2)] ;\n  else\n    opts.train.learningRate = 3e-3 * [ones(1,10) 0.1*ones(1,2)] ;\n  end\n\n  opts.train.numEpochs = numel(opts.train.learningRate) ;\nelseif strcmp(model,'resnext50') || strcmp(model,'resnext101')\n  % download from http://www.robots.ox.ac.uk/~albanie/models/pytorch-imports/resnext_50_32x4d-pt-mcn.mat\n  % download from http://www.robots.ox.ac.uk/~albanie/models/pytorch-imports/resnext_101_32x4d-pt-mcn.mat\n  if strcmp(model,'resnext50')\n    opts.modelPath = fullfile('models','resnext_50_32x4d-pt-mcn.mat') ;\n  else\n    opts.modelPath = fullfile('models','resnext_101_32x4d-pt-mcn.mat') ;\n  end\n  opts.modelPath = fullfile('models','resnext_50_32x4d-pt-mcn.mat') ;\n  opts.networkFn = @cnn_init_resnext ;\n  if strcmp(input,'rgb')  \n    opts.train.learningRate = 1e-2 * [ones(1,2) 0.1*ones(1,8) ] ;\n  else\n    opts.train.learningRate = 1e-2 * [ones(1,2) 0.1*ones(1,2) ] ;\n  end\nend\n\naddpath dicnn ;\n\n[net, info] = trainfn(opts)\n", "meta": {"author": "hbilen", "repo": "dynamic-image-nets", "sha": "96b91afab1095967459f1db95541d864c5fc8ace", "save_path": "github-repos/MATLAB/hbilen-dynamic-image-nets", "path": "github-repos/MATLAB/hbilen-dynamic-image-nets/dynamic-image-nets-96b91afab1095967459f1db95541d864c5fc8ace/main_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24523271931511548}}
{"text": "%% Snake Demo\n%\n% An example using a SNAKETOY function.\n%\n% This function creates a snake toy graphic.  Each block\n% in the snake is an hgtransform object.  A vector of angles (in\n% radians) can be passed in to create a new shape by twisting the\n% snake.  Twisting occurs using the hgtransform's 'Matrix'\n% property.\n%\n% <snaketoy.m>\n\n% Copyright (C) 2005-2011 The MathWorks Inc.\n\n% Create a snake\nsnake = snaketoy;\n\n%% Transform the snake\n%\n% By passing in a list of angles, you can transform the snake into\n% a new shape.\nsnaketoy(snake,[ 0 0 0 pi pi 0 0 0 pi 0 pi pi ...\n                   0 pi 0 pi pi 0 pi 0 pi pi 0 pi]);\ncamzoom(2)\n%% Named Shapes\n%\n% Some shapes have pre-defined names encoded in the file.\n% You can reference these by name.\nsnaketoy(snake, 'box');\n\n%% Transformation Methods\n%\n% You can cause a shape to transform in different ways by moving\n% linearly through the pattern from one of the snake to the other,\n% choosing random joints to twist, or twisting all joints at the\n% same time.\nsnaketoy(snake, 'dog','once');\n\n%% Demonstration Mode\n%\n% You can run the script in demo mode by calling SNAKETOY\n% with no arguments.  This feature runs infinitly, constantly\n% transforming the snake into new shapes using arbitrary\n% transformation methods.\n\n% snaketoy\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7270-snake-toy/snake/snakedemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24523271358032467}}
{"text": "function LDR = openldr(FN,PERMISSION,Mode,arg4,arg5,arg6)\n% OPENLDR loads neuroscan LDR files\n% LDR = OPENLDR(Filename [, PERMISSION [, Mode]]);\n% LDR = OPENLDR(LDR [, PERMISSION [, Mode]]);\n%\n% LDR is a struct with the following fields\n%   LDR.FileName \tName of LDR-file\n%   LDR.Label_Out\tLabels of output channels\n%   LDR.Label_In\tLabels of input channels\n%   LDR.RR\t\tre-referencing matrix\n%   LDR.datatype\t'REREF_MATRIX' indicates this datatype\n%\n% PERMISSION\t'r'\treads LDR file\n% \t\t'w'\twrites LDR file\n% \t\t'r+w'\treads and writes LDR file \n%\t\t\t(useful in combination with RESCALE-Mode) \n%\n% Mode [optional] 'RESCALE' performs a rescaling of the weights\n%\t\tsum of positive weights becomes +1\n%\t\tsum of negative weights becomes -1\n%\n\n%\t$Id: openldr.m 2473 2010-06-04 09:56:57Z schloegl $\n%\tCopyright (C) 1997-2003,2008 by Alois Schloegl <a.schloegl@ieee.org>\t\n%    \tThis is part of the BIOSIG-toolbox http://biosig.sf.net/\n\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 3\n% of the  License, or (at your option) any later version.\n\n\nif nargin<2, PERMISSION=''; end;\nif nargin<3, Mode=''; end;\n\nif ~isstruct(FN), \n        LDR.FileName = FN;\n        PERMISSION = [PERMISSION,'r']; \nelse\n        LDR = FN;\n        PERMISSION = [PERMISSION,'w']; \nend;\n\n\nif any(PERMISSION=='r'); \n        % load LDR-file \n        fid = fopen(LDR.FileName);\n        if fid<0, fprintf(2,'File %s not found.\\n',LDR.FileName); return; end; \n        \n        % reads line 1: size information\n        s  = fgetl(fid);\n        if ~ischar(s), fprintf(2,'ERROR LOADLDR: file %s corrupted\\n',FN); end;\n        sz = str2num(s);\n        \n        % reads line 2: output labels\n        s  = fgetl(fid);\n        if ~ischar(s), fprintf(2,'ERROR LOADLDR: file %s corrupted\\n',FN); end;\n        tmp = reshape(s,12,sz(2)+1)';\n        LDR.Label_Out = tmp(2:sz(2)+1,:);\n        \n        % read lines 3+: input labels and weights\n        for k = 1:sz(1),\n                s = fgetl(fid);\n                if ~ischar(s), fprintf(2,'ERROR LOADLDR: file %s corrupted\\n',FN); end;\n                r = reshape(s,12,sz(2)+1)';\n                LDR.Label_In(k,1:12) = char(abs(s(1:12)));\n                LDR.RR(k,1:sz(2)) = str2num(r(2:size(r,1),:))';\n        end;\n        \n        fclose(fid);\n        LDR.datatype='REREF_MATRIX';\n        \nend;\n\n\nif strcmp(Mode,'RESCALE');\n        tmp = LDR.RR;\n        tmp(tmp<0) = 0;\n        w = sum(tmp);\n        RR = zeros(sz);\n        if ~all(w==0 | w==1)\n                ix = find(w);\n                RR(:,ix) = tmp(:,ix)./w(ones(sz(1),1),ix);\n                % RR(:,ix) = (tmp(:,ix)>0)./(ones(sz(1),1)*sum(tmp(:,ix)>0));\n        end;\n        tmp = LDR.RR;\n        tmp(tmp>0)=0;\n        w = sum(tmp);\n        if ~all(w==0 | w==-1)\n                ix = find(w);\n                RR(:,ix) = tmp(:,ix)./w(ones(sz(1),1),ix);\n                % RR(:,ix) = RR(:,ix)-(tmp(:,ix)<0)./(ones(sz(1),1)*sum(tmp(:,ix)<0));\n        end;\n        LDR.RR=RR;\nend;\n\nif any(PERMISSION=='w'); \n        tmp = isfield(LDR,'datatype') & strcmp(LDR.datatype,'REREF_MATRIX');\n        if ~tmp,\n                warning('LDR.datatype does not fit');\n        end;\n        sz = size(LDR.RR);\n        if sz(1)~=size(LDR.Label_In,1);\n                fprintf(2,'Size of Label_In does not fit RR\\n');\n                return;\n        end;\n        if sz(2)~=size(LDR.Label_Out,1);\n                fprintf(2,'Size of Label_Out does not fit RR\\n');\n                return;\n        end;\n        \n\t% open LDR-file \n        fid = fopen(LDR.FileName,'w+');\n\tif fid<0, fprintf(2,'Couldnot open file %s .\\n',LDR.FileName); return; end; \n        \n        % write line 1: size information\n        fprintf(fid,'%i %i\\n',sz);\n        \n        % condition label information\n        %LDR.Label_Out = char(LDR.Label_Out);\n\n        nc = size(LDR.Label_Out,2);\n        if nc<12,\n                LDR.Label_Out = [LDR.Label_Out,abs(' ')*ones(sz(1),12-nc)];\n        elseif nc>12,\n                LDR.Label_Out = LDR.Label_Out(:,1:12);\n        end;\n        %LDR.Label_In = char(LDR.Label_In);\n        nc = size(LDR.Label_In,2);\n        if nc<12,\n                LDR.Label_In = [LDR.Label_In,abs(' ')*ones(sz(1),12-nc)];\n        elseif nc>12,\n                LDR.Label_In = LDR.Label_In(:,1:12);\n        end;\n        \n\t% write line 2: out-labels\n        fwrite(fid,32+zeros(12,1),'uint8');\n        %fprintf(fid,'%c',abs(' ')*ones(12,1));\n\tfor k = 1:sz(2),\n                fwrite(fid,abs(LDR.Label_Out(k,1:12)),'uint8');\n        end;\n        \n        % write lines 3+: in-labels and weights\n        for k = 1:sz(1),\n                fprintf(fid,'\\n');\n                fwrite(fid,abs(LDR.Label_In(k,1:12)),'uint8');\n                fprintf(fid,'%12.5f',LDR.RR(k,:));\n        end;\n        fclose(fid);\nend;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/biosig-partial/t200_FileAccess/openldr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2452327135803246}}
{"text": "% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos\n% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n\n\nfunction CstTeflonPTFElossy(mws)\n\n%'@ define material: Teflon (PTFE) (lossy)\n\nmaterial = invoke(mws,'material');\ninvoke(material,'Reset');\ninvoke(material,'Name','Teflon (PTFE) (lossy)'); \ninvoke(material,'FrqType','all');\ninvoke(material,'Type','Normal');\ninvoke(material,'SetMaterialUnit','GHz','mm');\ninvoke(material,'Epsilon','2.1');\ninvoke(material,'Mue','1.0');\ninvoke(material,'Kappa','0.0');\ninvoke(material,'TanD','0.0002');\ninvoke(material,'TanDFreq','10.0');\ninvoke(material,'TanDGiven','True');\ninvoke(material,'TanDModel','ConstTanD');\ninvoke(material,'KappaM','0.0');\ninvoke(material,'TanDM','0.0');\ninvoke(material,'TanDMFreq','0.0');\ninvoke(material,'TanDMGiven','False');\ninvoke(material,'TanDMModel','ConstKappa');\ninvoke(material,'DispModelEps','None');\ninvoke(material,'DispModelMue','None');\ninvoke(material,'DispersiveFittingSchemeEps','General 1st');\ninvoke(material,'DispersiveFittingSchemeMue','General 1st');\ninvoke(material,'UseGeneralDispersionEps','False');\ninvoke(material,'UseGeneralDispersionMue','False');\ninvoke(material,'Rho','2200.0');\ninvoke(material,'ThermalType','Normal');\ninvoke(material,'ThermalConductivity','0.2');\ninvoke(material,'HeatCapacity','1.0'); \ninvoke(material,'SetActiveMaterial','all');\ninvoke(material,'MechanicsType','Isotropic'); \ninvoke(material,'YoungsModulus','0.5'); \ninvoke(material,'PoissonsRatio','0.4'); \ninvoke(material,'ThermalExpansionRate','140');\ninvoke(material,'Colour','0.94','0.82','0.76');\ninvoke(material,'Wireframe','False');\ninvoke(material,'Transparency','0');\ninvoke(material,'Create');\nrelease(material);\nend\n\n\n", "meta": {"author": "simos421", "repo": "CST-MATLAB-API", "sha": "a6019ad6f33fa14ebfd459579b6e7151dd3d4ece", "save_path": "github-repos/MATLAB/simos421-CST-MATLAB-API", "path": "github-repos/MATLAB/simos421-CST-MATLAB-API/CST-MATLAB-API-a6019ad6f33fa14ebfd459579b6e7151dd3d4ece/Materials/CstTeflonPTFElossy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2452008839009126}}
{"text": "function q = divine(im)\n% DIIVINE Software release.\n% \n% \n% ========================================================================\n% \n% -----------COPYRIGHT NOTICE STARTS WITH THIS LINE------------\n% Copyright (c) 2010 The University of Texas at Austin\n% All rights reserved.\n% \n% Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, \n% modify, and distribute this code (the source files) and its documentation for\n% any purpose, provided that the copyright notice in its entirety appear in all copies of this code, and the \n% original source of this code, Laboratory for Image and Video Engineering (LIVE, http://live.ece.utexas.edu)\n% and Center for Perceptual Systems (CPS, http://www.cps.utexas.edu) at the University of Texas at Austin (UT Austin, \n% http://www.utexas.edu), is acknowledged in any publication that reports research using this code. The research\n% is to be cited in the bibliography as:\n% \n% 1. A. K. Moorthy and A. C. Bovik, \"Blind Image Quality Assessment: From Natural\n% Scene Statistics to Perceptual Quality\", IEEE Transactions on Image Processing, to appear (2011).\n% \n% 2. A. K. Moorthy and A. C. Bovik, \"DIVINE Software Release\", \n% URL: http://live.ece.utexas.edu/research/quality/DIIVINE_release.zip, 2010\n% \n% IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT AUSTIN BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, \n% OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS DATABASE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF TEXAS\n% AT AUSTIN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n% \n% THE UNIVERSITY OF TEXAS AT AUSTIN SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE DATABASE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS,\n% AND THE UNIVERSITY OF TEXAS AT AUSTIN HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n% \n% -----------COPYRIGHT NOTICE ENDS WITH THIS LINE------------%\n% \n% Author  : Anush Krishna Moorthy\n% Version : 1.1\n% \n% The authors are with the Laboratory for Image and Video Engineering\n% (LIVE), Department of Electrical and Computer Engineering, The\n% University of Texas at Austin, Austin, TX.\n% \n% Kindly report any suggestions or corrections to anushmoorthy@gmail.com\n% \n% ========================================================================\n% \n% This is a demonstration of the Distortion Identification based image Verity and INtegrity Evaluation (DIVINE) index.\n% It is an implementation of the BIQI in the reference.\n% The algorithm is described in:\n% A. K. Moorthy and A. C. Bovik, \"Blind Image Quality Assessment: From Natural\n% Scene Statistics to Perceptual Quality\",  IEEE Transactions on Image Processing, to appear (2011).\n% \n% You can change this program as you like and use it anywhere, but please\n% refer to its original source (cite our paper and our web page at\n% http://live.ece.utexas.edu/research/quality/DIIVINE_release.zip).\n% \n% Input : A test 8bits/pixel grayscale image loaded in a 2-D array\n% Output: A quality score of the image. The score typically has a value\n%        between 0 and 100 (0 represents the best quality, 100 the worst).\n% \n% Usage:\n% \n% 1. Load the image, for example\n% \n%   image = rgb2gray(imread('testimage.jpg')); \n% \n% 2. Call this function to calculate the quality score:\n% \n%    quality = divine(image)\n% \n% Dependencies: \n% Steerable Pyramid Toolbox, Download from: http://www.cns.nyu.edu/~eero/steerpyr/\n% LibSVM package for MATLAB, Download from: http://www.csie.ntu.edu.tw/~cjlin/libsvm/\n% You may need the MATLAB Image Processing Toolbox\n% \n% Dependencies--\n% \n% MATLAB files:  ssim_index_new.m, norm_sender_normalized.m, find_spatial_hist_fast.m, divine_overall_quality.m\n%               divine_feature_extract.m,  map_matrix_to_closest_vec.m (provided with release)\n% \n% Data files: data_live_trained.mat (provided with release)\n% \n% This code has been tested on Windows and Mac OSX (Snow Leopard)\n% \n% ========================================================================% \n% Note on training: \n% This release version of BIQI was trained on the entire LIVE database.\n% \n% \n\nimport divine.*\n\n\n\nf = divine_feature_extract(im);\nq = divine_overall_quality(f);", "meta": {"author": "dsoellinger", "repo": "blind_image_quality_toolbox", "sha": "4d12c43c77bba538f684df0b62621e9350854c43", "save_path": "github-repos/MATLAB/dsoellinger-blind_image_quality_toolbox", "path": "github-repos/MATLAB/dsoellinger-blind_image_quality_toolbox/blind_image_quality_toolbox-4d12c43c77bba538f684df0b62621e9350854c43/+divine/divine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24515028723720894}}
{"text": "clear\n\nload('./results/results_clnf_wild.mat');\n\n[clnf_error, ~,~,frontal_ids] = compute_error( experiment.labels,  experiment.shapes-1.0);\nclnf_error_frontal = clnf_error(frontal_ids);\nclnf_error_profile = clnf_error(~frontal_ids);\n\nload('./results/results_ceclm_general.mat');\n\n[ceclm_error,~,~,frontal_ids] = compute_error( experiment.labels,  experiment.shapes-1.0);\nceclm_error_frontal = ceclm_error(frontal_ids);\nceclm_error_profile = ceclm_error(~frontal_ids);\n\nload('results/CFAN_JANUS.mat');\n\n[cfan_error,~,~,frontal_ids] = compute_error( labels_all,  shapes_all-1.0);\ncfan_error_frontal = cfan_error(frontal_ids);\ncfan_error_profile = cfan_error(~frontal_ids);\n\nload('results/JANUS_3DDFA.mat');\n\n[error_3ddfa,~,~,frontal_ids] = compute_error( labels_all,  shapes-1.0);\nerror_3ddfa_frontal = error_3ddfa(frontal_ids);\nerror_3ddfa_profile = error_3ddfa(~frontal_ids);\n\nload('results/JANUS-CFSS.mat');\nshapes = zeros(68,2, size(estimatedPose,1));\n\nfor i = 1:size(shapes, 3)\n    shapes(:,1,i) = estimatedPose(i,1:68);\n    shapes(:,2,i) = estimatedPose(i,69:end);\nend\n\n[cfss_error,~,~,frontal_ids] = compute_error( experiment.labels, shapes-1.0);\ncfss_error_frontal = cfss_error(frontal_ids);\ncfss_error_profile = cfss_error(~frontal_ids);\n\n%\nload('results/tcdcn_JANUS.mat');\nshapes_c = shapes;\nshapes = zeros(68,2, numel(shapes_c));\n\nfor i = 1:size(shapes, 3)\n    shapes(:,1,i) = shapes_c{i}(:,1);\n    shapes(:,2,i) = shapes_c{i}(:,2);\nend\n\n[tcdcn_error,~,~,frontal_ids] = compute_error( experiment.labels, shapes-1);\ntcdcn_error_frontal = tcdcn_error(frontal_ids);\ntcdcn_error_profile = tcdcn_error(~frontal_ids);", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/experiments_JANUS/Extract_table_results_68.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24512060709041225}}
{"text": "function imdb = vid(prefix, opts)\nsavefn = fullfile(opts.dataDir, [prefix '.mat']);\nif exist(savefn, 'file')\n    imdb = load(savefn);\n    return;\nend\nviddir = fullfile(opts.dataDir, 'VehicleID_V1.0');\n\n% imgs, vid\nimg2vid = fullfile(viddir, 'attribute', 'img2vid.txt');\n[imgs, vid] = textread(img2vid, '%d %d');\nn = numel(imgs);\n\n% model info\nmid = zeros(n, 1);\nvid2model = fullfile(viddir, 'attribute', 'model_attr.txt');\n[vid_m, mid_m] = textread(vid2model, '%d %d');\nfor i = 1:length(vid_m)\n    mid(vid == vid_m(i)) = mid_m(i) + 1;\nend\n\n% color info\ncid = zeros(n, 1);\nvid2color = fullfile(viddir, 'attribute', 'color_attr.txt');\n[vid_c, cid_c] = textread(vid2color, '%d %d');\nfor i = 1:length(vid_c)\n    mid(vid == vid_c(i)) = cid_c(i) + 1;\nend\n\n% train/test\nsets = zeros(n, 4);  % [train test_small test_medium test_large]\n\ntrainFile = fullfile(viddir, 'train_test_split', 'train_list.txt');\n[~, vid_train] = textread(trainFile, '%d %d');\nsets(ismember(vid, vid_train), 1) = 1;\nlogInfo('train: %d imgs', sum(sets(:, 1)));\n\ntestSmallFile = fullfile(viddir, 'train_test_split', 'test_list_800.txt');\n[~, vid_s] = textread(testSmallFile, '%d %d');\nsets(ismember(vid, vid_s), 2) = 1;\nlogInfo('test-small: %d imgs', sum(sets(:, 2)));\n\ntestMediumFile = fullfile(viddir, 'train_test_split', 'test_list_1600.txt');\n[~, vid_m] = textread(testMediumFile, '%d %d');\nsets(ismember(vid, vid_m), 3) = 1;\nlogInfo('test-medium: %d imgs', sum(sets(:, 3)));\n\ntestLargeFile = fullfile(viddir, 'train_test_split', 'test_list_2400.txt');\n[~, vid_l] = textread(testLargeFile, '%d %d');\nsets(ismember(vid, vid_l), 4) = 1;\nlogInfo('test-large: %d imgs', sum(sets(:, 4)));\n\n% resize to 256x256\na = tic; tic;\nvid256 = fullfile(viddir, 'image_256x256');\nif ~exist(vid256, 'dir'), mkdir(vid256); end\nfn256 = cell(n, 1);\nfor i = 1:n\n    fn256{i} = sprintf('%s/%07d.jpg', vid256, imgs(i));\n    if ~exist(fn256{i}, 'file')\n        im = imread(sprintf('%s/image/%07d.jpg', viddir, imgs(i)));\n        im = imresize(im, [256 256]);\n        imwrite(im, fn256{i});\n    end\n    if toc > 20\n        logInfo(fn256{i}); tic;\n    end\nend\ntoc(a)\n\n% imdb\nimdb.images.data = fn256;\nimdb.images.labels = single([vid mid cid]) ;\nimdb.images.set = uint8(sets) ;\nimdb.meta.sets = {'train', 'test_small', 'test_medium', 'test_large'} ;\nsave(savefn, '-struct', 'imdb');\nend\n", "meta": {"author": "kunhe", "repo": "FastAP-metric-learning", "sha": "ca85b2ab3f22460795d4306c8fa01c655d17027e", "save_path": "github-repos/MATLAB/kunhe-FastAP-metric-learning", "path": "github-repos/MATLAB/kunhe-FastAP-metric-learning/FastAP-metric-learning-ca85b2ab3f22460795d4306c8fa01c655d17027e/matlab/+imdb/vid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512060080581893}}
{"text": "%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  calc_VIDEVAL_feat.m\n%  \n%  This function extract the VIDEVAL feature vector (60-dim)\n%\n%\n%  Input: \n%           test_video:             Path to the test video file (YUV420 format)\n%           width, height:          Resolution of the YUV video \n%           framerate:              number of frames per second\n%                       \n%  Output:\n%           VIDEVAL_all_features:   Resulting VIDEVAL feature vector (60-dim)\n%\n% Note: this is a light version of VIDEVAL, which has been spatially and \n%       temporally sped up.\n%\n%  - Resized frames to 720p if larger than 720p keeping aspect ratio\n%  - Sampled at most 6 frames for each 1-second block\n\n%%\nfunction [VIDEVAL_all_features] = calc_VIDEVAL_feats_light(test_video, ...\n        width, height, framerate, max_reso, frs_per_blk)\n    % setup speededup params\n%     max_reso = 480;\n%     frs_per_blk = 3;\n    \n    % subsampling ratio\n    ratio = max_reso / min(width, height);\n    fr_step = max(floor(framerate / frs_per_blk),1); \n    \n    % Try to open test_video; if cannot, return\n    test_file = fopen(test_video,'r');\n    if test_file == -1\n        fprintf('Test YUV file not found.');\n        VIDEVAL_all_features = [];\n        return;\n    end\n    % Open test video file\n    fseek(test_file, 0, 1);\n    file_length = ftell(test_file);\n    fprintf('Video file size: %d bytes (%d frames)\\n',file_length, ...\n            floor(file_length/width/height/1.5));\n    % get frame number\n    frame_start = 1; \n    frame_end = (floor(file_length/width/height/1.5)-3);\n    first_frame_loaded = 0;\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Loop through all the frames in the frame_range to compute frame features \n    %\n    fprintf('Computing frame features on frames %d..%d\\n', ...\n            frame_start, frame_end);\n     \n    frame_features_all = [];\n    for i = frame_start:fr_step:frame_end\n        % Read frames i-i, i and i+1 (note that frame_start must be > 0)\n        if first_frame_loaded\n            % prev_YUV_frame = next_YUV_frame;\n            prev_YUV_frame = YUVread(test_file,[width height],i-1);\n            this_YUV_frame = YUVread(test_file,[width height],i);\n            next_YUV_frame = YUVread(test_file,[width height],i+1);\n            if ratio < 1\n                this_YUV_frame = imresize(this_YUV_frame, ratio);\n                next_YUV_frame = imresize(next_YUV_frame, ratio);\n            end\n        else\n            prev_YUV_frame = YUVread(test_file,[width height],i-1);\n            this_YUV_frame = YUVread(test_file,[width height],i);\n            next_YUV_frame = YUVread(test_file,[width height],i+1);\n            first_frame_loaded = 1;\n            if ratio < 1\n                prev_YUV_frame = imresize(prev_YUV_frame, ratio);\n                this_YUV_frame = imresize(this_YUV_frame, ratio);\n                next_YUV_frame = imresize(next_YUV_frame, ratio);\n            end\n        end\n        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        % Compute BRISQUE features # 5(std), 9, 23, 29\n        % features_all(1:4) #4\n        brisque_feats = compute_brisque_features(this_YUV_frame(:,:,1));\n\n        % compute GM-LOG features # 2(std), 4(std), 8, 18(std), 20, 23, 34(std), 40(both) \n        % features_all(5:12) #8\n        gmlog_feats = compute_gmlog_features(this_YUV_frame(:,:,1));\n\n        % compute HIGRADE features # 3, 13, 14, 16, 21(both), 28, 30, 33\n        % features_all(13:20) #8\n        higrade_feats = compute_higrade_features(this_YUV_frame(:,:,1));\n\n        % compute FRIQUEE_lUMA features # 5(std), 8(std), 27(std), 32(std), 58, 62(std), 66, 68(std), 70(both), 71, 72(std) \n        % features_all(21:31) #11\n        friquee_luma_feats = compute_friquee_luma_features(this_YUV_frame(:,:,1));\n\n        % compute FRIQUEE_CHRO features # 4  7(std) 15   24   26   47   60   62   72   73   79\n        % features_all(32:42) #11\n        friquee_chroma_feats = compute_friquee_chroma_features(this_YUV_frame(:,:,:));\n\n        % compute FRIQUEE LMS features # 52 \n        % features_all(43:43) # 1\n        friquee_lms_feats = compute_friquee_lms_features(this_YUV_frame(:,:,:));\n\n        % compute TLVQM LCF features # 1 5(both) 12 16 18 19(std) 22(std)\n        % features_all(44:50) # 7\n        tlvqm_lcf_feats = compute_tlvqm_lcf_features(this_YUV_frame./255, ...\n                                                     prev_YUV_frame./255, ...\n                                                     next_YUV_frame./255); \n        % concat features\n        frame_features_all = [frame_features_all; [brisque_feats, gmlog_feats, higrade_feats, ...\n            friquee_luma_feats, friquee_chroma_feats, friquee_lms_feats, tlvqm_lcf_feats]];\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Compute mean and std pooling\n    %\n    std_feats = [];\n    avg_feats = [];\n    std_pool_idx = [1, 5, 6, 8, 11, 12, 17, 21, 22, 23, 24, 26, 28, 29, 31, ...\n        33, 45, 49, 50];\n    avg_pool_idx = [2:4, 7, 9, 10, 12, 13:20, 25, 27, 29, 30, 32, 34:48];\n    n_temp_vecs = length(frame_features_all(:,1)); \n%     half_framerate = floor(framerate/2);\n    \n    fprintf('Mean and standard deviation pooling of frame-wise features...\\n');\n    for j = 1:frs_per_blk:n_temp_vecs - frs_per_blk\n        j_start = j; \n        j_end = min(n_temp_vecs, j + frs_per_blk);\n        % mean and std pooling\n        std_feats = [std_feats; nanstd(frame_features_all(j_start:j_end, std_pool_idx))];\n        avg_feats = [avg_feats; nanmean(frame_features_all(j_start:j_end, avg_pool_idx))];\n    end\n    \n    % compute TLVQM HCF features # 1 2 17 22 24 30\n    tlvqm_hcf_feats = [];\n    fprintf('Computing TLVQM-HCF features at 1fps...\\n');\n    for fr=floor(framerate/2):framerate:frame_end\n        YUV_frame = YUVread(test_file,[width height],fr-1);\n        if ratio < 1\n            YUV_frame = imresize(YUV_frame, ratio);\n        end\n        ftrs = compute_tlvqm_hcf_features(YUV_frame./255);\n        tlvqm_hcf_feats = [tlvqm_hcf_feats; ftrs];\n    end\n    \n    % Combine feature vectors\n    VIDEVAL_all_features = [nanmean(avg_feats, 1)   ...\n                    nanmean(std_feats, 1) ...\n                    nanmean(tlvqm_hcf_feats, 1)];\n    \n    fclose(test_file);\n    fprintf('Extracting VIDEVAL features for %s finished!\\n', test_video);\nend\n\n%% compute_brisque_features\nfunction feat = compute_brisque_features(imgray)\n% Compute BRISQUE features # 5(std), 9, 23, 29\n    window = fspecial('gaussian',7,7/6);\n    window = window/sum(sum(window));\n    feat = [];\n    %% scale1 5, 9\n    mu = filter2(window, imgray, 'same');\n    mu_sq = mu.*mu;\n    sigma = sqrt(abs(filter2(window, imgray.*imgray, 'same') - mu_sq));\n    imstruct = (imgray-mu)./(sigma+1);\n    shifts = [0 1; 1 0];\n    for itr_shift =1:2\n        shifted_imstruct = circshift(imstruct,shifts(itr_shift,:));\n        pair = imstruct(:).*shifted_imstruct(:);\n        [~, leftstd, ~] = estimateaggdparam(pair);\n        feat =[feat leftstd^2];\n    end\n    \n    %% scale2 5, 11\n    imgray = imresize(imgray,0.5);\n    mu = filter2(window, imgray, 'same');\n    mu_sq = mu.*mu;\n    sigma = sqrt(abs(filter2(window, imgray.*imgray, 'same') - mu_sq));\n    imstruct = (imgray-mu)./(sigma+1);\n    shifts = [0 1; 1 1];\n    for itr_shift =1:2\n        shifted_imstruct = circshift(imstruct,shifts(itr_shift,:));\n        pair = imstruct(:).*shifted_imstruct(:);\n        [alpha, leftstd, ~] = estimateaggdparam(pair);\n        if itr_shift == 1\n            feat = [feat leftstd^2];\n        else \n            feat = [feat alpha];\n        end\n    end\nend\n\n%% compute_gmlog_features\nfunction feat = compute_gmlog_features(imgray)\n% compute GM-LOG features # 2(std), 4(std), 8, 18(std), 20, 23, 34(std), 40(both) \n    sigma = 0.5;\n    [gx,gy] = gaussian_derivative(imgray,sigma);\n    grad_im = sqrt(gx.^2+gy.^2);\n\n    window2 = fspecial('log', 2*ceil(3*sigma)+1, sigma);\n    window2 =  window2/sum(abs(window2(:)));\n    log_im = abs(filter2(window2, imgray, 'same'));\n\n    ratio = 2.5; % default value 2.5 is the average ratio of GM to LOG on LIVE database\n    grad_im = abs(grad_im/ratio);\n\n    %Normalization\n    c0 = 4*0.05;\n    sigmaN = 2*sigma;\n    window1 = fspecial('gaussian',2*ceil(3*sigmaN)+1, sigmaN);\n    window1 = window1/sum(window1(:));\n    Nmap = sqrt(filter2(window1,mean(cat(3,grad_im,log_im).^2,3),'same'))+c0;\n    grad_im = (grad_im)./Nmap;\n    log_im = (log_im)./Nmap;\n    % remove the borders, which may be the wrong results of a convolution\n    % operation\n    h = ceil(3*sigmaN);\n    grad_im = abs(grad_im(h:end-h+1,h:end-h+1,:));\n    log_im = abs(log_im(h:end-h+1,h:end-h+1));\n\n    ctrs{1} = 1:10;ctrs{2} = 1:10;\n    % histogram computation\n    step1 = 0.20;\n    step2 = 0.20;\n    grad_qun = ceil(grad_im/step1);\n    log_im_qun = ceil(log_im/step2);\n\n    N1 = hist3([grad_qun(:),log_im_qun(:)],ctrs);\n    N1 = N1/sum(N1(:));\n    NG = sum(N1,2); NL = sum(N1,1);\n\n    alpha1 = 0.0001;\n    % condition probability: Grad conditioned on LOG\n    cp_GL = N1./(repmat(NL,size(N1,1),1)+alpha1);\n    cp_GL_H=  sum(cp_GL,2)';\n    cp_GL_H = cp_GL_H/sum(cp_GL_H);\n    % condition probability: LOG conditioned on Grad\n    cp_LG = N1./(repmat(NG,1,size(N1,2))+alpha1);\n    cp_LG_H = sum(cp_LG,1);\n    cp_LG_H = cp_LG_H/(sum(cp_LG_H));\n\n    out = [NG', NL, cp_GL_H,cp_LG_H];\n    \n    feat = out([2, 4, 8, 18, 20, 23, 34, 40]);\nend\n\nfunction [gx,gy] = gaussian_derivative(imd,sigma)\n    window1 = fspecial('gaussian',2*ceil(3*sigma)+1+2, sigma);\n    winx = window1(2:end-1,2:end-1)-window1(2:end-1,3:end);winx = winx/sum(abs(winx(:)));\n    winy = window1(2:end-1,2:end-1)-window1(3:end,2:end-1);winy = winy/sum(abs(winy(:)));\n    gx = filter2(winx,imd,'same');\n    gy = filter2(winy,imd,'same');\nend\n\n%% compute_higrade_features\nfunction feat = compute_higrade_features(imgray)\n% compute HIGRADE features # 3, 13, 14, 16, 21(both), 28, 30, 33\n[Gmag, ~] = imgradient(imgray);\nwindow = fspecial('gaussian',7,7/6);\nwindow = window/sum(sum(window));\nscale_num = 2;\nfeat = [];\nfor scale = 1:scale_num\n    if scale == 1\n        im = Gmag;\n%         ggdpara = [];\n        shifts = [0 1;1 0 ; 1 1; -1 1];\n\n        mu = filter2(window, im, 'same');\n        mu_sq = mu.*mu;\n        sigma = sqrt(abs(filter2(window, im.*im, 'same') - mu_sq));\n        structdis = (im-mu)./(sigma+1);\n        [sigma_tmp, ~] = gaussian_para_esti(structdis(:));\n        feat = [feat sigma_tmp]; %3 \n        structdis = log(abs(structdis) + .1);\n        for itr_shift = 1:4\n            structdis_shift_tmp = circshift(structdis, shifts(itr_shift,:));\n            structdis_diff = structdis - structdis_shift_tmp;\n            structdis_shift(itr_shift) = {[structdis_shift_tmp]};\n        end\n        structdis_diff = structdis + structdis_shift{1,3} - structdis_shift{1,1} - structdis_shift{1,2};\n        [sigma_tmp_0, alpha_tmp_0] = gaussian_para_esti(structdis_diff(:));\n        feat = [feat  sigma_tmp_0 alpha_tmp_0]; % 13 14\n        win_tmp_1 = [0 1 0; -1 0 -1; 0 1 0;];\n        structdis_diff_1 = filter2(win_tmp_1, structdis, 'same');\n        [~, alpha_tmp_1] = gaussian_para_esti(structdis_diff_1(:));%16\n        feat = [feat alpha_tmp_1];\n    else\n        im = Gmag;\n        shifts = [0 1;1 0 ; 1 1; -1 1];\n        \n        mu = filter2(window, im, 'same');\n        mu_sq = mu.*mu;\n        sigma = sqrt(abs(filter2(window, im.*im, 'same') - mu_sq));\n        structdis = (im-mu)./(sigma+1);\n        [sigma_tmp, ~] = gaussian_para_esti(structdis(:));\n        feat = [feat sigma_tmp]; %3 \n        \n        for itr_shift = 1:4\n            structdis_shift_tmp = circshift(structdis, shifts(itr_shift,:));\n            if itr_shift == 3\n                structdis_diff = structdis - structdis_shift_tmp;\n                [~, alpha_tmp] = gaussian_para_esti(structdis_diff(:));\n                feat = [feat alpha_tmp]; % 10\n            elseif itr_shift == 4\n                structdis_diff = structdis - structdis_shift_tmp;\n                [~, alpha_tmp] = gaussian_para_esti(structdis_diff(:));\n                feat = [feat alpha_tmp]; % 12\n            end\n            structdis_shift(itr_shift) = {[structdis_shift_tmp]};\n        end\n        win_tmp_1 = [0 1 0; -1 0 -1; 0 1 0;];\n        structdis_diff_1 = filter2(win_tmp_1, structdis, 'same');\n        [sigma_tmp_1, ~] = gaussian_para_esti(structdis_diff_1(:));%15\n        feat = [feat sigma_tmp_1];\n    end\n    Gmag = imresize(Gmag, 0.5);\nend\nend\n\n%% compute_friquee_luma_features\nfunction feat = compute_friquee_luma_features(imgray)\n% # 5(std), 8(std), 27(std), 32(std), 58, 62(std), 66, 68(std), 70(both), 71, 72(std) \n% 1:31 32:62\n\n    scalenum=2;\n    imGray1=imgray;\n    \n    % The array that aggregates all the features from different feature\n    % maps.\n    feat = [];\n    %% 1 scale 31 features x2 = 62\n    %% scale1: 5, 8, 27\n    [structdis,~] = divisiveNormalization(imgray);\n    shifts = [ 0 1;1 0];\n    for itr_shift =1:2\n        % Construct the product neighborhood map.\n        shifted_structdis = circshift(structdis,shifts(itr_shift,:));\n        pair = structdis(:).*shifted_structdis(:); % Element wise product.\n        if itr_shift == 1\n            feat = [feat skewness(pair(:))]; %5\n        else\n                    % Fit an AGGD and extract its parameters.\n            [alpha, leftstd, rightstd] = estimateaggdparam(pair);\n            const = (sqrt(gamma(1/alpha))/sqrt(gamma(3/alpha)));\n            meanparam = (rightstd-leftstd)*(gamma(2/alpha)/gamma(1/alpha))*const;\n            feat = [feat meanparam]; %8\n        end\n    end\n    %Extract the sigma field from the image.\n    sigmaMap = computeSigmaMap(imgray);\n    \n    % Compute kurtosis, skewness and average of the sigma field\n    feat = [feat mean2(sigmaMap)];%27\n    \n    %% sclae2: 32,58,62 - 31 = 1, 27,31\n    imgray = imresize(imgray,0.5);  \n    shifts = [ 0 1];\n    for itr_shift =1:1\n        % Construct the product neighborhood map.\n        shifted_structdis = circshift(structdis,shifts(itr_shift,:));\n        pair = structdis(:).*shifted_structdis(:); % Element wise product.\n        \n        % Fit an AGGD and extract its parameters.\n        [alpha, ~, ~] = estimateaggdparam(pair);\n%         const = (sqrt(gamma(1/alpha))/sqrt(gamma(3/alpha)));\n%         meanparam = (rightstd-leftstd)*(gamma(2/alpha)/gamma(1/alpha))*const;\n        feat = [feat alpha];%% 1\n    end\n     %Extract the sigma field from the image.\n    sigmaMap = computeSigmaMap(imgray);\n    \n    % Compute kurtosis, skewness and average of the sigma field\n    feat = [feat mean2(sigmaMap)];%27\n    \n      % Apply DNT\n    [imDivNorm,~] = divisiveNormalization(imgray);\n    feat = [feat skewness(imDivNorm(:))]; %31\n\n    %% \n    imgray=imGray1;\n    %% Original Scales\n    \n    % 63:64\n    % Features from the Yellow color channel map.\n%     yFeat=yellowColorChannelMap(rgb);\n%     feat = [feat yFeat];\n    \n    % 65:70 --> 63:68\n    % Features from the Difference of Gaussian (DoG) of Sigma Map \n    \n    %Get the sigma map of the image.\n    sigmaMap = computeSigmaMap(imgray);\n    \n    % Construct two Gaussian windows where sig2 = 1.5*sig1;\n    k=1.5;\n    \n    window1 = fspecial('gaussian',7,7/6);\n    window1 = window1/sum(sum(window1));\n\n    window2 = fspecial('gaussian',7,7*k/6);\n    window2 = window2/sum(sum(window2));\n    \n    %Compute DOG of the sigmaMap\n    DoGSigma= filter2((window1-window2), sigmaMap, 'same');\n    \n    %Compute the sigmaMap of DoGSigma\n    DoGSigma1 = computeSigmaMap(DoGSigma);\n    \n    %DNT of DOG of sigma.\n    divNormDoGSigma = divisiveNormalization(DoGSigma);\n\n    %shape, variance, skewness.\n    [~,lsigma] = estimateggdparam(divNormDoGSigma(:));\n    \n    % Apply DNT on DoGSigma1\n    divNormDoGSigma1 = divisiveNormalization(DoGSigma1);\n    \n    feat = [feat lsigma kurtosis(divNormDoGSigma(:)) kurtosis(divNormDoGSigma1(:))];\n    \n    % 71:74 --> 69:72\n    % Laplacian of the Luminance Map\n    addpath(genpath(fullfile('include', 'matlabPyrTools')));\n    \n    % Extract the first laplacian of the image.\n    [pyr pind] = buildLpyr(imgray,4);\n    res =  pyrBand(pyr, pind, 1);\n    \n    % Fit a GGD to the laplacian image.\n    [alpha, sigma] = estimateggdparam(res(:));\n    \n    \n    feat = [feat alpha sigma];\n%     feat = feat([5,8,27,32,58,62,64,66,68,69,70]);\nend\n\n%% compute_friquee_chroma_features\nfunction feat = compute_friquee_chroma_features(imyuv)\n%% # 4  7(std) 15   24   26   47   60   62   72   73   79\n    rgb = ycbcr2rgb(uint8(imyuv));\n%     lab=rgb2lab(rgb);\n    colorTransform = makecform('srgb2lab');\n    lab = applycform(rgb, colorTransform);\n\n    \n    % Get the A and B components of the LAB color space.\n    A = double(lab(:,:,2));\n    B = double(lab(:,:,3));\n    \n    % Compute the chroma map.\n    imChroma = sqrt(A.*A + B.*B);\n    \n    % Initializations\n    scalenum=2;   \n    imChroma1=imChroma;\n    \n    % The array that aggregates all the features from different feature\n    % maps.\n    feat = [];\n    \n    %% scale1: 4 7 15 24\n    % Applying divisive normalization operation on the given gray scale image.\n    [structdis,~] = divisiveNormalization(imChroma);\n    \n    % The four neighborhood maps that would be constructed [1]\n    shifts = [ 0 1;1 0 ; 1 1; -1 1];\n    for itr_shift =1:4\n        % Construct the product neighborhood map.\n        shifted_structdis = circshift(structdis,shifts(itr_shift,:));\n        pair = structdis(:).*shifted_structdis(:); % Element wise product.\n        \n        if itr_shift ==1\n        % Fit an AGGD and extract its parameters.\n        [~, ~, rightstd] = estimateaggdparam(pair);\n        feat = [feat rightstd^2];%4\n        elseif itr_shift ==2\n        % Fit an AGGD and extract its parameters.\n        [alpha, ~, ~] = estimateaggdparam(pair);\n        feat = [feat alpha];%7\n        elseif itr_shift ==3\n        [~, leftstd, ~] = estimateaggdparam(pair);\n        feat = [feat  leftstd^2];%15\n        elseif itr_shift ==4\n          feat = [feat kurtosis(pair(:))];%24\n        end\n    end\n    sigmaMap = computeSigmaMap(imChroma);\n    feat = [feat skewness(sigmaMap(:))];%26\n    %% scale2:   47   60   62 - 35 = 12    25    27\n    imChroma = imresize(imChroma,0.5);\n\n    % Applying divisive normalization operation on the given gray scale image.\n    [structdis,~] = divisiveNormalization(imChroma);\n\n    shifts = [1 0];\n\n    % Construct the product neighborhood map.\n    shifted_structdis = circshift(structdis,shifts);\n    pair = structdis(:).*shifted_structdis(:); % Element wise product.\n\n    feat = [feat kurtosis(pair(:))]; %12\n\n    sigmaMap = computeSigmaMap(imChroma);\n    feat = [feat kurtosis(sigmaMap(:)) mean2(sigmaMap)]; %25 27\n    % Some features are computedcccccccc at multiple scales %% 1 scale 35 features x2 =\n    % 70\n    \n    imChroma=imChroma1;\n    \n    %Get the sigma map of the image.\n    sigmaMap = computeSigmaMap(imChroma);\n        % Construct two Gaussian windows where sig2 = 1.5*sig1;\n    k=1.5;\n    \n    window1 = fspecial('gaussian',7,7/6);\n    window1 = window1/sum(sum(window1));\n\n    window2 = fspecial('gaussian',7,7*k/6);\n    window2 = window2/sum(sum(window2));\n     %Compute DOG of the sigmaMap\n    DoGSigma= filter2((window1-window2), sigmaMap, 'same');\n    %DNT of DOG of sigma.\n    divNormDoGSigma = divisiveNormalization(DoGSigma);\n    %shape, variance, skewness.\n    [~,lsigma] = estimateggdparam(divNormDoGSigma(:));\n    feat = [feat lsigma skewness(divNormDoGSigma(:))];% 72 73\n    \n    % Laplacian of the Chroma Map\n    addpath(genpath(fullfile('include', 'matlabPyrTools')));\n\n    [pyr pind] = buildLpyr(imChroma,4);\n    res =  pyrBand(pyr, pind, 1);\n    feat = [feat skewness(res(:))];%79\nend\n\n%% compute_friquee_lms_features\nfunction feat = compute_friquee_lms_features(imyuv)\n    % compute FRIQUEE LMS features # 52 \n    rgb = ycbcr2rgb(uint8(imyuv));\n    lms = (colorspace('RGB->CAT02 LMS',rgb));\n     % Get the M and S components from the LMS color space.\n%     LM = double(lms(:,:,2));\n    LS = double(lms(:,:,3));\n    %FRIQUEE features from the LMS color space.\n%     fM = friqueeMS(LM);%1:32\n%     fS = friqueeMS(LS);%33:64\n    LS = imresize(LS,0.5);\n    sigmaMap = computeSigmaMap(LS);\n    dnSigmaFeat = debiasedNormalizedFeats(sigmaMap);%8:11 19:20:21\n%     featOpp = lmsColorOpponentFeats(lms); % Color opponency features.\n    feat = dnSigmaFeat(2);\nend\n\n%% compute_tlvqm_lcf_features\nfunction features = compute_tlvqm_lcf_features(this_fr, prev_fr, next_fr)\n % compute TLVQM LCF features # 1 5(both) 12 16 18 19(std) 22(std)\n    [height,width,~] = size(this_fr);\n    % Initialize parameters \n    bl_size = floor(width/40);  \n    src_win = floor(width/40);\n    \n    % The following computations are done with reduced resolution\n    this_fr = imresize(this_fr,0.5); \n    prev_fr = imresize(prev_fr,0.5);  \n    next_fr = imresize(next_fr,0.5);     \n    [height,width,~] = size(this_fr);   \n    this_Y = this_fr(:,:,1);\n    prev_Y = prev_fr(:,:,1);\n    next_Y = next_fr(:,:,1);\n    this_fr = ycbcr2rgb(this_fr);    \n    \n    % Apply Sobel filter to the frames\n    H = [-1 -2 -1; 0 0 0; 1 2 1]./8;\n    sob_h_this = imfilter(this_Y,H'); \n    sob_v_this = imfilter(this_Y,H);\n    \n    % Reset edge pixels in the Sobeled frames\n    sob_h_this(1:4,1:width)=0;\n    sob_h_this(height-3:height,1:width)=0;\n    sob_h_this(1:height,1:4)=0;\n    sob_h_this(1:height,width-3:width)=0;\n    sob_v_this(1:4,1:width)=0;\n    sob_v_this(height-3:height,1:width)=0;\n    sob_v_this(1:height,1:4)=0;\n    sob_v_this(1:height,width-3:width)=0;\n          \n    sob_tot = sqrt(sob_v_this.^2+sob_h_this.^2);   \n    sob_h_prev = imfilter(prev_Y,H');\n    sob_v_prev = imfilter(prev_Y,H); \n    sob_h_next = imfilter(next_Y,H');\n    sob_v_next = imfilter(next_Y,H);     \n    \n    H1 = [1 1 1 1 1;1 1 1 1 1;-2 -2 0 1 1;-2 -2 -2 1 1;-2 -2 -2 1 1]./32;\n    H2 = [-2 -2 -2 1 1;-2 -2 -2 1 1;-2 -2 0 1 1;1 1 1 1 1;1 1 1 1 1]./32;\n    H3 = [1 1 -2 -2 -2;1 1 -2 -2 -2;1 1 0 -2 -2;1 1 1 1 1;1 1 1 1 1]./32;\n    H4 = [1 1 1 1 1;1 1 1 1 1;1 1 0 -2 -2;1 1 -2 -2 -2;1 1 -2 -2 -2]./32;\n    \n    corner_avg(:,:,1) = abs(imfilter(this_Y, H1));\n    corner_avg(:,:,2) = abs(imfilter(this_Y, H2));\n    corner_avg(:,:,3) = abs(imfilter(this_Y, H3));\n    corner_avg(:,:,4) = abs(imfilter(this_Y, H4));   \n    corner_max = max(corner_avg,[],3);\n    corner_this = corner_max-min(corner_avg,[],3); \n    \n    mot_threshold = 0.01; \n    \n%     cor_max = sort(corner_max(:),'ascend');\n%     glob_blockiness = 0;\n%     if std2(cor_max(1:floor(0.99*end)))>0\n%         glob_blockiness = 0.5*((mean(cor_max(1:floor(0.99*end)))/ ...\n%                           std2(cor_max(1:floor(0.99*end))))^2);\n%     end\n       \n    % Reset edge pixels in the corner point filtered frame\n    corner_this(1:src_win+3,1:width)=0;\n    corner_this(height-src_win-2:height,1:width)=0;\n    corner_this(1:height,1:src_win+3)=0;\n    corner_this(1:height,width-src_win-2:width)=0;\n                                              \n    corner_this_copy = corner_this(:);   \n    key_pix = zeros((height-6)*(width-6),2);\n    n_key_pix = 0;\n    \n    im_y_vec = mod(0:width*height, height)+1;\n    im_x_vec = floor((0:width*height-1)/height)+1;\n    sob_this_cp = corner_this_copy(corner_this_copy>mot_threshold);\n    im_y_vec = im_y_vec(corner_this_copy>mot_threshold);\n    im_x_vec = im_x_vec(corner_this_copy>mot_threshold);\n    \n    % In the following loop, find the key pixels\n    [mx,idx] = max(sob_this_cp);\n    if ~isempty(idx)\n        while mx>mot_threshold\n            i = im_y_vec(idx(1));\n            j = im_x_vec(idx(1));\n\n            n_key_pix = n_key_pix + 1;\n            key_pix(n_key_pix,:) = [i j];\n\n            idx_remove = find(im_y_vec>=i-floor(bl_size) & ...\n                              im_y_vec<=i+floor(bl_size) & ...\n                              im_x_vec>=j-floor(bl_size) & ...\n                              im_x_vec<=j+floor(bl_size));\n            sob_this_cp(idx_remove)=[];\n            im_y_vec(idx_remove)=[];\n            im_x_vec(idx_remove)=[];\n\n            [mx,idx] = max(sob_this_cp);\n        end\n    end\n    key_pix=key_pix(1:n_key_pix,:);\n       \n    non_mot_area = ones(height, width);\n    \n    num_mot_points = 0;\n    max_mot_points = (height/bl_size)*(width/bl_size);\n    \n    %tic\n    % In the following loop, find the motion vectors for each key pixel\n    motion_vec = [];\n    \n    distance_matrix = ones(2*src_win+1);\n    for i=1:2*src_win+1\n        for j=1:2*src_win+1\n            distance_matrix(i,j) = ...\n                sqrt((1+src_win-i).^2+(1+src_win-j).^2)/sqrt(2*src_win^2);\n        end\n    end\n    distances = distance_matrix(:);\n    \n    uncertain = 0;\n\n    % Loop through the key pixels\n    for z = 1:n_key_pix\n\n        tar_y = key_pix(z,1);\n        tar_x = key_pix(z,2);\n        match_y_bw = tar_y;\n        match_x_bw = tar_x;\n        match_y_fw = tar_y;\n        match_x_fw = tar_x;\n        \n        surr_win_v_prev = sob_v_prev(tar_y-src_win-2:tar_y+src_win+2, ...\n                                     tar_x-src_win-2:tar_x+src_win+2);\n        surr_win_h_prev = sob_h_prev(tar_y-src_win-2:tar_y+src_win+2, ...\n                                     tar_x-src_win-2:tar_x+src_win+2);\n        diff_win_prev = (sob_v_this(tar_y, tar_x)-surr_win_v_prev).^2 + ...\n                        (sob_h_this(tar_y, tar_x)-surr_win_h_prev).^2;\n                    \n        surr_win_v_next = sob_v_next(tar_y-src_win-2:tar_y+src_win+2, ...\n                                     tar_x-src_win-2:tar_x+src_win+2);\n        surr_win_h_next = sob_h_next(tar_y-src_win-2:tar_y+src_win+2, ...\n                                     tar_x-src_win-2:tar_x+src_win+2);\n        diff_win_next = (sob_v_this(tar_y, tar_x)-surr_win_v_next).^2 + ...\n                        (sob_h_this(tar_y, tar_x)-surr_win_h_next).^2;\n                    \n        for i=-1:1\n            for j=-1:1\n                if i~=0 || j~=0\n                    diff_win_prev(3:end-2,3:end-2) = ...\n                        diff_win_prev(3:end-2,3:end-2) + ...\n                        (sob_v_this(tar_y+i, tar_x+j)- ...\n                          surr_win_v_prev(3+i:end-2+i,3+j:end-2+j)).^2+ ...\n                        (sob_h_this(tar_y+i, tar_x+j)- ...\n                          surr_win_h_prev(3+i:end-2+i,3+j:end-2+j)).^2;   \n                    diff_win_next(3:end-2,3:end-2) = ...\n                        diff_win_next(3:end-2,3:end-2) + ...\n                        (sob_v_this(tar_y+i, tar_x+j)- ...\n                          surr_win_v_next(3+i:end-2+i,3+j:end-2+j)).^2+...\n                        (sob_h_this(tar_y+i, tar_x+j)- ...\n                        surr_win_h_next(3+i:end-2+i,3+j:end-2+j)).^2;   \n                end\n            end\n        end\n        diff_win_prev = diff_win_prev(3:end-2,3:end-2);\n        diff_win_next = diff_win_next(3:end-2,3:end-2);\n                    \n        orig_diff_bw = diff_win_prev(1+src_win,1+src_win);\n        orig_diff_fw = diff_win_next(1+src_win,1+src_win);\n \n        diff_bw = diff_win_prev(1+src_win,1+src_win);   \n        if orig_diff_bw>0.005\n            [sorted,idx] = sort(diff_win_prev(:),'ascend');\n            min_diff = orig_diff_bw;\n            if length(sorted)>=2\n                if sorted(1)<=0.8*sorted(2) || ...\n                   distances(idx(1))<distances(idx(2))\n                    min_diff = sorted(1);\n                else\n                    [idx,~] = find(0.8.*diff_win_prev(:)<=sorted(1));\n                    [~,idx2] = sort(distances(idx),'ascend');\n                    if diff_win_next(idx(idx2(1)))<1.1*sorted(1)\n                        min_diff = diff_win_prev(idx(idx2(1)));\n                    elseif sorted(1)<diff_bw*0.9\n                        min_diff = sorted(1);\n                    end\n                    uncertain = uncertain + 1;\n                end\n                if min_diff*1.01<orig_diff_bw\n                    [y,x] = find(diff_win_prev==min_diff);\n                    match_y_bw = tar_y+y(1)-src_win-1;\n                    match_x_bw = tar_x+x(1)-src_win-1;        \n                    diff_bw = diff_win_prev(y(1),x(1));\n                end\n            end\n        end\n        \n        diff_fw = diff_win_next(1+src_win,1+src_win);  \n        if orig_diff_fw>0.005\n            [sorted,idx] = sort(diff_win_next(:),'ascend');\n            min_diff = orig_diff_fw;\n            if length(sorted)>=2\n                if sorted(1)<0.8*sorted(2) || ...\n                   distances(idx(1))<distances(idx(2))\n                    min_diff = sorted(1);\n                else                \n                    [idx,~] = find(0.8.*diff_win_next(:)<=sorted(1));\n                    [~,idx2] = sort(distances(idx),'ascend');\n                    if diff_win_next(idx(idx2(1)))<1.1*sorted(1)\n                        min_diff = diff_win_next(idx(idx2(1)));\n                    elseif sorted(1)<diff_fw*0.9\n                        min_diff = sorted(1);\n                    end\n                    uncertain = uncertain + 1;\n                end\n                if min_diff*1.01<orig_diff_fw\n                    [y,x] = find(diff_win_next==min_diff);\n                    match_y_fw = tar_y+y(1)-src_win-1;\n                    match_x_fw = tar_x+x(1)-src_win-1;        \n                    diff_fw = diff_win_next(y(1),x(1));\n                end  \n            end\n        end\n             \n        % Add motion vector to the list of motion vectors\n        if (orig_diff_bw > diff_bw*1.01 && ...\n                (tar_y ~= match_y_bw || tar_x ~= match_x_bw)) || ...\n           (orig_diff_fw > diff_fw*1.01 && ...\n                (tar_y ~= match_y_fw || tar_x ~= match_x_fw))     \n\n            non_mot_area(max(1,tar_y-bl_size):min(height,tar_y+bl_size),...\n                max(1,tar_x-bl_size):min(width,tar_x+bl_size))=0;\n            non_mot_area(max(1,match_y_bw-bl_size): ...\n                min(height,match_y_bw+bl_size),...\n                max(1,match_x_bw-bl_size):...\n                min(width,match_x_bw+bl_size)) = 0;\n            non_mot_area(max(1,match_y_fw-bl_size):...\n                min(height,match_y_fw+bl_size),...\n                max(1,match_x_fw-bl_size):...\n                min(width,match_x_fw+bl_size)) = 0;\n        end\n        \n        num_mot_points = num_mot_points + 1;\n        motion_vec = [motion_vec; ...\n                      tar_y-match_y_bw tar_x-match_x_bw ...\n                      match_y_fw-tar_y match_x_fw-tar_x ...\n                      tar_y tar_x ...\n                      orig_diff_bw diff_bw ...\n                      orig_diff_fw diff_fw];\n    end\n    %toc \n % Compute motion point related statistics\n%     motion_uncertainty = 0.5*uncertain/max_mot_points;\n%     motion_density = 0;\n    motion_intensity = 0;\n%     std_mot_intensity = 0;\n%     avg_mot_pos = 0;\n%     avg_mot_sprd = 0;\n%     mot_pred_acc = 0;\n    mot_y = 0.5;\n%     mot_x = 0.5;\n    jerkiness = 0;\n%     jerk_cons = 0;\n    motion_vec_bg = [];\n    num_bg_mot_points = 0;\n    if num_mot_points>0\n%         motion_density = num_mot_points/(width*height/bl_size^2);    \n        mot_intensity_vec = sqrt(((motion_vec(:,1)./src_win).^2 + ...\n                                  (motion_vec(:,2)./src_win).^2 + ...\n                                  (motion_vec(:,3)./src_win).^2 + ...\n                                  (motion_vec(:,4)./src_win).^2)./4.0);\n        sum_mot_int = sum(mot_intensity_vec);\n        motion_intensity = (sum(mot_intensity_vec)/max_mot_points)^0.25;\n%         std_mot_intensity = std(mot_intensity_vec);\n        \n        if sum_mot_int>0\n            % Compute motion position in relation with the screen midpoint\n%             avg_motp_y = sum(mot_intensity_vec.*motion_vec(:,5))/...\n%                            sum_mot_int;\n%             std_motp_y = sqrt(sum(mot_intensity_vec.*...\n%                            (motion_vec(:,5)-avg_motp_y).^2)/sum_mot_int);\n%             avg_mot_pos_y = (avg_motp_y-height/2)/(height/2);\n%             sprd_mot_pos_y = std_motp_y/height;  \n%             avg_motp_x = sum(mot_intensity_vec.*motion_vec(:,6))/...\n%                            sum_mot_int;\n%             std_motp_x = sqrt(sum(mot_intensity_vec.*...\n%                            (motion_vec(:,6)-avg_motp_x).^2)/sum_mot_int);\n%             avg_mot_pos_x = (avg_motp_x-width/2)/(width/2);\n%             sprd_mot_pos_x = std_motp_x/width;\n% \n%             avg_mot_pos = sqrt(avg_mot_pos_y^2+avg_mot_pos_x^2);  \n%             avg_mot_sprd = sqrt(sprd_mot_pos_y^2+sprd_mot_pos_x^2);\n\n            % Mean motion along x and y axis\n            mot_y = mean(0.25.*(motion_vec(:,1)+motion_vec(:,3))./ ...\n                      src_win+0.5);    \n%             mot_x = mean(0.25.*(motion_vec(:,2)+motion_vec(:,4))./ ...\n%                       src_win+0.5);\n\n            % Average motion prediction improvement\n%             mot_pred_acc_bw = mean(motion_vec(:,7)-motion_vec(:,8));\n%             mot_pred_acc_fw = mean(motion_vec(:,9)-motion_vec(:,10));\n%             mot_pred_acc = 0.5*(mot_pred_acc_bw+mot_pred_acc_fw).^0.5;\n\n            % Motion jerkiness\n            mot_y_diff = 0.5.*(motion_vec(:,1)'-motion_vec(:,3)')./src_win;\n            mot_x_diff = 0.5.*(motion_vec(:,2)'-motion_vec(:,4)')./src_win;\n            mot_diff = sqrt(mot_y_diff.^2+mot_x_diff.^2);\n            jerkiness = mean(mot_diff.^0.5);        \n%             jerk_cons = std(mot_diff.^0.5);\n        end\n        \n        avg_mot_x = mean(0.5.*motion_vec(:,2)+0.5.*motion_vec(:,4));\n        avg_mot_y = mean(0.5.*motion_vec(:,1)+0.5.*motion_vec(:,3));\n        std_mot_x = std(0.5.*motion_vec(:,2)+0.5.*motion_vec(:,4));\n        std_mot_y = std(0.5.*motion_vec(:,1)+0.5.*motion_vec(:,3));\n\n        for z=1:num_mot_points\n            mot_x_this = 0.5*motion_vec(z,2)+0.5*motion_vec(z,4);\n            mot_y_this = 0.5*motion_vec(z,1)+0.5*motion_vec(z,3);\n            if mot_x_this > avg_mot_x-std_mot_x && ...\n               mot_x_this < avg_mot_x+std_mot_x && ...\n               mot_y_this > avg_mot_y-std_mot_y && ...\n               mot_y_this < avg_mot_y+std_mot_y\n\n                num_bg_mot_points = num_bg_mot_points + 1;\n                motion_vec_bg = [motion_vec_bg; motion_vec(z,:)];\n            end\n        end\n    end\n % Compute motion point related statistics\n%     egomotion_density = 0;\n%     egomotion_intensity = 0;\n    std_egomot_intensity = 0;\n%     avg_egomot_pos = 0;\n%     avg_egomot_sprd = 0;\n%     egomot_pred_acc = 0;\n%     mot_y_bg = 0.5;\n%     mot_x_bg = 0.5;\n    if num_bg_mot_points>0\n%         egomotion_density = num_bg_mot_points/(width*height/bl_size^2);    \n        bg_mot_intensity_vec = sqrt(((motion_vec_bg(:,1)./src_win).^2 + ...\n                                     (motion_vec_bg(:,2)./src_win).^2 + ...\n                                     (motion_vec_bg(:,3)./src_win).^2 + ...\n                                     (motion_vec_bg(:,4)./src_win).^2)  ...\n                                      ./4.0);\n%         sum_bg_mot_int = sum(bg_mot_intensity_vec);\n%         egomotion_intensity = (sum(bg_mot_intensity_vec)/...\n%                                 max_mot_points)^0.25;\n        std_egomot_intensity = std(bg_mot_intensity_vec);\n        \n        % Compute motion position in relation with the screen midpoint\n%         if sum_bg_mot_int>0\n%             avg_motp_y = sum(bg_mot_intensity_vec.*motion_vec_bg(:,5))/...\n%                            sum_bg_mot_int;\n%             std_motp_y = sqrt(sum(bg_mot_intensity_vec.*...\n%                            (motion_vec_bg(:,5)-avg_motp_y).^2)/...\n%                               sum_bg_mot_int);\n%             avg_mot_pos_y = (avg_motp_y-height/2)/(height/2);\n%             sprd_mot_pos_y = std_motp_y/height;  \n%             avg_motp_x = sum(bg_mot_intensity_vec.*motion_vec_bg(:,6))/...\n%                            sum_bg_mot_int;\n%             std_motp_x = sqrt(sum(bg_mot_intensity_vec.*...\n%                            (motion_vec_bg(:,6)-avg_motp_x).^2)/...\n%                            sum_bg_mot_int);\n%             avg_mot_pos_x = (avg_motp_x-width/2)/(width/2);\n%             sprd_mot_pos_x = std_motp_x/width;\n% \n%             avg_egomot_pos = sqrt(avg_mot_pos_y^2+avg_mot_pos_x^2);  \n%             avg_egomot_sprd = sqrt(sprd_mot_pos_y^2+sprd_mot_pos_x^2);\n\n            % Average egomotion prediction improvement\n%             mot_pred_acc_bw = mean(motion_vec_bg(:,7)-motion_vec_bg(:,8));\n%             mot_pred_acc_fw = mean(motion_vec_bg(:,9)-motion_vec_bg(:,10));\n%             egomot_pred_acc = 0.5*(mot_pred_acc_bw+mot_pred_acc_fw).^0.5;\n\n%             mot_y_bg = mean(0.25.*(motion_vec_bg(:,1)+...\n%                                    motion_vec_bg(:,3))./src_win+0.5);    \n%             mot_x_bg = mean(0.25.*(motion_vec_bg(:,2)+...\n%                                    motion_vec_bg(:,4))./src_win+0.5);        \n%         end\n    end\n\n%     mot_size = sum(sum(1-non_mot_area));  \n    non_mot_size = sum(sum(non_mot_area));  \n%  static_area_flicker = 0;\n    static_area_flicker_std = 0;\n    if non_mot_size>0\n        % Sum of the pixel differences in the static area\n        static_area_flicker_bw = sum(non_mot_area(:) .* ...\n                                 abs(this_Y(:)-prev_Y(:)))/non_mot_size;\n        static_area_flicker_fw = sum(non_mot_area(:) .* ...\n                                 abs(this_Y(:)-next_Y(:)))/non_mot_size;\n        static_area_flicker = 0.5*(static_area_flicker_bw + ...\n                                   static_area_flicker_fw);\n        % Variance of pixel differences in the static area\n        st_diff_bw = abs(this_Y(:)-prev_Y(:));\n        st_diff_fw = abs(this_Y(:)-next_Y(:));\n        static_area_flicker_std = sum(non_mot_area(:)' .* ...\n                                  abs(max([st_diff_bw'; st_diff_fw']) - ...\n                                  static_area_flicker))/non_mot_size;\n    end\n    \n    % Spatial activity in the static area\n    si = std2(sob_tot).^0.25;\n    \n    %[blur glob_blockiness si]\n    \n    % Temporal activity standard deviation in the static area\n    ti_prev = mean(abs(this_Y(:)-prev_Y(:)));\n    ti_next = mean(abs(this_Y(:)-next_Y(:)));\n    ti_mean = mean([ti_prev ti_next]).^0.25;\n      \n    % Normalize static area size\n%     mot_size = mot_size / (width*height);\n    features = [motion_intensity,  ...\n                std_egomot_intensity, ...\n                si, ...\n                jerkiness, ...\n                ti_mean, ...\n                mot_y, ...\n                static_area_flicker_std];\nend\n\n%% compute_tlvqm_hcf_features\nfunction features = compute_tlvqm_hcf_features(imyuv)\n% compute TLVQM HCF features # 1 2    17    22    24    30\n% Initializations\n    mono_image = imyuv(:,:,1);\n    image = ycbcr2rgb(imyuv);\n    lab_image = rgb2lab(image);\n    [height,width,depth] = size(image);\n        \n    % Make Sobeled image\n    mask = zeros(height,width);\n    mask(2:end-1,2:end-1)=1;\n    H = [1 2 1; 0 0 0; -1 -2 -1]./8;\n        \n    % Make Sobeled image in CIELAB color space\n    sob_image_lab_x = (imfilter(lab_image(:,:,1)./100.0,H).^2 + ...\n                       imfilter(lab_image(:,:,2)./50.0,H).^2 + ...\n                       imfilter(lab_image(:,:,3)./50.0,H).^2).*mask;\n    sob_image_lab_y = (imfilter(lab_image(:,:,1)./100.0,H').^2 + ...\n                       imfilter(lab_image(:,:,2)./50.0,H').^2 + ...\n                       imfilter(lab_image(:,:,3)./50.0,H').^2).*mask;\n    sob_image = sqrt(sob_image_lab_x+sob_image_lab_y);\n\n    % Compute fetures for different feature groups\n%     [a,b,sat_image1] = compute_saturation(mono_image,1);\n% %     sat_bright = [a];\n%     [a,b,sat_image2] = compute_saturation(mono_image,0);\n% %     sat_dark = [a b];\n%     sat_image = max(sat_image1, sat_image2);\n%     saturation_ftr = [sat_bright sat_dark]; % 5:8\n%     saturation_ftr = sat_bright;\n    spatial_ftr = spatial_activity_features(sob_image, []);% 1:4\n% %     noisiness_ftr = noise_features(mono_image, sat_image, lab_image); % 9:11\n%     blockiness_ftr = blockiness_features(sob_image_lab_x.^0.5, ...\n%                                          sob_image_lab_y.^0.5); % 12:14\n    contrast_color_ftr = contrast_chroma_features(lab_image, []); % 15:18\n%     dct_ftr = dct_features(mono_image); % 19:21\n    sharpness_ftr = sharpness_features(sob_image); % 22:30\n\n    % Make the HC feature vector\n    features = [spatial_ftr   ...\n                contrast_color_ftr   ...\n                sharpness_ftr];\nend\n\n% This function computes the saturation (bright or dark)\nfunction [len,num,segs] = compute_saturation(image, is_bright)\n\n    [height,width] = size(image);\n\n    lens = [];\n    num = 0;    \n    \n    segs = zeros(height,width);\n    \n    if (is_bright==1 && max(max(image))>0.9) || ...\n       (is_bright==0 && min(min(image))<0.1)     \n    \n        segs = seg_loop(image,segs,3,3,0.05, is_bright);\n        for i=1:max(max(segs))\n            len = length(find(segs==i));\n            if len<50\n                segs(find(segs==i))=0;\n            else\n                lens = [lens len];\n                num = num + 1;\n            end\n        end \n        segs(find(segs>0))=1;\n    end\n    \n    len = sum(lens)/(width*height);\n    if num > 0\n        num = len / num;\n    end\n\nend\n\n% This function is used for segmentation by measure_saturation\nfunction segim = seg_loop(image, segs, wh, ww, interval, is_bright)\n\n    [height,width] = size(image);\n\n    segim = segs;\n    \n    maxi = max(max(image));\n    mini = min(min(image));\n    \n    for i=1:height-wh+1\n        for j=1:width-ww+1\n            if (is_bright == 1 && ...\n              min(min(image(i:i+wh-1,j:j+ww-1)))>maxi-interval) || ...\n              (is_bright == 0 && ...\n              max(max(image(i:i+wh-1,j:j+ww-1)))<mini+interval)\n            \n                maxsg = max(max(segim(i:i+wh-1,j:j+ww-1)));\n                if maxsg>0\n                    segs_temp = reshape(segim(i:i+wh-1,j:j+ww-1),wh*ww,1);\n                    minsg=min(segs_temp(find(segs_temp>0)));\n                    segim(i:i+wh-1,j:j+ww-1)=minsg;\n                    if minsg<maxsg\n                        segim(find(segim==maxsg))=minsg;\n                    end\n                else\n                    segim(i:i+wh-1,j:j+ww-1)=max(max(segim(:,:)))+1;\n                end\n            end\n        end\n    end\n\nend\n\n% This function is used to compute noise related features\nfunction out = noise_features(mono_image, sat_im, lab_image)\n    \n    [height,width] = size(mono_image);\n\n    new_im = zeros(height, width, 3);\n\n    nonsat_pix = 0;\n    noise_pix = 0;\n    noise_int = [];\n    \n    % Loop through pixels to find noise pixels\n    for i=5:height-4\n        for j=5:width-4\n            if sat_im(i,j)==0\n                surr_pix = mono_image(i-2:i+2,j-2:j+2);\n                surr_pix = surr_pix(:);\n                surr_pix = [surr_pix(1:12); surr_pix(14:25)];\n                if (mono_image(i,j)>max(surr_pix) || ...\n                    mono_image(i,j)<min(surr_pix))\n                    surr_pix = mono_image(i-4:i+4,j-4:j+4);\n                    if std(surr_pix)<0.05\n                        new_im(i,j,2) = 1;\n                        pix_diff = sqrt( ...\n                            (mean(lab_image(i-3:i+3,j-3:j+3,1))-...\n                                 lab_image(i,j,1)).^2 + ...\n                            (mean(lab_image(i-3:i+3,j-3:j+3,2))-...\n                                 lab_image(i,j,2)).^2 + ...\n                            (mean(lab_image(i-3:i+3,j-3:j+3,3))-...\n                                  lab_image(i,j,3)).^2);\n                        noise_int = [noise_int pix_diff/100]; \n                        noise_pix = noise_pix + 1;\n                    end\n                end\n                nonsat_pix = nonsat_pix + 1;\n            end\n        end\n    end\n\n    a = 0;\n    b = 0;\n    c = 0;\n    \n    if nonsat_pix > 0 && noise_pix > 0\n        % noise density\n        a = noise_pix / nonsat_pix;\n        b = mean(noise_int);\n        c = std(noise_int);\n    end\n    \n    out = [a b c];\n       \nend\n\n% This function is used to compute spatial activity features\nfunction out = spatial_activity_features(sobel_image, ~)\n    \n%     [height,width] = size(sobel_image);\n%        \n%     sob_dists = zeros(1,height*width);\n%     sob_dists2 = zeros(height*width,2);\n%     sob_str = zeros(1,height*width);\n%     sumstr = 0;\n%     \n%     n = 0;\n%     for i=1:height\n%         for j=1:width\n%             if sat_image(i,j)==0\n%                 if sobel_image(i,j)<0.01\n%                     sobel_image(i,j)=0;\n%                 end\n%                 sumstr = sumstr + sobel_image(i,j);\n%                 if sobel_image(i,j) > 0\n%                     n = n + 1;\n%                     sob_str(n) = sobel_image(i,j);\n%                     sob_dists(n) = sqrt((i/height-0.5)^2+(j/width-0.5)^2);\n%                     sob_dists2(n,1) = i/height-0.5;\n%                     sob_dists2(n,2) = j/width-0.5;                   \n%                 end\n%             end\n%         end\n%     end  \n%     \n%     sob_str = sob_str(1:n);\n%     sob_dists = sob_dists(1:n);\n%     sob_dists2 = sob_dists2(1:n,:);\n\n%     a = 0;\n%     b = 0;\n%     c = 0;\n%     d = 0;\n    \n%     if ~isempty(sob_str)>0\n        a = mean(mean(sobel_image));\n        b = std2(sobel_image);\n%         d = w_std(sob_dists, sob_str);        \n%         mean_y = sum(sob_str'.*sob_dists2(:,1))/sum(sob_str);\n%         mean_x = sum(sob_str'.*sob_dists2(:,2))/sum(sob_str);        \n%         c = sqrt(mean_y^2+mean_x^2);\n%     end\n    \n%     out = [a b c d];\n    out = [ a b];\n\nend\n\n% Function for \"weighted standard deviation\", used by function\n% measure_spatial_activity\nfunction res = w_std(input, weights)\n\n    wg_n = sum(weights);\n    wg_input = input.*weights;\n    wg_mean = mean(input.*weights);\n    \n    res = sqrt(sum((wg_input-wg_mean).^2)/wg_n);\nend\n\n% This function is used to compute blockiness index\nfunction blockiness = blockiness_features(sob_y, sob_x)\n    \n    [height,width] = size(sob_y);\n       \n    hor_tot = zeros(1,height-4);\n    ver_tot = zeros(1,width-4);\n    \n    for i=3:height-2\n        hor_tot(i)=mean(sob_y(i,:)-sob_x(i,:));\n    end\n    for j=3:width-2\n        ver_tot(j)=mean(sob_x(:,j)-sob_y(:,j));\n    end\n    \n    % compute autocorrelations\n    autocr_hor = zeros(1,23);\n    autocr_ver = zeros(1,23);\n    for i=0:22\n        autocr_hor(i+1) = sum(hor_tot(1:end-i).*hor_tot(1+i:end));\n        autocr_ver(i+1) = sum(ver_tot(1:end-i).*ver_tot(1+i:end));\n    end\n    \n    % Find the highest local maximum (other than 0)\n    localpeaks = 0;\n%     peakdist = 0;\n    max_hor = 0;\n    max_ver = 0;\n    min_hor = autocr_hor(1);\n    min_ver = autocr_ver(1);\n    max_hor_diff = 0;\n    max_ver_diff = 0;\n    for i=2:22\n        if autocr_hor(i)>max(autocr_hor(i-1),autocr_hor(i+1))\n            localpeaks = localpeaks+1/42;\n        end\n        if autocr_hor(i)<min(autocr_hor(i-1),autocr_hor(i+1)) && ...\n                autocr_hor(i)<min_hor\n            min_hor = autocr_hor(i);\n        elseif autocr_hor(i)>max(autocr_hor(i-1),autocr_hor(i+1)) && ...\n                autocr_hor(i)-min_hor>max_hor_diff\n            max_hor = autocr_hor(i);\n            max_hor_diff = max_hor-min_hor;\n%             peakdist = (i-1)/21;\n        end\n        if autocr_ver(i)>max(autocr_ver(i-1),autocr_ver(i+1))\n            localpeaks = localpeaks + 1/42;\n        end\n        if autocr_ver(i)<min(autocr_ver(i-1),autocr_ver(i+1)) && ...\n                autocr_ver(i)<min_ver\n            min_ver = autocr_ver(i);\n        elseif autocr_ver(i)>max(autocr_ver(i-1),autocr_ver(i+1)) && ...\n                autocr_ver(i)-min_ver>max_ver_diff\n            max_ver = autocr_ver(i);\n            max_ver_diff = max_ver-min_ver;\n%             peakdist = (i-1)/21;\n        end\n    end\n    \n    a = 0;\n    if autocr_hor(1)>0 && autocr_ver(1)>0\n        if max_hor>0 && max_ver>0\n            a = max((max_hor_diff/autocr_hor(1)), ...\n                             (max_ver_diff/autocr_ver(1)))^0.5;\n        elseif max_hor>0\n            a = (max_hor_diff/autocr_hor(1))^0.5;\n        elseif max_ver>0\n            a = (max_ver_diff/autocr_ver(1))^0.5;\n        end\n    end\n    \n%     b = peakdist;\n%     c = localpeaks;\n    blockiness = a;\nend\n\n% This function is used to compute contrast and chroma related features\nfunction out = contrast_chroma_features(lab_image, ~)\n\n%     a=0;\n%     b=0;\n    c=0;\n%     d=0;\n    \n%     [height,width,depth] = size(lab_image);\n%     yuv_int = floor(lab_image(:,:,1));\n    \n    %sat_image = sat_image(:);\n%     yuv_int2 = yuv_int(sat_image(:)==0);\n%     cumu_err = 0;\n%     cumu_tar = 0;\n%     if ~isempty(yuv_int2)\n%         for i=0:100\n%             cumu_tar = cumu_tar + 1/100;\n%             cumu_err = cumu_err + (sum(yuv_int2<=i)/length(yuv_int2) - ...\n%                                    cumu_tar)/100;\n%         end\n% %         a = (cumu_err+1.0)/2.0;\n%         b = 0.5*(1-cumu_err);\n%     else\n% %         a = 1;\n%         b = sum(sum(lab_image(:,:,1)))/50;\n%     end\n    c = sqrt(mean(mean((lab_image(:,:,2)./50).^2 + ...\n         (lab_image(:,:,3)./50).^2)));\n%     d = 0;\n%     if std2(lab_image(:,:,1))>0\n%         d = 0.01*(std2(lab_image(:,:,2))+std2(lab_image(:,:,3)));\n%     end\n    \n    out = [c];\nend\n    \n% This function is used to compute dct derived features\nfunction out = dct_features(im)\n    \n    % Input is monochrome image\n    [height,width] = size(im);\n    \n    out_im = abs(dct2(im)).^.5;\n    \n    area1 = imresize(out_im(1:floor(height/2),1:floor(width/2)),0.25);\n    area2 = imresize(out_im(1:floor(height/2),...\n                            width:-1:width-floor(width/2)+1),0.25);\n    area3 = imresize(out_im(height:-1:height-floor(height/2)+1,...\n                            1:floor(width/2)),0.25);\n    area4 = imresize(out_im(height:-1:height-floor(height/2)+1,...\n                            width:-1:width-floor(width/2)+1),0.25);\n    a = max(0,max(corr(area1(:),area2(:)),corr(area1(:),area3(:))));\n%     b = 0;\n%     if mean(area1)>0\n%         b = mean(area4)/mean(area1);\n%     end\n%     c = 0;\n%     if max(mean(area2),mean(area3))>0\n%         c = min(mean(area2),mean(area3))/max(mean(area2),mean(area3));\n%     end\n    \n    out = [a];\n    \nend\n\n% This function is used to compute sharpness related features\nfunction out = sharpness_features(im)\n\n    [~, width] = size(im);\n    \n    % Full HD video could be downsized\n    if width>1280\n        im = imresize(im,0.5);\n    end\n    \n    H = [-1 -2 -1; 0 0 0; 1 2 1]./8;\n    im_s_h = imfilter(im,H');\n    im_s_v = imfilter(im,H);\n    im_s = sqrt(im_s_h.^2+im_s_v.^2);\n    \n    [height,width] = size(im_s_h);\n    bl_size = 16;\n    conv_list = [];\n    \n    blur_im = zeros(height,width);\n    edge_strong = [];\n    edge_all = [];\n    \n    conv_cube = [];\n    blurvals = [];\n    \n    n_blks = 0;\n    \n    conv_val_tot = zeros(17);\n    for y=floor(bl_size/2):bl_size:height-ceil(3*bl_size/2)\n        for x=floor(bl_size/2):bl_size:width-ceil(3*bl_size/2)\n            \n            n_blks = n_blks + 1;\n            \n            conv_val = zeros(17);\n            for i=0:6\n                for j=0:6\n                    if i==0 || j==0 || i==j\n                        weight_h = 1;\n                        weight_v = 1;\n                        if i~=0 || j~=0\n                            weight_h = abs(i)/(abs(i)+abs(j));\n                            weight_v = abs(j)/(abs(i)+abs(j));\n                        end\n                        diff_h = (im_s_h(y+i:y+bl_size+i,   ...\n                                         x+j:x+bl_size+j).* ...\n                                  im_s_h(y:y+bl_size,       ...\n                                         x:x+bl_size));\n                        diff_v = (im_s_v(y+i:y+bl_size+i,   ...\n                                         x+j:x+bl_size+j).* ...\n                                  im_s_v(y:y+bl_size,       ...\n                                         x:x+bl_size));\n                        conv_val(i+9,j+9) = weight_h*(mean(diff_h(:)))+ ...\n                                            weight_v*(mean(diff_v(:)));\n                    end\n                end\n            end\n            blur_im(y:y+bl_size-1,x:x+bl_size-1)=0.5;\n            edge_all =  [edge_all conv_val(9,9)];\n            if conv_val(9,9)>0.0001\n                edge_strong =  [edge_strong conv_val(9,9)];\n                conv_val=conv_val./conv_val(9,9);\n                conv_val_tot = conv_val_tot + conv_val;\n\n                new_conv_v = [];\n                for i=1:6\n                    new_conv_v = [new_conv_v sum(sum(conv_val(9-i:9+i,...\n                                                            9-i:9+i)))- ...\n                                             sum(sum(conv_val(10-i:8+i, ...\n                                                            10-i:8+i)))];\n                end\n                if new_conv_v(1)>0\n                    new_conv_v=new_conv_v./new_conv_v(1);\n                end\n\n                conv_list = [conv_list; new_conv_v];\n                conv_cube(:,:,1)=conv_val;\n                blurvals = [blurvals std2(im_s(y:y+bl_size, x:x+bl_size))];\n\n                blur_im(y:y+bl_size-1,x:x+bl_size-1) = ...\n                                  0.5 + mean(new_conv_v(2:6))/5;\n            end\n        end\n    end\n\n    % Find the sharpest blocks\n    blurs_sharp = [];\n    blurs_blur = [];\n    if ~isempty(blurvals)    \n        for i=1:length(blurvals)\n            if blurvals(i)>mean(blurvals)\n                conv_val_tot = + conv_val_tot + conv_cube(:,:,1);\n                blurs_sharp = [blurs_sharp blurvals(i)];\n            else\n                blurs_blur = [blurs_blur blurvals(i)];\n            end\n        end\n    end\n    \n    n_sharps = length(blurs_sharp)/n_blks;\n    n_blurs = length(blurs_blur)/n_blks;\n    mean_sharps = 0;\n    mean_blurs = 0;\n    if ~isempty(blurs_sharp)\n        mean_sharps = mean(blurs_sharp);\n    end\n    if ~isempty(blurs_blur)\n        mean_blurs = mean(blurs_blur);\n    end\n    \n%     if conv_val_tot(9,9)>0\n%         conv_val_tot=conv_val_tot./conv_val_tot(9,9);\n%     end\n    \n    new_conv_v = zeros(1,9);\n    if ~isempty(edge_strong)>0\n        if length(conv_list(:,1))>1\n            new_conv_v = mean(conv_list);\n        else\n            new_conv_v = conv_list;\n        end\n    end \n       \n    % find local min and/or local max\n%     localmin=0;\n%     localmindist=0;\n%     localmax=0;\n%     localmaxdist=0;\n%     for i=9:14\n%         for j=9:14\n%             if (i~=9 && j==9) || (j~=9 && i==9) || (i==j && i>9) \n%                 conv_val_comp=conv_val_tot(i-1:i+1,j-1:j+1);\n%                 conv_val_comp=conv_val_comp(:);\n%                 if i==9\n%                     conv_val_comp=conv_val_comp([4 6]);\n%                 elseif j==9\n%                     conv_val_comp=conv_val_comp([2 8]);\n%                 else\n%                     conv_val_comp=conv_val_comp([1 9]);\n%                 end    \n%                 if conv_val_tot(i,j)>max(conv_val_comp) && ...\n%                         conv_val_tot(i,j)>localmax\n%                     localmax = conv_val_tot(i,j);\n% %                     localmaxdist = sqrt((i-9)^2+(j-9)^2);\n%                 elseif conv_val_tot(i,j)<min(conv_val_comp) && ...\n%                         conv_val_tot(i,j)<localmin\n%                     localmin = conv_val_tot(i,j);\n% %                     localmindist = sqrt((i-9)^2+(j-9)^2);\n%                 end\n%             end\n%         end\n%     end\n\n%     out = [mean(new_conv_v(2:6)) mean(new_conv_v(2:4)) new_conv_v(2) ...           \n%            localmaxdist/5 localmindist/5 ...\n%            n_sharps n_blurs mean_sharps mean_blurs];\n       \n    out = [mean(new_conv_v(2:6)) new_conv_v(2) mean_blurs];\nend\n\n\n% Read one frame from YUV file\nfunction YUV = YUVread(f,dim,frnum)\n\n    % This function reads a frame #frnum (0..n-1) from YUV file into an\n    % 3D array with Y, U and V components\n    \n    fseek(f,dim(1)*dim(2)*1.5*frnum,'bof');\n    \n    % Read Y-component\n    Y=fread(f,dim(1)*dim(2),'uchar');\n    if length(Y)<dim(1)*dim(2)\n        YUV = [];\n        return;\n    end\n    Y=cast(reshape(Y,dim(1),dim(2)),'double');\n    \n    % Read U-component\n    U=fread(f,dim(1)*dim(2)/4,'uchar');\n    if length(U)<dim(1)*dim(2)/4\n        YUV = [];\n        return;\n    end\n    U=cast(reshape(U,dim(1)/2,dim(2)/2),'double');\n    U=imresize(U,2.0);\n    \n    % Read V-component\n    V=fread(f,dim(1)*dim(2)/4,'uchar');\n    if length(V)<dim(1)*dim(2)/4\n        YUV = [];\n        return;\n    end    \n    V=cast(reshape(V,dim(1)/2,dim(2)/2),'double');\n    V=imresize(V,2.0);\n    \n    % Combine Y, U, and V\n    YUV(:,:,1)=Y';\n    YUV(:,:,2)=U';\n    YUV(:,:,3)=V';\nend\n    \n", "meta": {"author": "vztu", "repo": "VIDEVAL", "sha": "8a86166bb9a9c8fc5e5eac5db7a77771cf576947", "save_path": "github-repos/MATLAB/vztu-VIDEVAL", "path": "github-repos/MATLAB/vztu-VIDEVAL/VIDEVAL-8a86166bb9a9c8fc5e5eac5db7a77771cf576947/include/calc_VIDEVAL_feats_light.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.2450863382428071}}
{"text": "function y = iterapp(op,afun,atype,afcnstr,x,varargin)\n%ITERAPP   Apply matrix operator to vector and error gracefully.\n%   ITERAPP(OP,AFUN,ATYPE,AFCNSTR,X) applies matrix operator AFUN to vector\n%   X. If ATYPE is 'matrix, then AFUN is a matrix and the OP is applied\n%   directly. OP is either 'mtimes' or 'mldivide'.\n%   ATYPE and AFCNSTR are used in case of error.\n%   ITERAPP(OP,AFUN,ATYPE,AFCNSTR,X,P1,P2,...) allows extra arguments to\n%   AFUN(X,P1,P2,...) although this usage is now discouraged in favor of\n%   using anonymous functions.\n%   AFUN(X,P1,P2,...,PN,TFLAG) should accept a TFLAG as its final input if\n%   the calling function is BICG, LSQR or QMR. TFLAG is either 'transp' or\n%   'notransp' depending on whether A' OP X or A OP X is required.\n%   ITERAPP is designed for use by iterative methods like PCG which\n%   require matrix operators AFUN representing matrices A to operate on\n%   vectors X and return A*X and may also have operators MFUN representing\n%   preconditioning matrices M operate on vectors X and return M\\X.\n%\n%   See also BICG, BICGSTAB, CGS, GMRES, LSQR, MINRES, PCG, QMR, SYMMLQ.\n\n%   Copyright 1984-2004 The MathWorks, Inc.\n%   $Revision: 1.7.4.2 $ $Date: 2004/12/06 16:35:55 $\n\nif isequal(atype,'matrix')\n    switch lower(op)\n        case 'mtimes'\n            if (nargin >= 6) & isequal(varargin{end},'transp')\n                y = afun' * x;\n            else\n                y = afun * x;\n            end\n        case 'mldivide'\n            if (nargin >= 6) & isequal(varargin{end},'transp')\n                y = afun' \\ x;\n            else\n                y = afun \\ x;\n            end\n        otherwise\n            error('MATLAB:iterapp:InvalidOp', 'Invalid operation.')\n    end\nelse\n    try\n        if (nargin >= 6) & isequal(varargin{end},'notransp')\n            % A request for A*x coming from BICG, LSQR and QMR\n            try\n                % New syntax: we now request afun(x,P1,P2,...,PN,'notransp')\n                y = afun(x,varargin{:});\n            catch\n                % Old syntax: we used to accept afun(x,P1,P2,...,PN)\n                y = afun(x,varargin{1:end-1});\n            end\n        else\n            % A request for A*x\n            % coming from BICGSTAB, CGS, GMRES, MINRES, PCG or SYMMLQ\n            % with the call always afun(P1,P2,...,PN)\n            % or a request for A'*x coming from\n            % BICG, LSQR and QMR in the afun(x,P1,P2,...,PN,'transp') case\n            y = afun(x,varargin{:});\n        end\n    catch\n        error('MATLAB:InvalidInput', ['user supplied %s ==> %s\\n' ...\n            'failed with the following error:\\n\\n%s'], ...\n            atype,afcnstr,lasterr);\n    end\n\n    if ~isvector(y) || (size(y,2) ~= 1)\n        error('MATLAB:MustReturnColumn', ['user supplied %s ==> %s\\n' ...\n            'must return a column vector.'], ...\n            atype,afcnstr)\n    end\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/matlab704/iterapp_704.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.24507923728798509}}
{"text": "function model = mogUpdatePrior(model)\n\n% MOGUPDATEPRIORML Update the priors of an MOG model.\n% FORMAT\n% DESC updates the prior probabilities of a mixtures of\n% Gaussians model. \n% ARG model : the model which is to be updated.\n% RETURN model : the model with updated priors.\n%\n% SEEALSO : mogCreate, mogUpdateMean, mogUpdateCovariance, mogEstep\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2008\n\n% MLTOOLS\n\nif model.isInfinite\n  % First compute expectations of v.\n  sumS = sum(model.posterior);\n  a0bar = model.a0 + sumS; % Posterior value for a_0.\n  a1bar = model.a1 + cumsum(sumS); % Posterior value for a_1.\n  model.v = a0bar./(a0bar+a1bar);\n  tmp = cumprod(1-model.v);\n  model.prior = model.v;\n  model.prior(2:end) = model.prior(2:end).*tmp(1:end-1);\nelse\n  model.prior = mean(model.posterior);\n  model.prior(find(model.prior==0))=1e-100;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/mogUpdatePrior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24507922615038055}}
{"text": "function marginal = marginal_nodes(engine, b, nodes, t, add_ev)\n% MARGINAL_NODES Compute the marginal on the specified nodes (hmm_2TBN)\n% marginal = marginal_nodes(engine, b, nodes, t, add_ev)\n%\n% nodes must be a singleton set \n\nassert(length(nodes)==1)\nss = engine.slice_size;\n\ni = nodes(1);\nbigT = b.gamma;\ndom = i + (t-1)*ss;\n\n%id = engine.marg_singleton_ndx_id(i);\n%global SD_NDX\n%ndx = SD_NDX{id};\n%marginal.T = marg_table_ndxSD(bigT, engine.maximize, ndx);\n\nns = engine.eff_node_sizes(:);\nbigdom = 1:ss;\nmarginal.T = marg_table(bigT, bigdom + (t-1)*ss, ns(bigdom), dom, engine.maximize);\n\nmarginal.domain = dom;\nassert(~add_ev);\n%if add_ev\n%  marginal = add_ev_to_dmarginal(marginal, engine.evidence, engine.node_sizes);\n%end    \n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/online/@hmm_2TBN_inf_engine/marginal_nodes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2449800509836695}}
{"text": "function spm_htw_from_fit(varargin)\n% When fitting a 1st-level SPM model with multiple basis functions,\n% reconstructs fitted response at each voxel beta images and basis functions, and\n% estimates height (amplitude), time-to-peak, and response width (duration and half-max)\n% For each condition. Saves maps of these across voxels, and contrasts\n% across height, time-to-peak, and width maps if contrasts are specified.\n% This provides contrast images to take to 2nd-level analyses for group statistics when\n% using multiple basis functions at the 1st level.\n%\n% :Usage:\n% ::\n%\n%     function spm_htw_from_fit(varargin)\n%\n% :NOTES:\n%\n% This function loads the SPM.mat file in the current directory and uses\n% the basis set specified in the loaded SPM structure.\n%\n% : Required Inputs:\n% \tNone - run within an SPM first-level analysis directory\n% \n% :Optional Inputs:\n%\n%   **'amplitudes'**:\n%       do amplitudes only; no contrasts\n%\n%   **'contrasts'**:\n%       do contrasts only; no amplitudes\n%\n%   **'noamplitudes'**\n%        skip create amping images (combination of betas\n%        across basis functions)\n%\n%   **'nocontrasts'**\n%        skip creation of contrast images\n%        (running contrast images assumes that amplitude images are already\n%        created)\n%\n%   **'all'**\n%        will run both the amplitudes and contrasts sections\n%\n%          - The second way uses CANlab HTW code to estimate height, time to peak,\n%            width, and area under the curve (see Lindquist & Wager 2007 for\n%            simulations using a version of this code).\n%            It requires SCANlab specific functions, in SCN_Core_Support\n%            (unlike the deriv. boost).\n%            To turn this OFF, enter 'nohtw' as an optional argument\n%\n%   **'startend'**\n%        followed by starting and ending values in seconds for amplitude\n%        estimation window (for HTW estimation only).\n%        If you do not enter this, it will show you a plot and ask you to pick\n%        these values.\n%        If you enter them here as inputs, you can skip the interactive step and\n%        loop over subjects.\n%\n%   **'condition_numbers'**\n%        followed by which index numbers in your list should\n%        be used to calculate h, t, w from.  You should use this if you\n%        are entering regressors of no interest, besides the intercepts.\n%\n% :Important for Contrasts:\n%    disp('Using contrasts entered as F-contrasts. Assuming the first contrast vector in each F-contrast '\n%\n%    disp('is a contrast of interest across the CANONICAL basis function regressors.')\n%\n% :Output:\n% ::\n% Reconstructed amplitude, time-to-peak, and duration (width) images for each event type\n% e.g., for Event type (condition) 001:\n% htw_amplitude_001.nii\t\n% htw_time_to_peak_001.nii\n% htw_width_001.nii\n% htw_area_under_curve_001.nii\n% \n% Contrasts across these, using names stored in SPM.xCon.name:\n% e.g., \n% con_htw_ampl_targetvsstandards5.nii\n% con_htw_time_targetvsstandards5.nii\t\n% con_htw_widt_targetvsstandards5.nii\n% con_htw_area_targetvsstandards5.nii\t\n%\n% :Examples:\n% ::\n%\n%    % RUN THIS IN COMMAND WINDOW TO BATCH\n%    subj = dir('06*')\n%    for i = 1:length(subj), cd(subj(i).name), spm_htw_from_fit, cd('..'); end\n%\n%    % ANOTHER BATCH EXAMPLE:\n%    d = dir('remi*'); d = d(cat(2, d.isdir)); [mydirs{1:length(d)}] = deal(d.name)\n%    for i = 1:length(mydirs), cd(mydirs{i}), spm_htw_from_fit('all', 'nodb', 'startend', [4 15]), cd('..'); end\n%\n%    %An example for an event-related design, specifying condition numbers to get HTW from:\n%    spm_htw_from_fit('all', 'contrasts', 'condition_numbers', 1:14, 'startend', [4 10]);\n%\n%    % CALCULATE CONTRASTS ONLY ON ALREADY-ESTIMATED HTW IMAGES\n%    spm_htw_from_fit('contrasts','condition_numbers',1:14);\n%\n% :References:\n% ::\n% Lindquist, M. A. & Wager, T. D. (2007). Validity and power in hemodynamic response modeling: \n% a comparison study and a new approach. Human Brain Mapping. 8:764-84.\n%\n% Lindquist, M. A., Meh Loh, J., Atlas, L. Y. & Wager T. D. (2009). Modeling the hemodynamic \n% response function in fMRI: efficiency, bias and mis-modeling. Neuroimage. 45:187-98.\n\n% Notes: \n% This function is adapted from apply_derivative_boost.m, which was\n% originally intended to implement Calhoun derivative boost, but this is\n% now deprecated.\n% Original documentation:\n%        In addition, 'amplitudes' now has two separate parts:\n%          - The first uses Vince Calhoun's derivative boost (Calhoun, 2004) to\n%             estimate amplitudes.  NOTE: *We have not worked out the scaling yet, so\n%             I'm not sure this is working right*\n%             To turn this OFF, enter 'nodb' as an optional argument\n%\n\n    spmname = fullfile(pwd, 'SPM.mat');     % SETUP INPUTS\n    if ~exist(spmname, 'file'), error('You must be in an SPM 1st-level results directory with SPM5 SPM.mat file.'); end\n    \n    load(spmname);\n    \n    nbf = size(SPM.xBF.bf, 2);\n    \n    docontrasts = 1;\n    doamps = 1;\n    nodb = 1;\n    nohtw = 0;\n    condition_numbers = [];\n    do_downsample = [];          % downsample; default = 1 sec if units are seconds (1/dt)\n    \n    for i = 1:length(varargin)\n        if ischar(varargin{i})\n            switch varargin{i}\n                % reserved keywords\n                case 'all', docontrasts = 1; doamps = 1;\n\n                case 'amplitudes', doamps = 1; docontrasts = 0;\n\n                case 'contrasts', docontrasts = 1; doamps = 0;\n\n                case 'noamplitudes', doamps = 0;\n                    \n                case 'nocontrasts', docontrasts = 0;\n                    \n                case 'db', nodb = 0; % original DB estimation (legacy, deprecated)\n\n                case 'nohtw', nohtw = 1; % skip HTW estimation\n\n                case 'startend', startend = varargin{i + 1};  % starting and ending values in seconds for amplitude estimation window (for HTW estimation only).\n                  \n                case 'condition_numbers',  condition_numbers = varargin{i + 1}; \n                    \n                case 'nodownsample', do_downsample = 0;\n                    \n                case 'downsample', do_downsample = varargin{i + 1};\n                    \n                otherwise, warning(['Unknown input string option:' varargin{i}]);\n            end\n        end\n    end\n\n    if isempty(do_downsample)\n        % default downsampling\n        do_downsample = round(1 ./ SPM.xBF.dt);\n    end\n    \n    if ~(docontrasts || doamps)\n        disp('Nothing to do! Enter ''contrasts'' ''amplitudes'' or ''all'' as input argument.');\n        return\n    end\n    \n    \n    % ---------------------------------------------\n    % FILE NAMES and imgtype\n    % ---------------------------------------------\n    \n    imgs = dir(sprintf(['beta*img'])); imgs = char(imgs.name);\n    \n    if isempty(imgs)\n        imgs = dir(sprintf(['beta*nii'])); imgs = char(imgs.name);\n        imgtype = '.nii';\n    else\n        imgtype = '.img';\n    end\n    \n    if isempty(imgs)\n        error('Cannot find beta*img or beta*nii files in current folder')\n    end\n    \n    n = size(imgs, 1);\n    \n        \n    if doamps\n        % ---------------------------------------------\n        % ---------------------------------------------\n\n        % ESTIMATE AMPLITUDES\n\n        % ---------------------------------------------\n        % ---------------------------------------------\n\n\n\n\n        fprintf('Found %3.0f beta images', n); fprintf('\\n');\n\n        %load(spmname);\n        nsess = length(SPM.Sess);\n        fprintf('I think there are %3.0f sessions (runs)', nsess); fprintf('\\n');\n\n        if ~isempty(condition_numbers)\n            wh_intercept = true(1, size(imgs, 1));  % exclude these\n            wh_intercept(condition_numbers) = 0;\n            wh_intercept = find(wh_intercept);\n\n            fprintf('\\nIncluding only these images: ');\n            fprintf('%3.0f ', condition_numbers);\n            fprintf('\\n');\n\n        else\n            wh_intercept = SPM.xX.iB;\n            fprintf('\\nI think these images are intercepts, and am not using them: ');\n            fprintf('%3.0f ', wh_intercept);\n            fprintf('\\n');\n        end\n        \n        imgs(wh_intercept, :) = [];\n\n        %not used; only when using image_eval_function\n        %mask_img = './mask.img';\n\n        n = size(imgs, 1);\n\n\n        if n / nbf ~= round(n / nbf), error('Error!  Wrong number of images for the specified number of basis functions.'); end\n\n\n\n        if nodb\n            % skip Derivative Boost estimation and go straight to HTW\n        else\n            % DO DB\n            \n            switch nbf\n                case 2\n                    derivative_case = 'timeonly';\n                case 3\n                    derivative_case = 'timedispersion';\n                    \n                otherwise\n                    warning('Deriv. Boost only works for SPM canonical hrf with time or time + dispersion derivatives.  This SPM.mat doesn''t match those specs.');\n            end\n            \n            % Not used; only for image eval function\n            % boost = @(b) sign(b(1)) .* sqrt(sum(b .^ 2));\n            \n            \n    \n            % ---------------------------------------------\n            % CALCULATE\n            % ---------------------------------------------\n            cond_indx = 1;\n\n            for i = 1: nbf : (n - nbf + 1)\n\n                imgs_cond = imgs(i : i+nbf - 1, :);\n\n                disp('Working on :')\n                disp(imgs_cond)\n\n                out_name = sprintf(['db_amplitude_%03d',imgtype ], cond_indx);\n\n                % This code uses SCN lab tools to create images\n                % ---------------------------------------------\n                % %     y = image_eval_function(imgs_cond, boost, 'mask', mask_img, ...\n                % %         'outimagelabels', {out_name});\n                % ---------------------------------------------\n\n                % This code uses SPM instead\n                % ---------------------------------------------\n                switch derivative_case\n                    case 'timeonly'\n                        spm_imcalc(imgs_cond, out_name, 'sign(i1) .* sqrt(i1.^2 + i2.^2)');\n                    case 'timedispersion'\n                        spm_imcalc(imgs_cond, out_name, 'sign(i1) .* sqrt(i1.^2 + i2.^2 + i3.^2)');\n                    otherwise\n                        error('Basis set is incompatible with DB estimation!');\n                end\n\n                fprintf('Created %s\\n', out_name);\n                % ---------------------------------------------\n\n                cond_indx = cond_indx + 1;\n            end\n\n            % Get and save names\n            db_amp_names = [];\n            for i = 1:nsess\n                sessnames = char(SPM.Sess(i).Fc.name);\n                sessnames = [repmat(sprintf('Sess%02d_', i), size(sessnames, 1), 1) sessnames];\n                db_amp_names = strvcat(db_amp_names, sessnames);\n            end\n\n            save db_amplitude_names db_amp_names\n            disp(db_amp_names);\n            disp(' ')\n            disp('Saved DB amplitude condition names for each image in db_amplitude_names.mat');\n\n            fprintf('\\n*-----------------------------*\\nApplied DB successfully\\n*-----------------------------*\\n')\n\n        end\n\n        if nohtw\n            % skip this\n\n        else\n\n            % ---------------------------------------------\n            % Estimated amplitude from fit: HTW\n            % ---------------------------------------------\n            % This code uses SCN lab tools to create images\n\n            disp(' ')\n            disp('Next: Estimating amplitude, time to peak, width, and area-under-curve images from fitted response using SCN lab code.')\n            disp(' ')\n\n            % downsample bf, if requested\n            if do_downsample\n                mytimeres = SPM.xBF.dt * do_downsample;\n                SPM.xBF.bf = downsample(SPM.xBF.bf, do_downsample);\n                \n            else\n                mytimeres = SPM.xBF.dt;\n            end\n           \n            if exist('startend', 'var')\n                % just check, and use input values\n                if length(startend) ~= 2, error('Startend input must have two values, a starting and ending value in seconds for the amp. estimate window'), end\n            \n            else\n                % Set range in sec\n                htw_from_fit(SPM.xBF.bf, ones(size(SPM.xBF.bf, 2), 1), mytimeres, 'plot', 'verbose');\n\n                disp(' ')\n                disp('Enter the range in seconds within which to estimate peak amplitude.')\n                disp('Example: type [3 12] and press return for a typical event-related setup.');\n                disp('More sustained responses, like pain responses, may require a longer window.');\n                disp('This estimates the amplitude of the IMPULSE RESPONSE, before convolution with the stimulus function')\n                disp('so if you have an epoch design, a typical window of [3 12] sec is still appropriate.');\n                disp('Also note: AUC images are calculated as the area under the curve within the window you specify.')\n                disp(' ')\n                disp('In the future, you can input ''startend'', [3 12] (for example) to skip interactive selection')\n                startend = input('Enter your choice in [ ] and press return: ');\n            end\n\n            % Test your choice by showing you a plot\n            htwfunction = @(b) htw_from_fit(SPM.xBF.bf, b, mytimeres, 'startval', startend(1), 'endval', startend(2), 'plot', 'verbose');\n            htwfunction(ones(size(SPM.xBF.bf, 2), 1))\n            drawnow\n\n            % Create without plot option for loop through brain.\n            htwfunction = @(b) htw_from_fit(SPM.xBF.bf, b, mytimeres, 'startval', startend(1), 'endval', startend(2));\n\n            disp('Check the screen for a plot of your choice of window.')\n            disp(' ')\n\n\n            % ---------------------------------------------\n            % CALCULATE\n            % ---------------------------------------------\n            cond_indx = 1;\n\n            for i = 1: nbf : (n - nbf + 1)\n\n                imgs_cond = imgs(i : i+nbf - 1, :);\n\n                disp('Working on :')\n                disp(imgs_cond)\n\n                clear out_name\n                out_name{1} = sprintf(['htw_amplitude_%03d',imgtype], cond_indx);\n                out_name{2} = sprintf(['htw_time_to_peak_%03d',imgtype], cond_indx);\n                out_name{3} = sprintf(['htw_width_%03d',imgtype], cond_indx);\n                out_name{4} = sprintf(['htw_area_under_curve_%03d',imgtype], cond_indx);\n\n                % ---------------------------------------------\n                [h, t, w, auc] = image_eval_function(imgs_cond, htwfunction, 'mask', fullfile(pwd, ['mask', imgtype]), ...\n                    'outimagelabels', out_name);\n\n                h;t;w;auc;  % we need the outputs above to tell it to write 4 images.\n                % ---------------------------------------------\n\n                cond_indx = cond_indx + 1;\n            end\n\n            % Get and save names\n            htw_amp_names = [];\n            for i = 1:nsess\n                sessnames = char(SPM.Sess(i).Fc.name);\n                sessnames = [repmat(sprintf('Sess%02d_', i), size(sessnames, 1), 1) sessnames];\n                htw_amp_names = strvcat(htw_amp_names, sessnames);\n            end\n\n            if ~exist(fullfile(pwd, 'db_amplitude_names.mat'), 'file')\n                save db_amplitude_names htw_amp_names\n            else\n                save db_amplitude_names -append htw_amp_names\n            end\n            disp(htw_amp_names);\n            disp(' ')\n            disp('Saved HTW amplitude condition names for each image in db_amplitude_names.mat');\n\n            fprintf('\\n*-----------------------------*\\nApplied HTW estimation successfully\\n*-----------------------------*\\n')\n\n        end\n\n    end  % amplitudes\n\n\n\n    % ---------------------------------------------\n    % ---------------------------------------------\n\n    % CREATE CONTRAST FOR THIS SUBJECT\n\n    % ---------------------------------------------\n    % ---------------------------------------------\n\n    if docontrasts\n\n        % Load contrast vectors\n\n        % -----------------------------------------\n        %load(spmname);\n        % nsess = length(SPM.Sess);\n\n        % Define which indices to exclude from contrasts\n        if ~isempty(condition_numbers)\n            nconvals = length(SPM.xCon(1).c(:, 1));  % test contrast\n            wh_intercept = true(1, nconvals);  % exclude these\n            wh_intercept(condition_numbers) = 0;\n            wh_intercept = find(wh_intercept);\n\n            fprintf('\\nIncluding only these images: ');\n            fprintf('%3.0f ', condition_numbers);\n            fprintf('\\n');\n\n        else\n            wh_intercept = SPM.xX.iB;\n            fprintf('\\nI think these images are intercepts, and am not using them: ');\n            fprintf('%3.0f ', wh_intercept);\n            fprintf('\\n');\n        end\n\n\n        if ~isfield(SPM, 'xCon')\n            error('Enter F-contrasts first, with the first contrast vector in each F-contrast the contrast across the CANONICAL basis function.');\n        else\n            disp('Using contrasts entered as F-contrasts. Assuming the first contrast vector in each F-contrast ')\n            disp('is a contrast of interest across the CANONICAL basis function regressors.')\n        end\n\n        wh_F = strmatch('F', char(SPM.xCon.STAT), 'exact');\n\n        wh_T = strmatch('T', char(SPM.xCon.STAT), 'exact');\n        \n        wh_F = [wh_F wh_T];\n        \n        if isempty(wh_F) && isempty(wh_T), error('No F-contrasts or T-contrasts entered yet.'); end\n\n        % All sets of contrast images\n        % ------------------------------------------\n        if ~nodb\n            \n            ampimgs_name = sprintf(['db_amplitude_*',imgtype]);\n            \n            ampimgs = dir(ampimgs_name); ampimgs = char(ampimgs.name);\n            \n            if ~isempty(ampimgs)\n                contrast_image_names_dbamp = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype);\n            end\n            \n        end\n        \n        \n        % HTW amplitude\n        % ------------------------------------------\n        ampimgs_name = sprintf(['htw_amplitude_*',imgtype]);\n\n        ampimgs = dir(ampimgs_name); ampimgs = char(ampimgs.name);\n\n        if ~isempty(ampimgs)\n            contrast_image_names_htwamp = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype);\n        else\n            disp(['Checked for but did not find: ' ampimgs_name]);\n        end\n\n\n        % HTW time\n        % ------------------------------------------\n        ampimgs_name = sprintf(['htw_time_to_peak_*',imgtype]);\n\n        ampimgs = dir(ampimgs_name); ampimgs = char(ampimgs.name);\n\n        if ~isempty(ampimgs)\n            contrast_image_names_htwtime = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype);\n        else\n            disp(['Checked for but did not find: ' ampimgs_name]);\n        end\n\n\n        % HTW width\n        % ------------------------------------------\n        ampimgs_name = sprintf(['htw_width_*',imgtype]);\n\n        ampimgs = dir(ampimgs_name); ampimgs = char(ampimgs.name);\n\n        if ~isempty(ampimgs)\n            contrast_image_names_htwwid = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype);\n        else\n            disp(['Checked for but did not find: ' ampimgs_name]);\n        end\n\n\n        % HTW area\n        % ------------------------------------------\n        ampimgs_name = sprintf(['htw_area_under_curve_*',imgtype]);\n\n        ampimgs = dir(ampimgs_name); ampimgs = char(ampimgs.name);\n\n        if ~isempty(ampimgs)\n            contrast_image_names_htwarea = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype);\n        else\n            disp(['Checked for but did not find: ' ampimgs_name]);\n        end\n        \n        check_it = whos('contrast_image_names*');\n        \n        if isempty(check_it)\n            disp('No valid images found to create contrasts on');\n            \n        else\n            save('db_amplitude_names', '-append', 'contrast_image_names*');\n            disp('Saved lists of contrast image names in db_amplitude_names.mat');\n        end\n        \n    end % end contrasts\n\n    \n\n\n    %% INLINE\n\n\n\nend  % main function\n\n\n\n\n\n\n\nfunction contrast_image_names = calc_contrasts(ampimgs_name, ampimgs, wh_F, SPM, wh_intercept, nbf, imgtype)\n\n\n    n = size(ampimgs, 1);\n\n    fprintf('Found %3.0f images:\\n', n);\n    disp(ampimgs)\n\n    disp('Reading image data.')\n    V = spm_vol(ampimgs);\n    vols = spm_read_vols(V);\n\n    % spm_check_registration(ampimgs);\n    % colormap jet\n\n    contrast_image_names = [];\n\n    for i = 1:length(wh_F)\n\n\n        name = SPM.xCon(wh_F(i)).name;\n        disp(['Calculating contrast on: ' name])\n        original_name = name;\n\n        name = deblank(name);\n        wh_bad = (name == ' ' | name == ',' | name == '.' | name == '^' | name == '~' | name == '''' | name == ':' | name == '*' | name == '%' | name == ';' | name == '@' | name == '&');\n        name(wh_bad) = [];\n\n        name = ['con_', ampimgs_name(1:8), '_', name, imgtype];\n\n        c = SPM.xCon(wh_F(i)).c(:, 1);\n        c(wh_intercept) = [];\n        c = c(1 : nbf : end);\n\n        if length(c) ~= n, error('Contrast is wrong length for some reason!  Coding error in this function?  Or wrong number of db_amplitude images.'); end\n\n        fprintf('Contrast values: ')\n        fprintf('%01d ', c)\n        fprintf('\\n')\n        \n        % calculate and save\n\n        contrast_image_calc(name, c, vols, V, original_name)\n\n        disp(['Written: ' name]);\n\n        contrast_image_names = strvcat(contrast_image_names, name);\n\n        disp(' ');\n\n    end\n\n    fprintf('\\n*-----------------------------*\\nContrasts Done successfully!\\n*-----------------------------*\\n')\n    spm_check_registration(contrast_image_names);\n\nend\n\n\n\n\n\nfunction contrast_image_calc(Q, myc, vols, V, original_name)\n\n    % FROM:\n    % function contrast_image(Q, myc)\n    %\n    % Tor Wager\n    %\n    % Creates a contrast image called Q (do not include path)\n    % Given a list of img files P (spm format, with path)\n    % and a contrast vector myc\n    % In the directory of 1st image in P.\n\n\n    if ~(length(myc) == size(vols,4))\n        error('Contrast vector length is not equal to number of image files.')\n    end\n\n    myc2 = zeros(size(vols));\n\n    for i = 1:length(myc)\n        myc2(:,:,:,i) = myc(i);\n    end\n\n    cvol = vols .* myc2;\n    cvol = sum(cvol,4);\n\n    % -------------------------\n    % write\n    % -------------------------\n    dd = fileparts(V(1).fname);\n    Q = fullfile(dd, Q);\n    Vo = V(1);\n    Vo.fname = Q;\n    Vo.descrip = ['Contrast ' original_name];\n\n    spm_write_vol(Vo,cvol);\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Image_computation_tools/spm_htw_from_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24498004492533793}}
{"text": "function render = tbx_cfg_render\n% Configuration file for toolbox 'Rendering'\n%__________________________________________________________________________\n% Copyright (C) 2008-2016 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: tbx_cfg_render.m 6960 2016-12-05 17:05:09Z guillaume $\n\nif ~isdeployed, addpath(fullfile(spm('dir'),'toolbox','SRender')); end\n\n%--------------------------------------------------------------------------\n% images Input Images\n%--------------------------------------------------------------------------\nimages         = cfg_files;\nimages.tag     = 'images';\nimages.name    = 'Input Images';\nimages.help    = {\n    'These are the images that are used by the calculator.'\n    'They are referred to as i1, i2, i3, etc in the order that they are specified.'\n    }';\nimages.filter  = 'image';\nimages.ufilter = '.*';\nimages.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% expression Expression\n%--------------------------------------------------------------------------\nexpression         = cfg_entry;\nexpression.tag     = 'expression';\nexpression.name    = 'Expression';\nexpression.help    = {\n    'Example expressions (f):'\n    '    * Mean of six images (select six images)'\n    '       f = ''(i1+i2+i3+i4+i5+i6)/6'''\n    '    * Make a binary mask image at threshold of 100'\n    '       f = ''i1>100'''\n    '    * Make a mask from one image and apply to another'\n    '       f = ''i2.*(i1>100)'''\n    '             - here the first image is used to make the mask, which is applied to the second image'\n    '    * Sum of n images'\n    '       f = ''i1 + i2 + i3 + i4 + i5 + ...'''\n    }';\nexpression.strtype = 's';\nexpression.num     = [2  Inf];\nexpression.val     = {'i1'};\n\n%--------------------------------------------------------------------------\n% thresh Surface isovalue(s)\n%--------------------------------------------------------------------------\nthresh         = cfg_entry;\nthresh.tag     = 'thresh';\nthresh.name    = 'Surface isovalue(s)';\nthresh.help    = {'Enter the value at which isosurfaces through the resulting image is to be computed.'};\nthresh.strtype = 'e';\nthresh.num     = [1  1];\nthresh.val     = {0.5};\n\n%--------------------------------------------------------------------------\n% surface Surface\n%--------------------------------------------------------------------------\nsurface      = cfg_branch;\nsurface.tag  = 'surface';\nsurface.name = 'Surface';\nsurface.val  = {expression thresh };\nsurface.help = {'An expression and threshold for each of the surfaces to be generated.'};\n\n%--------------------------------------------------------------------------\n% Surfaces Surfaces\n%--------------------------------------------------------------------------\nSurfaces        = cfg_repeat;\nSurfaces.tag    = 'Surfaces';\nSurfaces.name   = 'Surfaces';\nSurfaces.help   = {'Multiple surfaces can be created from the same image data.'};\nSurfaces.values = {surface };\nSurfaces.num    = [0 Inf];\n\n%--------------------------------------------------------------------------\n% SExtract Surface Extraction\n%--------------------------------------------------------------------------\nSExtract      = cfg_exbranch;\nSExtract.tag  = 'SExtract';\nSExtract.name = 'Surface Extraction';\nSExtract.val  = {images Surfaces };\nSExtract.help = {'User-specified algebraic manipulations are performed on a set of images, with the result being used to generate a surface file. The user is prompted to supply images to work on and a number of expressions to evaluate, along with some thresholds. The expression should be a standard matlab expression, within which the images should be referred to as i1, i2, i3,... etc. An isosurface file is created from the results at the user-specified threshold.'};\nSExtract.prog = @spm_sextract;\nSExtract.vout = @vout_sextract;\n\n%--------------------------------------------------------------------------\n% SurfaceFile Surface File\n%--------------------------------------------------------------------------\nSurfaceFile         = cfg_files;\nSurfaceFile.tag     = 'SurfaceFile';\nSurfaceFile.name    = 'Surface File';\nSurfaceFile.help    = {\n    'Filename of the surf_*.gii file containing the rendering information.'\n    'This can be generated via the surface extraction routine in SPM.'\n    'Normally, a surface is extracted from grey and white matter tissue class images, but it is also possible to threshold e.g. an spmT image so that activations can be displayed.'\n    };\nSurfaceFile.filter  = 'mesh';\nSurfaceFile.ufilter = '.*';\nSurfaceFile.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% Red Red\n%--------------------------------------------------------------------------\nRed        = cfg_menu;\nRed.tag    = 'Red';\nRed.name   = 'Red';\nRed.help   = {'The intensity of the red colouring (0 to 1).'};\nRed.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'};\nRed.values = {0 0.2 0.4 0.6 0.8 1};\nRed.val    = {1};\n\n%--------------------------------------------------------------------------\n% Green Green\n%--------------------------------------------------------------------------\nGreen        = cfg_menu;\nGreen.tag    = 'Green';\nGreen.name   = 'Green';\nGreen.help   = {'The intensity of the green colouring (0 to 1).'};\nGreen.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nGreen.values = {0 0.2 0.4 0.6 0.8 1};\nGreen.val    = {1};\n\n%--------------------------------------------------------------------------\n% Blue Blue\n%--------------------------------------------------------------------------\nBlue        = cfg_menu;\nBlue.tag    = 'Blue';\nBlue.name   = 'Blue';\nBlue.help   = {'The intensity of the blue colouring (0 to 1).'};\nBlue.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nBlue.values = {0 0.2 0.4 0.6 0.8 1};\nBlue.val    = {1};\n\n%--------------------------------------------------------------------------\n% Color Color\n%--------------------------------------------------------------------------\nColor      = cfg_branch;\nColor.tag  = 'Color';\nColor.name = 'Color';\nColor.val  = {Red Green Blue};\nColor.help = {\n    'Specify the colour using a mixture of red, green and blue.'\n    'For example, white is specified by 1,1,1, black is by 0,0,0 and purple by 1,0,1.'\n    }';\n\n%--------------------------------------------------------------------------\n% DiffuseStrength Diffuse Strength\n%--------------------------------------------------------------------------\nDiffuseStrength        = cfg_menu;\nDiffuseStrength.tag    = 'DiffuseStrength';\nDiffuseStrength.name   = 'Diffuse Strength';\nDiffuseStrength.help   = {'The strength with which the object diffusely reflects light. Mat surfaces reflect light diffusely, whereas shiny surfaces reflect speculatively.'};\nDiffuseStrength.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nDiffuseStrength.values = {0 0.2 0.4 0.6 0.8 1};\nDiffuseStrength.val    = {0.8};\n\n%--------------------------------------------------------------------------\n% AmbientStrength Ambient Strength\n%--------------------------------------------------------------------------\nAmbientStrength        = cfg_menu;\nAmbientStrength.tag    = 'AmbientStrength';\nAmbientStrength.name   = 'Ambient Strength';\nAmbientStrength.help   = {'The strength with which the object reflects ambient (non-directional) lighting.'};\nAmbientStrength.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nAmbientStrength.values = {0 0.2 0.4 0.6 0.8 1};\nAmbientStrength.val    = {0.2};\n\n%--------------------------------------------------------------------------\n% SpecularStrength Specular Strength\n%--------------------------------------------------------------------------\nSpecularStrength        = cfg_menu;\nSpecularStrength.tag    = 'SpecularStrength';\nSpecularStrength.name   = 'Specular Strength';\nSpecularStrength.help   = {'The strength with which the object specularly reflects light (i.e. how shiny it is). Mat surfaces reflect light diffusely, whereas shiny surfaces reflect speculatively.'};\nSpecularStrength.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nSpecularStrength.values = {0 0.2 0.4 0.6 0.8 1};\nSpecularStrength.val    = {0.2};\n\n%--------------------------------------------------------------------------\n% SpecularExponent Specular Exponent\n%--------------------------------------------------------------------------\nSpecularExponent        = cfg_menu;\nSpecularExponent.tag    = 'SpecularExponent';\nSpecularExponent.name   = 'Specular Exponent';\nSpecularExponent.help   = {'A parameter describing the specular reflectance behaviour. It relates to the size of the high-lights.'};\nSpecularExponent.labels = {'0.01' '0.1' '10' '100'};\nSpecularExponent.values = {0.01  0.1 10 100};\nSpecularExponent.val    = {10};\n\n%--------------------------------------------------------------------------\n% SpecularColorReflectance Specular Color Reflectance\n%--------------------------------------------------------------------------\nSpecularColorReflectance        = cfg_menu;\nSpecularColorReflectance.tag    = 'SpecularColorReflectance';\nSpecularColorReflectance.name   = 'Specular Color Reflectance';\nSpecularColorReflectance.help   = {'Another parameter describing the specular reflectance behaviour.'};\nSpecularColorReflectance.labels = {'0.0' '0.2' '0.4' '0.6' '0.8'  '1.0'};\nSpecularColorReflectance.values = {0 0.2 0.4 0.6  0.8 1};\nSpecularColorReflectance.val    = {0.8};\n\n%--------------------------------------------------------------------------\n% FaceAlpha Face Alpha\n%--------------------------------------------------------------------------\nFaceAlpha        = cfg_menu;\nFaceAlpha.tag    = 'FaceAlpha';\nFaceAlpha.name   = 'Face Alpha';\nFaceAlpha.help   = {\n    'The opaqueness of the surface.'\n    'A value of 1 means it is opaque, whereas a value of 0 means it is transparent.'\n    }';\nFaceAlpha.labels = {'0.0' '0.2' '0.4' '0.6' '0.8' '1.0'}';\nFaceAlpha.values = {0 0.2 0.4 0.6 0.8 1};\nFaceAlpha.val    = {1};\n\n%--------------------------------------------------------------------------\n% Object Object\n%--------------------------------------------------------------------------\nObject      = cfg_branch;\nObject.tag  = 'Object';\nObject.name = 'Object';\nObject.val  = {SurfaceFile Color DiffuseStrength AmbientStrength SpecularStrength SpecularExponent SpecularColorReflectance FaceAlpha };\nObject.help = {'Each object is a surface (from a surf_*.gii file), which may have a number of light-reflecting qualities, such as colour and shinyness.'};\n\n%--------------------------------------------------------------------------\n% Objects Objects\n%--------------------------------------------------------------------------\nObjects        = cfg_repeat;\nObjects.tag    = 'Objects';\nObjects.name   = 'Objects';\nObjects.help   = {'Several surface objects can be displayed together in different colours and with different reflective properties.'};\nObjects.values = {Object };\nObjects.num    = [0 Inf];\n\n%--------------------------------------------------------------------------\n% Position Position\n%--------------------------------------------------------------------------\nPosition         = cfg_entry;\nPosition.tag     = 'Position';\nPosition.name    = 'Position';\nPosition.help    = {'The position of the light in 3D.'};\nPosition.strtype = 'e';\nPosition.num     = [1  3];\nPosition.val     = {[100 100 100]};\n\n%--------------------------------------------------------------------------\n% Light Light\n%--------------------------------------------------------------------------\nLight      = cfg_branch;\nLight.tag  = 'Light';\nLight.name = 'Light';\nLight.val  = {Position Color};\nLight.help = {'Specification of a light source in terms of position and colour.'};\n\n%--------------------------------------------------------------------------\n% Lights Lights\n%--------------------------------------------------------------------------\nLights        = cfg_repeat;\nLights.tag    = 'Lights';\nLights.name   = 'Lights';\nLights.help   = {'There should be at least one light specified so that the objects can be clearly seen.'};\nLights.values = {Light};\nLights.val    = {Light};\nLights.num    = [0 Inf];\n\n%--------------------------------------------------------------------------\n% SRender Surface Rendering\n%--------------------------------------------------------------------------\nSRender      = cfg_exbranch;\nSRender.tag  = 'SRender';\nSRender.name = 'Surface Rendering';\nSRender.val  = {Objects Lights};\nSRender.help = {'This utility is for visualising surfaces.  Surfaces first need to be extracted and saved in surf_*.gii files using the surface extraction routine.'};\nSRender.prog = @spm_srender;\n\n%--------------------------------------------------------------------------\n% render Rendering\n%--------------------------------------------------------------------------\nrender        = cfg_choice;\nrender.tag    = 'render';\nrender.name   = 'Rendering';\nrender.help   = {'This is a toolbox that provides a limited range of surface rendering options. The idea is to first extract surfaces from image data, which are saved in rend_*.mat files. These can then be loaded and displayed as surfaces. Note that OpenGL rendering is used, which can be problematic on some computers. The tools are limited - and they do what they do.'};\nrender.values = {SExtract SRender};\n\n\n%==========================================================================\nfunction dep = vout_sextract(job)\ndep = cfg_dep;\nfor k=1:numel(job.surface),\n    dep(k)            = cfg_dep;\n    dep(k).sname      = ['Surface File ' num2str(k)];\n    dep(k).src_output = substruct('.','SurfaceFile','()',{k});\n    dep(k).tgt_spec   = cfg_findspec({{'filter','mesh'}});\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/SRender/tbx_cfg_render.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24489642761036226}}
{"text": "function out = Pauli(data, sicd_meta)\n%PAULI Pauli Decomposition\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\nif (nargin>1) && isfield(sicd_meta,'ImageFormation') && ...\n        isfield(sicd_meta.ImageFormation,'TxRcvPolarizationProc')\n    % Try standard linear polarizations first\n    HH_ind=find(strcmpi('H:H',sicd_meta.ImageFormation.TxRcvPolarizationProc));\n    HV_ind=find(strcmpi('H:V',sicd_meta.ImageFormation.TxRcvPolarizationProc));\n    VH_ind=find(strcmpi('V:H',sicd_meta.ImageFormation.TxRcvPolarizationProc));\n    VV_ind=find(strcmpi('V:V',sicd_meta.ImageFormation.TxRcvPolarizationProc));\n    % Less common circular polarization next in not linear\n    if isempty([HH_ind HV_ind VH_ind VV_ind])\n        pols = cellfun(@(x) split(x,':'), sicd_meta.ImageFormation.TxRcvPolarizationProc, 'UniformOutput', false);\n        HH_ind = find(cellfun(@(x) strcmpi(x{1},'LHC') && ...\n            (strcmpi(x{2},'LHC') || x{2}=='H'), pols));\n        HV_ind = find(cellfun(@(x) strcmpi(x{1},'LHC') && ...\n            (strcmpi(x{2},'RHC') || x{2}=='V'), pols));\n        VH_ind = find(cellfun(@(x) strcmpi(x{1},'RHC') && ...\n            (strcmpi(x{2},'LHC') || x{2}=='V'), pols));\n        VV_ind = find(cellfun(@(x) strcmpi(x{1},'RHC') && ...\n            (strcmpi(x{2},'RHC') || x{2}=='H'), pols));\n    end\nelse % Make band assumptions based on order\n    switch size(data,3)\n        case 2 % Co/cross\n            HH_ind = 1; HV_ind = 2; VH_ind = []; VV_ind = [];\n        case 3 % HH/cross/VV\n            HH_ind = 1; HV_ind = 2; VH_ind = []; VV_ind = 3;\n        case 4 % Full\n            HH_ind = 1; HV_ind = 2; VH_ind = 3; VV_ind = 4;\n    end\nend\n\nout = zeros(size(data,1),size(data,2),3);\n% Co-pol,cross-pol\nif xor(isscalar(HH_ind), isscalar(VV_ind)) && xor(isscalar(HV_ind), isscalar(VH_ind))\n    %incoherent assignment (co is magenta, cross is green)\n    out(:,:,1) = data(:,:,[HH_ind VV_ind]);\n    out(:,:,2) = data(:,:,[HV_ind VH_ind]);\n    out(:,:,3) = data(:,:,[HH_ind VV_ind]);\n% HH/VV\nelseif isscalar(HH_ind) && isscalar(VV_ind) && isempty(HV_ind) && isempty(VH_ind)\n    out(:,:,1) = data(:,:,HH_ind) - data(:,:,VV_ind);\n    out(:,:,2) = 0;\n    out(:,:,3) = data(:,:,HH_ind) + data(:,:,VV_ind);\n% HH,cross-pol,VV\nelseif isscalar(HH_ind) && isscalar(VV_ind) && xor(isscalar(HV_ind), isscalar(VH_ind))\n    out(:,:,1) = data(:,:,HH_ind) - data(:,:,VV_ind);\n    out(:,:,2) = 2*data(:,:,[HV_ind VH_ind]);\n    out(:,:,3) = data(:,:,HH_ind) + data(:,:,VV_ind);\n% Full-pol (HH,HV,VH,VV)\nelseif isscalar(HH_ind) && isscalar(VV_ind) && isscalar(HV_ind) && isscalar(VH_ind)\n    out(:,:,1) = data(:,:,HH_ind) - data(:,:,VV_ind);\n    out(:,:,2) = data(:,:,HV_ind) + data(:,:,VH_ind);\n    out(:,:,3) = data(:,:,HH_ind) + data(:,:,VV_ind);\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Visualization/polarimetric/+pol_decomp/Pauli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2448964276103622}}
{"text": "function [p, stats] = symamd2 (S, knobs)\n%SYMAMD Symmetric approximate minimum degree permutation.\n%    P = SYMAMD2(S) for a symmetric positive definite matrix S, returns the\n%    permutation vector p such that S(p,p) tends to have a sparser Cholesky\n%    factor than S.  Sometimes SYMAMD works well for symmetric indefinite\n%    matrices too.  The matrix S is assumed to be symmetric; only the\n%    strictly lower triangular part is referenced.   S must be square.\n%    Note that p = amd(S) is much faster and generates comparable orderings.\n%    The ordering is followed by an elimination tree post-ordering.\n%\n%    Note that this function is source code for the built-in MATLAB symamd\n%    function.  It has been renamed here to symamd2 to avoid a filename clash.\n%    symamd and symamd2 are identical.\n%\n%    See also SYMAMD, AMD, COLAMD, COLAMD2.\n%\n%    Example:\n%            P = symamd2 (S)\n%            [P, stats] = symamd2 (S, knobs)\n%\n%    knobs is an optional one- to two-element input vector.  If S is n-by-n,\n%    then rows and columns with more than max(16,knobs(1)*sqrt(n)) entries are\n%    removed prior to ordering, and ordered last in the output permutation P.\n%    No rows/columns are removed if knobs(1)<0.  If knobs(2) is nonzero, stats\n%    and knobs are printed.  The default is knobs = [10 0].  Note that knobs\n%    differs from earlier versions of symamd.\n\n%    Copyright 1998-2007, Timothy A. Davis, and Stefan Larimore\n%    Developed in collaboration with J. Gilbert and E. Ng.\n%    Acknowledgements: This work was supported by the National Science\n%       Foundation, under grants DMS-9504974 and DMS-9803599.\n\n%-------------------------------------------------------------------------------\n% perform the symamd ordering:\n%-------------------------------------------------------------------------------\n\nif (nargout <= 1 & nargin == 1)\t\t\t\t\t\t    %#ok\n    p = symamd2mex (S) ;\nelseif (nargout <= 1 & nargin == 2)\t\t\t\t\t    %#ok\n    p = symamd2mex (S, knobs) ;\nelseif (nargout == 2 & nargin == 1)\t\t\t\t\t    %#ok\n    [p, stats] = symamd2mex (S) ;\nelseif (nargout == 2 & nargin == 2)\t\t\t\t\t    %#ok\n    [p, stats] = symamd2mex (S, knobs) ;\nelse\n    error('symamd:  incorrect number of input and/or output arguments.') ;\nend\n\n%-------------------------------------------------------------------------------\n% symmetric elimination tree post-ordering:\n%-------------------------------------------------------------------------------\n\n[ignore, q] = etree (S (p,p)) ;\np = p (q) ;\n\n\n%    stats is an optional 20-element output vector that provides data about the\n%    ordering and the validity of the input matrix S.  Ordering statistics are\n%    in stats (1:3).  stats (1) = stats (2) is the number of dense or empty\n%    rows and columns ignored by SYMAMD and stats (3) is the number of\n%    garbage collections performed on the internal data structure used by\n%    SYMAMD (roughly of size 8.4*nnz(tril(S,-1)) + 9*n integers).\n%\n%    MATLAB built-in functions are intended to generate valid sparse matrices,\n%    with no duplicate entries, with ascending row indices of the nonzeros\n%    in each column, with a non-negative number of entries in each column (!)\n%    and so on.  If a matrix is invalid, then SYMAMD may or may not be able\n%    to continue.  If there are duplicate entries (a row index appears two or\n%    more times in the same column) or if the row indices in a column are out\n%    of order, then SYMAMD can correct these errors by ignoring the duplicate\n%    entries and sorting each column of its internal copy of the matrix S (the\n%    input matrix S is not repaired, however).  If a matrix is invalid in other\n%    ways then SYMAMD cannot continue, an error message is printed, and no\n%    output arguments (P or stats) are returned.  SYMAMD is thus a simple way\n%    to check a sparse matrix to see if it's valid.\n%\n%    stats (4:7) provide information if SYMAMD was able to continue.  The\n%    matrix is OK if stats (4) is zero, or 1 if invalid.  stats (5) is the\n%    rightmost column index that is unsorted or contains duplicate entries,\n%    or zero if no such column exists.  stats (6) is the last seen duplicate\n%    or out-of-order row index in the column index given by stats (5), or zero\n%    if no such row index exists.  stats (7) is the number of duplicate or\n%    out-of-order row indices.\n%\n%    stats (8:20) is always zero in the current version of SYMAMD (reserved\n%    for future use).\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/COLAMD/MATLAB/symamd2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2448964276103622}}
{"text": "function [nVertices, nFaces, BstMat] = out_tess_tri( BstFile, OutputFile, isOpenMEEG )\n% OUT_TESS_TRI: Exports a surface to a BrainVISA ASCII .tri file.\n% \n% USAGE:  [nVertices, nFaces] = out_tess_tri( BstFile, OutputFile )\n%         [nVertices, nFaces] = out_tess_tri( BstFile/TessMat, OutputFile, isOpenMEEG=0 )\n%\n% INPUT: \n%    - BstFile    : full path to Brainstorm file to export\n%    - OutputFile : full path to output file (with '.tri' extension)\n%    - isOpenMEEG : if flag set to 1, write the positions in meters instead of millimeters\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2011-2019\n\nif (nargin < 3) || isempty(isOpenMEEG)\n    isOpenMEEG = 0;\nend\n\n% ===== LOAD BRAINSTORM SURFACE =====\nif ischar(BstFile)\n    BstMat = in_tess_bst(BstFile);\nelse\n    BstMat = BstFile;\nend\n\n% ===== PREPARE VALUES ======\n% Vertices (=> in millimeters)\nif ~isOpenMEEG\n    BstMat.Vertices = BstMat.Vertices * 1000;\nend\n% Faces : remove 1 (convert to 0-based indices)\nFaces = BstMat.Faces - 1;\n% Normals\nVertNormals = BstMat.VertNormals;\n% Return surface sizes\nnVertices = length(BstMat.Vertices);\nnFaces = length(BstMat.Faces);\n\n% ===== SAVE FILE =====\n% Open file\n[fid, message] = fopen(OutputFile, 'w');\nif (fid < 0)\n    error(['Could not create file : ' message]);\nend\n% Write vertices and normals\nfprintf(fid, '- %g\\n', size(BstMat.Vertices,1));\nfprintf(fid, '%g %g %g %g %g %g\\n', [BstMat.Vertices, VertNormals]');\n% Write faces\nnfaces = size(Faces,1);\nfprintf(fid, '- %g %g %g\\n', [nfaces nfaces nfaces]);\nfprintf(fid, '%g %g %g\\n', Faces');\n% Close file\nfclose(fid);\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_tess_tri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24474176519895383}}
{"text": "% check whether the sequences are of the same length. \n% The sequences are aligned from begining. If some sequence is shorter, it\n% will be padded with a big negative number, i.e. -1e10, in the first dimension.  \n%\nfunction [mask, variableLength] = CheckTrajectoryLength(data)\n\nmask = permute(data(1,:,:), [2 3 1]) == -1e10;\n\nvariableLength = sum(mask(:));\n\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/CheckTrajectoryLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24461313884192076}}
{"text": "function [objset,trainList]=readAnnotation(Name_batch,theConf)\nMaxObjNum=1000000;\n\nminArea=theConf.data.minArea;\n\nfileID=fopen([theConf.data.catedir,'image_class_labels.txt'],'r');\nidClassPair=textscan(fileID,'%d %d');\nfclose(fileID);\nif((length(Name_batch)==1)&&(Name_batch(1)-'0'>0)&&(Name_batch(1)-'0'<=9))\n    logInd=idClassPair{2}==str2num(Name_batch);\n    imgIds=idClassPair{1}(logInd);\nelse\n    imgIds=idClassPair{1};\nend\n\nfileID=fopen([theConf.data.catedir,'train_test_split.txt'],'r');\nidTrainTestPair=textscan(fileID,'%d %d');\nfclose(fileID);\ntrainList=find(idTrainTestPair{2}==1);\n\nfileID=fopen([theConf.data.catedir,'classes.txt'],'r');\nbatchClassnamePair=textscan(fileID,'%d %s');\nfclose(fileID);\n%logInd=batchClassnamePair{1}==str2num(Name_batch);\n%classname=batchClassnamePair{2}(logInd);\n\nfileID=fopen([theConf.data.catedir,'images.txt'],'r');\nidNamePair=textscan(fileID,'%d %s');\nfclose(fileID);\n[~,idx,~]=intersect(idNamePair{1},imgIds);\nimgnames=idNamePair{2}(idx);\n\nfileID=fopen([theConf.data.catedir,'bounding_boxes.txt'],'r');\nidBndboxPair=textscan(fileID,'%d %d %d %d %d');\nfclose(fileID);\n[~,idx,~]=intersect(idBndboxPair{1},imgIds);\nx=idBndboxPair{2}(idx);\ny=idBndboxPair{3}(idx);\nwidth=idBndboxPair{4}(idx);\nheight=idBndboxPair{5}(idx);\n\nclear logInd fileID idClassPair idNamePair idBndboxPair\n\nobjset(MaxObjNum).folder=[];\nobjset(MaxObjNum).filename=[];\nobjset(MaxObjNum).name=[];\nobjset(MaxObjNum).bndbox=[];\nobjset(MaxObjNum).ID=[];\n\nj=0;\nfor i=1:length(imgnames)\n    filename=imgnames(i);\n    words=strsplit(filename{1},'.');\n    classID=str2num(words{1});\n    logInd=batchClassnamePair{1}==classID;\n    classname=batchClassnamePair{2}(logInd);\n    \n    name=classname;\n    bndbox.xmin=int2str(x(i));\n    bndbox.xmax=int2str(x(i)+width(i));\n    bndbox.ymin=int2str(y(i));\n    bndbox.ymax=int2str(y(i)+height(i));\n    if(~IsAreaValid(bndbox,minArea))\n        continue;\n    end\n    j=j+1;\n    objset(j).folder='.';\n    objset(j).filename=filename{1};\n    objset(j).name=name{1};\n    objset(j).bndbox=bndbox;\n    objset(j).ID=j;\n    if(j>MaxObjNum)\n        error('MaxObjNum is too small.');\n    end\nend\nobjset=objset(1:j);\n\n%load([theConf.output.dir,Name_batch,'/sampling.mat'],'validObj');\n%objset=objset(validObj);\nfor i=1:length(objset)\n    objset(i).ID=i;\nend\nend\n\n\nfunction pd=IsAreaValid(bndbox,minArea)\nxmin=str2double(bndbox.xmin);\nxmax=str2double(bndbox.xmax);\nymin=str2double(bndbox.ymin);\nymax=str2double(bndbox.ymax);\nif((xmax-xmin+1)*(ymax-ymin+1)>=minArea)\n    pd=true;\nelse\n    pd=false;\nend\nend\n", "meta": {"author": "zqs1022", "repo": "interpretableCNN", "sha": "6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823", "save_path": "github-repos/MATLAB/zqs1022-interpretableCNN", "path": "github-repos/MATLAB/zqs1022-interpretableCNN/interpretableCNN-6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823/code/data_input/data_input_CUB-200-2011/readAnnotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24461313884192076}}
{"text": "function map = yellowred(n)\n%CHROMAJS returns a divergent lightyellow-red color map\n%\n%   Usage: m = yellowred([n])\n%\n%   Input parameters:\n%       n - optional length of colormap (default uses the figure default length)\n%\n%   Output parameters:\n%       m - colormap [n 3]\n%\n%   YELLOWRED(N) returns an N-by-3 matrix containing a divergent colormap.\n%   Without a given N the same length as the current figure's colormap is used.\n%   For details on the colormap have a look at: https://bit.ly/2vC3Ogr\n%\n%   To change the colormap current figure run: colormap(yellowred)\n%\n% See also: generate_colormap, moreland, plot_sound_field\n\n%*****************************************************************************\n% The MIT License (MIT)                                                      *\n%                                                                            *\n% Copyright (c) 2010-2019 SFS Toolbox Developers                             *\n%                                                                            *\n% Permission is hereby granted,  free of charge,  to any person  obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without  restriction, including without limitation *\n% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *\n% and/or  sell copies of  the Software,  and to permit  persons to whom  the *\n% Software is furnished to do so, subject to the following conditions:       *\n%                                                                            *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software.                        *\n%                                                                            *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *\n% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *\n% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *\n% DEALINGS IN THE SOFTWARE.                                                  *\n%                                                                            *\n% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics.              *\n%                                                                            *\n% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking input parameters =======================================\nnargmin = 0;\nnargmax = 1;\nnarginchk(nargmin,nargmax);\nif nargin < nargmax\n    n = size(get(gcf,'colormap'),1);\nend\n\n\n%% ===== Computation =====================================================\ntable = [ 255, 255, 224\n255, 223, 184\n255, 188, 148\n255, 151, 119\n255, 105,  98\n238,  66,  86\n210,  31,  71\n176,   6,  44\n139,   0,   0];\nmap = generate_colormap(table,n);\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_plotting/colormaps/yellowred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24461313884192074}}
{"text": "classdef StructuredEdgeDetection < handle\n    %STRUCTUREDEDGEDETECTION  Class implementing edge detection algorithm\n    %\n    % As described in [Dollar2013].\n    %\n    % ### Structured forests for fast edge detection\n    %\n    % This module contains implementations of modern structured edge detection\n    % algorithms, i.e. algorithms which somehow takes into account pixel\n    % affinities in natural images.\n    %\n    % ![image01](https://docs.opencv.org/3.3.1/01.jpg)\n    % ![image02](https://docs.opencv.org/3.3.1/02.jpg)\n    % ![image03](https://docs.opencv.org/3.3.1/03.jpg)\n    % ![image04](https://docs.opencv.org/3.3.1/04.jpg)\n    % ![image05](https://docs.opencv.org/3.3.1/05.jpg)\n    % ![image06](https://docs.opencv.org/3.3.1/06.jpg)\n    % ![image07](https://docs.opencv.org/3.3.1/07.jpg)\n    % ![image08](https://docs.opencv.org/3.3.1/08.jpg)\n    % ![image09](https://docs.opencv.org/3.3.1/09.jpg)\n    % ![image10](https://docs.opencv.org/3.3.1/10.jpg)\n    % ![image11](https://docs.opencv.org/3.3.1/11.jpg)\n    % ![image12](https://docs.opencv.org/3.3.1/12.jpg)\n    %\n    % ## References\n    % [Dollar2013]:\n    % > Piotr Dollar and C Lawrence Zitnick. \"Structured forests for fast edge\n    % > detection\". In IEEE International Conference on Computer Vision (ICCV)\n    % > 2013, pages 1841-1848.\n    %\n    % [Lim2013]:\n    % > Joseph J Lim, C Lawrence Zitnick, and Piotr DollAr. \"Sketch tokens: A\n    % > learned mid-level representation for contour and object detection\".\n    % > In IEEE Conference on Computer Vision and Pattern Recognition (CVPR),\n    % > 2013, pages 3158-3165.\n    %\n    % See also: cv.StructuredEdgeDetection.StructuredEdgeDetection\n    %\n\n    properties (SetAccess = private)\n        % Object ID\n        id\n    end\n\n    methods\n        function this = StructuredEdgeDetection(model, varargin)\n            %STRUCTUREDEDGEDETECTION  The only constructor\n            %\n            %     obj = cv.StructuredEdgeDetection(model)\n            %     obj = cv.StructuredEdgeDetection(model, howToGetFeatures)\n            %\n            % ## Input\n            % * __model__ name of the file where the model is stored.\n            % * __howToGetFeatures__ optional name of MATLAB M-function that\n            %   implements custom feature extractor. A helper function for\n            %   training part of: \"P. Dollar and C. L. Zitnick. Structured\n            %   Forests for Fast Edge Detection, 2013\". You need it only if\n            %   you would like to train your own forest, otherwise leave it\n            %   unspecified for the default implementation. See example below.\n            %\n            % ## Example\n            % The following is an example of a custom feature extractor\n            % MATLAB function:\n            %\n            %     % This function extracts feature channels from src. The\n            %     % StructureEdgeDetection uses this feature space to detect\n            %     % edges.\n            %     function features = myRFFeatureGetter(src, opts)\n            %         % src: source image to extract features\n            %         % features: output n-channel floating-point feature matrix\n            %         % opts: struct of options\n            %         gnrmRad = opts.normRad;    % gradientNormalizationRadius\n            %         gsmthRad = opts.grdSmooth; % gradientSmoothingRadius\n            %         shrink = opts.shrink;      % shrinkNumber\n            %         outNum = opts.nChns;       % numberOfOutputChannels\n            %         gradNum = opts.nOrients;   % numberOfGradientOrientations\n            %\n            %         nsize = [size(src,1) size(src,2)] ./ shrink;\n            %         features = zeros([nsize outNum], 'single');\n            %         % ... here your feature extraction code\n            %     end\n            %\n            % TODO: Custom extractor is not internally used in the current\n            % cv.StructuredEdgeDetection implementation. See this\n            % [tutorial](https://docs.opencv.org/3.3.1/d2/d59/tutorial_ximgproc_training.html)\n            % for more information about training your own structured forest\n            % (it uses an external MATLAB toolbox for the training part).\n            %\n            % See also: cv.StructuredEdgeDetection.detectEdges\n            %\n            this.id = StructuredEdgeDetection_(0, 'new', model, varargin{:});\n        end\n\n        function delete(this)\n            %DELETE  Destructor\n            %\n            %     obj.delete()\n            %\n            % See also: cv.StructuredEdgeDetection\n            %\n            if isempty(this.id), return; end\n            StructuredEdgeDetection_(this.id, 'delete');\n        end\n    end\n\n    %% Algorithm\n    methods\n        function clear(this)\n            %CLEAR  Clears the algorithm state\n            %\n            %     obj.clear()\n            %\n            % See also: cv.StructuredEdgeDetection.empty,\n            %  cv.StructuredEdgeDetection.load\n            %\n            StructuredEdgeDetection_(this.id, 'clear');\n        end\n\n        function b = empty(this)\n            %EMPTY  Checks if detector object is empty\n            %\n            %     b = obj.empty()\n            %\n            % ## Output\n            % * __b__ Returns true if the detector object is empty (e.g in the\n            %   very beginning or after unsuccessful read).\n            %\n            % See also: cv.StructuredEdgeDetection.clear,\n            %  cv.StructuredEdgeDetection.load\n            %\n            b = StructuredEdgeDetection_(this.id, 'empty');\n        end\n\n        function save(this, filename)\n            %SAVE  Saves the algorithm parameters to a file\n            %\n            %     obj.save(filename)\n            %\n            % ## Input\n            % * __filename__ Name of the file to save to.\n            %\n            % This method stores the algorithm parameters in the specified\n            % XML or YAML file.\n            %\n            % See also: cv.StructuredEdgeDetection.load\n            %\n            StructuredEdgeDetection_(this.id, 'save', filename);\n        end\n\n        function load(this, fname_or_str, varargin)\n            %LOAD  Loads algorithm from a file or a string\n            %\n            %     obj.load(fname)\n            %     obj.load(str, 'FromString',true)\n            %     obj.load(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __fname__ Name of the file to read.\n            % * __str__ String containing the serialized model you want to\n            %   load.\n            %\n            % ## Options\n            % * __ObjName__ The optional name of the node to read (if empty,\n            %   the first top-level node will be used). default empty\n            % * __FromString__ Logical flag to indicate whether the input is a\n            %   filename or a string containing the serialized model.\n            %   default false\n            %\n            % This method reads algorithm parameters from the specified XML or\n            % YAML file (either from disk or serialized string). The previous\n            % algorithm state is discarded.\n            %\n            % See also: cv.StructuredEdgeDetection.save\n            %\n            StructuredEdgeDetection_(this.id, 'load', fname_or_str, varargin{:});\n        end\n\n        function name = getDefaultName(this)\n            %GETDEFAULTNAME  Returns the algorithm string identifier\n            %\n            %     name = obj.getDefaultName()\n            %\n            % ## Output\n            % * __name__ This string is used as top level XML/YML node tag\n            %   when the object is saved to a file or string.\n            %\n            % See also: cv.StructuredEdgeDetection.save,\n            %  cv.StructuredEdgeDetection.load\n            %\n            name = StructuredEdgeDetection_(this.id, 'getDefaultName');\n        end\n    end\n\n    %% StructuredEdgeDetection\n    methods\n        function dst = detectEdges(this, src)\n            %DETECTEDGES  The function detects edges in src and draw them to dst\n            %\n            %     dst = obj.detectEdges(src)\n            %\n            % ## Input\n            % * __src__ source image (RGB, float, in [0;1]) to detect edges.\n            %\n            % ## Output\n            % * __dst__ destination image (grayscale, float, in [0;1]) where\n            %   edges are drawn.\n            %\n            % The algorithm underlies this function is much more robust to\n            % texture presence, than common approaches, e.g. cv.Sobel.\n            %\n            % See also: cv.Sobel, cv.Canny\n            %\n            dst = StructuredEdgeDetection_(this.id, 'detectEdges', src);\n        end\n\n        function orientation_image = computeOrientation(this, edge_image)\n            %COMPUTEORIENTATION  Computes orientation map from edge image\n            %\n            %     orientation_image = obj.computeOrientation(edge_image)\n            %\n            % ## Input\n            % * **edge_image** edge image from `detectEdges` function.\n            %\n            % ## Output\n            % * **orientation_image** orientation image.\n            %\n            % See also: cv.StructuredEdgeDetection.detectEdges\n            %\n            orientation_image = StructuredEdgeDetection_(this.id, 'computeOrientation', edge_image);\n        end\n\n        function dst = edgesNms(this, edge_image, orientation_image, varargin)\n            %EDGESNMS  Suppress edges (nonmaximum suppression)\n            %\n            %     dst = obj.edgesNms(edge_image, orientation_image)\n            %     dst = obj.edgesNms(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * **edge_image** edge image from `detectEdges` function.\n            % * **orientation_image** orientation image from `computeOrientation` function.\n            %\n            % ## Output\n            % * __dst__ suppressed image (grayscale, float, in [0;1]).\n            %\n            % ## Options\n            % * __R__ radius for NMS suppression. default 2\n            % * __S__ radius for boundary suppression. default 0\n            % * __M__ multiplier for conservative suppression. default 1.0\n            % * __IsParallel__ enables/disables parallel computing.\n            %   default true\n            %\n            % The function suppresses edges where edge is stronger in\n            % orthogonal direction.\n            %\n            % See also: cv.StructuredEdgeDetection.detectEdges,\n            %  cv.StructuredEdgeDetection.computeOrientation\n            %\n            dst = StructuredEdgeDetection_(this.id, 'edgesNms', edge_image, orientation_image, varargin{:});\n        end\n    end\n\n    %% Static functions\n    methods (Static)\n        function features = getFeatures(src, opts)\n            %GETFEATURES  Extracts features from image\n            %\n            %     features = cv.StructuredEdgeDetection.getFeatures(src, opts)\n            %\n            % ## Input\n            % * __src__ source image to extract features (RGB float in [0;1]).\n            % * __opts__ a scalar struct of random forest options\n            %   (feature params), with the following fields:\n            %   * __normRad__ `gradientNormalizationRadius` gradient\n            %     normalization radius.\n            %   * __grdSmooth__ `gradientSmoothingRadius` radius for smoothing\n            %     of gradients (using convolution with triangle filter).\n            %   * __shrink__ `shrinkNumber` amount to shrink channels.\n            %   * __nChns__ `numberOfOutputChannels` number of edge\n            %     orientation bins for output.\n            %   * __nOrients__ `numberOfGradientOrientations` number of\n            %     orientations per gradient scale.\n            %\n            % ## Output\n            % * __features__ extracted features.\n            %\n            % Extracted features are appropriate for StructuredEdgeDetection\n            % training.\n            %\n            % See also: cv.StructuredEdgeDetection.StructuredEdgeDetection\n            %\n            features = StructuredEdgeDetection_(0, 'getFeatures', src, opts);\n        end\n    end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/StructuredEdgeDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24461313206361898}}
{"text": "function [contact, fric_coef, geometry] = RightSoleInside(robot)\n  \n    param = sys.GetExtraParams();\n    \n    \n    r_foot_frame = robot.Joints(getJointIndices(robot, 'r_leg_akx'));\n    contact = CoordinateFrame(...\n        'Name','RightSole',...\n        'Reference',r_foot_frame,...\n        'Offset',[0, param.wf/2, param.hf],...\n        'R',[0,0,0]... % z-axis is the normal axis, so no rotation required\n        );\n    \n    fric_coef.mu = param.mu;\n    fric_coef.gamma = param.gamma;\n    \n    \n    geometry.la = param.wf/2;\n    geometry.lb = param.wf/2;\n    geometry.La = param.lt;\n    geometry.Lb = param.lh;\nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/atlas/+sys/+frames/RightSoleInside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2445714984900063}}
{"text": "function tc = tc_visualizeGlm(tc, parent);\n%\n% tc = tc_visualizeGlm(tc, parent);\n%\n% Provide graphics that visualize the\n% setup and result of applying a general\n% linear model to a time course. Requires\n% that you first run tc_applyGlm on\n% the tc time course struct.\n%\n%\n% ras 04/05.\nif nargin<1,    tc = get(gcf,'UserData');     end\nif nargin<2,    parent = tc.ui.plot;          end\nif parent==gcf | parent==get(gcf, 'CurrentAxes')\n    % make a uipanel to fit on the target\n    parent = uipanel('Parent', parent, ...\n        'Units', 'normalized', ...\n        'BackgroundColor', get(gcf, 'Color'), ...\n        'Position', [0 0 1 1]);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% apply a GLM if needed\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(tc, 'glm')\n    tc = tc_applyGlm(tc);\nend\nX = tc.glm.designMatrix;\nY = tc.wholeTc(:);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% clean up existing objects in figure\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\notherAxes = findobj('Type', 'axes','Parent', parent);\ndelete(otherAxes);\notherUiControls = findobj('Type', 'uicontrol', 'Parent',parent);\ndelete(otherUiControls);\naxes('Parent', parent); % shift focus to parent uipanel\ndelete(gca);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Visualize results: diff't options for deconvolved\n% data and non-deconvolved (using HRF)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif isequal(tc.glm.type, 'selective averaging')\n    tc = tc_plotDeconvolvedTCs(tc, parent);\n    return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% if we got here, the GLM is non-deconvolved, using HRF   %\n% show hemodynamic response function used for GLM         %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naxes('Parent', parent, 'Position', [.05 .6 .15 .2]); % [.13 .58 .21 .34]\nplot(tc.glm.hrf,'k','LineWidth',2);\nif tc.params.grid==1\n    grid on\nend\nxlabel('Time, frames')\nylabel('Arbitrary Units')\nif isnumeric(tc.params.glmHRF)\n    opts = {sprintf('Mean trial for conditions \\n %s',num2str(tc.params.snrConds)), ...\n        'Boynton gamma function', 'SPM difference-of-gammas' ...\n        'Dale & Buckner ''97'};\n    hrfName = opts{tc.params.glmHRF};\nelse\n    hrfName = tc.params.glmHRF; hrfName(hrfName=='_') = ' ';\nend\ntitle({'HRF function used: ' hrfName}, 'FontWeight', 'bold')\naxis tight, axis square, set(gca, 'Box', 'off');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n% show design matrix                     %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \naxes('Parent', parent, 'Position', [.3 .55 .2 .34]); % [.13 .11 .21 .34]\nhImg = imagesc(X);\ncolormap autumn\nnConds = sum(tc.trials.condNums>0);\ntickPts = [1:nConds];\ntickLabels = {'Individual Conditions' 'DC Predictors for each run'};\nset(gca,'XTick',tickPts);\nxlabel('Predictors (Conditions + DC)')\nylabel('Time, Frames')\ntitle('Design Matrix', 'FontWeight', 'bold')\nset(hImg, 'ButtonDownFcn', 'zoom');\ncolorbar vert\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% bar beta values for selected conditions %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naxes('Parent', parent, 'Position', [.6 .55 .33 .34]);  %[.57 .58 .33 .34]\nsel = setdiff( find(tc_selectedConds(tc)), 1);\ntmp = tc.trials.condColors(sel);\nfor i = 1:length(sel), col(i,:) = tmp{i}; end\nxstr = tc_condInitials(tc.trials.condNames(sel));\n% for i = 1:length(sel), xstr{i} = num2str(tc.trials.condNums(sel(i))); end\nmybar(tc.glm.betas(sel-1), tc.glm.sems(sel-1), xstr, [], col);\n% xlabel Predictors\n% ylabel('% Signal Change')\nset(gca, 'Box', 'off');\nif tc.params.grid, grid on; else grid off; end\ntitle('Beta Values', 'FontWeight', 'bold');\nylabel('\\beta', 'FontWeight', 'bold', 'Rotation', 0, 'FontSize', 14);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n% show time course + selected predictors %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nif tc.params.legend, ysz = .58; else ysz = .72; end\ntc.glm.tcAxes = axes('Parent', parent, 'Position', [.1 .1 ysz .3]); \n\n% construct matrix of predictor functions for each condition:\n% (these predictors will include the dc components as well, so we \n% won't have them as separate traces):\ndc = nConds+1:size(tc.glm.betas, 2);  % indices of DC components\nfor c = 1:nConds\n\tpredictors(:,c) = X(:,[c dc]) * [tc.glm.betas(:,[c dc])'];\nend\n\n% plot\nt = [1:length(tc.wholeTc)] .* tc.TR;\nhold on\nhY = plot(t, tc.wholeTc(:), 'k-', 'LineWidth', 2);\nhPred = plot(t, predictors(:,sel-1), 'LineStyle', '-', 'LineWidth', 1.5);\nhTot = plot(t, X*tc.glm.betas', 'k-', 'LineWidth', 2); \nhRes = plot(t, tc.glm.residual(:), 'k--', 'LineWidth', 1.5);\nplot(t, zeros(size(t)), 'k:');\nset(hPred, 'Visible', 'off');\nset(hRes, 'Visible', 'off');\nset(gca, 'Box', 'off');\nif tc.params.grid, grid on; else grid off; end\nsetLineColors([{'k'} tc.trials.condColors(sel) {[.2 .4 .8] [.8 0 0]}]);\nxlabel('Time, sec')\nylabel('% Signal')\ntitle('Time course + Scaled Predictors', 'FontWeight', 'bold')\nzoom\n\n% for longer time courses, may want a UI control\n% scrollbar(tc.glm.tcAxes, tc.wholeTc);\nscale = 300;  % max seconds to nicely plot TC\nscrollbar(gca, scale);\n\n% create toggles for the different traces\nif tc.params.legend, xx = .72; else xx = .9; end\ncb = ['tmp = {''off'' ''on''}; val = get(gcbo, ''Value'')+1; ' ...\n      'set(get(gcbo,''UserData''), ''Visible'', tmp{val}); ' ...\n      'clear tmp val '];\n  \nh3 = uicontrol('Style', 'checkbox', 'Units', 'normalized', ...\n               'Position', [xx .4 .08 .04], 'String', 'Time Course', ...\n               'BackgroundColor', 'w', 'UserData', hY, ...\n               'Value', 1, 'Callback', cb);\nh4 = uicontrol('Style', 'checkbox', 'Units', 'normalized', ...\n               'Position', [xx .32 .08 .04], 'String', 'Predictors', ...\n               'BackgroundColor', 'w', 'UserData', hPred, ...\n               'Value', 0, 'Callback', cb);\nh5 = uicontrol('Style', 'checkbox', 'Units', 'normalized', ...\n               'Position', [xx .24 .08 .04], 'String', 'Best Fit', ...\n               'BackgroundColor', 'w', 'UserData', hTot, ...\n               'Value', 1, 'Callback', cb);\nh6 = uicontrol('Style', 'checkbox', 'Units', 'normalized', ...\n               'Position', [xx .16 .08 .04], 'String', 'Residual', ...\n               'BackgroundColor', 'w', 'UserData', hRes, ...\n               'Value', 0, 'Callback', cb);\n\n% lastly, show % variance explained\nvarEx = sprintf('%2.1f%% Variance Explained', tc.glm.varianceExplained * 100);\nuicontrol('Style', 'text', 'Units', 'normalized', ...\n          'Position', [xx-.1 .08 .18 .04], 'String', varEx, ...\n          'BackgroundColor', 'w','FontSize', 15);\n           \nreturn\n% /-------------------------------------------------------------------/ %\n\n\n\n\n% /-------------------------------------------------------------------/ %\nfunction tc = tc_plotDeconvolvedTCs(tc, parent)\n% plot the deconvolved time courses in the same way as for the\n% default plot, combining mean amplitudes on one side and mean time\n% courses on the other.\nsel = find(tc_selectedConds(tc));\n% sel = sel(sel>1); % no baseline estimated\nnConds = length(sel);\nframeWindow = unique(round(tc.timeWindow./tc.TR));\nprestim = -1 * frameWindow(1);\npeakFrames = unique(round(tc.peakPeriod./tc.TR));\nbslFrames = unique(round(tc.bslPeriod./tc.TR));\npeakFrames = find(ismember(frameWindow,peakFrames));\nbslFrames = find(ismember(frameWindow,bslFrames));\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% plot mean amplitudes %\n%%%%%%%%%%%%%%%%%%%%%%%%\naxes('Position', [.1 .2 .35 .6], 'Parent', parent);\n% exp7_plotAmps(tc);\nhold on\n\nh1 = gca;\n\nlineWidth = 2;\nlabels = {};\n\ncolors = tc.trials.condColors(sel);\nX = tc.trials.condNums(sel);\nY = tc.glm.amps(sel-1);\nE = tc.glm.amp_sems(sel-1);\nmybar(Y, E, tc_condInitials(tc.trials.condNames(sel)), [], colors);\naxis tight\nset(gca, 'Box', 'off')\nif tc.params.grid==1\n    grid on\nend\n\n% set line width\nhtmp = findobj('Type','line','Parent',gca);\nset(htmp,'LineWidth',lineWidth);\n\n% add labels\nset(gca,'XTick',[1:nConds]);\nif tc.params.legend==0, set(gca, 'XTickLabel', labels); end\nxlabel('Condition', 'FontWeight', 'bold', 'FontAngle', 'italic');\nylabel('Mean Amplitude, % Signal', 'FontWeight', 'bold', ...\n    'FontAngle', 'italic');\ntitle('Deconvolved Amplitudes', 'FontWeight', 'bold');\n\n% set axes to frame bars nicely\n% axis auto;\nAX = axis;\nAX(1:2) = [0 nConds+1];\nif isfield(tc.params,'axisBounds') & ~isempty(tc.params.axisBounds)\n    AX(3:4) = tc.params.axisBounds(3:4);\nend\naxis(AX);\n\n%%%%%%%%%%%%%%%%%%%%%\n% mean time courses %\n%%%%%%%%%%%%%%%%%%%%%\nh2 = axes('Position', [.5 .2 .4 .6], 'Parent', parent);\nhold on\n\nfor i = sel-1\n    htmp = errorbar(tc.timeWindow, tc.glm.betas(:,i), tc.glm.sems(:,i));\n    set(htmp, 'Color', tc.trials.condColors{i+1}, 'LineWidth', 2);\nend\n\n% indicate the peak and baseline periods, if selected\nif tc.params.showPkBsl==1\n    AX = axis;\n    plot(tc.bslPeriod, repmat(AX(3),size(tc.bslPeriod)), ...\n        'k', 'LineWidth', 3.5);\n    plot(tc.peakPeriod, repmat(AX(4),size(tc.peakPeriod)), ...\n        'r', 'LineWidth', 3.5);\nend\n\nif tc.params.grid==1\n    grid on\nend\n\nif isfield(tc.params,'axisBounds') & ~isempty(tc.params.axisBounds)\n    axis(h2, tc.params.axisBounds);\nend\n\nxlabel('Trial time, secs', 'FontWeight', 'bold', 'FontAngle', 'italic');\nylabel('% Signal', 'FontWeight', 'bold', 'FontAngle', 'italic');\ntitle('Deconvolved Time Courses', 'FontWeight', 'bold');\n\nAX = axis;\ntxt = sprintf('Variance Explained: %3.1f%%', 100*tc.glm.varianceExplained);\ntext(AX(1) + .1*diff(AX(1:2)), AX(3) + .9*diff(AX(3:4)), txt, ...\n           'FontSize', 12, 'FontWeight', 'bold');\n\nreturn\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/TimeCourseUI/tc_visualizeGlm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.244571492275262}}
{"text": "function [initXOptions, optionsAll] = hsvargplvmInitXOptions(Ytr, options, globalOpt)\n\nstackedOpt = globalOpt.stackedInitOpt;\n\n%--- Here we have the option of using Bayesian GPLVM or GPLVM for\n% initialising the latent spaces. If this is the case, train the\n% corresponding models\noptionsAll = hsvargplvmCreateOptions(Ytr, options, globalOpt);\ninitXOptions = cell(1, options.H);\nfor h=1:options.H\n    if strcmp(optionsAll.initX{h}, 'vargplvm') | strcmp(optionsAll.initX{h}, 'fgplvm')\n        initXOptions{h}{1} = optionsAll;\n        % DOn't allow the D >> N trick for layers > 1\n        if h~=1\n            if isfield(initXOptions{h}{1}, 'enableDgtN')\n                initXOptions{h}{1}.enableDgtN = false;\n            end\n        end\n        initXOptions{h}{1}.latentDim = optionsAll.Q{h};\n        initXOptions{h}{1}.numActive = optionsAll.K{h}{1};\n        initXOptions{h}{1}.kern = optionsAll.kern{h}{1};\n        initXOptions{h}{1}.initX = 'ppca';\n        initXOptions{h}{1}.initSNR = 90;\n        initXOptions{h}{1}.numActive = 50;\n        initXOptions{h}{2} = 160;\n        initXOptions{h}{3} = 30;\n        if ~isempty(stackedOpt)\n            if isfield(stackedOpt, 'stackedInitVardistIters') && ~isempty(stackedOpt.stackedInitVardistIters)\n                initXOptions{h}{2} = stackedOpt.stackedInitVardistIters;\n            end\n            if isfield(stackedOpt, 'stackedInitIters') && ~isempty(stackedOpt.stackedInitIters)\n                initXOptions{h}{3} = stackedOpt.stackedInitIters;\n            end\n            if isfield(stackedOpt, 'stackedInitSNR') && ~isempty(stackedOpt.stackedInitSNR)\n                initXOptions{h}{1}.initSNR = stackedOpt.stackedInitSNR;\n            end\n            if isfield(stackedOpt, 'stackedInitK') && ~isempty(stackedOpt.stackedInitK)\n                initXOptions{h}{1}.numActive = stackedInitK;\n            end\n        end\n    elseif ~isempty(stackedOpt) && (iscell(stackedOpt) && ~isempty(stackedOpt{h}))\n        initXOptions{h} = stackedOpt{h};\n    else\n        initXOptions{h} = {};\n    end\nend", "meta": {"author": "SheffieldML", "repo": "deepGP", "sha": "f72410a0fb354451f2bf58cfe247d2b5d3b08e58", "save_path": "github-repos/MATLAB/SheffieldML-deepGP", "path": "github-repos/MATLAB/SheffieldML-deepGP/deepGP-f72410a0fb354451f2bf58cfe247d2b5d3b08e58/deepGP/matlab/hsvargplvmInitXOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24457149227526198}}
{"text": "function planC = getFFDCND(planC,leak,sigma,kernelSize)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n%leak = 0.035; %0.018; %leakage in per *100\n\n%sigma = 0.14; %0.02\n\n%kernelSize = 73; %5\n\nindexS = planC{end};\n\ndoseNum = 1;\n    \ni = find(strcmpi({planC{indexS.structures}.structureName}, 'skin'));\n\nif isempty(i)\n    i = find(strcmpi({planC{indexS.structures}.structureName}, 'Body'));\nend\n\nif isempty(i)\n    i = find(strcmpi({planC{indexS.structures}.structureName}, 'External'));\nend\n\nif isempty(i)\n    error('Skin structure must be defined to generate a uniform CT.');\nelse\n    i = i(1);    \nend\n    \nstructNum = i;\n    \nscanSet = 1;\n\n%currentDir = cd;\n\n% [FileName,path] = uigetfile('*.*','Select DICOM Dose File, RD');\n% \n% if path == 0\n%     errordlg('DICOM Dose File Should exist');\n%     error('DICOM Dose File Should exist');\n% end\n% \n% cd(path);\n% \n% fileList = dir;\n% \n% filesToRun = {};\n% \n% matches = strmatch('RD', {fileList.name});\n\n% cd(currentDir);\n% \n% for i = 1:length(matches)\n%     [maxDose, dA] = getDICOMMaxDose([path fileList(matches(i)).name]);\n%     dM(i) = maxDose;\n% end\n\nfor i = 1 : planC{7}.FractionGroupSequence.Item_1.NumberOfBeams\n\n    \n    BeamMeterset = planC{7}.FractionGroupSequence.Item_1.ReferencedBeamSequence.(['Item_' num2str(i)]).BeamMeterset;\n    \n    bs = planC{7}.BeamSequence.(['Item_' num2str(i)]);\n       \n    LS = getDICOMLeafPositions(bs);\n    \n    if ~isfield(LS,'manufacturer') && isfield(planC{7},'Manufacturer')\n        LS.manufacturer = planC{7}.Manufacturer;\n    elseif ~isfield(LS,'manufacturer') && ~isfield(planC{7},'Manufacturer')\n        errordlg('Manufacturer is not specified. Using Varian as default.');\n        LS.manufacturer = 'Varian';\n    end\n           \n    [inflMap, xV, yV, colDividerXCoord, rowDividerYCoord, rowLeafPositions,MLCopening] = getLSInfluenceMapFactor(LS,leak,bs.BeamNumber);\n          \n    gA = bs.ControlPointSequence.Item_1.GantryAngle;\n    iC = bs.ControlPointSequence.Item_1.IsocenterPosition;\n        \n    if ~isfield(planC{7},'PatientSetupSequence')\n        disp('Patient Setup Missing. Setting to defalt HSF');\n        position = 'HSF';\n    else\n        if ~isfield(planC{7}.PatientSetupSequence,(['Item_' num2str(i)]))\n            position = {planC{7}.PatientSetupSequence.(['Item_' num2str(1)]).PatientPosition};\n        else\n            position = {planC{7}.PatientSetupSequence.(['Item_' num2str(i)]).PatientPosition};\n        end\n    end\n    \n    isocenter = [];\n    \n    if strcmpi(position, 'HFP')\n        isocenter.x = iC(1)/10;\n        isocenter.y = iC(2)/10;\n        isocenter.z = -iC(3)/10;\n    else\n        isocenter.x = iC(1)/10;\n        isocenter.y = -iC(2)/10;\n        isocenter.z = -iC(3)/10;\n    end\n          \n    isodistance = bs.SourceAxisDistance/10;\n    \n    isocenter = [isocenter.x,isocenter.y, isocenter.z];\n    \n    [DoseF, rDepth, xMin, xMax, yMin, yMax, PBSizeX, PBSizeY, maxFlu] = getDose_UnitD(sigma,kernelSize,bs,inflMap, xV, yV,MLCopening);\n    \n    clear inflMap\n    \n    [xD, yD, zD] = getDoseXYZVals(planC{indexS.dose}(doseNum));\n    \n    [xM, yM, zM] = meshgrid(xD, yD, zD);\n        \n    coll3V = scan2Collimator([xM(:) yM(:) zM(:)], (gA/360)*2*pi, 0, 0, isocenter, isodistance);\n    \n%    distsquared = sepsq(coll3V', [0 0 0]');\n    \n    coll3V = (coll3V./ repmat(coll3V(:,3), [1 3])) * -isodistance;\n    \n    toKeep = coll3V(:,1) <= xMax + PBSizeX*(kernelSize+1)/2  & coll3V(:,1) >= xMin - PBSizeX*(kernelSize+1)/2 & coll3V(:,2) >= yMin - PBSizeY*(kernelSize+1)/2  & coll3V(:,2) <= yMax + PBSizeY*(kernelSize+1)/2 ;\n    \n    pointsToInterpolate = coll3V(toKeep,:);\n    \n    clear coll3V distsquared\n    \n    radDepthV = getRadiologicalDepth(xM(toKeep), yM(toKeep), zM(toKeep), (gA/360)*2*pi, isocenter, isodistance, structNum, scanSet, planC);\n    \n    dV = finterp3(pointsToInterpolate(:,1), pointsToInterpolate(:,2), radDepthV, DoseF, [(xMin - PBSizeX*(kernelSize+1)/2) PBSizeX (xMax + PBSizeX*(kernelSize+1)/2)], [(yMin - PBSizeY*(kernelSize+1)/2)  PBSizeY (yMax + PBSizeY*(kernelSize+1)/2)], rDepth, 0);\n    \n    %Should be checked for now turn off    \n    %dV = dV./distsquared(toKeep);\n    \n    dose3D = zeros(size(xM));\n         \n    dose3D(toKeep) = dV;\n    \n    %dose3D = dose3D/max(dose3D(:));\n    \n    %Normalize to max dose  \n    %dose3D = dM(i)*(dose3D/max(dose3D(:)));\n    \n    %Normalize to dose at isocentr\n%     [maxDose, dA] = getDICOMMaxDose([path fileList(matches(i)).name]);\n%     \n%     planC{indexS.dose}(end + 1) = planC{indexS.dose}(1);\n%     planC{indexS.dose}(end).doseArray = dA;\n%     \n%     Dose_Cl = getDoseAt(length(planC{indexS.dose}),isocenter(1),isocenter(2),isocenter(3),planC);\n%     \n%     planC{indexS.dose}(end) = [];\n%     \n%     planC{indexS.dose}(end + 1) = planC{indexS.dose}(1);\n%     planC{indexS.dose}(end).doseArray = dose3D;\n%     \n%     Dose_N = getDoseAt(length(planC{indexS.dose}),isocenter(1),isocenter(2),isocenter(3),planC);\n%     \n%     planC{indexS.dose}(end) = [];\n    \n %   dose3D = (Dose_Cl/Dose_N)*dose3D;\n \n dose3D = BeamMeterset*dose3D;\n    \n    if ~exist('dose')\n        dose = dose3D;\n    else\n        dose = dose + dose3D;\n    end\n    \n    clear xM yM zM dose3D;\n        \nend\n\nmask = find(planC{8}(1).doseArray);\n\ndose1 = zeros(size(planC{8}(1).doseArray));\n\ndose1(mask) = dose(mask);\n\nplanC{8}(end+1) = planC{8}(1);\n\nplanC{8}(end).doseArray = dose1;\n\nplanC{8}(end).fractionGroupID = 'planCheck_Dose';\n\n%m = max(planC{8}(1).doseArray(:));\n\nmM = mean(planC{8}(1).doseArray(:));\n\n%planC{8}(end).doseArray = m*planC{8}(end).doseArray./max(planC{8}(end).doseArray(:));\n\nplanC{8}(end).doseArray = mM*planC{8}(end).doseArray./mean(planC{8}(end).doseArray(:));", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/FFDC/getFFDCND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.24457016731765857}}
{"text": "function [structVol, planC] = getStructureVol(structNum,planC)\n% getStructureVol\n% This function returns the abslute volume of a structure. Can be accessed \n% from MATLAB command line or from CERR command. \n% \n% Created DK \n% Usage\n% structVol = getStructureVol(structNum)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n\nif ~exist('planC','var')\n    global planC\nend\nindexS = planC{end};\noptS    = planC{indexS.CERROptions};\n\n%Get the scan number associated with the requested structure.\nscanSet = getStructureAssociatedScan(structNum, planC);\n\ndeltaY = planC{indexS.scan}(scanSet).scanInfo(1).grid1Units;\n\nROIImageSize = [planC{indexS.scan}(scanSet).scanInfo(1).sizeOfDimension1  planC{indexS.scan}(scanSet).scanInfo(1).sizeOfDimension2];\n\n%Get raster segments for structure.\n[segmentsM, planC, isError] = getRasterSegments(structNum, planC);\nnumSegs = size(segmentsM,1);\n\n%Relative sampling of ROI voxels in this place, compared to CT spacing.\n%Set when rasterSegments are generated (usually on import).\nsampleRate = optS.ROISampleRate;\n\n%Sample the rows\nindFullV =  1 : numSegs;\nif sampleRate ~= 1\n    rV = 1 : length(indFullV);\n    rV([rem(rV+sampleRate-1,sampleRate)~=0]) = [];\n    indFullV = rV;\nend\n\n%Block process to avoid swamping on large structures\nif isfield(optS, 'DVHBlockSize') & ~isempty(optS.DVHBlockSize)\n    DVHBlockSize = optS.DVHBlockSize;\nelse\n    DVHBlockSize = 5000;\nend\n\nblocks = ceil(length(indFullV)/DVHBlockSize);\nvolsV  = [];\nscansV = [];\n\nstart = 1;\n\nfor b = 1 : blocks\n\n    %Build the interpolation points matrix\n\n    dummy = zeros(1,DVHBlockSize * ROIImageSize(1));\n    x1V = dummy;\n    y1V = dummy;\n    z1V = dummy;\n    volsSectionV =  dummy;\n\n    if start+DVHBlockSize > length(indFullV)\n        stop = length(indFullV);\n    else\n        stop = start + DVHBlockSize - 1;\n    end\n\n    indV = indFullV(start:stop);\n\n    mark = 1;\n    \n    for i = indV\n        tmpV = segmentsM(i,1:10);\n        delta = tmpV(5) * sampleRate;\n        xV = tmpV(3): delta : tmpV(4);\n        len = length(xV);\n        rangeV = ones(1,len);\n        yV = tmpV(2) * rangeV;\n        zV = tmpV(1) * rangeV;\n        sliceThickness = tmpV(10);\n        %v = delta^2 * sliceThickness;\n        v = delta * (deltaY*sampleRate) * sliceThickness;\n        x1V(mark : mark + len - 1) = xV;\n        y1V(mark : mark + len - 1) = yV;\n        z1V(mark : mark + len - 1) = zV;\n        volsSectionV(mark : mark + len - 1) = v;\n        mark = mark + len;\n    end\n\n    %cut unused matrix elements\n    x1V = x1V(1:mark-1);\n    y1V = y1V(1:mark-1);\n    z1V = z1V(1:mark-1);\n    volsSectionV = volsSectionV(1:mark-1);\n\n    %Get transformation matrices for both scan and structure.\n    transMScan    = getTransM('scan', scanSet, planC);\n    transMStruct  = getTransM('struct', structNum, planC);\n\n    %Forward transform the structure's coordinates.\n    if ~isempty(transMStruct)\n        [x1V, y1V, z1V] = applyTransM(transMStruct, x1V, y1V, z1V);\n    end\n\n    %Back transform the coordinates into the scans' coordinate system.\n    if ~isempty(transMScan)\n        [x1V, y1V, z1V] = applyTransM(inv(transMScan), x1V, y1V, z1V);\n    end\n\n    %Interpolate.\n    [scansSectionV] = getScanAt(scanSet, x1V, y1V, z1V, planC);\n\n    scansV = [scansV, scansSectionV];\n    volsV  = [volsV, volsSectionV];\n\n    start = stop + 1;\n\nend\n\nvolsV = volsV * sampleRate^2;  %must account for sampling rate!\nstructVol = sum(sum(volsV));", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/getStructureVol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2444767650454476}}
{"text": "%%*******************************************************************\n%% HSDHKMpred: Compute (dX,dy,dZ) for the H..K..M direction.\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*******************************************************************\n\nfunction [par,dX,dy,dZ,coeff,L,hRd] = ...\n    HSDHKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol)\n\nglobal schurfun schurfun_par\n%%\n%% compute HKM scaling\n%%\nZinv = cell(size(blk,1),1);   dd = cell(size(blk,1),1);\ngamx = cell(size(blk,1),1);   gamz = cell(size(blk,1),1);\nfor p = 1:size(blk,1)\n    pblk = blk(p,:);\n    n = sum(pblk{2});\n    numblk = length(pblk{2});\n    if strcmp(pblk{1},'l')\n        Zinv{p} = 1./Z{p};\n        dd{p} = X{p}./Z{p};\n    elseif strcmp(pblk{1},'q')\n        gaptmp  = qops(pblk,X{p},Z{p},1);\n        gamz2   = qops(pblk,Z{p},Z{p},2);\n        gamz{p} = sqrt(gamz2);\n        Zinv{p} = qops(pblk,-1./gamz2,Z{p},4);\n        dd{p}   = qops(pblk,gaptmp./gamz2,ones(n,1),4);\n    elseif strcmp(pblk{1},'s')\n        if (numblk == 1)\n            Zinv{p} = Prod2(pblk,full(invZchol{p}),invZchol{p}',1);\n        else\n            Zinv{p} = Prod2(pblk,invZchol{p},invZchol{p}',1);\n        end\n    end\nend\npar.Zinv = Zinv; par.gamx = gamx; par.gamz = gamz; par.dd = dd;\n%%\n%% compute schur matrix\n%%\nm = par.m;\nschur = sparse(m+2,m+2);\nUU = [];  EE = [];\n%%\nfor p = 1:size(blk,1)\n    pblk = blk(p,:);\n    if strcmp(pblk{1},'l')\n        [schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);\n    elseif strcmp(pblk{1},'q');\n        [schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.Zinv,X);\n    elseif strcmp(pblk{1},'s')\n        if isempty(schurfun{p})\n            schur = schurmat_sblk(blk,At,par,schur,p,X,par.Zinv);\n        elseif ischar(schurfun{p})\n            if ~isempty(par.permZ{p})\n                Zpinv = Zinv{p}(par.permZ{p},par.permZ{p});\n                Xp = X{p}(par.permZ{p},par.permZ{p});\n            else\n                Xp = X{p};\n                Zpinv = Zinv{p};\n            end\n            schurtmp = feval( schurfun{p}, Xp,Zpinv,schurfun_par(p,:));\n            schur = schur + schurtmp;\n        end\n    end\nend\n%%\n%% compute rhs\n%%\n[rhs,EinvRc,hRd] = HSDHKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);\n%%\n%% solve linear system\n%%\npar.addschur   = par.kap/par.tau;\nschur(m+1,m+1) = schur(m+1,m+1) + par.kap/par.tau;\nschur(m+2,m+2) = schur(m+2,m+2) + par.addschur;\n[xx,coeff,L] = HSDlinsysolve(par,schur,UU,EE,par.Umat,rhs);\n%%\n%% compute (dX,dZ)\n%%\n[par,dX,dy,dZ] = HSDHKMdirfun(blk,At,par,Rd,EinvRc,X,xx);\n%%*******************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDHKMpred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.24437630769750043}}
{"text": "%{\n * Copyright (C) 2020-2030, The Regents of The University of Michigan.\n * All rights reserved.\n * This software was developed in the Biped Lab (https://www.biped.solutions/) \n * under the direction of Jessy Grizzle, grizzle@umich.edu. This software may \n * be available under alternative licensing terms; contact the address above.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the Regents of The University of Michigan.\n * \n * AUTHOR: Bruce JK Huang (bjhuang[at]umich.edu)\n * WEBSITE: https://www.brucerobot.com/\n%}\n\n\nfunction [LiDARTag, AprilTag] = get4Corners(opt, mat_file_path, bagfile, target_len, pc_iter, num_scan)\n    pc = loadPointCloud(mat_file_path, bagfile);\n    X = getPayload(pc, pc_iter, num_scan);\n    \n    % cost\n    opt = optimizeCost(opt, X, target_len);\n    target_lidar = [0 -target_len/2 -target_len/2 1;\n                    0 -target_len/2  target_len/2 1;\n                    0  target_len/2  target_len/2 1;\n                    0  target_len/2 -target_len/2 1]';\n    LiDARTag.corners = inv(opt.H_opt) * target_lidar;\n    LiDARTag.corners = sortrows(LiDARTag.corners', 3, 'descend')';\n    LiDARTag.four_corners_line = point3DToLineForDrawing(LiDARTag.corners);\n    LiDARTag.points = X;\n\n%             HCamera = getAprilTagPose(app, app.image_num);\n    AprilTag.corners = getAprilTagCorners(bagfile);\n%             AprilTag.undistorted_corners = getApriltagUndistortedCorners(app, AprilTag.corners);\n    AprilTag.four_corners_line = [];\nend", "meta": {"author": "UMich-BipedLab", "repo": "extrinsic_lidar_camera_calibration", "sha": "d423c81e95c6de595e1dff79871385348b1c68f4", "save_path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration", "path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration/extrinsic_lidar_camera_calibration-d423c81e95c6de595e1dff79871385348b1c68f4/get4Corners.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.244329420657836}}
{"text": "function [ objectIndex ] = GetScenario_waypoint_90Degrees(varargin)\n% This scenario is designed to present a waypoint following exercise.\n\nfprintf('[SCENARIO]\\tGetting the waypoint following exercise.\\n');\n\n% DEFAULT CONFIGURATION\ndefaultConfig = struct('file','scenario.mat',...\n                       'agents',[],...\n                       'agentVelocity',0,...\n                       'noiseFactor',0,...\n                       'plot',0);  \n\n% Instanciate the scenario builder\nSBinstance = scenarioBuilder();                  \n% PARSE THE USER OVERRIDES USING THE SCENARIO BUILDER\n[inputConfig] = SBinstance.configurationParser(defaultConfig,varargin);\n% AGENT CONDITIONS\nagentIndex = inputConfig.agents;\nagentNumber = numel(agentIndex);                    % Declare the number of agents\n\n%% DEFINE THE AGENT CONFIGURATION\n% MOVE THROUGH THE AGENTS AND INITIALISE WITH GLOBAL PROPERTIES\nfprintf('[SCENARIO]\\tAssigning agent definition...\\n'); \nfor i=1:agentNumber\n    agentIndex{i}.SetGLOBAL('globalPosition',[0;0;0] + inputConfig.noiseFactor*randn(3,1));\n    agentIndex{i}.SetGLOBAL('globalVelocity',[inputConfig.agentVelocity;0;0] + inputConfig.noiseFactor*randn(3,1));\n    agentIndex{i}.SetGLOBAL('quaternion',[1;0;0;0]);\nend\n\n%% DEFINE THE WAYPOINT CONFIGURATION\nfprintf('[SCENARIO]\\tBuilding the new scenario...\\n');\nwaypointRadius = 0.1;\nnameString = sprintf('WP-%s',agentIndex{1}.name);\nwaypointPositions = [ 20 20;\n                       0 20;\n                       0 20];\n\n% ASSIGN AGENT GLOBAL PROPERTIES, ONE SIDE OF THE RINGS TO THE OTHER\nwaypointIndex{1} = waypoint('radius',waypointRadius,'name',nameString);\nwaypointIndex{1}.SetGLOBAL('globalPosition',waypointPositions(:,1));\nwaypointIndex{1}.SetGLOBAL('globalVelocity',zeros(3,1));\nwaypointIndex{1}.SetGLOBAL('quaternion',[1;0;0;0]);                        % Append properties from the sphereical scenario\n\nwaypointIndex{2} = waypoint('radius',waypointRadius,'name',nameString);\nwaypointIndex{2}.SetGLOBAL('globalPosition',waypointPositions(:,2));\nwaypointIndex{2}.SetGLOBAL('globalVelocity',zeros(3,1));\nwaypointIndex{2}.SetGLOBAL('quaternion',[1;0;0;0]);                        % Append properties from the sphereical scenario\n\nfor index = 1:numel(waypointIndex)\n   waypointIndex{index} = waypointIndex{index}.CreateAgentAssociation(agentIndex{1},1/index);  % Create waypoint with association to agent \nend\n\n% BUILD THE COLLECTIVE OBJECT INDEX\nobjectIndex = horzcat(agentIndex,waypointIndex);\n% PLOT THE SCENE\nif inputConfig.plot\n    SBinstance.plotObjectIndex(objectIndex);\nend\n% CLEAR THE REMAINING VARIABLES\nclearvars -except objectIndex\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/scenarios/GetScenario_waypoint_90Degrees.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2443294206578359}}
{"text": "classdef DisjointSetM < DisjointSet\n%%DISJOINTSETM A disjoint set class that can be used to partition a set of\n%              targets into clusters while keeping track of which\n%              measurements are associated with which cluster.\n%\n%This subclass generalizes the DisjointSet class to keep track of which\n%measurements caused the partitioning of the targets. The set size is the\n%number of ordered targets and a target is identifiable by its index number\n%in the set. The class is created for a fixed number of targets and\n%measurements. The main point of this class is to facilitate the creation\n%of ClusterSet classes for the targets that cluster together and for the\n%measurements that are associated with each cluster.\n%\n%November 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nproperties\n    numMeasInTree\n    measToNode\nend\nmethods\n    function newSet=DisjointSetM(numTar,numMeas)\n        %The constructor method.\n        newSet=newSet@DisjointSet(numTar);\n        newSet.numMeasInTree=zeros(numTar,1);\n        newSet.measToNode=zeros(numMeas,1);\n    end\n\n    function unionFromList(DSObj,uList,measNum)\n    %%UNIONFROMLIST Merge clusters of targets from a given common\n    %               measurement. NOTE: Calling unionFromList twice with\n    %               the same measurement number will produce incorrect\n    %               results.           \n    %\n    %INPUTS: DSObj  The implicitly passed calling object.\n    %        uList  A one-dimensional list of indices of targets to\n    %               merge into one cluster\n    %       measNum The index of the measurement.\n    %\n    %The uList passed for a particular measNum should a list of the\n    %indices of ALL of the targets that gate with the measurement.\n    %\n    %November 2013 David F. Crouse, Naval Research Laboratory, Washington\n    %D.C.\n    \n        numInList=length(uList);\n        if(numInList==0)\n            return;\n        end\n\n        rootIdx1=DSObj.find(uList(1));\n        DSObj.numMeasInTree(rootIdx1)=DSObj.numMeasInTree(rootIdx1)+1;\n        DSObj.measToNode(measNum)=rootIdx1;\n        for curTar=2:numInList\n            rootIdx2=DSObj.find(uList(curTar));\n            rootIdx1=DSObj.unionRoots(rootIdx1,rootIdx2);\n        end\n    end\n\n    function unionFromBoolList(DSObj,boolList,measNum)\n    %%UNIONFROMBOOLLIST Merge targets specified by a boolean array for\n    %               a given measurement index. NOTE: Calling\n    %               unionFromBoolList twice with the same measurement\n    %               number will produce incorrect results.    \n    %\n    %INPUTS: DSObj  The implicitly passed calling object.\n    %     boolList  A length numTarX1 or 1XnumTar boolean array\n    %               indicating whether which targets are in the same\n    %               cluster due to the specified measurement.\n    %       measNum The index of the measurement.\n    %\n    %November 2013 David F. Crouse, Naval Research Laboratory, Washington\n    %D.C.\n    \n        numTar=length(DSObj.setArray);\n        %Check for input validity.\n        assert(numTar==length(DSObj.setArray))\n\n        tarIdxCur=find(boolList,1);\n\n        if(isempty(tarIdxCur))\n            %If no target gates with the specified measurement.\n            return;\n        end\n\n        rootIdx1=DSObj.find(tarIdxCur);\n        DSObj.numMeasInTree(rootIdx1)=DSObj.numMeasInTree(rootIdx1)+1;\n        DSObj.measToNode(measNum)=rootIdx1;\n        for curTarIdx=(tarIdxCur+1):numTar\n            if(boolList(curTarIdx))\n                rootIdx2=DSObj.find(curTarIdx);\n                rootIdx1=DSObj.unionRoots(rootIdx1,rootIdx2);\n            end\n        end\n    end\n\n    function unionFromBinMat(DSObj,binMat)\n    %UNIONFROMBINMAT Given a binary matrix specifying which \n    %                measurements gate with which targets, cluster\n    %                together all targets that gate with each other.\n    %\n    %INPUTS: DSObj The implicitly passed calling object.\n    %       binMat A numTarXnumMeas binary matrix where numTar is the\n    %              same as the length of setArray in DSObj and numMeas\n    %              is the number of measurements with which the\n    %              DisjointSet object was created.\n    %\n    %The measurement number is assumed from the column index when\n    %clustering. This function should not be called multiple times with\n    %different binary matrices as it will produce incorrect results.\n    %Rather, multiple binary matrices can be OR-ed together prior to\n    %calling this method.\n    %\n    %November 2013 David F. Crouse, Naval Research Laboratory, Washington\n    %D.C.\n\n        numTar=size(binMat,1);\n        numMeas=size(binMat,2);\n\n        %Check for input validity\n        assert(numTar==length(DSObj.setArray))\n        if(~isempty(DSObj.measToNode))\n            assert(numMeas==length(DSObj.measToNode))\n        end\n\n        for curMeas=1:numMeas\n            rootIdx1=0;\n            for curTar=1:numTar\n                if(binMat(curTar,curMeas)~=0)\n                    if(rootIdx1==0)\n                        rootIdx1=DSObj.find(curTar);\n\n                        %Do measurement bookeeping.\n                        DSObj.measToNode(curMeas)=curTar;\n                        DSObj.numMeasInTree(rootIdx1)=DSObj.numMeasInTree(rootIdx1)+1;\n                    else\n                        rootIdx2=DSObj.find(curTar);\n                        rootIdx1=DSObj.unionRoots(rootIdx1,rootIdx2);\n                    end\n\n                    %Do measurement bookeeping.\n                    DSObj.measToNode(curMeas)=rootIdx1;\n                end\n            end\n        end\n    end\n\n    function [newCSet,newCSMeasSet,ungatedMeas]=createClusterSet(DSObj)\n    %%CREATECLUSTERSET Turn the DisjointSet object into a ClusterSet so\n    %                  that targets in each cluster can be easily\n    %                  addressed. Also produce a corresponding\n    %                  ClusterSet for the clusters of measurements that\n    %                  are associated with each cluster of targets and\n    %                  produce a list of which measurements do not gate\n    %                  with anything.\n    %\n    %OUTPUTS: newCSet A ClusterSet object representing the clustering\n    %                 given by this DisjointSetM object.\n    %    newCSMeasSet A ClusterSet object of the measurements that go\n    %                 with each cluster of targets.\n    %     ungatedMeas An array of indices of measurements that do not\n    %                 gate with anything.\n    %\n    %newCSet(c,:) is the set of targets in cluster c and\n    %newCSMeasSet(c,:) is the corresponding set of measurements.\n    %\n    %November 2013 David F. Crouse, Naval Research Laboratory, Washington\n    %D.C.\n\n        numTar=length(DSObj.setArray);\n        numMeas=length(DSObj.measToNode);\n\n        rootIdxList=zeros(DSObj.numberOfSets,1);\n        curNumAdded=zeros(DSObj.numberOfSets,1);\n\n        %This holds the numbers of targets per cluster.\n        rootRankList=zeros(DSObj.numberOfSets,1);\n        %This holds the numbers of measurements per cluster.\n        rootRankListMeas=zeros(DSObj.numberOfSets,1);\n        clusterEls=zeros(numTar,1);\n        clusterElsMeas=zeros(numMeas,1);\n\n        %First, record the indices and ranks of all of the root nodes.\n        rootNodesFound=0;\n        for curItem=1:numTar\n            if(DSObj.setArray(curItem)<0)\n                rootNodesFound=rootNodesFound+1;\n                rootIdxList(rootNodesFound)=curItem;\n                rootRankList(rootNodesFound)=DSObj.numInTree(curItem);\n                rootRankListMeas(rootNodesFound)=DSObj.numMeasInTree(curItem);\n\n                if(rootNodesFound==DSObj.numberOfSets)\n                    break;\n                end\n            end\n        end\n\n        %Next, sort the root nodes by their index, so that children can\n        %be efficiently assigned to them.\n        [rootIdxList,idx] = sort(rootIdxList,1,'ascend');\n        rootRankList=rootRankList(idx);\n        %The measurement clusters must correspond to the target\n        %clusters.\n        rootRankListMeas=rootRankListMeas(idx);\n\n        offsetArray=zeros(DSObj.numberOfSets,1);\n        offsetArray(2:end)=cumsum(rootRankList(1:(end-1)));\n        for curItem=1:numTar\n            %Find the root node for the given node.\n            rootNode=DSObj.find(curItem);\n            %Find the index of the cluster corresponding to that root\n            %node.\n            [~, clusterIdx]=binSearch(rootIdxList,rootNode);\n            %Add the node to the cluster.\n            clusterEls(1+offsetArray(clusterIdx)+curNumAdded(clusterIdx))=curItem;\n            curNumAdded(clusterIdx)=curNumAdded(clusterIdx)+1;\n        end\n        %Create the cluster set for the measurements\n        newCSet=ClusterSet(clusterEls,rootRankList,offsetArray);\n        %Create an array of the maximum possible size to hold the\n        %ungated measurements.\n        ungatedMeas=zeros(numMeas,1);\n        numUngatedMeas=0;\n\n        %Fill the measurement clusters in the same manner as done\n        %for the regular clusters.\n        curNumAdded=zeros(DSObj.numberOfSets,1);\n        offsetArrayMeas=zeros(DSObj.numberOfSets,1);\n        offsetArrayMeas(2:end)=cumsum(rootRankListMeas(1:(end-1)));\n        for curItem=1:numMeas\n            if(DSObj.measToNode(curItem)>0)\n                rootNode=DSObj.find(DSObj.measToNode(curItem));\n                %Find the index of the cluster corresponding to that root\n                %node.\n                [~, clusterIdx]=binSearch(rootIdxList,rootNode);\n                %Add the node to the cluster.\n                clusterElsMeas(1+offsetArrayMeas(clusterIdx)+curNumAdded(clusterIdx))=curItem;\n                curNumAdded(clusterIdx)=curNumAdded(clusterIdx)+1;\n            else\n                numUngatedMeas=numUngatedMeas+1;\n                ungatedMeas(numUngatedMeas)=curItem;\n            end\n        end\n\n        %Shorten the array to the actual number of ungated\n        %measurements.\n        ungatedMeas=ungatedMeas(1:numUngatedMeas);\n\n        newCSMeasSet=ClusterSet(clusterElsMeas,rootRankListMeas,offsetArrayMeas);\n    end\n\n    function mergedRootIdx=unionRoots(DSObj,rootIdx1,rootIdx2)\n    %%unionRoots Merge two sets given their root nodes, keeping\n    %            track of the number of measurements associated\n    %            with both sets.\n    %\n    %INPUTS: DSObj      The implicitly passed calling object.\n    %        rootIdx1   The root index of the first set to merge.\n    %        rootIdx2   The root index of the second set to merge.\n    %\n    %OUTPUTS: mergedRootIdx The index of the root of the merged\n    %                       cluster. It will either be rootIdx1 or\n    %                       rootIdx2.\n    %\n    %This is a union-by-rank algorithm. The merged cluster has a number\n    %of associated measurements equal to the sum of the number of\n    %measurements in both clusters. This method should not be called\n    %with indices that do not correspond to root nodes.\n    %\n    %November 2013 David F. Crouse, Naval Research Laboratory, Washington\n    %D.C.\n\n        %If the roots are the same, then there is nothing to merge.\n        if(rootIdx1==rootIdx2)\n            %Measurement bookeeping\n            DSObj.numMeasInTree(rootIdx1)=DSObj.numMeasInTree(rootIdx1);\n            mergedRootIdx=rootIdx1;\n            return;\n        end\n\n        %If root 2 is deeper, than make root2 the new root.\n        if(DSObj.setArray(rootIdx2)< DSObj.setArray(rootIdx1))\n            DSObj.setArray(rootIdx1)=rootIdx2;\n            DSObj.numInTree(rootIdx2)=DSObj.numInTree(rootIdx1)+DSObj.numInTree(rootIdx2);\n            mergedRootIdx=rootIdx2;\n\n            DSObj.numMeasInTree(rootIdx2)=DSObj.numMeasInTree(rootIdx1)+DSObj.numMeasInTree(rootIdx2);\n        else\n            %If they are the same height, then update the height of\n            %rootIdx1.\n            if(DSObj.setArray(rootIdx1)== DSObj.setArray(rootIdx2))\n                DSObj.setArray(rootIdx1)=DSObj.setArray(rootIdx1)-1;\n            end\n            DSObj.setArray(rootIdx2)=rootIdx1;\n            DSObj.numInTree(rootIdx1)=DSObj.numInTree(rootIdx1)+DSObj.numInTree(rootIdx2);\n            mergedRootIdx=rootIdx1;\n\n            DSObj.numMeasInTree(rootIdx1)=DSObj.numMeasInTree(rootIdx2)+DSObj.numMeasInTree(rootIdx1);\n        end\n\n        %Merging reduces the number of sets by one.\n        DSObj.numberOfSets=DSObj.numberOfSets-1;\n    end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Container_Classes/DisjointSetM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2443005306581844}}
{"text": "\nclassdef OMAS_modelViewer\n    properties\n        figureProperties;\n        targetObject;\n        triadPosition = [-2;-2;-2];  % Position of the model\n        triadScale = 0.5;\n        R        = eye(3);      % The rotation of the body and triad together\n        R_offset = eye(3);      % The offset between the body axis triad and geometry\n        %triad_b;\n        %triad_g;\n    end\n    methods\n        % Constructor\n        function obj = OMAS_modelViewer(varargin)\n            % Input sanity check\n            if numel(varargin) ~= 1\n                error('Please provide a target object class to view');\n            end\n            % Assume input is an object label\n            if ischar(varargin{1})\n                obj.targetObject = eval(varargin{1});                      % Instantiate the object\n            elseif ismember('objectDefinition',superclasses(varargin{1})) % Check for the object root class\n                obj.targetObject = varargin{1};\n            else\n                error('The variable provided is not a valid OpenMAS object.');\n            end\n            % Get the default figure properties\n            [obj.figureProperties] = obj.getFigureProperties();\n        end\n        % Set the model position\n        function [obj] = setTriadPosition(obj,p)\n            % Input sanity check\n            assert(numel(p) == 3 && size(p,1) == 3,'Position must be a column vector [3x1]');\n            % Set the triad's relative position\n            obj.triadPosition = p;\n        end\n        % Set the model rotation\n        function [obj] = setRotation(obj,eulers)\n            % Input sanity check\n            assert(numel(eulers) == 3,'Euler rotations must be a column vector [3x1]');\n            % Get the rotation matrix\n            obj.R = OMAS_geometry.eulersToRotationMatrix(eulers);\n        end\n        % Show scene\n        function [figureHandle] = show(obj,objectClass)\n            \n            % Input checking\n            if nargin > 1\n                target = objectClass;\n            else\n                target = obj.targetObject;\n            end\n            % For clarity\n            properties = obj.figureProperties;\n            \n            % Define plot\n            figureHandle = figure('Name',target.name);\n            ax = axes(figureHandle);\n            hold on;\n\n            % Other plot attributes\n            title(target.name,'fontweight',properties.fontWeight,'fontsize',properties.titleFontSize);\n            xlabel('x(m)','fontweight',properties.fontWeight,'fontSize',properties.axisFontSize);\n            ylabel('y(m)','fontweight',properties.fontWeight,'fontSize',properties.axisFontSize);\n            zlabel('z(m)','fontweight',properties.fontWeight,'fontSize',properties.axisFontSize);\n            set(ax,'FontSize',properties.axisFontSize,'fontWeight',properties.fontWeight);\n            set(ax,'Color',properties.axesColor);\n            axis('tight','equal');\n            grid on;  box on;\n            % AXES-ON LOGICAL\n            set(ax,'visible',properties.axesVisible)\n            % SET ORIENTATION\n            view(properties.orientation);\n            % REPRESENT GEOMETRY AS A PATCH\n            target.GEOMETRY = OMAS_graphics.normalise(target.GEOMETRY);\n            patch(ax,...\n                'Vertices',(target.GEOMETRY.vertices*obj.R_offset)*obj.R',...\n                'Faces',target.GEOMETRY.faces,...\n                'FaceColor',properties.faceColour,...\n                'EdgeColor',properties.edgeColour,...\n                'EdgeAlpha',properties.edgeAlpha,...\n                'FaceAlpha',properties.faceAlpha,...\n                'FaceLighting',properties.faceLighting,...\n                'LineWidth',0.1);\n            \n            % ADD ALIGNED TRIAD\n            triadHandle = OMAS_graphics.drawTriad(figureHandle,zeros(3,1),obj.R*obj.R_offset,obj.triadScale);\n            set(triadHandle(1,:),'lineWidth',1.2);\n            set(triadHandle(1,:),'lineStyle','-');\n            % set(triadHandle(1,:),'Color','k');\n            % ADD GLOBAL TRIAD\n            triadHandle = OMAS_graphics.drawTriad(figureHandle,obj.triadPosition,eye(3),obj.triadScale);\n            set(triadHandle(1,:),'lineWidth',1.2);\n            set(triadHandle(1,:),'lineStyle','-');\n            % set(triadHandle(1,:),'Color','k');\n        end\n    end\n    methods (Static)\n        % Get figure properties from 'OMAS_figureProperties'\n        function [figureProperties] = getFigureProperties()            \n            % Get the figure properties structure common to OMAS\n            figureProperties = OMAS_figureProperties();\n            % Specific default parameters\n            figureProperties.backgroundColor = 'w';\n            figureProperties.orientation = [0 90]; %[75 44];\n            figureProperties.axesVisible = 'off';\n            figureProperties.axesColor = 'none';\n            figureProperties.edgeAlpha = 0.02;\n            figureProperties.edgeColour = 'k';\n            figureProperties.edgeWidth = 0.1;\n            figureProperties.faceAlpha = 0.05;\n            figureProperties.faceColour = 'b';\n        end\n    end\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/OMAS_modelViewer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24421372091167384}}
{"text": "function d = degree(varargin)\n\nF = varargin{1};\nF = flatten(F);\nd = subdegree(F.clauses);\n\nfunction d = subdegree(clauses)\nd = -inf;\nfor i = 1:length(clauses)\n    d = max(d,degree(sdpvar(clauses{i}.data)));\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@lmi/degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.24408211334856855}}
{"text": "function varargout = metchgui_one(varargin)\n%    alldata = metchgui_one(node,elem,points) or metchgui_one(volume,points,pface)\n%\n%    A GUI to register a point cloud to a mesh or volumetric image\n%  \n%    author: Qianqian Fang <q.fang at neu.edu>\n%    date: 12/16/2008\n%  \n%   parameters: \n%        node: node coordinate of the surface mesh (nn x 3)\n%        elem: element list of the surface mesh (3 columns for \n%              triangular mesh, 4 columns for cubic surface mesh)\n%        points: the coordinates (3 columns for x/y/z) of the \n%              point cloud which you want to register\n%        pface:trianglular surface defined on the point cloud.\n%              pface is optional; if presents, metch will display \n%              a surface object instead of a point cloud.\n%\n%   the input can also be two parameters in form of metchgui_one(volume,points), \n%    where volume is a 3D image (array).\n%\n%   outputs:\n%        alldata: a structrure containing all processing outputs\n%        the fields include: \n%         .node: the input node \n%         .elem: the input surface mesh elements\n%         .volume: if the input volumetric image\n%         .A0: the affine rotation for selected point pairs (after Initialize)\n%         .b0: the affine translation for selected point pairs (after Initialize)\n%         .A: the affine rotation for the point cloud (after Optimize)\n%         .b: the affine translation for the point cloud (after Optimize)\n%         .points: the input point cloud\n%         .pointsinit: the point cloud after initialization\n%         .pointsopt: the point cloud after optimization\n%         .pointsproj: the point cloud after projecting to the surface\n%         .initplot: the handle to the point cloud plot after init\n%         .optplot: the handle to the point cloud plot after optimization\n%         .projplot: the handle to the point cloud plot after projection\n%\n%   If user supplys an output variable, the GUI will not return until the\n%   user hits the \"close\" button or close the window; if user does not\n%   supply any output, the call will return immediately; any data user\n%   intends to save, he has to click on \"Save Session\" button and provides\n%   a mat-file file name. A single structure named \"metchsession\" will be\n%   stored in this file.\n%\n%   example: (meshasphere/meshunitsphere are defined in iso2mesh http://iso2mesh.sf.net)\n%\n%       [noderef,faceref,elemref]=meshunitsphere(0.08,10);\n%       [no,fc]=removeisolatednode(noderef(:,1:3),faceref(:,1:3));\n%       [node,face,elem]=meshasphere([10 20 15],3,0.5,10);\n%       [no2,fc2]=removeisolatednode(node(:,1:3),face(:,1:3));\n%       alldata = metchgui(no,fc,no2);\n%       % or alldata = metchgui(no,fc,no2,fc2);\n%\n%   Please find more information at http://iso2mesh.sf.net/cgi-bin/index.cgi?metch\n%  \n%   this function is part of \"metch\" toobox, see COPYING for license\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name',       mfilename, ...\n                   'gui_Singleton',  gui_Singleton, ...\n                   'gui_OpeningFcn', @metchgui_one_OpeningFcn, ...\n                   'gui_OutputFcn',  @metchgui_one_OutputFcn, ...\n                   'gui_LayoutFcn',  @metchgui_one_LayoutFcn, ...\n                   'gui_Callback',   []);\nif nargin && ischar(varargin{1})\n    gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}, 'hasoutput');\nelse\n    gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before metchgui_one is made visible.\nfunction metchgui_one_OpeningFcn(hObject, eventdata, handles, varargin)\nhandles.hasoutput=0;\nif(isempty(varargin))\n    fprintf(1,'Metch GUI must be called with parameters:\\nFormat: alldata = metchgui_one(node,elem,points,pface);\\n');\n    close(handles.MetchGUI);\n    return;\nend\nif(ischar(varargin{end}) && strcmp(varargin{end},'hasoutput'))\n        handles.hasoutput=1;\n        varargin(end)=[];\nend\nhandles.output = hObject;\n\nset(handles.btAddMeshPt,'userdata',[handles.axMesh,handles.btAddMeshPt,handles.btAddCloudPt]);\nset(handles.btAddCloudPt,'userdata',[handles.axMesh,handles.btAddCloudPt,handles.btAddMeshPt]);\n\n% if uses supplied 2 input variables, assume a volume image and a point cloud\nif(isnumeric(varargin{1}) && length(size(varargin{1}))==3)\n       vol=varargin{1};\n       pt=varargin{2};\n       \n       dat.volume=vol;\n       dat.points=pt;\n\n       slice=round(size(vol,3)/2);\n       hs=imagesc(vol(:,:,slice),'parent',handles.axMesh);\n       set(handles.slPos,'max',size(vol,3),'min',1,'value',slice);\n\n       if(length(varargin)>=3)\n       \t pface=varargin{3};\n       \t dat.pface=pface;\n\t trisurf(pface(:,1:3),pt(:,1),pt(:,2),pt(:,3),'parent',handles.axPoints);\n       else\n         %plot3(pt(:,1),pt(:,2),pt(:,3),'.','parent',handles.axPoints);\n         ptcolor=(pt-repmat(min(pt),size(pt,1),1))./repmat(max(pt)-min(pt),size(pt,1),1);\n         drawnow;\n         scatter3(pt(:,1),pt(:,2),pt(:,3),3,ptcolor,'filled');\t\n       end\n       set(handles.MetchGUI,'userdata',dat);\n\n       axis(handles.axMesh,'equal');\n       axis(handles.axPoints,'equal');\n       axis(handles.axMesh,'off');\n       grid(handles.axPoints,'on');\n       %axis(handles.axPoints,'off');\n       \n       set(handles.axMesh,'tag','axMesh');\n       set(handles.axPoints,'tag','axPoints');\n       set(handles.slPos,'visible','on');\n       set(handles.lbZPos,'visible','on');\n       rotate3d(handles.axPoints,'on');\n       rotate3d(gcf,'on');\nend\n\n% if uses supplied 3 input variables, assume a surface mesh and a point cloud/surface\nif(length(varargin)>=3 && length(size(varargin{1}))==2)\n       node=varargin{1};\n       elem=varargin{2};\n       pt=varargin{3};\n       \n       dat.node=node;\n       dat.elem=elem;\n       dat.points=pt;\n       if(length(varargin)>=4)\n       \t pface=varargin{4};\n       \t dat.pface=pface;\n       end\n       set(handles.MetchGUI,'userdata',dat);\n\n       drawinit(handles,dat)\nend\nguidata(hObject, handles);\n\nif(handles.hasoutput)\n        uiwait(handles.MetchGUI);\nend\n\n%---------------------------------------------------------------------------\nfunction drawinit(handles,dat)\n\nnode=dat.node;\nelem=dat.elem;\npt=dat.points;\n\nhs=trisurf(elem,node(:,1),node(:,2),node(:,3),'parent',handles.axMesh);\n%set(hs,'linestyle','none');\n%set(hs,'facecolor','b','facealpha',0.8);\n\n%plot3(pt(:,1),pt(:,2),pt(:,3),'.','parent',handles.axPoints);\nif(~isfield(dat,'pface'))\n\tptcolor=(pt-repmat(min(pt),size(pt,1),1))./repmat(max(pt)-min(pt),size(pt,1),1);\n\tdrawnow;\n\tscatter3(pt(:,1),pt(:,2),pt(:,3),3,ptcolor,'filled');\nelse\n\ttrisurf(dat.pface,pt(:,1),pt(:,2),pt(:,3),'parent',handles.axPoints);\nend\n%hold(handles.axPoints,'on');\n%plot3(pt(5:7,1),pt(5:7,2),pt(5:7,3),'ro','parent',handles.axPoints);\n\naxis(handles.axMesh,'equal');\naxis(handles.axPoints,'equal');\naxis(handles.axMesh,'off');\n%axis(handles.axPoints,'off');\n\nset(handles.axMesh,'tag','axMesh');\nset(handles.axPoints,'tag','axPoints');\n\nif(~exist('OCTAVE_VERSION'))\n  rotate3d(handles.axPoints,'on');\n  rotate3d(handles.axMesh,'on');\nend\nrotate3d(gcf,'on');\n\n%---------------------------------------------------------------------------\nfunction varargout = metchgui_one_OutputFcn(hObject, eventdata, handles) \nif(length(handles) && isfield(handles,'output') && isfield(handles,'hasoutput') && handles.hasoutput)\n        handles.output=get(handles.MetchGUI,'userdata');\n        varargout{1} =handles.output;\n        close(handles.MetchGUI);\nend\n%---------------------------------------------------------------------------\nfunction lbMesh_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor','white');\nend\n\n%---------------------------------------------------------------------------\nfunction lbPoints_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor','white');\nend\n\n%---------------------------------------------------------------------------\nfunction edit1_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor','white');\nend\n\n%---------------------------------------------------------------------------\nfunction edit2_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor','white');\nend\n\n%---------------------------------------------------------------------------\nfunction edit3_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor','white');\nend\n\n%---------------------------------------------------------------------------\nfunction isSelect_Callback(hObject, eventdata, handles)\nif(get(hObject,'Value'))\n        datacursormode(gcf,'on');\n        set(datacursormode(gcf),'UpdateFcn',@myupdatefcn)\nelse\n        datacursormode(gcf,'off');\n        rotate3d(gcf,'on');\nend\n\n%---------------------------------------------------------------------------\n% the respond function when there is a data-tip to popup\n%---------------------------------------------------------------------------\nfunction txt=myupdatefcn(empt,event_obj)\npos = get(event_obj,'Position');\nidx=  get(event_obj,'DataIndex');\n\nif(length(pos)==3)\n  txt = {['x: ',num2str(pos(1))],...\n         ['y: ',num2str(pos(2))],['z: ',num2str(pos(3))],['index:', num2str(idx)]};\nelseif(length(pos)==2)\n  txt = {['x: ',num2str(pos(1))],['y: ',num2str(pos(2))]};\nend\ntargetup=get(get(event_obj,'Target'),'parent');\nset(targetup,'userdata',struct('pos',pos,'idx',idx));\nif(targetup==findobj('tag','axMesh'))\n         set(findobj('tag','btAddMeshPt'),'enable','on');\n         set(findobj('tag','btAddCloudPt'),'enable','off');\nelseif(targetup==findobj('tag','axPoints'))\n         set(findobj('tag','btAddMeshPt'),'enable','off');\n         set(findobj('tag','btAddCloudPt'),'enable','on');     \nend\n\n%---------------------------------------------------------------------------\nfunction bInit_Callback(hObject, eventdata, handles)\nmapto=get(handles.lbMesh,'userdata');\nmapfrom=get(handles.lbPoints,'userdata');\n\nmaptoidx=get(handles.txMapTo,'userdata');\nmapfromidx=get(handles.txMapFrom,'userdata');\n\nif(length(mapto)<4 | length(mapfrom)<4)\n        msgbox('You have to select >3 points from the point cloud plot and corresponding points from the mesh','Error','error');\n        return;\nend\n[A,b]=affinemap(mapfrom,mapto)\ndat=get(handles.MetchGUI,'userdata');\ndat.A0=A;\ndat.b0=b;\n\nnewpt=(A*dat.points'+repmat(b(:),1,size(dat.points,1)))';\ndat.pointsinit=newpt;\n\nhold(handles.axMesh,'on');\nif(isfield(dat,'initplot'))\n        delete dat.initplot;\n        dat.initplot=0;\nend\ndat.initplot=plot3(newpt(:,1),newpt(:,2),newpt(:,3),'r.','parent',handles.axMesh);\n\ndat.fromidx=mapfromidx;\ndat.toidx=maptoidx;\nset(handles.MetchGUI,'userdata',dat);\n\n%---------------------------------------------------------------------------\nfunction axPoints_ButtonDownFcn(hObject, eventdata, handles)\nif(get(handles.btSelect,'value')==1)\n        pp=getCursorInfo(datacursormode(gcf));\n        str=[get(handles.lbPoints,'string');mat2str(pp.Position)];\n        set(handles.lbPoints,'string',str);\nend\n\n%---------------------------------------------------------------------------\nfunction addselectedpt(pos,idx,lb)\nif(isempty(get(lb,'value')))\n    set(lb,'value',1);\nend\nlistpt=get(lb,'string');\nlistpt{end+1}=[num2str(idx) ':' mat2str(pos)];\nset(lb,'string',listpt);\nset(lb,'userdata',[get(lb,'userdata');pos]);\n\n\n%---------------------------------------------------------------------------\nfunction btAddMeshPt_Callback(hObject, eventdata, handles)\ndat=get(handles.axMesh,'userdata');\n\ndat0=get(handles.MetchGUI,'userdata');\nif(isfield(dat0,'volume'))\n    dat.pos(:,3)=get(handles.slPos,'value');\nend\n\nif(isfield(dat,'pos'))\n    addselectedpt(dat.pos,dat.idx,handles.lbMesh);\n    set(handles.txMapTo,'userdata',[get(handles.txMapTo,'userdata');dat.idx]);\n\tdat0.mapto=get(handles.lbMesh,'userdata');\n    dat0.maptoidx=get(handles.txMapTo,'userdata');\n    set(handles.MetchGUI,'userdata',dat0);\nelse\n        msgbox('No point was selected. Please click on \"Select\" and select a point on the mesh or point cloud','Error','error');\n        return;\nend\n\n%---------------------------------------------------------------------------\nfunction btAddCloudPt_Callback(hObject, eventdata, handles)\ndat=get(handles.axPoints,'userdata');\ndat0=get(handles.MetchGUI,'userdata');\nif(isfield(dat,'pos'))\n    addselectedpt(dat.pos,dat.idx,handles.lbPoints);\n    set(handles.txMapFrom,'userdata',[get(handles.txMapFrom,'userdata');dat.idx]);\n\tdat0.mapfrom=get(handles.lbPoints,'userdata');\n    dat0.mapfromidx=get(handles.txMapFrom,'userdata');\n    set(handles.MetchGUI,'userdata',dat0);\nelse\n        msgbox('No point was selected. Please click on \"Select\" and select a point on the mesh or point cloud','Error','error');\n        return;\nend\n\n%---------------------------------------------------------------------------\nfunction btOptimize_Callback(hObject, eventdata, handles)\ndat=get(handles.MetchGUI,'userdata');\nif(isfield(dat,'A0') && isfield(dat,'b0')& isfield(dat,'node')& isfield(dat,'elem')& ...\n   isfield(dat,'pointsinit')& isfield(dat,'toidx')& isfield(dat,'fromidx'))\n        pmask=-1*ones(size(dat.pointsinit,1),1);\n        pmask(dat.fromidx)=dat.toidx;\n        if(isfield(dat,'A') && isfield(dat,'b'))\n                [Anew,bnew,posnew]=regpt2surf(dat.node,dat.elem,dat.points,pmask,dat.A,dat.b,ones(12,1),10);\n        else\n                [Anew,bnew,posnew]=regpt2surf(dat.node,dat.elem,dat.points,pmask,dat.A0,dat.b0,ones(12,1),10);\n        end\n        dat.A=Anew;\n        dat.b=bnew;\n        dat.pointsopt=posnew;\n        if(isfield(dat,'optplot') && dat.optplot)\n                delete dat.optplot;\n                dat.optplot=0;\n        end\n        dat.optplot=plot3(posnew(:,1),posnew(:,2),posnew(:,3),'g+','parent',handles.axMesh);\nelse\n        msgbox('You have to select 4 points and click \"Initialize\" button first','Error','error');\n        return;\nend\nset(handles.MetchGUI,'userdata',dat);\n\n\n%---------------------------------------------------------------------------\nfunction slPos_Callback(hObject, eventdata, handles)\ndat=get(handles.MetchGUI,'userdata');\nif(isfield(dat,'volume'))\n        hold(handles.axMesh,'off');\n        imagesc(dat.volume(:,:,round(get(hObject,'value'))),'parent',handles.axMesh);\n        set(handles.axMesh,'tag','axMesh');\n        set(handles.lbZPos,'string',num2str(round(get(hObject,'value'))));\nend\nset(handles.MetchGUI,'userdata',dat);\n\n%---------------------------------------------------------------------------\nfunction slPos_CreateFcn(hObject, eventdata, handles)\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n%--------------------------------------------------------------------------\nfunction btProj_Callback(hObject, eventdata, handles)\ndat=get(handles.MetchGUI,'userdata');\nif(isfield(dat,'pointsopt'))\n        if(isfield(dat,'projplot') && dat.projplot)\n                delete dat.projplot;\n                dat.projplot=0;\n        end\n        nv=nodesurfnorm(dat.node,dat.elem);\n        [d2surf,cn]=dist2surf(dat.node,nv,dat.pointsopt);\n        [dat.pointsproj dat.elemid dat.weight]=proj2mesh(dat.node,dat.elem,dat.pointsopt,nv,cn);\n        hold(handles.axMesh,'on');\n        dat.projplot=plot3(dat.pointsproj(:,1),dat.pointsproj(:,2),dat.pointsproj(:,3),'c.','parent',handles.axMesh);\nelse\n        msgbox('You have to first select 4 points, then click \"Initialize\" and \"Optimize\" button','Error','error');\n        return;\nend\nset(handles.MetchGUI,'userdata',dat);\n\n%--------------------------------------------------------------------------\nfunction btSaveRes_Callback(hObject, eventdata, handles)\n[filename, pathname] = uiputfile('*.mat', 'Save Metch Workspace as');\nmapto=get(handles.lbMesh,'userdata');\nmapfrom=get(handles.lbPoints,'userdata');\n\nmaptoidx=get(handles.txMapTo,'userdata');\nmapfromidx=get(handles.txMapFrom,'userdata');\n\nmetchsession=get(handles.MetchGUI,'userdata');\nif(~isempty(mapto))    metchsession.mapto=mapto; end\nif(~isempty(mapfrom))    metchsession.mapfrom=mapfrom; end\nif(~isempty(maptoidx))    metchsession.maptoidx=maptoidx; end\nif(~isempty(mapfromidx))    metchsession.mapfromidx=mapfromidx; end\nfname=[pathname filename];\nsave(fname,'metchsession');\n\n%--------------------------------------------------------------------------\nfunction btLoadSession_Callback(hObject, eventdata, handles)\n[filename, pathname] = uigetfile('*.mat', 'Load Metch Workspace from');\nfname=[pathname filename];\nload(fname);\nhandle.output=metchsession;\ncla(handles.axMesh);\ncla(handles.axPoints);\ndrawinit(handles,metchsession.node,metchsession.elem,metchsession.points);\n%--------------------------------------------------------------------------\nfunction btPlotResults_Callback(hObject, eventdata, handles)\n\nfunction btClose_Callback(hObject, eventdata, handles)\nguidata(hObject,handles);\nuiresume;\n\nfunction btHelp_Callback(hObject, eventdata, handles)\nhelpmsg={\n'Metch GUI: A mesh/volume registration toolbox',\n'',\n'Author: Qianqian Fang <q.fang at neu.edu>',\n'        Martinos Center for Biomedical Imaging',\n'        Charlestown, MA 02129, USA',\n'',\n'== Description of the workflow ==',\n'',\n' 1. when the GUI pops up, it will display the mesh and the points,',\n'    you can rotate both plots so that you can identify the matching ',\n'    features',\n' 2. switch on \"Select\" mode, then, click on a land-mark point on the point',\n'    plot, when a data-tip shows up, click \"Add Selected\" button',\n' 3. click on the corresponding position on the mesh, and click',\n'    \"Add Selected\"      ',\n' 4. repeat the above for at least 4 point pairs (you can select more);',\n'    if you want to change views, switch off \"Select\" box and rotate;',\n'    after rotation, switch on \"Select\" box again',\n' 5. click \"Initialize\": this will create the initial mapping using the',\n'    selected point pairs',\n' 6. click \"Optimize\": this will fit the surface with the whole point cloud',\n' 7. click \"Proj2Mesh\": this will project the fitted point clouds onto the',\n'    mesh',\n' 8. you can quit the GUI by hit \"Close\", your results will be saved to reg',\n' 9. close the window '};\n\nhelpdlg(helpmsg);\n\n\n% --- Creates and returns a handle to the GUI figure. \nfunction h1 = metchgui_one_LayoutFcn(policy)\n% policy - create a new figure or use a singleton. 'new' or 'reuse'.\n\npersistent hsingleton;\nif(strcmpi(policy, 'reuse')==1 && ~isempty(hsingleton) && ishandle(hsingleton))\n    h1 = hsingleton;\n    return;\nend\n\nappdata = [];\nappdata.GUIDEOptions = struct(...\n    'active_h', [], ...\n    'taginfo', struct(...\n    'figure', 2, ...\n    'axes', 3, ...\n    'listbox', 3, ...\n    'edit', 4, ...\n    'text', 8, ...\n    'checkbox', 2, ...\n    'togglebutton', 3, ...\n    'pushbutton', 13, ...\n    'slider', 2), ...\n    'override', 0, ...\n    'release', 13, ...\n    'resize', 'none', ...\n    'accessibility', 'callback', ...\n    'mfile', 1, ...\n    'callbacks', 1, ...\n    'singleton', 1, ...\n    'syscolorfig', 1, ...\n    'blocking', 0, ...\n    'lastSavedFile', '/autofs/space/earth_002/users/fangq/pmihome/metch/metchgui_one.m');\nappdata.lastValidTag = 'MetchGUI';\nappdata.GUIDELayoutEditor = [];\n\nh1 = figure(...\n'Units','characters',...\n'PaperUnits',get(0,'defaultfigurePaperUnits'),...\n'Color',[0.701960784313725 0.701960784313725 0.701960784313725],...\n'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...\n'IntegerHandle','off',...\n'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...\n'MenuBar','none',...\n'Name','Metch GUI: A mesh/image registration utility',...\n'NumberTitle','off',...\n'PaperPosition',get(0,'defaultfigurePaperPosition'),...\n'PaperSize',[20.98404194812 29.67743169791],...\n'PaperType',get(0,'defaultfigurePaperType'),...\n'Position',[103.8 16.8901098901099 144.5 44.5714285714286],...\n'Resize','off',...\n'HandleVisibility','callback',...\n'Tag','MetchGUI',...\n'UserData',[],...\n'Visible','on',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'axMesh';\n\nh2 = axes(...\n'Parent',h1,...\n'Units','characters',...\n'Position',[2.83333333333333 3 80.5 39.3571428571429],...\n'CameraPosition',[0.5 0.5 9.16025403784439],...\n'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...\n'Color',get(0,'defaultaxesColor'),...\n'ColorOrder',get(0,'defaultaxesColorOrder'),...\n'LooseInset',[18.9583333333333 5.28 13.8541666666667 3.6],...\n'XColor',get(0,'defaultaxesXColor'),...\n'YColor',get(0,'defaultaxesYColor'),...\n'ZColor',get(0,'defaultaxesZColor'),...\n'ButtonDownFcn','metchgui_one(''axMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','axMesh',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nh3 = get(h2,'title');\n\nset(h3,...\n'Parent',h2,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[0.5 1.00998185117967 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','bottom',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh4 = get(h2,'xlabel');\n\nset(h4,...\n'Parent',h2,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[0.497929606625259 -0.0408348457350272 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','cap',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh5 = get(h2,'ylabel');\n\nset(h5,...\n'Parent',h2,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[-0.056935817805383 0.498185117967332 1.00005459937205],...\n'Rotation',90,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','bottom',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh6 = get(h2,'zlabel');\n\nset(h6,...\n'Parent',h2,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','right',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[-0.036231884057971 1.0535390199637 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','middle',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','off',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nappdata = [];\nappdata.lastValidTag = 'axPoints';\n\nh7 = axes(...\n'Parent',h1,...\n'Units','characters',...\n'Position',[86.8333333333333 19.4285714285714 54.8333333333333 22.4285714285714],...\n'CameraPosition',[0.5 0.5 9.16025403784439],...\n'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...\n'Color',get(0,'defaultaxesColor'),...\n'ColorOrder',get(0,'defaultaxesColorOrder'),...\n'LooseInset',[18.9583333333333 5.28 13.8541666666667 3.6],...\n'XColor',get(0,'defaultaxesXColor'),...\n'YColor',get(0,'defaultaxesYColor'),...\n'ZColor',get(0,'defaultaxesZColor'),...\n'ButtonDownFcn','metchgui_one(''axPoints_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','axPoints',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nh8 = get(h7,'title');\n\nset(h8,...\n'Parent',h7,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[0.5 1.01751592356688 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','bottom',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh9 = get(h7,'xlabel');\n\nset(h9,...\n'Parent',h7,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[0.496960486322189 -0.0716560509554141 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','cap',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh10 = get(h7,'ylabel');\n\nset(h10,...\n'Parent',h7,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','center',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[-0.0835866261398175 0.495222929936306 1.00005459937205],...\n'Rotation',90,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','bottom',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','on',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nh11 = get(h7,'zlabel');\n\nset(h11,...\n'Parent',h7,...\n'Units','data',...\n'FontUnits','points',...\n'BackgroundColor','none',...\n'Color',[0 0 0],...\n'EdgeColor','none',...\n'FontAngle','normal',...\n'FontName','Helvetica',...\n'FontSize',10,...\n'FontWeight','normal',...\n'HorizontalAlignment','right',...\n'LineStyle','-',...\n'LineWidth',0.5,...\n'Margin',2,...\n'Position',[-1.58510638297872 1.11624203821656 1.00005459937205],...\n'Rotation',0,...\n'String','',...\n'Interpreter','tex',...\n'VerticalAlignment','middle',...\n'ButtonDownFcn',[],...\n'CreateFcn', {@local_CreateFcn, [], ''} ,...\n'DeleteFcn',[],...\n'BusyAction','queue',...\n'HandleVisibility','off',...\n'HitTest','on',...\n'Interruptible','on',...\n'SelectionHighlight','on',...\n'Tag','',...\n'UserData',[],...\n'Visible','off',...\n'XLimInclude','on',...\n'YLimInclude','on',...\n'ZLimInclude','on',...\n'Clipping','off');\n\nappdata = [];\nappdata.lastValidTag = 'lbMesh';\n\nh12 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Position',[85.5 4.35714285714286 27.5 9.35714285714285],...\n'String','',...\n'Style','listbox',...\n'Value',1,...\n'Tag','lbMesh',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'lbPoints';\n\nh13 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Position',[114 4.35714285714286 27.6666666666667 9.42857142857143],...\n'String','',...\n'Style','listbox',...\n'Value',1,...\n'Tag','lbPoints',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'isSelect';\n\nh14 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''isSelect_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[85.5 15.8571428571429 10 1.78571428571429],...\n'String','Select',...\n'Style','togglebutton',...\n'Tag','isSelect',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btDelete';\n\nh15 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btDelete_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[95.8333333333333 15.8571428571429 10 1.78571428571429],...\n'String','Delete',...\n'Tag','btDelete',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'bInit';\n\nh16 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''bInit_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[109 15.8571428571429 10 1.78571428571429],...\n'String','Initialize',...\n'Tag','bInit',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'txMesh';\n\nh17 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.614 0.052 0],...\n'ForegroundColor',[1 1 1],...\n'Position',[2.66666666666667 42.5 80.6666666666667 1.64285714285714],...\n'String','Surface mesh',...\n'Style','text',...\n'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','txMesh',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'txPoint';\n\nh18 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.0487072545035106 0 0.701960784313725],...\n'ForegroundColor',[1 1 1],...\n'Position',[85.5 42.5 56 1.64285714285714],...\n'String','Point cloud',...\n'Style','text',...\n'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','txPoint',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btAddMeshPt';\n\nh19 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btAddMeshPt_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[91.5 2.35714285714286 14.5 1.71428571428571],...\n'String','Add Selected',...\n'Tag','btAddMeshPt',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btAddCloudPt';\n\nh20 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btAddCloudPt_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[120 2.42857142857143 14.5 1.71428571428571],...\n'String','Add Selected',...\n'Tag','btAddCloudPt',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btProj';\n\nh21 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btProj_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[129.666666666667 15.8571428571429 12 1.78571428571429],...\n'String','Proj2Mesh',...\n'Tag','btProj',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'txMapTo';\n\nh22 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.542 0.063 0],...\n'ForegroundColor',[1 1 1],...\n'Position',[85.5 13.9285714285714 28 1.64285714285714],...\n'String','Map To',...\n'Style','text',...\n'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','txMapTo',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'txMapFrom';\n\nh23 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.0487072545035106 0 0.701960784313725],...\n'ForegroundColor',[1 1 1],...\n'Position',[113.666666666667 13.9285714285714 28 1.64285714285714],...\n'String','Map From',...\n'Style','text',...\n'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...\n'Tag','txMapFrom',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btOptimize';\n\nh24 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btOptimize_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[119.333333333333 15.8571428571429 10 1.78571428571429],...\n'String','Optimize',...\n'Tag','btOptimize',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'slPos';\n\nh25 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.9 0.9 0.9],...\n'Callback','metchgui_one(''slPos_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[2.83333333333333 1.42857142857143 80.5 1.57142857142857],...\n'String',{  'Slider' },...\n'Style','slider',...\n'CreateFcn', {@local_CreateFcn, 'metchgui_one(''slPos_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...\n'Tag','slPos',...\n'Visible','off');\n\nappdata = [];\nappdata.lastValidTag = 'lbZPos';\n\nh26 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Position',[41.8333333333333 -0.0714285714285714 6.66666666666667 1.57142857142857],...\n'String','',...\n'Style','text',...\n'Tag','lbZPos',...\n'Visible','off',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btSaveRes';\n\nh27 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btSaveRes_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[84.3333333333333 -0.0714285714285714 16 1.71428571428571],...\n'String','Save Session',...\n'Tag','btSaveRes',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btLoadSession';\n\nh28 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btLoadSession_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[100.833333333333 -0.0714285714285714 16 1.71428571428571],...\n'String','Load Session',...\n'Tag','btLoadSession',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btPlotResults';\n\nh29 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'Callback','metchgui_one(''btPlotResults_Callback'',gcbo,[],guidata(gcbo))',...\n'Position',[117.333333333333 -0.0714285714285714 16 1.71428571428571],...\n'String','Plot Results',...\n'Tag','btPlotResults',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btClose';\n\nh30 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.701960784313725 0.0456922325275102 0.0152120246425083],...\n'Callback','metchgui_one(''btClose_Callback'',gcbo,[],guidata(gcbo))',...\n'ForegroundColor',[1 1 1],...\n'Position',[134 -0.0714285714285714 10 1.71428571428571],...\n'String','Close',...\n'Tag','btClose',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\nappdata = [];\nappdata.lastValidTag = 'btHelp';\n\nh31 = uicontrol(...\n'Parent',h1,...\n'Units','characters',...\n'BackgroundColor',[0.12 0.542 0],...\n'Callback','metchgui_one(''btHelp_Callback'',gcbo,[],guidata(gcbo))',...\n'ForegroundColor',[1 1 1],...\n'Position',[108.166666666667 2.35714285714286 10 1.71428571428571],...\n'String','Help',...\n'Tag','btHelp',...\n'CreateFcn', {@local_CreateFcn, '', appdata} );\n\n\nhsingleton = h1;\n\n\n% --- Set application data first then calling the CreateFcn. \nfunction local_CreateFcn(hObject, eventdata, createfcn, appdata)\n\nif ~isempty(appdata)\n   names = fieldnames(appdata);\n   for i=1:length(names)\n       name = char(names(i));\n       setappdata(hObject, name, getfield(appdata,name));\n   end\nend\n\nif ~isempty(createfcn)\n   eval(createfcn);\nend\n\n\n% --- Handles default GUIDE GUI creation and callback dispatch\nfunction varargout = gui_mainfcn(gui_State, varargin)\n\ngui_StateFields =  {'gui_Name'\n                    'gui_Singleton'\n                    'gui_OpeningFcn'\n                    'gui_OutputFcn'\n                    'gui_LayoutFcn'\n                    'gui_Callback'};\ngui_Mfile = '';\nfor i=1:length(gui_StateFields)\n    if ~isfield(gui_State, gui_StateFields{i})\n        error('Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);        \n    elseif isequal(gui_StateFields{i}, 'gui_Name')\n        gui_Mfile = [gui_State.(gui_StateFields{i}), '.m'];\n    end\nend\n\nnumargin = length(varargin);\n\nif numargin == 0\n    % METCHGUI_ONE\n    % create the GUI\n    gui_Create = 1;\nelseif isequal(ishandle(varargin{1}), 1) && ispc && iscom(varargin{1}) && isequal(varargin{1},gcbo)\n    % METCHGUI_ONE(ACTIVEX,...)    \n    vin{1} = gui_State.gui_Name;\n    vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];\n    vin{3} = varargin{1};\n    vin{4} = varargin{end-1};\n    vin{5} = guidata(varargin{1}.Peer);\n    feval(vin{:});\n    return;\nelseif ischar(varargin{1}) && numargin>1 && isequal(ishandle(varargin{2}), 1)\n    % METCHGUI_ONE('CALLBACK',hObject,eventData,handles,...)\n    gui_Create = 0;\nelse\n    % METCHGUI_ONE(...)\n    % create the GUI and hand varargin to the openingfcn\n    gui_Create = 1;\nend\n\nif gui_Create == 0\n    varargin{1} = gui_State.gui_Callback;\n    if nargout\n        [varargout{1:nargout}] = feval(varargin{:});\n    else\n        feval(varargin{:});\n    end\nelse\n    if gui_State.gui_Singleton\n        gui_SingletonOpt = 'reuse';\n    else\n        gui_SingletonOpt = 'new';\n    end\n    \n    % Open fig file with stored settings.  Note: This executes all component\n    % specific CreateFunctions with an empty HANDLES structure.\n    \n    % Do feval on layout code in m-file if it exists\n    if ~isempty(gui_State.gui_LayoutFcn)\n        gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);\n        % openfig (called by local_openfig below) does this for guis without\n        % the LayoutFcn. Be sure to do it here so guis show up on screen.\n\tif(exist('movegui'))\n            movegui(gui_hFigure,'onscreen');\n\tend\n    else\n        gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);            \n        % If the figure has InGUIInitialization it was not completely created\n        % on the last pass.  Delete this handle and try again.\n        if isappdata(gui_hFigure, 'InGUIInitialization')\n            delete(gui_hFigure);\n            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);            \n        end\n    end\n    \n    % Set flag to indicate starting GUI initialization\n    setappdata(gui_hFigure,'InGUIInitialization',1);\n\n    % Fetch GUIDE Application options\n    gui_Options = getappdata(gui_hFigure,'GUIDEOptions');\n    \n    if ~isappdata(gui_hFigure,'GUIOnScreen')\n        % Adjust background color\n        if gui_Options.syscolorfig \n            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));\n        end\n\n        % Generate HANDLES structure and store with GUIDATA. If there is\n        % user set GUI data already, keep that also.\n        data = guidata(gui_hFigure);\n        handles = guihandles(gui_hFigure);\n        if ~isempty(handles)\n            if isempty(data)\n                data = handles;\n            else\n                names = fieldnames(handles);\n                for k=1:length(names)\n                    data.(char(names(k)))=handles.(char(names(k)));\n                end\n            end\n        end\n        guidata(gui_hFigure, data);\n    end\n    \n    % If user specified 'Visible','off' in p/v pairs, don't make the figure\n    % visible.\n    gui_MakeVisible = 1;\n    for ind=1:2:length(varargin)\n        if length(varargin) == ind\n            break;\n        end\n        len1 = min(length('visible'),length(varargin{ind}));\n        len2 = min(length('off'),length(varargin{ind+1}));\n        if ischar(varargin{ind}) && ischar(varargin{ind+1}) && ...\n                strncmpi(varargin{ind},'visible',len1) && len2 > 1\n            if strncmpi(varargin{ind+1},'off',len2)\n                gui_MakeVisible = 0;\n            elseif strncmpi(varargin{ind+1},'on',len2)\n                gui_MakeVisible = 1;\n            end\n        end\n    end\n    \n    % Check for figure param value pairs\n    for index=1:2:length(varargin)\n        if length(varargin) == index || ~ischar(varargin{index})\n            break;\n        end\n        try set(gui_hFigure, varargin{index}, varargin{index+1}), catch break, end\n    end\n\n    % If handle visibility is set to 'callback', turn it on until finished\n    % with OpeningFcn\n    gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');\n    if strcmp(gui_HandleVisibility, 'callback')\n        set(gui_hFigure,'HandleVisibility', 'on');\n    end\n    \n    feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});\n    \n    if ishandle(gui_hFigure)\n        % Update handle visibility\n        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);\n        \n        % Make figure visible\n        if gui_MakeVisible\n            set(gui_hFigure, 'Visible', 'on')\n            if gui_Options.singleton \n                setappdata(gui_hFigure,'GUIOnScreen', 1);\n            end\n        end\n\n        % Done with GUI initialization\n        rmappdata(gui_hFigure,'InGUIInitialization');\n    end\n    \n    % If handle visibility is set to 'callback', turn it on until finished with\n    % OutputFcn\n    if ishandle(gui_hFigure)\n        gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');\n        if strcmp(gui_HandleVisibility, 'callback')\n            set(gui_hFigure,'HandleVisibility', 'on');\n        end\n        gui_Handles = guidata(gui_hFigure);\n    else\n        gui_Handles = [];\n    end\n    \n    if nargout\n        [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);\n    else\n        feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);\n    end\n    \n    if ishandle(gui_hFigure)\n        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);\n    end\nend    \n\nfunction gui_hFigure = local_openfig(name, singleton)\n\n% this application data is used to indicate the running mode of a GUIDE\n% GUI to distinguish it from the design mode of the GUI in GUIDE.\nsetappdata(0,'OpenGuiWhenRunning',1);\n\n% openfig with three arguments was new from R13. Try to call that first, if\n% failed, try the old openfig.\ntry \n    gui_hFigure = openfig(name, singleton, 'auto');\ncatch\n    % OPENFIG did not accept 3rd input argument until R13,\n    % toggle default figure visible to prevent the figure\n    % from showing up too soon.\n    gui_OldDefaultVisible = get(0,'defaultFigureVisible');\n    set(0,'defaultFigureVisible','off');\n    gui_hFigure = openfig(name, singleton);\n    set(0,'defaultFigureVisible',gui_OldDefaultVisible);\nend\nrmappdata(0,'OpenGuiWhenRunning');\n\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/metchgui_one.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2440821133485685}}
{"text": "function reset_SPMcfg()\n% resets columns in SPMcfg by removing all non-intercept nuisance covariates.\n% runs on the SPMcfg.mat file in the current directory\n\n    if exist([pwd filesep 'SPMcfg.mat']) == 2\n        load SPMcfg\n    else\n        warning(['No SPMcfg.mat file found in current directory:' pwd])\n    end\n    \n    nsess=length(Sess);\n    xX.X(:,xX.iB(1:end - nsess)) = [];\n    \n    if length(xX.Xnames) > size(xX.X,2)\n        xX.Xnames(xX.iB(1:end - nsess)) = [];\n    end\n    \n    xX.iB = size(xX.X,2) - nsess + 1: size(xX.X,2); \n    \n    F_iX0.iX0 = xX.iB;\n    save SPMcfg F_iX0 SPMid Sess VY xGX xM xX xsDes\n\n    fprintf(1,'\\n SPMcfg xX modified to remove nuisance covariates and saved.\\n')\n    \nreturn\n    \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/diagnostics/reset_SPMcfg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24408211334856847}}
{"text": "% This script file loads input files defined in vector 'n'  and\n% selects some eartquakes based on various criteria\n% (e.g. latidude, longitude, magnitude, depth error)\n\n% The selected EQ are stored in matrix 'a'.\n%\n%  Stefan Wiemer, June 1994\n\nreport_this_filefun(mfilename('fullpath'));\n\nclear\na = []\nn = [ 'calsplitaa'\n    'calsplitab'\n    'calsplitac'\n    'calsplitad'\n    'calsplitae'\n    'calsplitaf'\n    'calsplitag'\n    'calsplitah'\n    'calsplitai'\n    'calsplitaj'\n    'calsplitak'\n    'calsplital'\n    'calsplitam'\n    'calsplitan'\n    'calsplitao'\n    'calsplitap'\n    'calsplitaq'\n    'calsplitar'\n    ]\n\nfor i = 1:length(n)\n\n    lofi = ['load ' n(i,1:10) ]\n    eval(lofi)\n    comm = [' s = ' n(i,1:10) ';']\n    eval(comm)\n    a2 = [ -s(:,1) s(:,2) s(:,3) s(:,4) s(:,5) s(:,6) s(:,7)/100 s(:,8)/100];\n    l = a2(:,8) < 2.0 & a2(:,1) < -121.2 & a2(:,1) > -122.4 & a2(:,2) > 36.65  & a2(:,2) < 37.8;\n    a2 = a2(l,:);\n\n    a = [a ; a2];\n    size(a)\n    comm = [' clear a2 s ' n(i,1:10)]\n    eval(comm)\nend\n\na2 = a;\nload /FM1/ramon/matlab/zmapv1.1/eq_data/landers_cata.mat\na = a2;\nclear a2;\nsave /FM1/ramon/matlab/zmapv1.1/eq_data/centcal_cata.mat\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/joinsel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.24403571196279375}}
{"text": "%%  StoichTools: Tools for Doing Stoichiometry\n%\n% StoichTools comprises a set of Matlab functions for doing stoichiometric\n% analysis. These functions parse standard chemical notation for a variety\n% of stoichiometric calculations including finding molecular weights,\n% balancing reactions for atom and charge conservation, finding independent\n% reactions, and displaying formulas in Hill notation. The functions\n% account for both change and atomic balances so they can be used to\n% balance ionic reactions and chemical half reactions.\n%\n% StoichTools has extensive documentation including a set of worked\n% homework problems demonstrating use of the functions.\n%\n% These functions were developed to support introductory courses in\n% Chemical Engineering.\n%\n%  Jeff Kantor\n%  December 18, 2010\n\n%% What is StoichTools?\n%\n% StoichTools works with two types of data:\n%\n% # *Chemical formulas*. Each chemical formula is a string written in a\n% nearly universal chemical notation. For example, |H2SO4| represents\n% Sulfuric Acid. Grouping is allowed (e.g., |CH3(CH2)6CH3| for octane) with\n% either parentheses '()' or brackets '[]'.  Charge is indicated by a\n% trailing + or - followed by an optional number (e.g., |Fe+3| or |HSO4-|).\n% Phase information may be included as a terminal (aq), (l), (g), or (s).\n% Cell arrays can be used in most places to work with multiple formulas at\n% one time (e.g., {'H2SO4','H+','SO4-2'}).\n% # *Atomic representation*. Many calculations require knowledge of the\n% charge, and of number of atoms of each type in a chemical species. This\n% is maintained in a Matlab structure where r.C, for example, is the\n% number of carbon atoms. The symbol after the dot is the standard 1 or 2\n% character symbol for an element. The symbol |Q| is reserved to indicated\n% charge. A Matlab structure array is used to store multiple atomic\n% reprentations in a single variable.\n%\n% StoichTools provides functions for the following types of chemical\n% calculations:\n%\n% *Working with Chemical Formulas*\n%\n% * |r = parse_formula(s)| processes a chemical formula to produce an\n%   atomic representation. This function is mainly used by other functions\n%   to process chemical formulas.\n% * |hillformula| processes a chemical formula or atomic reprentation to\n%   produce a chemical formula in standard Hill notation. The Hill notation\n%   widely used to represent species in chemical databases, such as the\n%   NIST Chemistry Webbook.\n%\n% *Calculating Molecular Weights*\n%\n% * |mw = molweight(s)| computes the molecular weights of chemical\n%   compounds. Input can be a chemical formula, a cell array of chemical\n%   formulas, or an array of atomic representations. If no output is\n%   indicated, then a table of molecular weights is printed.\n%\n% *Stoichiometry*\n%\n% * |[A,atoms,species] = atomic(s)| constructs the atomic matrix for a set\n%   of chemical compounds. Element |A(i,j)| is the number of |atoms{i}| in\n%   |species{j}|. Inputs may be chemical formula, a cell array of chemical\n%   formulas, If there are ionic species, then a special atom 'Q' is\n%   indicates the charge of the species. If no output is indicated, then\n%   the atomic matrix is displayed in tabular form.\n% * |V = stoich(s)| computes the stoichiometric matrix for a set of\n%   chemical compounds. The input is a cell array of chemical formulas, or\n%   an array of atomic representations. The columns of |V| correspond to\n%   independent chemical reactions satisfying atomic and charge balances.\n%   Element |V(j,k)| is the stoichiometric coefficient for species |j| in\n%   reaction |k|. A negative value denotes a reactant, a positive value\n%   denotes a product. If no output is indicated, then |disp_reaction| is\n%   used to display all independent reactions.\n% * |Vout = disp_reaction(V,s)| If no output is indicated, then format\n%   and displays the chemical reactions denoted by stoichiometric matrix\n%   |V| and the array of species |s|. The species may be cell array of\n%   formulas or an array of atomic representations. If feasible, the\n%   coefficients are scaled to integers.  It integer coefficients are too\n%   long, then either rational or floating point coefficients are\n%   displayed. If an output is indicated, then |Vout| is a stoichiometric\n%   matrix with rescaled coefficients, and the reactions are not displayed.\n%\n% *Homework Problems with Solutions*\n%\n% The StoichTools folder includes a number of worked homework problems.\n% These are Matlab scripts with titles in the pattern |HW_xx.m|. Each\n% script begins with a cell containing the problem statement. Subsequent\n% cells demonstrate solution to the problem. The homework files can be\n% sviewed by using the Matlab publishing function.\n\n\n%% Parsing Chemical Formulas\n%\n% Given a set of chemical species, |r = parse_formula(s)| parses a cell\n% array of chemical formulas to produce a structure array r. The value is\n% the number of atoms of that element present in the corresponding formula.\n% The structure array includes a field for each atomic element in the set\n% of species. We call this the atomic represenation of the species.\n\n% Parsing methane\n\nparse_formula('CH4')\n\n%% Additional Parsing Examples\n\nex{1} = 'NaHCO3';\nex{2} = 'KFe3(SO4)2(OH)6';     % Jorosite\nex{3} = 'KFe3(AsO4)2(HAsO4)2'; % Potassium-Iron-Arsenate\nex{4} = '(CH4)8(H2O)46';       % Methane Clathrate\nex{4} = 'HSO4-(aq)';\n\nfor k = 1:length(ex)\n    disp(ex{k});\n    parse_formula(ex{k})\nend\n\n%% Chemical Abbreviations and Isotopes\n%\n% * Formulas may include D (Deuterium) or T (Tritium). These are treated as\n%   elements and included as distinct species in any atom balances.\n% * The common organic chemistry abbreviations Me (Methyl, CH3), Et (Ethyl,\n%   C2H5), Bu (Butyl, C4H9), Ph (Phenol, C6H5) may be included in formulas.\n%   These are replaced by their atomic formulas during the parsing process.\n% * The symbols M (any metal) and X (any halogen) may be used in formulas.\n%   Formulas containing the symbol M or X have unknown molecular weight.\n\nparse_formula('D2O')\nparse_formula('EtOH')\nmolweight({'H2O','D2O','T2O','EtOH','PhOH','TiO2','MO2'});\n\n%% Non-stoichiometric Formulas\n%\n% Some applications of stoichiometry involve complex chemical compounds not\n% easily described by simple chemical fomulas. So-called\n% 'non-stoichiometric' compounds can be also be parsed.\n\nbacteria = 'CH1.8N0.24O0.36';\nparse_formula(bacteria);\n\n\n%% From Atoms to Chemical Formulas\n%\n% Given a structure array of atomic representations, |s = hillformula(r)}\n% constructs a cell array of corresponding chemical formulas.\n\n% Formula for octane\n\noctane.C = 8;\noctane.H = 18;\nhillformula(octane)\n\n\n%% Hill Notation & Canonical Representations\n%\n% The Hill notation is a commonly used system for writing chemical formulas\n% in a standard form. % |hillformula(r)| produces a simple canonical\n% representation of a chemical species. Note, however, that there may be\n% many isomers for a given formula.\n\ns = {'Zr3B2','HBr','HCl','CH3(CH2)6CH3','NaCO3','CaC2','CH3OH', ...\n     'CH3COOH','HNO3','H2SO4','NH3','SnH4','CH3HgCH3','(CH3CH2)4Pb', ...\n     '[Co(NH3)6]+3','[B12H12]-2'};\n\nfprintf('\\n%-15s %-15s\\n----------      ----------\\n', ...\n    'Formula','Hill Notation');\nfor k = 1:length(s)\n    fprintf('%-15s %-15s\\n',s{k},char(hillformula(s{k})));\nend\n\n\n%% Molecular Weight\n%\n%  mw = molweight(s)\n%  mw = molweight(r)\n%\n% Given a cell array of chemical formulas, or a structure array of atomic\n% representations, |molweight| computes a corresponding vector of molecular\n% weights.\n\n% Molecular Mass of Dimethyl Mercury\n\ns = 'CH3HgCH3';\nmw = molweight('CH3HgCH3');\nfprintf('Molecular Weight of Dimethyl Mercury (%s) = %g\\n',s,mw);\n\n\n%% Creating Molecular Weight Tables\n%\n% If molweight as no output, then it prints a table of molecular weights.\n\nmolweight(s);\n\n%% Atomic Matrix\n%\n%  [A,atoms,species] = atomic(s)\n%  [A,atoms,species] = atomic(r)\n% \n% Given a cell array of chemical formulas |s|, or a structure array of\n% atomic representations |r|, |atomic| computes the atomic matrix A.\n% |atoms| is a a cell array of the atomic elements, |species| is a cell\n% array of species. A(i,j) is the number of atoms of element atoms{i} in\n% species species{j}. % When called without an output argument, |atomic|\n% displays the atomic matrix.\n\ns = {'CH4','O2','H2O','CO2'};\n\natomic(s);\nA = atomic(s);\ndisp(' ');\ndisp('A = ');\ndisp(A);\n\n%% Atomic Matrix for Ionic Species\n%\n% For ionic species an additional row is added, labeled by 'Q', indicating\n% the net charge on each of the species included in the matrix.\n\ns = {'Fe+3','SO4-2','H+','OH-','H2O','Fe2(SO4)3'};\natomic(s);\n\n%% Balancing a Reaction\n%\n% Given a cell array of chemical formulas, or an array of atomic\n% representations, |stoich(s)| computes stoichiometric coefficients that\n% satisfy charge and atom balances. If no output is specified, then\n% balanced reactions are displayed.\n\nstoich({'NaPb','CH3CH2Cl','(CH3CH2)4Pb','NaCl','Pb'});\nstoich({'H+(aq)','OH-(aq)','H2O(l)'});\n\n%% Stoichiometric Matrix\n%\n% Given a cell array of chemical formulas, or a structure array of atomic\n% representations, |V = stoich(s)| computes the stoichiometric matrix |V|.\n% |V(n,r)| is the stoichiometric coeffient of species |n| in reaction |r|.\n% The atomic and stoichiometric matrices satisfies the relationship |A*V =\n% 0|.\n\ns = {'C8H18','O2','C','CO','CO2','H2O'};\nV = stoich(s);\ndisp('Stoichiometric Matrix V = ');\ndisp(V);\n\n%% Mulitple Independent Reactions\n%\n%  V = stoich(s)\n%  disp_reaction(V,s)\n%\n% The columns of the stoichiometric matrix |V| represent independent\n% reactions. The function |disp_reaction(V,s)| displays the reactions in a\n% conventional human readable form.\n\ns = {'C8H18','O2','C','CO','CO2','H2O'};\nV = stoich(s);\ndisp_reaction(V,s);\n\n\n%% Further Examples of Complex Reactions\n%\n% Examples from \n% <http://www.chemistryhelp.net/chemistry-calculator/chemical-equation-balancer>\n\nstoich({'P2I4','P4','H2O','H3PO4','PH4I'});\n\nstoich({'[Cr(N2H4CO)6]4[Cr(CN)6]3','KMnO4','H2SO4','K2Cr2O7', ...\n     'MnSO4','CO2','KNO3','K2SO4','H2O'});\n \nstoich({'Cu(s)','HNO3(aq)','Cu(NO3)2(aq)','NO(g)','H2O(l)'});\n\nstoich({'Cu','HNO3','H2O','Cu(NO3)2','NO'});\n\nstoich({'KMnO4','C3H5(OH)3','K2CO3','Mn2O3','CO2','H2O'});\n\nstoich({'K2Cr2O7','FeCl2','HCl','KCl', ...\n    'CrCl3','FeCl3','H2O'});\n\nstoich({'Bi(NO3)3(H2O)5','NaOH','H2O2','RuCl3', ...\n     'NaNO3','NaCl','Bi2Ru2O7','H2O'});\n\nstoich({'(NH4)2MoO4','NH4NO3','Na3PO4','H2O', ...\n    '(NH4)3[P(Mo3O10)4]','NaNO3','NH3'});\n\nstoich({'H2','Ca(CN)2','NaAlF4','FeSO4','MgSiO3','KI','H3PO4', ...\n    'PbCrO4','BrCl','CF2Cl2','SO2','PbBr2','CrCl3','MgCO3', ...\n    'KAl(OH)4','Fe(SCN)3','PI3','Na2SiO3','CaF2','H2O'});\n\nstoich({'NH4ClO4','NaY(OH)4','Ru(SCN)3','PBr5','TiCl2CrI4','BeCO3', ...\n    'Rb2ZrO3','ZnAt2','CAt2I2','Rb0.998YAt4','RuS2','BeZrO3','Zn(CN)2', ...\n    'NaHBr1.997','H3PO4','TiCrO4','ClI','H2SO4','H2O'});\n\n   \n%% Chemical Equations with Ionic Charges\n%\n% The charge on ionic species is indicated by + or - followed by an\n% optional digit indicating the amount of charge.  If ionic species are\n% present, then a charge balance is include in the computation of the\n% stoichiometric coefficients.\n\nstoich({'ClO2+(aq)','H3O+(aq)','Cl2(g)','H2O(l)','ClO3-(aq)','ClO2(aq)'});\nstoich({'Bi+3(aq)','HSnO2-(aq)','OH-(aq)','Bi(s)','H2O','SnO3-2(aq)'});\nstoich({'CH3CH2OH','Cr2O7-2','H+','CH3COOH','Cr+3','H2O'});\nstoich({'I-','I2','Mn+2','MnO4-','H+','H2O'});\nstoich({'Cl2','Cl-','Fe+2','Fe+3'});\nstoich({'Mn+2','BiO-3','H+','MnO4-','Bi3+','H2O'});\nstoich({'NpO2+2','NpO2(OH)H2C2O4+','NpO2+','CO2','H+','O2'});\nstoich({'H3PO4','(NH4)6Mo7O24','H+','(NH4)3PO4(MoO3)12','NH4+','H2O'});\n\n\n%% Chemical Half Equations\n%\n% Include the bare electron 'e-' to balance chemical half reactions. In\n% acidic solutions, if one of the main reactants contains oxygen, add 'H+'\n% and 'H2O'. In basic solutions, if one of the main reactants contains\n% oxygen then add 'OH-' and 'H2O'.\n\nstoich({'Al+3(aq)','Al(s)','e-'});\nstoich({'Cl-(aq)','Cl2(g)','e-'});\n\n% Acidic Solutions \n\nstoich({'MnO4-(aq)','Mn+2(aq)','H2O(l)','H+(aq)','e-'});\nstoich({'O2(g)','H2O(l)','H+(aq)','e-'});\nstoich({'Ag2O3','Ag+','H2O','H+','e-'});\nstoich({'S2O3-2(aq)','S(s)','H2O(l)','H+(aq)','e-'});\nstoich({'HOOCCOOH(aq)','CO2(g)','H2O(l)','H+(aq)','e-'});\n\n% Alkali Solutions\n\nstoich({'MnO4-(aq)','Mn+2(aq)','H2O(l)','OH-(aq)','e-'});\nstoich({'Cr(OH)6-2','CrO4-2','H2O','OH-','e-'});\nstoich({'NH3OH(aq)','N2(g)','H2O(l)','OH-(aq)','e-'});\nstoich({'Al(OH)4-(aq)','Al(s)','H2O(l)','OH-(aq)','e-'});\nstoich({'ZrO(OH)2','Zr','H2O','OH-','e-'});\n\n\n%% Nested Formulas\n%\n% Matlab regular expressions capabilities are used to parse chemical\n% formulas. While this keeps StoichTools simple and fast, one of the\n% drawbacks of regular expressions is the difficulty of matching nested\n% expressions. Thus nesting is limited to bracketed expressions inside of\n% parentheses, or parentheses inside of brackets. By this rule, [Fe2(SO4)3]\n% and (Fe2[SO4]3) are allowed, but (Fe2(SO4)3) and [Fe2[SO4]3] are not. In\n% practice, chemical formula rarely need more than two levels of nesting.\n\ndisp('These work fine.');\nmolweight({'[Fe2(SO4)3]','(Fe2[SO4]3)'});\n\nfprintf('\\n\\n');\ntry\n    molweight({'(Fe2(SO4)3)','[Fe2[SO4]3]'})\ncatch exception\n    disp('But this does not.');\n    disp(exception.message);\nend\n\n%% Version History\n%\n% * 2010/12/18  Submitted to Matlab Central\n% * 2010/12/19  Updated documentation, added solved homeworks\n% * 2010/12/19  Put rows of the atomic matrix in Hill order\n% * 2010/12/19  Expanded regular expression parsing to include phases\n% * 2010/12/20  Enhanced parser to accept non-stoichiometric formulas\n% * 2010/12/20  Enhanced disp_reaction for better coefficient formatting\n% * 2010/12/21  Parser to include common symbols D, T, Et, Me, Bu, Ph\n% * 2010/12/30  Fixed all mlint messages, reduced McCabe complexity\n% * 2010/12/30  Update to Matlab Central\n% * 2010/12/30  Further improvements to error handling (assert's)\n% * 2010/12/31  Fixed bug with NaN in molweight\n% * 2010/12/31  Renamed homework files so it makes more sense on MC\n% * 2010/12/31  Update to Matlab Central\n%\n%\n% To Do's\n%\n% * Add Generation/Consumption Analysis\n% * Add Extent of Reaction Analysis\n% * Include an electrochemistry howework example (battery?)\n% * Add a display feature for stoich \n% * Add webbook lookup for chemical property data\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/StoichTools/README.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24399277324591526}}
{"text": "img = which('keuken_2014_enhanced_for_underlay.img');\n\n% sup colliculus\nxyz = [5.1767  -32.3069   -4.2592\n-5.1767  -32.3069  -4.2592];\n\nmyradius = 3.5;\n\ncluster_orthviews();\n\ncl = sphere_roi_tool_2008(img, myradius, xyz, 'useexisting');\n\nr = cluster2region(cl);\nobj = region2imagevec(r);\n\n% Mask with brainstem\nbstem = fmri_data(which('brainstem_mask_tight_2018.img'));\nobj = apply_mask(obj, bstem);\nr = region(obj);\northviews(r)\n\nr(1).shorttitle = 'R_SC';\nr(2).shorttitle = 'L_SC';\n\nsc_regions = r;\nsc_obj = obj;\n\n\n%% inf coll\n\nxyz = [4.8186  -37.2304   -9.9917\n      -4.8186  -37.2304   -9.9917];\n\n  myradius = 3;\n\n%cluster_orthviews();\n\ncl = sphere_roi_tool_2008(img, myradius, xyz, 'useexisting');\n\nr = cluster2region(cl);\nobj = region2imagevec(r);\n\n% Mask with brainstem\nbstem = fmri_data(which('brainstem_mask_tight_2018.img'));\nobj = apply_mask(obj, bstem);\nr = region(obj);\northviews(r)\n\nr(1).shorttitle = 'R_IC';\nr(2).shorttitle = 'L_IC';\n\nic_regions = r;\nic_obj = obj;\n\n\n%% Save\n\ncd('/Users/tor/Documents/Code_Repositories/CanlabCore/CanlabCore/canlab_canonical_brains/Thalamus_brainstem_ROIs_surfaces')\nsavename = 'sup_inf_colliculus_roi_2018_tor';\n\npag_regions = r;\npag_obj = obj;\n\nsave(savename, 'sc_regions', 'sc_obj', 'ic_regions', 'ic_obj');\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/canlab_canonical_brains/Thalamus_brainstem_ROIs_surfaces/draw_sup_inf_colliculus_roi_2018.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372686425363768}}
{"text": "function [dateNum, dateStr] = datestr2datenum(dateStr)\ndateNum = 0;\n\nc = str2cell(dateStr, ' ');\nif length(c)<2\n    return\nend\ndateStr = c{1};\ntimeStr = c{2};\n\ndateStr(dateStr=='-')='';\ntimeStr(timeStr==':')='';\n\ntimeNum = str2num(timeStr);\ndateNum = str2num(dateStr) + timeNum/1e6;\n\ndateStr = [c{1}, ' ', c{2}];", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/Utils/Shared/datestr2datenum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24372501437868957}}
{"text": "function F = in_fread_bci2000(sFile, SamplesBounds)\n% IN_FREAD_BCI2000: Read a block of recordings from a BCI2000 .dat file\n%\n% Uses library: https://www.bci2000.org/mediawiki/index.php/User_Reference:Matlab_MEX_Files\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Author: Francois Tadel 2022\n\n% Parse inputs\nif (nargin < 2) || isempty(SamplesBounds)\n    if ~isempty(sFile.epochs)\n        SamplesBounds = round(sFile.epochs(iEpoch).times .* sFile.prop.sfreq);\n    else\n        SamplesBounds = round(sFile.prop.times .* sFile.prop.sfreq);\n    end\nend\n\n% Install plugin BCI2000\nif ~exist('load_bcidat', 'file')\n    [isInstalled, errMsg] = bst_plugin('Install', 'bci2000');\n    if ~isInstalled\n        error(errMsg); \n    end\nend\n\n% Read signals\nF = load_bcidat(sFile.filename, SamplesBounds + 1, '-calibrated')';\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_bci2000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24365168107199117}}
{"text": "function [imo,rois] = wsddn_get_batch(images, imdb, batch, opts)\n% cnn_wsddn_get_batch  Load, preprocess, and pack images for CNN evaluation\n\nif isempty(images)\n  imo = [] ;\n  rois = [] ;\n  return ;\nend\n\n% fetch is true if images is a list of filenames (instead of\n% a cell array of images)\nfetch = ischar(images{1}) ;\n\n% prefetch is used to load images in a separate thread\nprefetch = fetch & opts.prefetch ;\n\n% pick size\nimSize = imdb.images.size(batch(1),:);\nfactor = min(opts.scale(1)/imSize(1),opts.scale(1)/imSize(2));\nheight = floor(factor*imSize(1));\n\nif prefetch\n  vl_imreadjpeg(images, 'numThreads',opts.numThreads,'Resize',height,'prefetch') ;\n  imo = [] ;\n  rois = [] ;\n  return ;\nend\n\nif fetch\n  ims = vl_imreadjpeg(images,'numThreads',opts.numThreads,'Resize',height) ;\nelse\n  ims = images ;\nend\n\nfor i=1:numel(images)\n  % acquire image\n  if isempty(ims{i})\n    imt = imread(images{i}) ;\n    if size(imt,3) == 1\n      imt = cat(3, imt, imt, imt) ;\n    end\n    \n    ims{i} = imresize(imt,factor,'Method',opts.interpolation);\n    ims{i} = single(ims{i}) ; % faster than im2single (and multiplies by 255)\n  end\nend\n\n\n\nbboxes = cell(1,numel(batch));\nnBoxes = 0;\nfor b=1:numel(batch)\n  bboxes{b} = double(imdb.images.boxes{batch(b)});\n  nBoxes = nBoxes + size(bboxes{b},1);\nend\n \n\nrois = zeros(nBoxes,5);\ncountr = 0;\n\nmaxW = 0;\nmaxH = 0;\n\n\n\nfor b=1:numel(batch)\n  \n  hw = imdb.images.size(batch(b),:);\n  h = hw(1);\n  w = hw(2);\n  \n  imsz = size(ims{b});\n  \n  if opts.flip(b)\n    im = ims{b};\n    ims{b} = im(:,end:-1:1,:);\n    \n    bbox = bboxes{b};\n    bbox(:,[2,4]) = w + 1 - bbox(:,[4,2]);\n    bboxes{b} = bbox;\n  end\n  \n\n  maxH = max(imsz(1),maxH);\n  maxW = max(imsz(2),maxW);\n \n  % adapt bounding boxes into new coord\n  bbox = bboxes{b};\n  if any(bbox(:)<=0)\n    error('bbox error');\n  end\n  nB = size(bbox,1);\n  tbbox = scale_box(bbox,[h,w],imsz);\n  if any(tbbox(:)<=0)\n    error('tbbox error');\n  end\n\n  rois(countr+1:countr+nB,:) = [b*ones(nB,1),tbbox];\n  countr = countr + nB;\nend\n\n% rois = single(rois);\ndepth = size(ims{1},3);\nimo = zeros(maxH,maxW,depth,numel(batch),'single');\n\nif isempty(opts.averageImage)\n  avgIm = [];\nelseif numel(opts.averageImage)==depth\n  avgIm = opts.averageImage;\nend\n\n\nfor b=1:numel(batch)\n  sz = size(ims{b});\n\n  imo(1:sz(1),1:sz(2),:,b) = single(ims{b});\n  \n  if ~isempty(avgIm)\n    imo(1:sz(1),1:sz(2),:,b) = single(bsxfun(@minus,imo(1:sz(1),1:sz(2),:,b),opts.averageImage));\n  end\n  if ~isempty(opts.rgbVariance)\n    imo(1:sz(1),1:sz(2),:,b) = bsxfun(@plus, imo(1:sz(1),1:sz(2),:,b), ...\n        reshape(opts.rgbVariance * randn(3,1), 1,1,3)) ;\n  end\nend\n\n\nfunction boxOut = scale_box(boxIn,szIn,szOut)\n  \n  h = szIn(1);\n  w = szIn(2);\n\n  bxr = 0.5 * (boxIn(:,2)+boxIn(:,4)) / w;\n  byr = 0.5 * (boxIn(:,1)+boxIn(:,3)) / h;\n \n  bwr = (boxIn(:,4)-boxIn(:,2)+1) / w;\n  bhr = (boxIn(:,3)-boxIn(:,1)+1) / h;\n  \n  % boxIn center in new coord\n  byhat = (szOut(1) * byr);\n  bxhat = (szOut(2) * bxr);\n  \n  % relative width, height\n  bhhat = szOut(1) * bhr;\n  bwhat = szOut(2) * bwr;\n  \n  % transformed boxIn\n  boxOut = [max(1,round(byhat - 0.5 * bhhat)),...\n    max(1,round(bxhat - 0.5 * bwhat)), ...\n    min(szOut(1),round(byhat + 0.5 * bhhat)),...\n    min(szOut(2),round(bxhat + 0.5 * bwhat))];\n\n", "meta": {"author": "hbilen", "repo": "WSDDN", "sha": "bfdaa3f9ffed45e52a11a1342fd7476e08dfac39", "save_path": "github-repos/MATLAB/hbilen-WSDDN", "path": "github-repos/MATLAB/hbilen-WSDDN/WSDDN-bfdaa3f9ffed45e52a11a1342fd7476e08dfac39/core/wsddn_get_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24361672462087028}}
{"text": "function [d,fp,dt,tc,t]=readhtk(file)\n%READHTK  read an HTK parameter file [D,FP,DT,TC,T]=(FILE)\n%\n% Input:\n%    FILE = name of HTX file\n% Outputs:\n%       D = data: column vector for waveforms, one row per frame for other types\n%      FP = frame period in seconds\n%      DT = data type (also includes Voicebox code for generating data)\n%             0  WAVEFORM     Acoustic waveform\n%             1  LPC          Linear prediction coefficients\n%             2  LPREFC       LPC Reflection coefficients:  -lpcar2rf([1 LPC]);LPREFC(1)=[];\n%             3  LPCEPSTRA    LPC Cepstral coefficients\n%             4  LPDELCEP     LPC cepstral+delta coefficients (obsolete)\n%             5  IREFC        LPC Reflection coefficients (16 bit fixed point)\n%             6  MFCC         Mel frequency cepstral coefficients\n%             7  FBANK        Log Fliter bank energies\n%             8  MELSPEC      linear Mel-scaled spectrum\n%             9  USER         User defined features\n%            10  DISCRETE     Vector quantised codebook\n%            11  PLP          Perceptual Linear prediction\n%            12  ANON\n%      TC = full type code = DT plus (optionally) one or more of the following modifiers\n%               64  _E  Includes energy terms\n%              128  _N  Suppress absolute energy\n%              256  _D  Include delta coefs\n%              512  _A  Include acceleration coefs\n%             1024  _C  Compressed\n%             2048  _Z  Zero mean static coefs\n%             4096  _K  CRC checksum (not implemented yet)\n%             8192  _0  Include 0'th cepstral coef\n%            16384  _V  Attach VQ index\n%            32768  _T  Attach delta-delta-delta index\n%       T = text version of type code e.g. LPC_C_K\n\n%   Thanks to Dan Ellis (ee.columbia.edu) for sorting out decompression.\n%   Thanks to Stuart Anderson (whispersys.com) for making it work on 64 bit machines.\n\n%      Copyright (C) Mike Brookes 2005\n%      Version: $Id: readhtk.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfid=fopen(file,'r','b');\nif fid < 0\n    error(sprintf('Cannot read from file %s',file));\nend\nnf=fread(fid,1,'int32');             % number of frames\nfp=fread(fid,1,'int32')*1.E-7;       % frame interval (converted to seconds)\nby=fread(fid,1,'int16');            % bytes per frame\ntc=fread(fid,1,'int16');            % type code (see comments above for interpretation)\ntc=tc+65536*(tc<0);\ncc='ENDACZK0VT';                    % list of suffix codes\nnhb=length(cc);                     % number of suffix codes\nndt=6;                              % number of bits for base type\nhb=floor(tc*pow2(-(ndt+nhb):-ndt));\nhd=hb(nhb+1:-1:2)-2*hb(nhb:-1:1);   % extract bits from type code\ndt=tc-pow2(hb(end),ndt);            % low six bits of tc represent data type\n\n% hd(7)=1 CRC check\n% hd(5)=1 compressed data\nif (dt==5)  % hack to fix error in IREFC files which are sometimes stored as compressed LPREFC\n    fseek(fid,0,'eof');\n    flen=ftell(fid);        % find length of file\n    fseek(fid,12,'bof');\n    if flen>14+by*nf        % if file is too long (including possible CRCC) then assume compression constants exist\n        dt=2;               % change type to LPREFC\n        hd(5)=1;            % set compressed flag\n        nf=nf+4;            % frame count doesn't include compression constants in this case\n    end\nend\n\nif any(dt==[0,5,10])        % 16 bit data for waveforms, IREFC and DISCRETE\n    d=fread(fid,[by/2,nf],'int16').';\n    if ( dt == 5),\n        d=d/32767;                    % scale IREFC\n    end\nelse\n    if hd(5)                            % compressed data - first read scales\n        nf = nf - 4;                    % frame count includes compression constants\n        ncol = by / 2;\n        scales = fread(fid, ncol, 'float');\n        biases = fread(fid, ncol, 'float');\n        d = ((fread(fid,[ncol, nf], 'int16')+repmat(biases,1,nf)).*repmat(1./scales,1,nf)).';\n    else                              % uncompressed data\n        d=fread(fid,[by/4,nf],'float').';\n    end\nend;\nfclose(fid);\nif nargout > 4\n    ns=sum(hd);                 % number of suffixes\n    kinds={'WAVEFORM' 'LPC' 'LPREFC' 'LPCEPSTRA' 'LPDELCEP' 'IREFC' 'MFCC' 'FBANK' 'MELSPEC' 'USER' 'DISCRETE' 'PLP' 'ANON' '???'};\n    t=[kinds{min(dt+1,length(kinds))} reshape(['_'*ones(1,ns);cc(hd>0)],1,2*ns)];\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/readhtk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24361671903168114}}
{"text": "function t = model_cmp(m1, m2)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n[v1, b1, map1] = model2blocks(m1);\n[v2, b2, map2] = model2blocks(m2);\n\ne = sum(abs(v1-v2));\nif e > 0\n  fprintf('error: %.14f\\n', e);\n  for i = 1:length(b1)\n    I = find(b1{i} ~= b2{i});\n    if ~isempty(I)\n      for j = 1:length(I)\n        fprintf('at %s : index %d [%.5f vs %.5f]\\n', ...\n                map1{i}, I(j), b1{i}(I(j)), b2{i}(I(j)));\n      end\n    end\n  end\nelse\n  fprintf('no error\\n');\nend\n\n\nfunction [m, blocks, map] = model2blocks(model)\n\nblocks = cell(model.numblocks, 1);\n\n% filters\nfor i = 1:model.numfilters\n  if model.filters(i).flip == 0\n    bl = model.filters(i).blocklabel;\n    w = my_get_block(model, model.filters(i));\n    blocks{bl} = w(:);\n    map{bl} = ['filter ' num2str(i)];\n  end\nend\n\n% offsets\nfor i = 1:length(model.rules)\n  for j = 1:length(model.rules{i})\n    bl = model.rules{i}(j).offset.blocklabel;\n    w = my_get_block(model, model.rules{i}(j).offset);\n    blocks{bl} = w;\n    map{bl} = ['offset rule ' num2str(i) ' ind ' num2str(j)];\n  end\nend\n\n% deformation models\nfor i = 1:length(model.rules)\n  for j = 1:length(model.rules{i})\n    if model.rules{i}(j).type == 'D' && model.rules{i}(j).def.flip == 0\n      bl = model.rules{i}(j).def.blocklabel;\n      w = my_get_block(model, model.rules{i}(j).def);\n      blocks{bl} = w(:);\n      map{bl} = ['def rule ' num2str(i)];\n    end\n  end\nend\n\n% concatenate\nm = [];\nfor i = 1:model.numblocks\n  m = [m; blocks{i}];\nend\n\n\nfunction w = my_get_block(model, obj)\n\nif isfield(model, 'blocks')\n  w = model_get_block(model, obj);\nelse\n  w = obj.w;\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/utils/model_cmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.24354672606361621}}
{"text": "function [w,backAzimuth,trigger,staLat,staLon,origLat,origLon] = demo(TC)\n\n%DEMO\n% DEMO(THREECOMP) Loads demo waveforms and plots a station map of data used\n% in the demo.\n\n\n% LOAD DEMO WAVEFORMS\nload('private/demo_waveforms.mat');\n\n\n% SET TRIGGER TIMES\n% These times represent crude surface wave picks on the\n% transverse component\ntrigger =datenum({'2000/06/26 15:44:06'\n'2000/06/26 15:43:39'\n'2000/06/26 15:43:49'\n'2000/06/26 15:44:07'\n'2000/06/26 15:44:43'\n'2000/06/26 15:44:05'\n'2000/06/26 15:44:36'\n'2000/06/26 15:43:54'\n'2000/06/26 15:44:03'\n'2000/06/26 15:43:44'\n'2000/06/26 15:43:44'\n'2000/06/26 15:44:02'\n'2000/06/26 15:44:07'\n'2000/06/26 15:43:59'});\n\n\n% STATION LOCATIONS AND NAMES\nstaLat = get(w(:,1),'STATIONLATITUDE');\nstaLon = get(w(:,1),'STATIONLONGITUDE');\norigLat = get(w(:,1),'ORIGINLATITUDE');\norigLon = get(w(:,1),'ORIGINLONGITUDE');\nstaName = get(w(:,1),'STATION');\n\n\n% PLOT MAP OF DEMO DATA\ncookbooks.threecomp_cookbook_map(threecomp,w,backAzimuth);\n\n\nclear TC\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@threecomp/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24347137216504566}}
{"text": "function [flow_out, time_shifted_points_out] = em1_flow_with_prior(...\n    events, ...\n    feature_pos, ...\n    prev_shifted_points, ...\n    prev_shifted_weights, ...\n    flow_init, ...\n    params, ...\n    fig)\n%EM1_FLOW_WITH_PRIOR Estimates optical flow for an event feature.\n%\n% EM1_FLOW_WITH_PRIOR estimates the optical flow of a set of events\n% combined to form a 'feature'. This EM step uses the time shifted points\n% from the previous iteration as a template, as in:\n% Alex Zihao Zhu, Nikolay Atanasov and Kostas Daniilidis.\n% \"Event-based Visual Inertial Odometry\", \n% IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2017.\n%\n% Syntax:  [flow_out, time_shifted_points_out] = EM1_FLOW_WITH_PRIOR(...\n%            events, ... \n%            feature_pos, ...\n%            prev_shifted_points, ...\n%            prev_shifted_weights, ...\n%            flow_init, ...\n%            params, ...\n%            fig)\n%\n% Inputs:\n%    events               - 4xN, each column is (x,y,t,p).\n%    feature_pos          - 2x1, pixel position of the feature.\n%    prev_shifted_points  - 2xM, time shifted points from the previous\n%                           iteration, used as a template.\n%    prev_shifted_weights - 1xM, weights for each shifted point.\n%    flow_init            - 2x1, initialization for the flow.\n%    params               - parameters, defined in get_params().\n%    fig                  - figure handle for plotting.\n%\n% Outputs:\n%    flow_out                - 2x1, estimated flow.\n%    time_shifted_points_out - 2xN, input events in the feature window\n%                              shifted by the flow [x; y] + dt * flow.\n%\n% See also GET_PARAMS\n%\n% Author: Alex Zihao Zhu, University of Pennsylvania\n% Email: alexzhu(at)seas.upenn.edu\n% Copyright 2018 University of Pennsylvania \n% Alex Zihao Zhu, Nikolay Atanasov, Kostas Daniilidis\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, CONTRIBUTORS, AND THE \n% TRUSTEES OF THE UNIVERSITY OF PENNSYLVANIA \"AS IS\" AND ANY EXPRESS OR \n% IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES \n% OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \n% IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE TRUSTEES OF \n% THE UNIVERSITY OF PENNSYLVANIA BE LIABLE FOR ANY DIRECT, INDIRECT, \n% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT \n% NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \n% THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF \n% THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n%% Initialization\nflow = flow_init;\nprev_flow = flow;\n% Estimated flow\nflow_out = [nan; nan];\n% Estimated canonical events\ntime_shifted_points_out = [];\ndelta_flows = zeros(params.em1_params.max_iters, 1);\nnum_iter = 0;\nscatter_plot_handle = [];\nevent_window = [];\n\ntarget_time = events(3, 1);\n\ncentered_events = events;\ncentered_events(1:2, :) = bsxfun(@minus, events(1:2, :), feature_pos);\n\nkdtree = KDTreeSearcher(...\n    prev_shifted_points' / (sqrt(2) * params.em1_params.sigma), ...\n    'Distance', 'euclidean');\n\nif params.debug\n    set(0, 'CurrentFigure', fig)\n    subplot(2,1,2)\n    if ~isempty(prev_shifted_points)\n        scatter(prev_shifted_points(1, :), prev_shifted_points(2, :), prev_shifted_weights * 10, 'b.')\n    end\nend\n\n%% Main EM Loop\nwhile true\n    if num_iter > params.em1_params.max_iters\n        return\n    end\n    \n    time_shifted_points = centered_events(1:2,:) + ...\n        bsxfun(@times, flow,(target_time-centered_events(3,:)));\n\n    if isempty(event_window)\n        event_window = ...\n            time_shifted_points(1, :) >= -params.window_size/2 &...\n            time_shifted_points(2, :) >= -params.window_size/2 & ...\n            time_shifted_points(1, :) <= params.window_size/2 & ...\n            time_shifted_points(2, :) <= params.window_size/2;\n        \n        n_in_window = sum(event_window);\n        if n_in_window < params.min_events_for_em\n            return\n        end\n        \n        centered_events = centered_events(:, event_window);\n        time_shifted_points = time_shifted_points(:, event_window);\n        \n        weights = zeros(size(prev_shifted_points, 2), size(time_shifted_points, 2));\n    end\n    \n    [neighbors_cell, distances_cell] = rangesearch(...\n        kdtree, ...\n        time_shifted_points' / (sqrt(2) * params.em1_params.sigma), ...\n        params.em1_params.max_distance);\n\n    distancesstacked = cell2mat(cellfun(...\n        @transpose, distances_cell, 'UniformOutput', false))';\n    \n    if isempty(distancesstacked)\n        return\n    end\n    \n    % NOTE: 'length' is not the same as @length\n    num_neighbors = cellfun('length', neighbors_cell);\n    prev_correspondences = cell2mat(cellfun(...\n        @transpose, neighbors_cell, 'UniformOutput', false))';\n    curr_correspondences = repelem(1:size(time_shifted_points, 2), num_neighbors);\n    \n    % It's cheaper to multiply to 0 to reset the weights matrix than to\n    % reinitialize it using zeros.\n    weightsstacked = exp(-distancesstacked); \n    weights = weights * 0;\n    \n    valid_inds = sub2indc(...\n        curr_correspondences, ...\n        prev_correspondences, ...\n        size(weights));\n    \n    weights(valid_inds) = weightsstacked;\n    weights = bsxfun(@times, prev_shifted_weights, weights);\n    weights_sum = sum(weights, 1);\n    valid_weights = weights_sum > 0;\n    weights = bsxfun(@rdivide, weights, weights_sum + 1e-10);\n        \n    % Simultaneously minimize over flow and translation\n    weighted_prior_points = prev_shifted_points * weights;\n    weighted_prior_points = weighted_prior_points(:, valid_weights);\n    \n    valid_centered_events = centered_events(:, valid_weights);\n    dx = weighted_prior_points(1:2, :) - valid_centered_events(1:2, :);\n    dt = target_time - valid_centered_events(3, :);\n    \n    flow = (dx*dt') / (dt*dt');\n    \n    %% Calculate change in flow, plot debug information.\n    if (norm(flow - prev_flow) < params.em1_params.min_err)\n        break;\n    end\n    \n    delta_flows(num_iter+1) = norm(flow - prev_flow);\n    prev_flow = flow;\n    \n    if params.debug\n        set(0, 'CurrentFigure', fig)\n        subplot(2,1,1)\n        plot(delta_flows(delta_flows > 0),'b')\n        title('EM1 with prior change in flow (convergence criterion)')\n        xlim([0 params.em1_params.max_iters])\n        \n        subplot(2,1,2)\n        if (~isempty(scatter_plot_handle))\n            delete(scatter_plot_handle)\n        end\n        \n        if ~isempty(prev_shifted_points)\n            hold on\n        end\n        \n        scatter_plot_handle = scatter(time_shifted_points(1, :), time_shifted_points(2, :),'r.');\n        hold off\n        axis equal\n        axis([-params.window_size/2-5 params.window_size/2+5 -params.window_size/2-5 params.window_size/2+5])\n        axis ij\n        \n        title('EM1 with prior time shifted events')\n        pause(0.01)\n    end\n    \n    num_iter = num_iter + 1;\nend\n\nif params.debug\n    pause(0.5)\nend\n\nflow_out = flow;\n\ndt = events(3, end) - events(3, 1);\ncentered_events = bsxfun(@minus, events(1:2, :), feature_pos + flow * dt);\ntime_shifted_points = centered_events(1:2, :) + ...\n    bsxfun(@times, flow, (events(3, end) - events(3,:)));\n\n\n% Make the window a little bigger.\nwindow_size = round(params.window_size * 1.5);\n\nevent_window = time_shifted_points(1, :) >= -window_size/2 & ... \n    time_shifted_points(2, :) >= -window_size/2 & ...\n    time_shifted_points(1, :) <= window_size/2 & ...\n    time_shifted_points(2, :) <= window_size/2;\n\n\ntime_shifted_points_out = time_shifted_points(:, event_window);\nend", "meta": {"author": "daniilidis-group", "repo": "event_feature_tracking", "sha": "b29f85f18121bef638fc117922038dbad9de7068", "save_path": "github-repos/MATLAB/daniilidis-group-event_feature_tracking", "path": "github-repos/MATLAB/daniilidis-group-event_feature_tracking/event_feature_tracking-b29f85f18121bef638fc117922038dbad9de7068/EventFeatureTracking/Tracker/em1_flow_with_prior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24347137216504566}}
{"text": "function planC = uniformizeScanSupInf(planC, tMin, tMax, optS, hBar)\n%\"uniformizeScanSupInf\"\n%    Creates the superior and inferior scan arrays so that they \n%   are uniform, consistent with the rest of the scan array.\n%\n%Latest modifications:\n% 16 Aug 02, V H Clark, first version.\n% 09 Apr 03, JOD, added hBar to input parameter list.\n% 18 Feb 05, JRA, Added support for multiple scans.\n%\n%Usage:\n%   function planC = uniformizeScanSupInf(planC, tMin, tMax, optS, hBar)\n\nindexS = planC{end};\n\nfor scanNum=1:length(planC{indexS.scan})\n    scanStruct = planC{indexS.scan}(scanNum);\n    \n\tuniformScanInfo = planC{indexS.scan}(scanNum).uniformScanInfo;\n\tsliceNumSup = uniformScanInfo.sliceNumSup; %superior slice number of original CT scan still being used\n\tsliceNumInf = uniformScanInfo.sliceNumInf; %inferior slice number of original CT scan still being used\n\tuniformSliceThickness = uniformScanInfo.sliceThickness;\n\tscanArray = planC{indexS.scan}(scanNum).scanArray;\n\tscanInfo = planC{indexS.scan}(scanNum).scanInfo;\n\t\n\t[scanArraySup, scanArrayInf, uniformScanFirstZValue] = uniformizeScanEnds(scanStruct, sliceNumSup, sliceNumInf, uniformSliceThickness, tMin, tMax, optS, hBar);\n\t\n\tuniformScanInfo.firstZValue = uniformScanFirstZValue;\n\tuniformScanInfo.supInfScansCreated = 1;\n\t\n\tplanC{indexS.scan}(scanNum).scanArraySuperior = scanArraySup;\n\tplanC{indexS.scan}(scanNum).scanArrayInferior = scanArrayInf;\n\t\n\tplanC{indexS.scan}(scanNum).uniformScanInfo = uniformScanInfo;\t\nend\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/uniformizeScanSupInf_plnChk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24333894270930434}}
{"text": "function Ma = timesv(M,a);\n%function Ma = timesv(M,a);\n%\n% Multiplies a by M:\n% a(:,:,i) = M*a(:,:,i)\n%\n% See also FILTER.\n\ndima = size(a,1);\nI = eye(dima);\nMa = armafilterv(a,I,M);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3680-automatic-spectral-analysis/AutomaticSpectra/Vectors/timesv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2433389427093043}}
{"text": "classdef EventDeltaVExpendedConstraint < AbstractConstraint\n    %EventDeltaVConstraint Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        normFact = 1;\n        event LaunchVehicleEvent\n        eventNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n        \n        lb(1,1) double = 0;\n        ub(1,1) double = 0;\n        \n        evalType(1,1) ConstraintEvalTypeEnum = ConstraintEvalTypeEnum.FixedBounds;\n        stateCompType(1,1) ConstraintStateComparisonTypeEnum = ConstraintStateComparisonTypeEnum.Equals;\n        stateCompEvent LaunchVehicleEvent\n        stateCompNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n    end\n    \n    methods\n        function obj = EventDeltaVExpendedConstraint(event, lb, ub)\n            obj.event = event;\n            obj.lb = lb;\n            obj.ub = ub;   \n            \n            obj.id = rand();\n        end\n        \n        function [lb, ub] = getBounds(obj)\n            lb = obj.lb;\n            ub = obj.ub;\n        end\n        \n        function [c, ceq, value, lwrBnd, uprBnd, type, eventNum, valueStateComp] = evalConstraint(obj, stateLog, celBodyData)           \n            type = obj.getConstraintType();\n\n            deltaVExpended = EventDeltaVExpendedConstraint.computeTotalDeltaV(stateLog, obj.event);\n            value = deltaVExpended;\n                       \n            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)               \n                valueStateComp = EventDeltaVExpendedConstraint.computeTotalDeltaV(stateLog, obj.stateCompEvent);\n                \n            else\n                valueStateComp = NaN;\n            end\n            \n            [c, ceq] = obj.computeCAndCeqValues(value, valueStateComp);   \n            \n            lwrBnd = obj.lb;\n            uprBnd = obj.ub;\n            \n            eventNum = obj.event.getEventNum();\n        end\n        \n        function sF = getScaleFactor(obj)\n            sF = obj.normFact;\n        end\n        \n        function setScaleFactor(obj, sF)\n            obj.normFact = sF;\n        end\n        \n        function tf = usesStage(obj, stage)\n            tf = false;\n        end\n        \n        function tf = usesEngine(obj, engine)\n            tf = false;\n        end\n        \n        function tf = usesTank(obj, tank)\n            tf = false;\n        end\n        \n        function tf = usesEngineToTankConn(obj, engineToTank)\n            tf = false;\n        end\n        \n        function tf = usesEvent(obj, event)\n            tf = obj.event == event;\n            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n                tf = tf || obj.stateCompEvent == event;\n            end\n        end\n        \n        function tf = usesStopwatch(obj, stopwatch)\n            tf = false;\n        end\n        \n        function tf = usesExtremum(obj, extremum)\n            tf = false;\n        end\n        \n        function tf = canUseSparseOutput(obj)\n            tf = false;\n        end\n        \n        function event = getConstraintEvent(obj)\n            event = obj.event;\n        end\n        \n        function type = getConstraintType(obj)\n            type = 'Event Delta-V Expended';\n        end\n        \n        function [unit, lbLim, ubLim, usesLbUb, usesCelBody, usesRefSc] = getConstraintStaticDetails(obj)\n            unit = 'km/s';\n            lbLim = 0;\n            ubLim = Inf;\n            usesLbUb = true;\n            usesCelBody = false;\n            usesRefSc = false;\n        end\n        \n        function addConstraintTf = openEditConstraintUI(obj, lvdData)\n%             addConstraintTf = lvd_EditGenericMAConstraintGUI(obj, lvdData);\n            \n            output = AppDesignerGUIOutput({false});\n            lvd_EditGenericMAConstraintGUI_App(obj, lvdData, output);\n            addConstraintTf = output.output{1}; \n        end\n    end\n    \n    methods(Static, Access=private)\n        function deltaVExpended = computeTotalDeltaV(stateLog, event)\n            subStateLog = stateLog.getAllStateLogEntriesForEvent(event);\n\n            if(length(subStateLog) > 1)\n                g0 = getG0();\n                deltaVExpended = 0;\n                \n                for(i=1:length(subStateLog)-1) %#ok<NO4LP>\n                    stateLogEntry1 = subStateLog(i);\n                    stateLogEntry2 = subStateLog(i+1);\n\n                    ut = stateLogEntry1.time;\n                    rVect = stateLogEntry1.position;\n                    vVect = stateLogEntry1.velocity;\n\n                    bodyInfo = stateLogEntry1.centralBody;\n                    tankStates = stateLogEntry1.getAllActiveTankStates();\n                    stageStates = stateLogEntry1.stageStates;\n                    lvState = stateLogEntry1.lvState;\n\n                    dryMass = stateLogEntry1.getTotalVehicleDryMass();\n                    tankStatesMasses = [tankStates.tankMass]';\n                    \n                    throttleModel = stateLogEntry1.throttleModel;\n                    steeringModel = stateLogEntry1.steeringModel;\n\n                    altitude = norm(rVect) - bodyInfo.radius;\n                    pressure = getPressureAtAltitude(bodyInfo, altitude); \n\n                    powerStorageStates = stateLogEntry1.getAllActivePwrStorageStates();\n                    storageSoCs = NaN(size(powerStorageStates));\n                    for(j=1:length(powerStorageStates))\n                        storageSoCs(j) = powerStorageStates(j).getStateOfCharge();\n                    end\n                    \n                    throttle = throttleModel.getThrottleAtTime(ut, rVect, vVect, tankStatesMasses, dryMass, stageStates, lvState, tankStates, bodyInfo, storageSoCs, powerStorageStates);\n\n                    [tankMDots, totalThrust, ~] = LaunchVehicleStateLogEntry.getTankMassFlowRatesDueToEngines(tankStates, tankStatesMasses, stageStates, throttle, lvState, pressure, ut, rVect, vVect, bodyInfo, steeringModel, storageSoCs, powerStorageStates, []);\n\n                    if(abs(sum(tankMDots)) > 0)\n                        tankMDotsKgS = tankMDots * 1000;\n                        totalMDotKgS = sum(tankMDotsKgS); %should be negative\n                        totalThrustN = totalThrust * 1000;\n                        effIsp = totalThrustN / (getG0() * abs(totalMDotKgS)); %sec\n\n                        totalMass1 = dryMass + stateLogEntry1.getTotalVehiclePropMass();\n                        totalMass2 = dryMass + stateLogEntry2.getTotalVehiclePropMass();\n                        \n                        if(totalMass1 > totalMass2 && stateLogEntry1.time < stateLogEntry2.time)\n                            deltaVExpended = deltaVExpended + (g0 * effIsp * log(totalMass1 / totalMass2))/1000; %need to convert to km/s\n                        end\n                    end\n                end\n            else\n                deltaVExpended = 0;\n            end\n        end\n    end\n    \n    methods(Static)\n        function constraint = getDefaultConstraint(~, ~)            \n            constraint = EventDeltaVExpendedConstraint(LaunchVehicleEvent.empty(1,0),0,0);\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/constraints/@EventDeltaVExpendedConstraint/EventDeltaVExpendedConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2431884100770308}}
{"text": "% Li, Hui and Wu, Xiao-Jun and Durrani, Tariq S. Infrared and Visible Image Fusion with ResNet and zero-phase component analysis\n% Infrared Physics & Technology, v102, 2019.\n% ResNet50 + ZCA & norm(l1, l2, nuclear)\n\nclear all\nclc\n\naddpath(genpath('D:\\develop\\matconvnet\\matlab\\')); % matconvnet path\n% load the pre-trained model - ResNet-50\nmodel_path = './models/';\n% http://www.vlfeat.org/matconvnet/pretrained/\nnet_ = load([model_path, 'imagenet-resnet-50-dag.mat']);\nnet = dagnn.DagNN.loadobj(net_);\nnet.mode = 'test';\n%% remove layers - ResNet50\n% Conv5 - res5cx\nfor i = 173:175\n    net.removeLayer(net.layers(173).name);\nend\nnet_res5cx = net;\n% Conv4 - res4fx\nnet = dagnn.DagNN.loadobj(net_);\nnet.mode = 'test';\nfor i = 141:175\n    net.removeLayer(net.layers(141).name);\nend\nnet_res4fx = net;\n\n%% Start\nn = 20; % number of sourc image\ntime = zeros(n,1);\n\n% testing dataset\ntest_path_ir = './IV_images/IR/';\nfileFolder_ir=fullfile(test_path_ir);\ndirOutput_ir =dir(fullfile(fileFolder_ir,'*'));\nnum_ir = length(dirOutput_ir);\n\ntest_path_vis = replace(test_path_ir, '/IR/', '/VIS/');\nfileFolder_vis=fullfile(test_path_vis);\ndirOutput_vis =dir(fullfile(fileFolder_vis,'*'));\n\nfor i=3:num_ir\n    index = i;\n    disp(num2str(index));\n    \n    % infrared and visible images\n    path1 = [test_path_ir,dirOutput_ir(i).name]; % IR image\n    path2 = [test_path_vis,dirOutput_vis(i).name]; % VIS image\n\n    % block - 5*5\n    % l1 norm\n    fuse_path5 = ['./fused_iv/fused_resnet_zca_',dirOutput_ir(i).name];\n    \n    image1 = imread(path1);\n    image2 = imread(path2);\n    image1 = im2double(image1);\n    image2 = im2double(image2);\n\n    tic;\n    %% Extract features, run the net - ResNet50\n    disp('ResNet');\n    if size(image1, 3)<3\n        I1 = make_3c(image1);\n    end\n    if size(image2, 3)<3\n        I2 = make_3c(image2);\n    end\n    I1 = single(I1) ; % note: 255 range\n    I2 = single(I2) ; % note: 255 range\n\n    % I1\n    disp('run the ResNet - I1');\n    net_res4fx.eval({'data', I1}) ;\n    output4_1 = net_res4fx.vars(net_res4fx.getVarIndex('res4fx')).value ;\n    net_res5cx.eval({'data', I1}) ;\n    output5_1 = net_res5cx.vars(net_res5cx.getVarIndex('res5cx')).value ;\n    % I2\n    disp('run the ResNet - I2');\n    net_res4fx.eval({'data', I2}) ;\n    output4_2 = net_res4fx.vars(net_res4fx.getVarIndex('res4fx')).value ;\n    net_res5cx.eval({'data', I2}) ;\n    output5_2 = net_res5cx.vars(net_res5cx.getVarIndex('res5cx')).value ;\n\n    %% extract features - ZCA & l1-norm operation\n    disp('extract features(whitening operation) - I1');\n    feature4_1 = whitening_norm(output4_1);\n    feature5_1 = whitening_norm(output5_1);\n    disp('extract features(whitening operation) - I2');\n    feature4_2 = whitening_norm(output4_2);\n    feature5_2 = whitening_norm(output5_2);\n\n    %% fusion strategy - resize to original size and soft-max\n    disp('fusion strategy(weighting)');\n    % output4 - 1024\n    [F_relu4, weight4_a, weight4_b] = fusion_strategy(feature4_1, feature4_2, image1, image2);\n    % output5 - 2048\n    [F_relu5, weight5_a, weight5_b] = fusion_strategy(feature5_1, feature5_2, image1, image2);\n    time(i) = toc;\n\n%     imwrite(F_relu4,fuse_path4,'png');\n    imwrite(F_relu5,fuse_path5,'png');\nend\n\n\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ResNet_ZCA_Image_Fusion_Codes/fusion_method_ResNet50_4layers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24318841007703076}}
{"text": "%% triangleRayIntersection\n% Below is a demonstration of the features of the |triangleRayIntersection| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[V_intersect,L_intersect,T] = triangleRayIntersection (V_ori,R,V,F,optStruct);|\n\n%% Description \n% UNDOCUMENTED \n%% Examples \n% \n%%\n% \n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>\n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_triangleRayIntersection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24318841007703076}}
{"text": "function domisfit(catalog,sig,plu,az,phi,R)\n    % domisfit calculates the misfit for each EQ to a given stress tensor orientation.\n    % The actual calculation is done using a call to a fortran program.\n    %\n    % Stefan Wiemer 07/95\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    \n    global mi mif1 mif2 newcat2 mi2\n    global cumu2\n    report_this_filefun();\n    \n    \n    hodis = fullfile(ZG.hodi, 'external');\n    cd(hodis);\n    \n    % prepare the focal; mechnism in Gephard format ...\n    tmp = [catalog(:,10:12) ];\n    tmp(tmp(:,2) >89.999,2) = 89.;\n    \n    try\n        save data.inp tmp -ascii\n    catch ME\n        error_handler(ME, ['Error - could not save file ' ZmapGlobal.Data.Directories.output 'data.inp - permission?']);\n    end\n    \n    infi =  'data.inp';\n    outfi = 'tmpin.dat';\n    fid = fopen('inmifi.dat','w');\n    fprintf(fid,'%s\\n',infi);\n    fprintf(fid,'%s\\n',outfi);\n    fclose(fid);\n    \n    delete(outfi)\n    \n    [status, result] = system('datasetupDD < inmifi.dat');\n    \n    fid = ('tmpin.dat');\n    format = '%f%f%f%f%f';\n    %[d1, d2, d3, d4, d5] = textread(fid,format,'headerlines',1);\n    C = textscan(fid,format,'HeaderLines',1); %Problem: \"Errorlines\" cause crashes.\n    dall=[C{:}];\n    \n    %dall = [d1, d2, d3, d4, d5];\n    save tmpin.dat dall -ascii\n    \n    \n    infi = 'tmpin.dat';\n    outfi = 'tmpout.dat';\n    \n    fid = fopen('inmifi.dat','w');\n    \n    fprintf(fid,'%s\\n',infi);\n    fprintf(fid,'%s\\n',outfi);\n    fprintf(fid,'%2.0f\\n',sig);\n    fprintf(fid,'%6.2f\\n',plu);\n    fprintf(fid,'%6.2f\\n',az);\n    fprintf(fid,'%6.2f\\n',phi);\n    fprintf(fid,'%3.2f\\n',R);\n    le = catalog.Count;\n    fprintf(fid,'%6i\\n',le);\n    \n    fclose(fid);\n    try\n        delete outfi\n    catch ME\n        warning(ME.message);\n    end\n    \n    comm = 'testfm < inmifi.dat'\n    [status,result]=system(comm)\n    try\n        % CGR: it looks like the format will be:\n        % line 1: ndata kdata  [where ndata is # of data, kdata is # of fault planes]\n        % lines 2-end : az1 dip1 az2 dip2 wt\n        % load('tmpout.dat')\n        s=importdata('../external/tmpout.dat', ' ', 1); \n        \n        headernumbers=str2num(s.textdata{1});\n        nData=headernumbers(1);\n        kData=headernumbers(2);\n        \n        mi = s.data; % probably as [az1, dip1, az2, dip2, wt ; ...]\n    catch ME\n        warning(ME.message)\n    end\n    \n    % mi = tmpout; % mi gets results from the fortran progarm\n    \n    misfitAngle=mi(:,2);\n    \n    \n    \n    mif1=findobj('Type','Figure','-and','Name','Misfit Map');\n    \n    if isempty(mif1)\n        mif1 = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit Map',...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n        \n        create_my_menu_1();\n        \n        \n        labelList=['Size | Size + Thickness | Size +Thickness +color  '];\n        labelPos = [0.2 0.93 0.35 0.05];\n        hndl2=uicontrol(...\n            'Style','popup',...\n            'Units','normalized',...\n            'Position',labelPos,...\n            'String',labelList,...\n            'BackgroundColor',[0.7 0.7 0.7]',...\n            'callback',@callbackfun_005);\n        \n        decimationList=['1 | 1/2 | 1/3 | 1/4 | 1/5 | 1/6| 1/7| 1/8 | 1/9 | 1/10'];\n        labelPos = [0.9 0.93 0.10 0.05];\n        uicontrol(...\n            'Style','popup',...\n            'Units','normalized',...\n            'Position',labelPos,...\n            'Value',4,...\n            'String',decimationList,...\n            'BackgroundColor',[0.7 0.7 0.7]',...\n            'callback',@store_decimation_cb);\n        \n        uicontrol(...\n            'Style','pushbutton',...\n            'Units','normalized',...\n            'Position',[0.9 0.6 0.08 0.08],...\n            'String','X-sec',...\n            'callback',@callbackfun_007);\n        set(gca,'NextPlot','add')\n        %end killed\n        uicontrol(...\n            'Style','pushbutton',...\n            'Units','normalized',...\n            'Position',[0.9 0.7 0.08 0.08],...\n            'String','Map',...\n            'callback',@callbackfun_008);\n        set(gca,'NextPlot','add')\n    end\n    \n    figure(mif1)\n    \n    plotmima(4, mi)\n    \n    mif2=findobj('Type','Figure','-and','Name','Misfit ');\n    \n    \n    \n    if isempty(mif2)\n        mif2 = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit ',...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n        \n        create_my_menu_2();\n        listFields={'Longitude','Latitude','Time','Magnitude','Depth','Strike','Default'};\n        labelPos = [0.7 0.9 0.25 0.08];\n        hFieldChoice=uicontrol(...\n            'Style','popup',...\n            'Units','normalized',...\n            'Position',labelPos,...\n            'String',listFields,...\n            'BackgroundColor',[0.7 0.7 0.7]',...\n            'callback',@callbackfun_012);\n        set(gca,'NextPlot','add')\n    end\n    \n    figure(mif2)\n    delete(findobj(mif2,'Type','axes'));\n    \n    plotmi(listFields{1}, catalog, mi)\n    \n    \n    %% ui functions\n    function create_my_menu_1() %TODO rename to something more intelligent\n        add_menu_divider();    %\n        omp2= uimenu('Label','Tools');\n        uimenu(omp2,'label','Misfit-Magnitude',...\n            'MenuSelectedFcn',@cb_misfitmag);\n        uimenu(omp2,'label','Misfit-Depth',...\n            'MenuSelectedFcn',@cb_misfitdep);\n        uimenu(omp2,'label','Earthquake-Depth',...\n            'MenuSelectedFcn',@cb_eqdep);\n        uimenu(omp2,'label','Earthquake-Strike',...\n            'MenuSelectedFcn',@cb_eqstrike);\n        %\n    end\n    \n    function create_my_menu_2() %TODO rename to something more intelligent\n        add_menu_divider();\n        omp1= uimenu('Label','Tools');\n        uimenu(omp1,'label','Save sorted catalog',...\n            'MenuSelectedFcn',@callbackfun_009);\n        uimenu(omp1,'label','AS Function',...\n            'MenuSelectedFcn',@cb_astmisfit);\n        uimenu(omp1,'label','Compare',...\n            'MenuSelectedFcn',@cb_comparemisfit);\n    end\n    \n    %% callback functions\n    function cb_misfitmag(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        mi_ma(misfitAngle);\n    end\n    \n    function cb_misfitdep(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        mi_dep(misfitAngle);\n    end\n    \n    function cb_eqdep(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        eq_dep(misfitAngle);\n    end\n    \n    function cb_eqstrike(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        earthquake_strike();\n    end\n    \n    function callbackfun_005(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        in2=hndl2.Value;\n        plotmima(in2, mi);\n    end\n    \n    function store_decimation_cb(mysrc,myevt)\n        global oneOfHowManyPopupIdx\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        in3=mysrc.Value;\n        oneOfHowManyPopupIdx=in3;\n        in2=hndl2.Value;\n        plotmima(in2, mi) ;\n    end\n    \n    function callbackfun_007(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        var1 = 3;\n        plotmimac(mi, inde); % No idea what inde is or where it comes from\n    end\n    \n    function callbackfun_008(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        var1 = 1;\n        mifigrid(var1,mi);\n    end\n    \n    function callbackfun_009(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        save_sortpere;\n    end\n    \n    function cb_astmisfit(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ast_misfit();\n    end\n    \n    function cb_comparemisfit(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        compare_misfit();\n    end\n    \n    function callbackfun_012(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        in2=hFieldChoice.Value;\n        plotmi(listfields{in2}, catalog, mi);\n    end\n    \nend\n\nfunction earthquake_strike()\n    % plot the earthquake number along the strike on the map view\n    %\tAugust 1995 by Zhong Lu\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    report_this_filefun();\n    myFigName='Earthquake Number Map';\n    mif55=findobj('Type','Figure','-and','Name',myFigName);\n    \n    \n    \n    if isempty(mif55)\n        mif55 = figure_w_normalized_uicontrolunits( ...\n            'Name',myFigName,...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n    end\n    figure(mif55)\n    \n    set(gca,'NextPlot','add')\n    \n    tt = newcat2;\n    [ts,ti] = sort(tt(:,15));\n    tt = tt(ti(:,1),:);\n    \n    for i = 1:length(tt)\n        pt = plot(tt(i,1),tt(i,2),'o');\n        set(gca,'NextPlot','add')\n    end\n    \nend\n\nfunction eq_dep(misfitAngle) \n    %  earthquake_depth\n    % August 95 by Zhong Lu\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    myFigName='Depth vs Earthquake Number';\n    \n    mif66=findobj('Type','Figure','-and','Name',myFigName);\n    \n    if isempty(mif66)\n        mif66 = figure_w_normalized_uicontrolunits( ...\n            'Name',myFigName,...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n    end\n    figure(mif66)\n    set(gca,'NextPlot','add')\n    \n    x = [1:length(mmi)]';\n    [ss,ssi]=sort(catalog.Depth);\n    plot(x,ss,'go');\n    \n    grid on\n    \n    ylabel('Depth of Earthquake','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    xlabel('Earthquake Number','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    set(gca,'NextPlot','replace');\nend\n\nfunction mi_dep(misfitAngle)\n    %  misfit_magnitude\n    % August 95 by Zhong Lu\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    mif77=findobj('Type','Figure','-and','Name','Misfit as a Function of Depth');\n    \n    \n    \n    if isempty(mif77)\n        mif77 = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit as a Function of Depth',...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n        \n        \n        \n        set(gca,'NextPlot','add')\n        \n    end\n    figure_w_normalized_uicontrolunits(mif77)\n    set(gca,'NextPlot','add')\n    \n    \n    plot(catalog.Depth,misfitAngle,'go');\n    \n    grid\n    %set(gca,'box','on',...\n    %        'SortMethod','childorder','TickDir','out','FontWeight',...\n    %        'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2);\n    \n    xlabel('Depth of Earthquake','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    ylabel('Misfit Angle ','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    set(gca,'NextPlot','replace');\nend\n\nfunction mi_ma(misfitAngle)\n    %  misfit_magnitude\n    % August 95 by Zhong Lu\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    mif88=findobj('Type','Figure','-and','Name','Misfit as a Function of Magnitude');\n    \n    \n    \n    if isempty(mif88)\n        mif88 = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit as a Function of Magnitude',...\n            'NumberTitle','off', ...\n            'backingstore','on',...\n            'NextPlot','add', ...\n            'Visible','off', ...\n            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n        \n        set(gca,'NextPlot','add')\n        \n    end\n    figure(mif88)\n    set(gca,'NextPlot','add')\n    \n    \n    plot(catalog.Magnitude,misfitAngle,'go');\n    \n    grid\n    %set(gca,'box','on',...\n    %        'SortMethod','childorder','TickDir','out','FontWeight',...\n    %        'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2);\n    \n    xlabel('Magnitude of Earthquake','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    ylabel('Misfit Angle ','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    set(gca,'NextPlot','replace');\nend\n\nfunction ast_misfit()\n    %  ast_misfit calculates A as(t) value for a cumulative number curve and displayed in the plot.\n    %\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    dat(:,2)=mi2(:,2);\n    dat(:,1)=[1:length(mi2(:,1))]';\n    cumu = dat(:,2);\n    xt = dat(:,1);\n    cumu2 = cumsum(cumu);\n    \n    %  winlen_days is the cutoff at the beginning and end of the analyses\n    %  to avoid spikes at the end\n    winlen_days = 5;\n    \n    %\n    % calculate mean and z value\n    ncu = length(xt);\n    as = zeros(1,ncu);\n    \n    t0b = dat(1,1);\n    n = length(dat(:,1));\n    teb = dat(n,1);\n    tdiff = ncu;\n    \n    \n    \n    for i = winlen_days+1:tdiff-winlen_days\n        mean1 = mean(cumu(1:i));\n        mean2 = mean(cumu(i+1:ncu));\n        var1 = cov(cumu(1:i));\n        var2 = cov(cumu(i+1:ncu));\n        as(i) = (mean1 - mean2)/(sqrt(var1/i+var2/(tdiff-i)));\n    end     % for i\n    \n    %  Plot the as(t)\n    %clf\n    figure;\n    orient landscape\n    % orient tall\n    rect = [0.1,  0.10, 0.8, 0.7];\n    axes('position',rect);\n    yyaxis('left')\n    plot(xt,as);\n    yyaxis('right')\n    plot(xt,cumu2);\n    xlabel('Event');\n    ylabel('z-value');\n    grid\n    \n    set(gca,'NextPlot','add');\n    \n    %  show option from here\n    %\n    uicontrol('Units','normal','Position',[.9 .86 .10 .05],'String','Close', 'callback',@(~,~)close())\n    \n    str2 = 'AS of Earthquake Number';\n    title(str2);\nend\n\nfunction compare_misfit() \n    % Compare is used to compare the significance of two segments\n    % in the plot of cumulative misfit as a function of earthquake number.\n    %  --- Zhong Lu, June 1994.\n    %\n    % turned into function by Celso G Reyes 2017\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    dat(:,2)=mi2(:,2);\n    dat(:,1)=[1:length(mi2(:,1))]';\n    cumu = dat(:,2);\n    xt = dat(:,1);\n    cumu2 = cumsum(cumu);\n    \n    set(gca,'NextPlot','add');\n    ZG.bin_dur = days(0.5);\n    par2 = 1.0;\n    choice = input('type 1 to select range with cursor, 2 to input event numbers  ');\n    if choice == 1\n        t1 = [];\n        t1 = ginput(1);\n        t1(1)=round(t1(1));\n        t1p = [  t1 ; t1(1) t1(2)-ZG.bin_dur];\n        plot(t1p(:,1),t1p(:,2),'r');\n        text( t1(1),t1(2)-par2,['t1: ', num2str(t1p(1))] );\n        \n        t2 = [];\n        t2 = ginput(1);\n        t2(1)=round(t2(1));\n        t2p = [  t2 ; t2(1) t2(2)-ZG.bin_dur];\n        plot(t2p(:,1),t2p(:,2),'r');\n        text( t2(1),t2(2)-par2,['t2: ', num2str(t2p(1))] );\n        \n        t3 = [];\n        t3 = ginput(1);\n        t3(1)=round(t3(1));\n        t3p = [  t3 ; t3(1) t3(2)+ZG.bin_dur];\n        plot(t3p(:,1),t3p(:,2),'r');\n        text( t3(1),t3(2)+par2,['t3: ', num2str(t3p(1))] );\n        \n        t4 = [];\n        t4 = ginput(1);\n        t4(1)=round(t4(1));\n        t4p = [  t4 ; t4(1) t4(2)+ZG.bin_dur];\n        plot(t4p(:,1),t4p(:,2),'r');\n        text( t4(1),t4(2)+par2,['t4: ', num2str(t4p(1))] );\n    else\n        %tmp = 't1(1),t2(1),t3(1),t4(1)';\n        t1(1) = str2double(input('type the 1st event number, then return    ','s'));\n        t2(1) = str2double(input('type the 2nd event number, then return    ','s'));\n        t3(1) = str2double(input('type the 3rd event number, then return    ','s'));\n        t4(1) = str2double(input('type the last event number, then return    ','s'));\n    end  % if\n    set(gca,'NextPlot','add');\n    \n    mean1 = mean(cumu(t1(1):t2(1)));\n    mean2 = mean(cumu(t3(1):t4(1)));\n    var1  = cov(cumu(t1(1):t2(1)));\n    var2  = cov(cumu(t3(1):t4(1)));\n    zvalue = (mean1 - mean2)/(sqrt(var1/(t2(1)-t1(1)+1)+var2/(t4(1)-t3(1)+1)))\n    \n    if abs(zvalue) >= 2.58 %99%\n        S = sprintf('Significant at 99%% ');\n        disp(S);\n    elseif abs(zvalue) >= 1.96 %95%\n        S = sprintf('Significant at 95%% ');\n        disp(S);\n    elseif abs(zvalue) >= 1.64 %90%\n        S = sprintf('Significant at 90%% ');\n        disp(S);\n    elseif abs(zvalue) >= 1.44 %85%\n        S = sprintf('Significant at 85%% ');\n        disp(S);\n    else\n        S = sprintf('May Significant below 85%% ');\n        disp(S);\n    end % if\n    \n    % use the t-test\n    tvalue=(mean1 - mean2) * sqrt(t2(1)-t1(1)+t4(1)-t3(1)) / sqrt((t2(1)-t1(1)) * var1+(t4(1)-t3(1))*var2) / sqrt(1.0/(t2(1)-t1(1)+1)+1.0/(t4(1)-t3(1)+1))\n    \n    N=t2(1)-t1(1)+t4(1)-t3(1)\n    disp('N=n1+n2-2');\n    \nend\n\nfunction plotmima(var1, mi)\n    report_this_filefun();\n    \n    ZG=ZmapGlobal.Data;\n    global mif1\n    global oneOfHowManyPopupIdx\n    \n    sc = oneOfHowManyPopupIdx;\n    angMisfit = mi(:,2)+1; % added 1 because it's used as sizes\n    figure(mif1) %TODO figure out where mif1 comes from\n    delete(findobj(mif1,'Type','axes'));\n    rect = [0.15,  0.20, 0.75, 0.65];\n    axes('position',rect)\n    watchon\n    \n    \n    if var1 == 1\n        \n        for i = 1:catalog.Count\n            pl =  plot(catalog.Longitude(i),catalog.Latitude(i),'ro');\n            set(gca,'NextPlot','add')\n            set(pl,'MarkerSize',angMisfit(i)/sc)\n        end\n        \n    elseif var1 == 2\n        \n        for i = 1:catalog.Count\n            pl =  plot(catalog.Longitude(i),catalog.Latitude(i),'bx');\n            set(gca,'NextPlot','add')\n            set(pl,'MarkerSize',angMisfit(i)/sc,'LineWidth',angMisfit(i)/sc)\n        end\n        \n    elseif var1 == 3\n        \n        for i = 1:catalog.Count\n            pl =  plot(catalog.Longitude(i),catalog.Latitude(i),'bx');\n            set(gca,'NextPlot','add')\n            c = angMisfit(i)/max(angMisfit);\n            set(pl,'MarkerSize',angMisfit(i)/sc,'LineWidth',angMisfit(i)/sc,'Color',[ c c c ] )\n        end\n        \n    elseif var1 == 4\n        pl =  plot(catalog.Longitude,catalog.Latitude,'bx');\n    end\n    \n    set(gca,'NextPlot','add')\n    %axis([ s2_west s1_east s4_south s3_north])\n    %zmap_update_displays();\n    \n    xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n    ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n    strib = 'Misfit Map ';\n    title(strib,'FontWeight','bold',...\n        'FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')\n    \n    set(gca,'Color',color_bg);\n    set(gca,'box','on',...\n        'SortMethod','childorder','TickDir','out','FontWeight',...\n        'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2)\n    watchoff\nend\n\nfunction plotmimac(mi,inde)\n    \n    % TODO maybe move into domisfit\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    global mif2 mif1\n    global oneOfHowManyPopupIdx\n    \n    %var1 = 4;\n    sc = oneOfHowManyPopupIdx;\n    figure(UNK) % FIXME: really? this figure? unsure\n    delete(findobj(UNK,'Type','axes'));\n    rect = [0.15,  0.20, 0.75, 0.65];\n    axes('position',rect)\n    watchon\n    \n    % check if cross-section exists\n    figNumber=findobj('Type','Figure','-and','Name','Cross -Section');\n    \n    if isempty(figNumber)\n        errordlg('Please create a cross-section first, then rerun the last selection');\n        nlammap\n        return\n    end\n    \n    \n    % check if cross-section is still current\n    if max(mi(:,1)) > length(mi(:,1))\n        errordlg('Please rerun the cross-section first, then rerun the last selection');\n        nlammap\n        return\n    end\n    \n    \n    mic = mi(inde,:);\n    le = size(newa,2); %FIXME where does newa come from? ZG.newa? input parameter?  Needs to be treated like a ZmapCatalog\n    \n    if var1 == 1\n        for i = 1:length(newa(:,6))\n            pl =  plot(newa(i,le),-newa(i,7),'ro');\n            set(gca,'NextPlot','add')\n            set(pl,'MarkerSize',mic(i,2)/sc)\n        end\n        \n    elseif var1 == 2\n        \n        for i = 1:length(newa(:,6))\n            pl =  plot(newa(i,le),-newa(i,7),'bx');\n            set(gca,'NextPlot','add')\n            set(pl,'MarkerSize',mic(i,2)/sc,'LineWidth',mic(i,2)/sc)\n        end\n        \n    elseif var1 == 3\n        \n        for i = 1:length(newa(:,6))\n            pl =  plot(newa(i,le),-newa(i,7),'bx');\n            set(gca,'NextPlot','add')\n            c = mic(i,2)/max(mic(:,2));\n            %c = newa(i,15)*10;\n            set(pl,'MarkerSize',mic(i,2)/sc+3,'LineWidth',mic(i,2)/sc+0.5,'Color',[ c c c ] )\n        end\n        \n    elseif var1 == 4\n        \n        g = jet;\n        for i = 1:length(newa(:,6))\n            pl =  plot(newa(i,le),-newa(i,7),'bx');\n            set(gca,'NextPlot','add')\n            c = floor(mic(i,2)/max(mic(:,2))*63+1);\n            set(pl,'MarkerSize',4,'LineWidth',2,'Color',[ g(c,:) ] )\n        end\n        colorbar\n        colormap(jet)\n    end\n    \n    if exist('maex', 'var')\n        set(gca,'NextPlot','add')\n        pl = plot(maex,-maey,'*m');\n        set(pl,'MarkerSize',8,'LineWidth',2)\n    end\n    \n    if exist('maex', 'var')\n        set(gca,'NextPlot','add')\n        pl = plot(maex,-maey,'*m');\n        set(pl,'MarkerSize',8,'LineWidth',2)\n    end\n    \n    xlabel('Distance [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n    ylabel('Depth [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n    strib = [  'Misfit '];\n    title(strib,'FontWeight','bold',...\n        'FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')\n    \n    set(gca,'Color',color_bg);\n    set(gca,'box','on',...\n        'SortMethod','childorder','TickDir','out','FontWeight',...\n        'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2)\n    uicontrol(...\n        'Style','pushbutton',...\n        'Units','normalized',...\n        'Position',[0.9 0.7 0.08 0.08],...\n        'String','Grid',...\n        'callback',@(~,~)mificrgr(mi,inde));\n    \n    uicontrol(...\n        'Style','pushbutton',...\n        'Units','normalized',...\n        'Position',[0.9 0.6 0.08 0.08],...\n        'String','Sel EQ',...\n        'callback',@cb_pickinv);\n    \n    watchoff\n    \n    function cb_pickinv(~,~)\n        newa2=crosssel(newa);\n        ZG.newt2=newa2;\n        ZG.newcat=newa2;\n        ctp=CumTimePlot(ZG.newt2);\n        ctp.plot();\n    end\nend\n\nfunction newcat2=plotmi(var1, newcat2, mi)\n    %plot misfit (?)\n    % TODO make this work with the new catalogs\n    report_this_filefun();\n    \n    global  mif2 mif1\n    global tmp % REALLY? global tmp?  \"tmp\" is 1:nEvents\n    % cumu2 mi2\n    figNumber=findobj('Type','Figure','-and','Name','Misfit ');\n    figure(figNumber);\n    delete(findobj(figNumber,'Type','axes'));\n    rect = [0.15,  0.15, 0.75, 0.65];\n    axes('position',rect)\n    ax=gca;\n    nEvents=newcat2.Count;\n    tmp=1:nEvents;\n    sixSlices=round(0 : nEvents/5 : nEvents);\n    sixSlices(1)=1;\n    \n    var2=var1;\n    \n    misfitAngle = mi(:,2);\n    X = 1:nEvents;\n    xtitle=sprintf('Number of Eqs (sorted by %s)',lower(var1));\n    switch (var1)\n        case {'Longitude','Latitude','Magnitude','Depth'}\n            % plot_by_lon(); %by lon\n            plot_by_field(var1);\n        case 'Time'\n            plot_by_time(); % by date\n        case 'Strike'\n            plot_by_strike(); % along strike\n        case 'Default'\n            option_7(); %unsorted\n        otherwise\n            error('unknown choice for plotmi');\n    end\n    \n    grid('on')\n    set(ax,'Color',color_bg);\n    set(ax,'box','on',...\n        'SortMethod','childorder','TickDir','out','FontWeight',...\n        'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2)\n    ylabel('Cumulative Misfit ','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m);\n    xlabel(xtitle,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n    \n    if var1 ~= \"Default\"\n        set(gca,'NextPlot','add')\n        for i=1:6\n            plot(ax,tmp(sixSlices(i)),cumu2(sixSlices(i)),'xr');\n            str=['  ',num2str(newcat2(sixSlices(i),var2))];\n            te=text(tmp(sixSlices(i)),cumu2(sixSlices(i)),str);\n            set(te,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n        end\n    else\n        \n    end\n    \n    \n    function plot_by_field(name)\n        % assumes that misfit matrix (mi) has same number of rows as \n        % number of earthquakes in catalog\n        [~,is] = sort(newcat2.(name));\n        newcat2.sort(name); % sort the catalog itself by this field\n        \n        cumu2=cumsum(misfitAngle(is));\n        plot(1:nEvents , cumu2 , 'o');\n        xtitle=sprintf('Number of Eqs (sorted by %s)',lower(name));\n    end\n    \n    \n    function plot_by_time()\n        [~,is] = sort(newcat2.Date);\n        newcat2.sort(Date);\n        cumu2=cumsum(misfitAngle(is));\n        pl = plot(tmp,cumu2,'o');\n        xtitle='Number of Eqs (sorted by time)';\n    end\n    \n    function plot_by_strike()\n        % [~,is] = sort(newcat2(:,15));\n        [~,is] = sort(newcat2(:,end));\n        newa2 = newcat2.subset(is) ;\n        cumu2=cumsum(misfitAngle(is));\n        pl = plot(newa2(:,16)-18.6,cumu2,'o');\n        xtitle='Number of Eqs (sorted along strike)';\n        var2=15;\n    end\n    \n    function option_7()\n        mi2 = mi ;\n        cumu2=cumsum(mi2(:,2));\n        pl = plot(tmp,cumu2,'o');\n        xtitle='Number of Eqs ';\n    end\nend\n\nfunction mifigrid(var1,mi) \n    \n    % This function creates a grid with spacing dx, dy (in degrees)\n    % The size is selected interactively in an input window.\n    % The relative quiescence will be calculated for every grid point\n    % for a specific time and plotted in a Seismolap-Quiescence map\n    %\n    % turned into function by Celso G Reyes 2017\n    %\n    %MIFIGRID(var1,mi)\n    % \n    % Alexander Allmann\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    global  ni me1 va1\n    global a h1 map dx dy Mmin lap1 seismap\n    global normlap1 normlap2 mif1 mifmap\n    \n    if var1==1\n        \n        \n        %input window\n        %\n        %default parameters\n        dx= .5;                      %grid spacing east-west\n        dy= .5;                      %grid spacing north-south\n        % ldx=100;                     %side length of interaction zone in km (for seislap)\n        % tlap=300;                    %interaction time in days (for seislap)\n        Mmin=3;                      %minimum magnitude\n        \n        \n        %create a input window\n        figure_w_normalized_uicontrolunits(...\n            'Name','Grid Input Parameter',...\n            'NumberTitle','off', ...\n            'NextPlot','new', ...\n            'units','points',...\n            'Visible','off', ...\n            'Position',[ ZG.welcome_pos + [200, -200], 450, 250]);\n        axis off\n        \n        %create a dialog box for the input\n        freq_field1=uicontrol('Style','edit',...\n            'Position',[.60 .36 .15 .08],...\n            'Units','normalized','String',num2str(dx),...\n            'callback',@callbackfun_001);\n        \n        freq_field2=uicontrol('Style','edit',...\n            'Position',[.60 .27 .15 .08],...\n            'Units','normalized','String',num2str(dy),...\n            'callback',@callbackfun_002);\n        \n        freq_field3=uicontrol('Style','edit',...\n            'Position',[.60 .48 .15 .08],...\n            'Units','normalized','String',num2str(ni),...\n            'callback',@callbackfun_003);\n        \n        close_button=uicontrol('Style','Pushbutton',...\n            'Position',[.70 .05 .15 .12 ],...\n            'Units','normalized', 'Callback', @callbackfun_004,'String','Cancel');\n        \n        \n        go_button1=uicontrol('Style','Pushbutton',...\n            'Position',[.20 .05 .15 .12 ],...\n            'Units','normalized',...\n            'callback',@callbackfun_005,...\n            'String','Go');\n        \n        txt4 = text(...\n            'Position',[0.50 0.74 0 ],...\n            'FontSize',ZmapGlobal.Data.fontsz.l ,...\n            'FontWeight','bold',...\n            'String',' Grid Parameter');\n        txt5 = text(...\n            'Position',[0. 0.35 0 ],...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'FontWeight','bold',...\n            'String','Spacing in x (dx) in deg:');\n        \n        txt6 = text(...\n            'Position',[0. 0.25 0 ],...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'FontWeight','bold',...\n            'String','Spacing in y (dy) in deg:');\n        \n        txt2 = text(...\n            'Position',[0. 0.5 0 ],...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'FontWeight','bold',...\n            'String',' # of EQ Ni:');\n        \n        set(gcf,'visible','on');\n        watchoff\n        \n    elseif var1==2           %area selection\n        \n        figure(map);\n        set(gca,'NextPlot','add')\n        ax=findobj(gcf,'Tag','mainmap_ax');\n        [x,y, mouse_points_overlay] = select_polygon(ax);\n        \n        \n        %figure_w_normalized_uicontrolunits(mif1)\n        \n        plos2 = plot(x,y,'b-');        % plot outline\n        sum3 = 0.;\n        pause(0.3)\n        \n        %create a rectangular grid\n        xvect=[min(x):dx:max(x)];\n        yvect=[min(y):dy:max(y)];\n        tmpgri=zeros((length(xvect)*length(yvect)),2);\n        n=0;\n        for i=1:length(xvect)\n            for j=1:length(yvect)\n                n=n+1;\n                tmpgri(n,:)=[xvect(i) yvect(j)];\n            end\n        end\n        %extract all gridpoints in chosen polygon\n        XI=tmpgri(:,1);\n        YI=tmpgri(:,2);\n        ll = polygon_filter(x,y, XI, YI, 'inside');\n        %grid points in polygon\n        newgri=tmpgri(ll,:);\n        \n        % Plot all grid points\n        gcf\n        plot(newgri(:,1),newgri(:,2),'+k')\n        drawnow\n        \n        \n        if length(xvect) < 2  ||  length(yvect) < 2\n            errordlg('Selection too small! (not a matrix)');\n            return\n        end\n        \n        %calculate lap1(relative quiescence) at every grid point\n        %\n        ZG.newcat=a;                   %ZG.newcat is only a local variable\n        bcat=ZG.newcat;\n        \n        me1=zeros(length(newgri(:,1)),1);\n        va1=zeros(length(newgri(:,1)),1);\n        \n        wai = waitbar(0,' Please Wait ...  ');\n        set(wai,'NumberTitle','off','Name','Makegrid - Percent completed');\n        drawnow\n        \n        \n        \n        for i= 1:length(me1)   %all eqs which are in spacewindow in east-west direction\n            l = sqrt(((ZG.newcat.Longitude-newgri(i,1))*cosd(newgri(i,2))*111).^2 +...\n                ((ZG.newcat.Latitude-newgri(i,2))*111).^2) ;\n            [s,is] = sort(l);\n            b = ZG.newcat.subset(is) ;       % re-orders matrix to agree row-wise\n            mi2 = mi(is(:,1),2);    % take first ni points\n            mi2 = mi2(1:ni);\n            me1(i) = mean(mi2);\n            va1(i) = std(mi2);\n            if rem(i,20)==0;  waitbar(i/length(me1));end\n            \n        end\n        \n        \n        close(wai)\n        %make a color map\n        % Find out if figure already exists\n        %\n        mifmap=findobj('Type','Figure','-and','Name','Misfit-Map 2');\n        \n        % Set up the Seismicity Map window Enviroment\n        %\n        if isempty(mifmap)\n            mifmap = figure_w_normalized_uicontrolunits( ...\n                'Name','Misfit-Map 2',...\n                'NumberTitle','off', ...\n                'NextPlot','replace', ...\n                'backingstore','on',...\n                'Visible','off', ...\n                'Position',[ 600 400 500 650]);\n            % make menu bar\n            \n            \n            \n            set(gca,'NextPlot','add')\n        end\n        figure(mifmap)\n        delete(findobj(mifmap,'Type','axes'));\n        \n        set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','SortMethod','childorder')\n        \n        %minimum and maximum of normlap2 for automatic scaling\n        ZG.maxc = max(normlap2);\n        ZG.minc = min(normlap2);\n        \n        %construct a matrix for the color plot\n        normlap1=ones(length(tmpgri(:,1)),1);\n        normlap2=nan(length(tmpgri(:,1)),1)\n        normlap3=nan(length(tmpgri(:,1)),1)\n        normlap1(ll)=me1;\n        normlap2(ll)=normlap1(ll);\n        normlap1(ll)=va1;\n        normlap3(ll)=normlap1(ll);\n        \n        normlap2=reshape(normlap2,length(yvect),length(xvect));\n        normlap3=reshape(normlap3,length(yvect),length(xvect));\n        \n        %plot color image\n        orient tall\n        memifig2\n        \n        return\n        \n        rect = [0.25,  0.60, 0.7, 0.35];\n        axes('position',rect)\n        set(gca,'NextPlot','add')\n        pco1 = pcolor(xvect,yvect,normlap2);\n        shading interp\n        colormap(jet)\n        axis([ s2_west s1_east s4_south s3_north])\n        set(gca,'NextPlot','add')\n        colorbar\n        overlay\n        title('Mean of the Misfit','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        \n        set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','TickDir','out')\n        \n        rect = [0.25,  0.10, 0.7, 0.35];\n        axes('position',rect)\n        set(gca,'NextPlot','add')\n        pco1 = pcolor(xvect,yvect,normlap3);\n        axis([ s2_west s1_east s4_south s3_north])\n        set(gca,'NextPlot','add')\n        shading interp\n        colormap(jet)\n        set(gca,'NextPlot','add')\n        colorbar\n        title(' Variance of the Misfit','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        \n        set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','TickDir','out')\n        \n        overlay\n        memifig2\n    end\n    \n    function callbackfun_001(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        dx=str2double(freq_field1.String);\n        freq_field1.String=num2str(dx);\n    end\n    \n    function callbackfun_002(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        dy=str2double(freq_field2.String);\n        freq_field2.String=num2str(dy);\n    end\n    \n    function callbackfun_003(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ni=str2double(freq_field3.String);\n        freq_field3.String=num2str(ni);\n    end\n    \n    function callbackfun_004(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        close;\n        \n    end\n    \n    function callbackfun_005(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        close;\n        var1 = 2;\n        mifigrid(var1, mi);\n    end\n    \nend\n\nfunction memifig2() \n    % Misfitmap 2 (?)\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    report_this_filefun();\n    \n    \n    %input window\n    %\n    %default parameters\n    \n    %make a color map\n    % Find out if figure already exists\n    %\n    mifmap=findobj('Type','Figure','-and','Name','Misfit-Map 2');\n    \n    % Set up the Seismicity Map window Enviroment\n    %\n    if isempty(mifmap)\n        mifmap = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit-Map 2',...\n            'NumberTitle','off', ...\n            'NextPlot','replace', ...\n            'backingstore','on',...\n            'Visible','off', ...\n            'Position',[ 600 400 500 350]);\n        % make menu bar\n        set(gca,'NextPlot','add')\n    end\n    \n    figure(mifmap);\n    delete(findobj(mifmap,'Type','axes'));\n    \n    set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...\n        'FontWeight','bold','LineWidth',1.5,...\n        'Box','on','SortMethod','childorder')\n    \n    %minimum and maximum of normlap2 for automatic scaling\n    ZG.maxc = max(normlap2);\n    ZG.minc = min(normlap2);\n    \n    %construct a matrix for the color plot\n    normlap1=ones(length(tmpgri(:,1)),1);\n    normlap2=nan(length(tmpgri(:,1)),1)\n    normlap3=nan(length(tmpgri(:,1)),1)\n    normlap1(ll)=me1;\n    normlap2(ll)=normlap1(ll);\n    normlap1(ll)=va1;\n    normlap3(ll)=normlap1(ll);\n    \n    normlap2=reshape(normlap2,length(yvect),length(xvect));\n    normlap3=reshape(normlap3,length(yvect),length(xvect));\n    \n    %plot color image\n    orient tall\n    gx = xvect; gy = yvect;\n    \n    set(gca,'NextPlot','add')\n    pco1 = pcolor(xvect,yvect,normlap2);\n    shading interp\n    colormap(flipud(jet(10)));\n    axis([ min(gx) max(gx) min(gy) max(gy)])\n    axis image\n    \n    set(gca,'NextPlot','add')\n    h5 = colorbar('vert');\n    set(h5,'Pos',[0.82 0.46 0.02 0.20],...\n        'FontSize',12)\n    \n    \n    \n    if exist('maex', 'var')\n        set(gca,'NextPlot','add')\n        pl = plot(maex,-maey,'*k');\n        set(pl,'MarkerSize',6,'LineWidth',2)\n    end\n    \n    overlay\n    title(['Mean of the Misfit (' num2str(sig) '/' num2str(az)  '/' num2str(plu) '/' num2str(phi) '/' num2str(R) ')'] ,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    xlabel('Longitude in [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    ylabel('latitude in [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    \n    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...\n        'FontWeight','bold','LineWidth',1.5,...\n        'Box','on','TickDir','out')\nend\n\nfunction mificrgr( mi, inde) \n    % This function creates a grid with spacing dx, dy (in degrees)\n    % The size is selected interactively in an input window.\n    % The relative quiescence will be calculated for every grid point\n    % for a specific time and plotted in a Seismolap-Quiescence map\n    %  Alexander Allmann\n    %\n    % turned into function by Celso G Reyes 2017\n    \n    \n    %global freq_field1 freq_field2 freq_field3 freq_field4 freq_field5\n    %global freq_field6 ni me1 va1\n    %global h1 map dx dy Mmin lap1 seismap\n    %global normlap1 normlap2 mif1 mifmap\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    report_this_filefun();\n    \n    %input window\n    %\n    %default parameters\n    dx= .5;                      %grid spacing east-west\n    dy= .5;                      %grid spacing north-south\n    %ldx=100;                     %side length of interaction zone in km (for seislap)\n    %tlap=300;                    %interaction time in days (for seislap)\n    Mmin=3;                      %minimum magnitude\n    ni=100; % number of events\n    \n    %create a input window\n    fig=figure_w_normalized_uicontrolunits(...\n        'Name','Grid Input Parameter',...\n        'NumberTitle','off', ...\n        'NextPlot','new', ...\n        'units','points',...\n        'Visible','off', ...\n        'MenuBar','none',...\n        'Position',[ ZG.welcome_pos + [200, -200], 700, 250]);\n    axis off\n    \n    gridOpts = ZG.gridopt;\n    esp = EventSelectionParameters('NumClosestEvents',ni);\n    selOpts = EventSelectionChoice(fig,'evsel',esp);\n    \n    \n    close_button=uicontrol('Style','Pushbutton',...\n        'Position',[.70 .05 .15 .12 ],...\n        'Units','normalized', 'Callback', @callbackfun_cancel,'String','Cancel');\n    \n    \n    go_button1=uicontrol('Style','Pushbutton',...\n        'Position',[.20 .05 .15 .12 ],...\n        'Units','normalized',...\n        'callback',@callbackfun_go,...\n        'String','Go');\n    \n    set(gcf,'visible','on');\n    watchoff\n    \n    function my_calculate()\n        \n        xsec_h=xsec_fig();\n        \n        if isempty(xsec_h) % best guess at figure handle variable\n            nlammap\n        else\n            figure(xsec_h);\n        end\n        \n        set(gca,'NextPlot','add')\n        ax=findobj(gcf,'Tag','mainmap_ax');\n        [x,y, mouse_points_overlay] = select_polygon(ax);\n        \n        \n        figure(xsec_h)\n        \n        plos2 = plot(x,y,'b-');        % plot outline\n        sum3 = 0.;\n        pause(0.3)\n        \n        %create a rectangular grid\n        xvect=[min(x):dx:max(x)];\n        yvect=[min(y):dy:max(y)];\n        tmpgri=zeros((length(xvect)*length(yvect)),2);\n        n=0;\n        for i=1:length(xvect)\n            for j=1:length(yvect)\n                n=n+1;\n                tmpgri(n,:)=[xvect(i) yvect(j)];\n            end\n        end\n        %extract all gridpoints in chosen polygon\n        XI=tmpgri(:,1);\n        YI=tmpgri(:,2);\n        \n        ll = polygon_filter(x,y, XI, YI, 'inside');\n        %grid points in polygon\n        newgri=tmpgri(ll,:);\n        \n        % Plot all grid points\n        gcf\n        plot(newgri(:,1),newgri(:,2),'+k')\n        drawnow\n        \n        if length(xvect) < 2  ||  length(yvect) < 2\n            errordlg('Selection too small! (not a matrix)');\n            return\n        end\n        \n        \n        \n        %\n        ZG.newcat=a;                   %ZG.newcat is only a local variable\n        bcat=ZG.newcat;\n        \n        me1=zeros(length(newgri(:,1)),1);\n        va1=zeros(length(newgri(:,1)),1);\n        mic = mi(inde,:);\n        \n        wai = waitbar(0,' Please Wait ...  ');\n        set(wai,'NumberTitle','off','Name','Makegrid - Percent completed');\n        drawnow\n        \n        for i= 1:length(me1)   %all eqs which are in spacewindow in east-west direction\n            x = newgri(i,1);y = newgri(i,2);\n            \n            l = sqrt(((xsecx' - x)).^2 + ((xsecy + y)).^2) ;\n            [s,is] = sort(l);\n            b = ZG.newcat.subset(is) ;       % re-orders matrix to agree row-wise\n            mi2 = mic(is(:,1),2);    % take first ni points\n            mi2 = mi2(1:ni);\n            me1(i) = mean(mi2);\n            va1(i) = std(mi2);\n            if rem(i,20)==0;  waitbar(i/length(me1));end\n        end\n        \n        \n        close(wai)\n        %make a color map\n        % Find out if figure already exists\n        %\n        mifmap=findobj('Type','Figure','-and','Name','Misfit-Map 2');\n        \n        % Set up the Seismicity Map window Enviroment\n        %\n        if isempty(mifmap)\n            mifmap = figure_w_normalized_uicontrolunits( ...\n                'Name','Misfit-Map 2',...\n                'NumberTitle','off', ...\n                'NextPlot','replace', ...\n                'backingstore','on',...\n                'Visible','off', ...\n                'Position',[ 600 400 500 650]);\n            % make menu bar\n            \n            \n            \n            set(gca,'NextPlot','add')\n        end\n        \n        figure(mifmap);\n        delete(findobj(mifmap,'Type','axes'));\n        \n        set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','SortMethod','childorder')\n        \n        %minimum and maximum of normlap2 for automatic scaling\n        ZG.maxc = max(normlap2);\n        ZG.minc = min(normlap2);\n        \n        %construct a matrix for the color plot\n        normlap1=ones(length(tmpgri(:,1)),1);\n        normlap2=nan(length(tmpgri(:,1)),1)\n        normlap3=nan(length(tmpgri(:,1)),1)\n        normlap1(ll)=me1;\n        normlap2(ll)=normlap1(ll);\n        normlap1(ll)=va1;\n        normlap3(ll)=normlap1(ll);\n        \n        normlap2=reshape(normlap2,length(yvect),length(xvect));\n        normlap3=reshape(normlap3,length(yvect),length(xvect));\n        \n        %plot color image\n        orient tall\n        gx = xvect; \n        gy = yvect;\n        memifig\n        \n        return\n        \n        rect = [0.25,  0.60, 0.7, 0.35];\n        axes('position',rect)\n        set(gca,'NextPlot','add')\n        pco1 = pcolor(xvect,yvect,normlap2);\n        shading interp\n        colormap(jet)\n        %axis([ s2_west s1_east s4_south s3_north])\n        axis([ min(gx) max(gx) min(gy) max(gy)])\n        axis image\n        \n        set(gca,'NextPlot','add')\n        colorbar\n        if exist('maex', 'var')\n            set(gca,'NextPlot','add')\n            pl = plot(maex,-maey,'*m');\n            set(pl,'MarkerSize',8,'LineWidth',2)\n        end\n        \n        %overlay\n        title('Mean of the Misfit','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        xlabel('Distance in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        ylabel('Depth in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        \n        set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','TickDir','out')\n        \n        rect = [0.25,  0.10, 0.7, 0.35];\n        axes('position',rect)\n        set(gca,'NextPlot','add')\n        pco1 = pcolor(xvect,yvect,normlap3);\n        axis([ min(gx) max(gx) min(gy) max(gy)])\n        axis image\n        \n        if exist('maex', 'var')\n            set(gca,'NextPlot','add')\n            pl = plot(maex,-maey,'*w');\n            set(pl,'MarkerSize',8,'LineWidth',2)\n        end\n        \n        \n        set(gca,'NextPlot','add')\n        shading interp\n        colormap(jet)\n        set(gca,'NextPlot','add')\n        colorbar\n        title(' Variance of the Misfit','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        xlabel('Distance in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        ylabel('Depth in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n        \n        set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n            'FontWeight','bold','LineWidth',1.5,...\n            'Box','on','TickDir','out')\n        \n    end\n    \n    function callbackfun_cancel(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        close;\n        \n    end\n    \n    function callbackfun_go(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        dx=gridOpts.dx;\n        dy=gridOpts.dy;\n        ni=selOpts.ni;\n        delete(selOpts);\n        close;\n        my_calculate();\n    end\n    \nend\n\nfunction memifig() \n    % turned into function by Celso G Reyes 2017\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    report_this_filefun();\n    \n    \n    %input window\n    %\n    %default parameters\n    \n    %make a color map\n    % Find out if figure already exists\n    %\n    mifmap=findobj('Type','Figure','-and','Name','Misfit-Map 2');\n    \n    % Set up the Seismicity Map window Enviroment\n    %\n    if isempty(mifmap)\n        mifmap = figure_w_normalized_uicontrolunits( ...\n            'Name','Misfit-Map 2',...\n            'NumberTitle','off', ...\n            'NextPlot','replace', ...\n            'backingstore','on',...\n            'Visible','off', ...\n            'Position',[ 600 400 500 350]);\n        % make menu bar\n        \n        \n        \n        set(gca,'NextPlot','add')\n    end\n    figure(mifmap);\n    delete(findobj(mifmap,'Type','axes'));\n    \n    set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...\n        'FontWeight','bold','LineWidth',1.5,...\n        'Box','on','SortMethod','childorder')\n    \n    %minimum and maximum of normlap2 for automatic scaling\n    ZG.maxc = max(normlap2);\n    ZG.minc = min(normlap2);\n    \n    %construct a matrix for the color plot\n    normlap1=ones(length(tmpgri(:,1)),1);\n    normlap2=nan(length(tmpgri(:,1)),1)\n    normlap3=nan(length(tmpgri(:,1)),1)\n    normlap1(ll)=me1;\n    normlap2(ll)=normlap1(ll);\n    normlap1(ll)=va1;\n    normlap3(ll)=normlap1(ll);\n    \n    normlap2=reshape(normlap2,length(yvect),length(xvect));\n    normlap3=reshape(normlap3,length(yvect),length(xvect));\n    \n    %plot color image\n    orient tall\n    gx = xvect; gy = yvect;\n    \n    set(gca,'NextPlot','add')\n    pco1 = pcolor(xvect,yvect,normlap2);\n    shading interp\n    colormap( flipud(jet(64)) );\n    axis([ min(gx) max(gx) min(gy) max(gy)])\n    axis image\n    \n    set(gca,'NextPlot','add')\n    h5 = colorbar('vert');\n    set(h5,'Pos',[0.82 0.46 0.03 0.10],...\n        'FontSize',2)\n    \n    \n    \n    if exist('maex', 'var')\n        set(gca,'NextPlot','add')\n        pl = plot(maex,-maey,'*w');\n        set(pl,'MarkerSize',6,'LineWidth',1)\n    end\n    \n    %overlay\n    title('Mean of the Misfit','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    xlabel('Distance in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    ylabel('Depth in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)\n    \n    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...\n        'FontWeight','bold','LineWidth',1.5,...\n        'Box','on','TickDir','out')\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/domisfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24318841007703076}}
{"text": "function o = cat(dr,varargin)\n% Concatenate file_array objects.  The result is a non-simple object\n% that can no longer be reshaped.\n% _______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id: cat.m 1143 2008-02-07 19:33:33Z spm $\n\n\nif dr>32 || dr<0, error('Unknown command option.'); end;\ndr   = max(round(dr),1);\nd    = ones(nargin-1,16);\ntmp  = {};\ndpos = 0;\nfor i=1:nargin-1,\n    vi = varargin{i};\n    if strcmp(class(vi),'file_array')\n        sz                = size(vi);\n        d(i,1:length(sz)) = sz;\n        svi               = struct(vi);\n        svi               = svi(:);\n        for j=1:length(svi(:)),\n            if length(svi(j).pos)<dr\n                svi(j).pos((length(svi(j).pos)+1):dr) = 1;\n            end\n            svi(j).pos(dr)= svi(j).pos(dr) + dpos;\n        end;\n        dpos              = dpos + d(i,dr);\n        tmp{i}            = svi;\n    else\n        error(['Conversion to file_array from ' class(vi) ' is not possible.']);\n    end;\nend;\nif any(diff(d(:,[1:(dr-1) (dr+1):end]),1,1))\n    error('All matrices on a row in the bracketed expression must have the same number of rows.');\nelse\n    o = vertcat(tmp{:});\n    o = class(o,'file_array');\nend;\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/External/spm8/@file_array/cat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24318840356301313}}
{"text": "function [scores, blocks] = readscorestats(inffile, model)\n\n% [scores, blocks] = readscorestats(inffile, model)\n%\n% Read a score statistics file and parse it into labels, total scores, \n% unique flags, and block scores.\n\nfid = fopen(inffile, 'rb');\nnum = fread(fid, 1, 'int32');\nscores = zeros(num, 1);\nblocks = zeros(num, model.numblocks);\nfor i = 1:num\n  tmp = fread(fid, model.numblocks+1, 'double');\n  scores(i) = tmp(1);\n  blocks(i,:) = tmp(2:end);\nend\nfclose(fid);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/star-cascade-master/readscorestats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2431017652866156}}
{"text": "function [X,Y,T,options,A,R2_pca,pca_opt,features] = preproc4hmm(X,Y,T,options)\n% Prepare data to run TUDA\n% 1. check parameters, including the type of classifier (regression is default)\n% 2. Format X and Y accordingly to the classifier\n% 3. Sets up state to be sequential , if asked\n% 4. Preprocesses the data, including embedding\n\nif length(size(X))==3 % 1st dim, time; 2nd dim, trials; 3rd dim, channels\n    X = reshape(X,[size(X,1)*size(X,2), size(X,3)]);\nend\n\nN = length(T);\np = size(X,2);\n\nif any(isnan(Y(:))), error('NaN found in Y'); end\nif ~isfield(options,'Y_is_continuous') %ie not discrete\n    options.Y_is_continuous = length(unique(Y(:))) > 50;\nend\n\nif size(X,1) ~= sum(T), error('Dimension of X not correct'); end\nif size(Y,1) < size(Y,2); Y = Y'; end\nif (size(Y,1) ~= sum(T)) && (size(Y,1) ~= length(T))\n    error('Dimension of Y not correct');\nend\nq = size(Y,2);\n  \nif ~isfield(options,'K'), error('K needs to be specified'); end\nif isfield(options,'downsample') && options.downsample\n   error('Downsampling is not currently an option') \nend\nif isfield(options,'filter') && ~isempty(options.filter) && ~isfield(options,'Fs')\n   error('You must specify options.Fs if you are to filter the data') \nend\n\n% options relative to the regression setting\nif ~isfield(options,'classifier'), options.classifier = ''; end \n% if empty, it is meant to be used with a continuous response\nif ~isfield(options,'Nfeatures'), Nfeatures = p;\nelse, Nfeatures = options.Nfeatures; end\nif ~isfield(options,'standardise'), standardise = 0;\nelse, standardise = options.standardise; end % otherwise it's done per trial\nif ~isfield(options,'onpower'), onpower = 0;\nelse, onpower = options.onpower; end\nif ~isfield(options,'embeddedlags'), embeddedlags = 0;\nelse, embeddedlags = options.embeddedlags; end\nif ~isfield(options,'filter'), filter = [];\nelse, filter = options.filter; end\nif ~isfield(options,'detrend'), detrend = 0;\nelse, detrend = options.detrend; end\n% econ_embed saves memory at the expense of speed, when pca is applied\nif ~isfield(options,'econ_embed'), econ_embed = 0;\nelse, econ_embed = options.econ_embed; end\nif ~isfield(options,'parallel_trials'), parallel_trials = all(T==T(1)) & length(T)>1;\nelse, parallel_trials = options.parallel_trials; end\nif ~isfield(options,'acrosstrial_constrained'), options.acrosstrial_constrained = 0; end\n\nif ~isfield(options,'pca'), pca_opt = 0;\nelse, pca_opt = options.pca; end\nif ~isfield(options,'A'), A = [];\nelse, A = options.A; end\nif isfield(options,'downsample') && options.downsample~=0\n    warning('Downsampling is not possible for TUDA')\nend\nif ~isfield(options,'encodemodel')\n    options.encodemodel = false;\nend\n%options relative to classification models:\nif ~isempty(options.classifier) || options.encodemodel\n    if strcmp(options.classifier,'logistic')\n        %set default options for logistic regression classification:\n        options.distribution = 'logistic';\n        demeanstim = false;\n        %determine if multinomial or binomial:\n        vals = unique(Y(:));\n        if length(vals) == 2\n            if all((vals == 0) | (vals == 1))\n                Y = 2*(Y)-1;\n            elseif q==1 && all((vals == 1) | (vals == 2))\n                Y(Y==2) = -1;\n            elseif any((vals ~= -1) & (vals ~= 1))  \n                error('Format of Y incorrect for classification tasks');\n            end\n        elseif length(vals) > 2 && q == 1\n            % Y entered as categorical format\n            fprintf(['\\nFitting multinomial logistic classifier with classes ',int2str(vals'), '\\n']);\n            Y = convertToMultinomial(Y);\n        elseif length(vals) == 3\n            if any((vals ~= -1) & (vals ~= 1) & (vals ~= 0))  \n                error('Format of Y incorrect for classification tasks');\n            end\n        end\n        options.logisticYdim=size(Y,2);\n        if ~isfield(options,'balancedata')\n            options.balancedata = 0;\n        else\n            options.balancedata = options.balancedata;\n        end\n        if ~isfield(options,'intercept'), options.intercept = 0; end\n        if options.intercept\n           X = [X,ones(size(X,1),1)];\n        end\n        options = rmfield(options,'intercept');\n        if ~isfield(options,'sequential')\n            options.sequential = 1;\n        end\n        if ~isfield(options,'inittype')\n            if options.sequential ~= 0\n                options.inittype = 'sequential';\n            else\n                options.inittype = 'HMM-MAR';\n            end\n        end\n        add_noise = 0;\n        if ~isfield(options,'cyc'), options.cyc = 1; end\n   elseif strcmp(options.classifier,'LDA') || options.encodemodel\n       % set default options for LDA model:\n       options.distribution = 'Gaussian';\n       demeanstim = false;\n        if ~isfield(options,'intercept'), options.intercept = 1; end\n        if options.intercept\n            if size(Y,2)==1 && all((Y==0) + (Y==1))\n                Y = [ones(size(Y,1),1),Y==1];\n            else\n                Y = [ones(size(Y,1),1),Y];\n            end\n            q = size(Y,2);\n        end\n        if ~isfield(options,'covtype')\n            options.covtype = 'sharedfull'; \n        end\n        options=rmfield(options,'intercept');\n        if ~isfield(options,'sequential')\n            options.sequential = 1;\n        end\n        if ~isfield(options,'inittype')\n            if options.sequential ~= 0\n                options.inittype = 'sequential';\n            else\n                options.inittype = 'HMM-MAR';\n            end\n        end\n        options.add_noise = 0;\n        add_noise = 0;\n    elseif strcmp(options.classifier,'SVM') || strcmp(options.classifier,'SVM_rbf') || ...\n            strcmp(options.classifier,'KNN') || ...\n            strcmp(options.classifier,'decisiontree')\n        add_noise = 0;\n        demeanstim = false;\n        options.sequential = 0;\n    elseif strcmp(options.classifier,'regression')\n        options.distribution = 'Gaussian';\n        demeanstim = false;\n        %determine if multinomial or binomial:\n        vals = unique(Y(:));\n        if length(vals) == 2 && q == 1\n            if all((vals == 0) | (vals == 1))\n                Y = 2*(Y)-1;\n            elseif any((vals ~= -1) & (vals ~= 1)) \n                error('Format of Y incorrect for classification tasks');\n            end\n            c1 = sum(Y==-1); c2 = sum(Y==1); c12 = length(Y);\n            Y(Y==-1) = - c12 / c1;  Y(Y==+1) = c12 / c2;\n        elseif length(vals) > 2 && q == 1\n            Ytmp = Y;\n            Y = zeros(size(Y,1),length(vals));\n            for jj = 1:length(vals), Y(Ytmp==vals(jj),jj) = 1; end\n            q = length(vals);\n        elseif q > 1\n            if any((vals ~= 0) & (vals ~= 1)) \n                error('Format of Y incorrect for classification tasks');\n            end\n        end      \n        add_noise = ~options.Y_is_continuous;\n        if ~isfield(options,'sequential')\n            options.sequential = 1;\n        end\n        if ~isfield(options,'inittype')\n            if options.sequential ~= 0\n                options.inittype = 'sequential';\n            else\n                options.inittype = 'HMM-MAR';\n            end\n        end\n    end\n    \nelse % Standard regression problem \n    \n    options.distribution = 'Gaussian'; %default for all non-classification models\n    demeanstim = true; \n    if ~isfield(options,'add_noise'), add_noise = 0;\n    else, add_noise = options.add_noise;\n    end\n    if ~isfield(options,'sequential')\n        options.sequential = 1;\n    end\n    if ~isfield(options,'inittype')\n        if options.sequential ~= 0\n            options.inittype = 'fixedsequential';\n        else\n            options.inittype = 'HMM-MAR';\n        end\n    end\n    if ~isfield(options,'intercept'), options.intercept = 0; end\n    if options.intercept\n       X = [X,ones(size(X,1),1)];\n    end\n    options = rmfield(options,'intercept');\n    if ~isfield(options,'cyc'), options.cyc = 1; end\nend\n\nif ~isfield(options,'cyc'), options.cyc = 25; end\nif ~isfield(options,'logisticYdim'), options.logisticYdim = 0; end\n\n% Set up states to be a a sequence\nif isfield(options,'sequential') && options.sequential ~= 0\n    options.Pistructure = zeros(1,options.K);\n    options.Pistructure(1:abs(options.sequential)) = 1;\n    options.Pistructure = logical(options.Pistructure);\n    options.Pstructure = logical(eye(options.K));\n    for k = 1:abs(options.sequential)\n        options.Pstructure = options.Pstructure + diag(ones(options.K-k,1),k);\n    end\n    if options.sequential < 0\n        for k = 1:abs(options.sequential)\n            options.Pstructure = options.Pstructure + diag(ones(options.K-k,1),-k);\n        end\n    end\nend\n\n% Options relative to constraints in the trans prob mat\nif ~isfield(options,'K'), error('K was not specified'); end\nif ~isfield(options,'Pstructure')\n    options.Pstructure = true(options.K);\nend\nif ~isfield(options,'Pistructure')\n    options.Pistructure = true(1,options.K);\nend\n\noptions.parallel_trials = parallel_trials;\nif ~isfield(options,'tudamonitoring'), options.tudamonitoring = 0; end\nif ~isfield(options,'plotGamma'), options.plotGamma = 0; end\n\nif parallel_trials && ~all(T==T(1))\n    error('parallel_trials can be used only when all trials have equal length');\nend\nif options.tudamonitoring && ~all(T==T(1))\n    error('tudamonitoring can be used only when all trials have equal length');\nend\n\n% options relative to the HMM\nif ~isfield(options,'distribution'),options.distribution='Gaussian';end\nif options.logisticYdim>0\n    options.distribution = 'logistic';\nend\nif strcmp(options.distribution,'logistic')\n    options.covtype = '';\nend\nif ~isfield(options,'covtype') && strcmp(options.distribution,'Gaussian')\n    options.covtype = 'shareddiag'; \nend\nif ~isfield(options,'inittype'), options.inittype = 'HMM-MAR'; end\n\noptions.order = 1;\noptions.zeromean = 1;\noptions.embeddedlags = 0; % it is done here\noptions.pca = 0; % it is done here\noptions.standardise = 0; % it is done here\noptions.onpower = 0; % it is done here\noptions.detrend = 0; % it is done here\noptions.filter = []; % it is done here\noptions.downsample = 0; % it is done here \noptions.dropstates = 0;\n\nif isfield(options,'econ_embed'), options = rmfield(options,'econ_embed'); end\nif isfield(options,'Nfeatures'), options = rmfield(options,'Nfeatures'); end\nif isfield(options,'demeanstim'), options = rmfield(options,'demeanstim'); end\n% Set a high prior for the initial probabilities because otherwise the\n% model is biased to have the first time point of each trial to be assigned\n% to just one state.\nif ~isfield(options,'PriorWeightingPi'), options.PriorWeightingPi = length(T)/20; end\nif ~isfield(options,'DirichletDiag'), options.DirichletDiag = 100; end\n\ndo_embedding = length(embeddedlags)>1;\ndo_pca = ~isempty(A) || length(pca_opt)>1 || (pca_opt>0 && pca_opt<(p*length(embeddedlags)));\ndo_pls = isfield(options,'pls');\n\nif ~do_embedding && econ_embed\n    econ_embed = 0;\nend\nif do_embedding && ~do_pca && econ_embed\n    warning('It only makes sense to use econ_embed when using pca')\n    econ_embed = 0;\nend\n\nemforw = max(max(embeddedlags),0);\nemback = max(-min(embeddedlags),0);\n\nif size(Y,1) == N % one value for the entire trial\n    %Y = reshape(repmat(reshape(Y,[1 N q]),[ttrial 1 1]),[N*ttrial q]);\n    Ytmp = Y;\n    Y = zeros(sum(T),q);\n    for n = 1:N\n        Y(sum(T(1:n-1)) + (1:T(n)),:) = repmat(Ytmp(n,:),T(n),1);\n    end; clear Ytmp\nend\n\nif q == 1 && length(unique(Y))==2\n    if ismember(0,unique(Y)) || all(unique(Y)>0) && ~strcmp(options.distribution,'logistic')\n        warning('Seems this is binary classification, transforming stimulus to have elements (-1,+1)')\n        if islogical(Y);Y=1*Y;end\n        v = unique(Y);\n        Y(Y==v(1)) = -1; Y(Y==v(2)) = +1;\n        if options.logisticYdim==0\n            Y = Y - mean(Y);\n        end\n    end\nend\n\nif demeanstim\n    % Demean stimulus\n    Y = bsxfun(@minus,Y,mean(Y));\nend\n% Add noise, to avoid numerical problems \nif add_noise > 0\n    if add_noise == 1\n        Y = Y + 1e-5 * randn(size(Y)) .* repmat(std(Y),size(Y,1),1);\n    else\n        Y = Y + add_noise * randn(size(Y)) .* repmat(std(Y),size(Y,1),1);\n    end\nend\n% Standardise data\nif standardise && N > 1\n   warning(['You have set standardise=1, so each channel and trial will be standardized. ' ...\n       'This will probably result in a loss of information in terms of how each stimulus is processed'])\n   X = standardisedata(X,T,standardise); \nend\n\n% Filtering\nif ~isempty(filter)\n    data = filterdata(X,T,options.Fs,filter);\nend\n% Detrend data\nif detrend\n    X = detrenddata(X,T);\nend\n\n% adjust dimension of Y according to embedding\nif do_embedding\n    Ttmp = T-emforw-emback;\n    Ytmp = Y;\n    Y = zeros(sum(Ttmp),q);\n    for n = 1:N\n        Y(sum(Ttmp(1:n-1)) + (1:Ttmp(n)),:) = ...\n            Ytmp(sum(T(1:n-1)) + (1+emforw:T(n)-emback) ,:);\n    end; clear Ytmp Ttmp\nend\n\n% feature selection\nif Nfeatures < p && Nfeatures > 0\n    me = sum((repmat(mean(Y),size(Y,1),1) - Y).^2);\n    C = zeros(p,1);\n    for j=1:p\n        if onpower\n            x = rawsignal2power(X(:,j),T);\n        else\n            x = X(:,j);\n        end\n        if do_embedding\n            x = embeddata(x,T,embeddedlags);\n        end\n        b = (x' * x) \\ (x' * Y);\n        e = sum((x * b - Y).^2);\n        C(j) = sum(1 - e ./ me);\n    end\n    [~,features] = sort(C,1,'descend');\n    features = features(1:Nfeatures);\n    X = X(:,features);\n    p = Nfeatures;\nelse\n    features = 1:p;\nend\n\n% Hilbert envelope\nif onpower\n    X = rawsignal2power(X,T);\nend\n\n% do embedding + PCA\nR2_pca = []; \nif econ_embed\n    \n    % build gram matrix subject by subject\n    for n = 1:N\n        t = (1:T(n)) + sum(T(1:n-1));\n        if do_embedding\n            Xn = embeddata(X(t,:),T(n),embeddedlags);\n        else\n            Xn = X(t,:);\n        end\n        Xn = Xn - repmat(mean(Xn),size(Xn,1),1); % must center\n        if n==1, C = zeros(size(Xn,2)); end\n        C = C + Xn' * Xn;\n    end\n    \n    % do SVD\n    if isempty(A)\n        [A,e,~] = svd(C);\n        e = diag(e);\n        e = cumsum(e)/sum(e);\n        p = num_comp_pca(e,pca_opt);\n        A = A(:,1:p);\n        R2_pca = e(p);\n    else\n        R2_pca = []; p = size(A,2);\n    end\n    % eigendecompose subject by subject\n    Xtmp = X; Ttmp = T;\n    T = T-emforw-emback;\n    X = zeros(sum(T),p);\n    for n = 1:N\n        t = (1:T(n)) + sum(T(1:n-1));\n        ttmp = (1:Ttmp(n)) + sum(Ttmp(1:n-1));\n        if do_embedding\n            Xn = embeddata(Xtmp(ttmp,:),Ttmp(n),embeddedlags);\n        else\n            Xn = Xtmp(ttmp,:);\n        end\n        Xn = Xn - repmat(mean(Xn),size(Xn,1),1); % must center\n        X(t,:) = Xn * A;\n    end\n        \nelse\n    \n    if do_embedding\n        [X,T] = embeddata(X,T,embeddedlags);\n        msg = '(embedded)';\n    else\n        msg = '';\n    end\n    if do_pca\n        if isempty(A)\n            [A,X,e] = pca(X);\n            e = cumsum(e)/sum(e);\n            p = num_comp_pca(e,pca_opt);\n            R2_pca = e(p);\n            X = X(:,1:p);\n            A = A(:,1:p);\n            fprintf('Working in PCA %s space, with %d components. \\n',msg,p)\n        else\n            X = bsxfun(@minus,X,mean(X));   \n            X = X * A; \n        end\n    else\n        R2_pca = 1;\n    end\n    if do_pls\n        [X,A] = PLSdimreduce(X,Y,T,options.pls);\n        options = rmfield(options,'pls');\n    end\nend\n\nend\n\n\nfunction ncomp = num_comp_pca(e,d)\n\nif length(d)==1 && d<1\n    ncomp = find(e>d,1);\nelseif length(d)==1 && d>=1\n    ncomp = d;\nelseif length(d)==2 || (length(d)==3 && d(3)==1)\n    ncomp = min(find(e>d(1),1),d(2));\nelseif length(d)==3 && d(3)==2\n    ncomp = max(find(e>d(1),1),d(2));\nelse\n    error('pca parameters are wrongly specified')\nend\n\nend\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/task/utils/preproc4hmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24295080894803311}}
{"text": "function vid_bic = interp_bicubic(vid_l, upscale)\n\nN = length(vid_l);\n\nfor i = 1: N\n    vid_bic{i} = imresize(vid_l{i}, upscale, 'bicubic');\n    %vid_bic{i} = imresize(vid_l{i}, upscale, 'nearest');\nend\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/BayesianVSR/functions/interp_bicubic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2429471413680615}}
{"text": "% STD_READTOPO - returns the scalp map of a specified ICA component, assumed\n%                  to have been saved in a Matlab file, [dataset_name].icatopo, \n%                  in the same directory as the dataset file. If this file does \n%                  not exist, use STD_TOPO to create it, else a pre-clustering \n%                  function that calls it: POP_PRECLUST or EEG_PRECLUST.  \n% Usage:    \n%   >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component);  \n%   >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component, transform, mode);  \n%\n% Inputs:\n%   ALLEEG     - vector of EEG datasets (can also be one EEG set). \n%                must contain the dataset of interest (see 'setindx' below).\n%   setindx    - [integer] an index of an EEG dataset in the ALLEEG\n%                structure, for which to get the component ERP.\n%   component  - [integer] index of the component for which the scalp map \n%                grid should be returned. \n%   transform  - ['none'!'laplacian'|'gradient'] transform scalp map to\n%                laplacian or gradient map. Default is 'none'.\n%   mode       - ['2dmap'|'preclust'] return either a 2-D array for direct\n%                plotting ('2dmap') or an array formatted for preclustering\n%                with all the NaN values removed (ncomps x points). Default\n%                is '2dmap' for 1 component and 'preclust' for several.\n%\n% Outputs:\n%   grid      - square scalp-map color-value grid for the requested ICA component \n%               in the specified dataset, an interpolated Cartesian grid as output \n%               by TOPOPLOT. \n%   y         - y-axis values for the interpolated grid\n%   x         - x-axis values of the interpolated grid\n%\n%  See also  STD_TOPO, STD_PRECLUST\n%\n% Authors: Arnaud Delorme, Hilit Serby, SCCN, INC, UCSD, February, 2005\n\n% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, hilit@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [X, yi, xi ] = std_readtopo(ALLEEG, abset, comps, option, mode)\n\nX = [];\nyi = [];\nxi = [];\nif nargin < 4\n    option = 'none';\nend\nif nargin < 5\n    mode = '2Dmap';\nend\nfilename = correctfile(fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icatopo']),ALLEEG(abset).filepath);\ntmpfile  = which(filename);\nif ~isempty(tmpfile), filename = tmpfile; end\n\n% 061411, 2:51pm\n% Modified by Joaquin\n% while getfield(dir(filename), 'bytes') < 1000\ni = 1;\nwhile getfield(dir(filename), 'bytes') < 5000\n    topo = load( '-mat', filename);\n    filename = correctfile(topo.file, ALLEEG(abset).filepath);\n    tmpfile  = which(filename);\n    if ~isempty(tmpfile), filename = tmpfile; end\n    if(i>100) \n        error('too many attempts to find valid icatopo');\n    end\n    i = i+1;\nend\n\nfor k = 1:length(comps)\n\n    if length(comps) < 3\n        lastwarn('', '');\n        try\n            topo = load( '-mat', filename, ...\n                         [ 'comp' int2str(comps(k)) '_grid'], ...\n                         [ 'comp' int2str(comps(k)) '_x'], ...\n                         [ 'comp' int2str(comps(k)) '_y'] );\n        catch\n            error( [ 'Cannot read file ''' filename '''' ]);\n        end\n        [~, warnId] = lastwarn();\n        if ~isempty(warnId)\n            error( 'Cannot find component %d in file %s', comps(k),  filename );\n        end\n    elseif k == 1\n        try\n            topo = load( '-mat', filename);\n        catch\n            error([ 'Missing scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]);\n        end\n    end\n    \n    try\n        tmp =  getfield(topo, [ 'comp' int2str(comps(k)) '_grid' ]);\n    catch\n        error([ 'Empty scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]);\n    end\n        \n    if strcmpi(option, 'gradient')\n        [tmpx, tmpy]  = gradient(tmp); % Gradient\n        tmp        = tmpx;\n        tmp(:,:,2) = tmpy;\n    elseif strcmpi(option, 'laplacian')\n        tmp = del2(tmp); % Laplacian\n    end\n\n    if length(comps) > 1 || strcmpi(mode, 'preclust')\n        tmp = tmp(find(~isnan(tmp))); % remove NaN for more than 1 component\n    end\n    if k == 1\n        X = zeros([ length(comps) size(tmp) ]) ;\n    end\n    X(k,:,:,:) =  tmp;\n    if k == 1 \n        yi   = getfield(topo, [ 'comp' int2str(comps(k)) '_y']);\n        xi   = getfield(topo, [ 'comp' int2str(comps(k)) '_x']);\n    end\nend\nX = squeeze(X);\n\nreturn;\n\nfunction filename = correctfile(filename, datasetpath)\n    comp = computer;\n    if filename(2) == ':' && ~strcmpi(comp(1:2), 'PC') \n        filename = [filesep filename(4:end) ];\n        filename(find(filename == '\\')) = filesep;\n    end\n    \n    if ~exist(filename)\n        [tmpp tmpf ext] = fileparts(filename);\n        if exist([tmpf ext])\n            filename = [tmpf ext];\n        else\n            [tmpp2 tmpp1] = fileparts(tmpp);\n            if exist(fullfile(tmpp1, [ tmpf ext ]))\n                filename = fullfile(tmpp1, [ tmpf ext ]);\n            else\n                filename = fullfile(datasetpath, [ tmpf ext ]);\n                if ~exist(filename)\n                    error([ 'Cannot load file ''' [ tmpf ext ] '''' 10 'Go back and recompute the data file.' 10 'Note that plotting ICA component ERPs require' 10 'to precompute ICA topographies (see tutorial)']);\n                end\n            end\n        end\n    end;        \n    \n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_readtopo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.24294714136806148}}
{"text": "function recoverScenario(struct, idx_recover, mode, file_name)\n\n% Authors:       \n%       Salih Guemues   \n%       Alexander Wischnewski\n% Description:  \n%   function used to recalculate one simulation step to recover the\n%   specific QP definition of the (soft) TMPC\n% Inputs/parameters:\n%   struct:      Log file struct\n%   idx_recover: ID of the optimization problem which is plotted (debug_slow.tmpc_cnt)\n%   mode:        Choose 'DD' for data dictionary parameters or 'script' for setupTMPCstruct to\n%                   obtain the parameters\n%   file_name:   if given, store results in seperate .mat file for dedicated visualization purposes\n\n%% -------------------- HOW TO USE ---------------------------- %%\n% Run Simulink model controller_dev -> \n% execute convertSimLogs(logsout,'SimTest.mat'); ->\n% load data via data = load('SimTest.mat');  \n% call this script via recoverScenario(data, t_recover, mode) and specify t_recover and mode\n\n%% -------------------- DEFINE PARAMETERS ---------------------------- %%\n% maximum number of iterations (high to check whether online solution may not have converged)\nmax_iter = 1000;\n\n%% ---------------------- IMPORT CONTROLLER AND VEHICLE DATA ------------------------- %%\n% get access to dictionary with controller parameters\nsysDict = Simulink.data.dictionary.open('il_mvdc_mpc.sldd');\ndDataSectObj2 = getSection(sysDict,'Design Data');\nif(strcmp(mode, 'DD'))\n    % load controller parameters from data dictionary\n    sys = getValue(getEntry(dDataSectObj2,'sys'));\nelseif(strcmp(mode, 'script'))\n    % load controller parameters from initialize script\n    sys = setupTMPCStruct(false); \nelse\n    disp('No valid mode has been specified. Use DD or script');\nend\nhelp = getValue(getEntry(dDataSectObj2,'P_VDC_VirtualController'));\nP_VDC_VirtualController = help.Value;\nhelp = getValue(getEntry(dDataSectObj2,'P_VDC_PositiveAxLimScale'));\nP_VDC_PositiveAxLimScale = help.Value;\n\n% get access to dictionary with controller parameters\nvehDict = Simulink.data.dictionary.open('il_vehicleparameter.sldd');\ndDataSectObj3 = getSection(vehDict,'Design Data');\n% get some more vehicle parameters\ndrag_coefficient = getValue(getEntry(dDataSectObj3, 'drag_coefficient'));\nhelp = getValue(getEntry(dDataSectObj3,'roh_air'));\nroh_air = help.Value;\nvehiclemass_kg = getValue(getEntry(dDataSectObj3, 'vehiclemass_kg'));\n\n%% ------------ IMPORT TRAJECTORY, VEHICLE, PREDICTION DATA AND RECONSTRUCT SCENARIO --------------- %%\n% create TargetTrajectory struct and fill with logged data\nTargetTrajectory.LapCnt         = struct.debug_slow.debug_slow_tartraj_LapCnt.Data(idx_recover,:);\nTargetTrajectory.TrajCnt        = struct.debug_slow.debug_slow_tartraj_TrajCnt.Data(idx_recover,:);\nTargetTrajectory.PointIdx       = uint16(0); \nTargetTrajectory.s_loc_m        = struct.debug_slow.debug_slow_tartraj_s_loc_m.Data(idx_recover,:)'; \nTargetTrajectory.s_glob_m       = struct.debug_slow.debug_slow_tartraj_s_glob_m.Data(idx_recover,:)'; \nTargetTrajectory.x_m            = struct.debug_slow.debug_slow_tartraj_x_m.Data(idx_recover,:)'; \nTargetTrajectory.y_m            = struct.debug_slow.debug_slow_tartraj_y_m.Data(idx_recover,:)';\nTargetTrajectory.psi_rad        = struct.debug_slow.debug_slow_tartraj_psi_rad.Data(idx_recover,:)';\nTargetTrajectory.kappa_radpm    = struct.debug_slow.debug_slow_tartraj_kappa_radpm.Data(idx_recover,:)';\nTargetTrajectory.v_mps          = struct.debug_slow.debug_slow_tartraj_v_mps.Data(idx_recover,:)';\nTargetTrajectory.ax_mps2        = struct.debug_slow.debug_slow_tartraj_ax_mps2.Data(idx_recover,:)';\nTargetTrajectory.banking_rad    = struct.debug_slow.debug_slow_tartraj_banking_rad.Data(idx_recover,:)';\nTargetTrajectory.ax_lim_mps2    = struct.debug_slow.debug_slow_tartraj_ax_lim_mps2.Data(idx_recover,:)';\nTargetTrajectory.ay_lim_mps2    = struct.debug_slow.debug_slow_tartraj_ay_lim_mps2.Data(idx_recover,:)';\n\n% create VehicleDynamicState struct and fill with logged data\nVehicleDynamicState.Pos.x_m             = struct.debug_slow.debug_slow_x_real_m.Data(idx_recover,:);\nVehicleDynamicState.Pos.y_m             = struct.debug_slow.debug_slow_y_real_m.Data(idx_recover,:);\nVehicleDynamicState.Pos.psi_rad         = struct.debug_slow.debug_slow_psi_real_rad.Data(idx_recover,:);\nVehicleDynamicState.beta_rad            = struct.debug_slow.debug_slow_beta_real_rad.Data(idx_recover,:);\nVehicleDynamicState.v_mps               = struct.debug_slow.debug_slow_vx_real_mps.Data(idx_recover,:);\n          \nax_dist_mps2 = struct.debug_slow.debug_slow_ax_dist_mps2.Data(idx_recover, :)'; \nay_dist_mps2 = struct.debug_slow.debug_slow_ay_dist_mps2.Data(idx_recover, :)'; \n% recalculate uncertainty matrices\nUncertaintyTube = calcTubeShapeMatrices(sys.A_d, sys.B_d, P_VDC_VirtualController, sys.M_1, [ax_dist_mps2'; ay_dist_mps2'], sys.N_hor+1);\n[PathPos, ~] = localTrajectoryMatching(VehicleDynamicState, TargetTrajectory); \n% extract terminal set speed\nv_terminal_mps = struct.debug_slow.debug_slow_be_l_abs.Data(idx_recover, 1); \ndot_d_numerical = struct.debug_slow.debug_slow_dot_d_numerical_mps.Data(idx_recover, 1); \n\n% get predictions vx_pred, d_psi_pred, s_dot_pred\nx_pred_log       = struct.debug_slow.debug_slow_x_pred_m.Data(idx_recover, :)'; \ny_pred_log       = struct.debug_slow.debug_slow_y_pred_m.Data(idx_recover, :)'; \nvx_pred_log      = struct.debug_slow.debug_slow_vx_pred_mps.Data(idx_recover, :)'; \nd_pred_log       = struct.debug_slow.debug_slow_d_pred_m.Data(idx_recover, :)'; \ndot_d_pred_log   = struct.debug_slow.debug_slow_dot_d_pred_mps.Data(idx_recover, :)'; \nax_pred_log      = struct.debug_slow.debug_slow_ax_pred_mps2.Data(idx_recover, :)'; \nax_tire_pred_log = struct.debug_slow.debug_slow_ax_tire_pred_mps2.Data(idx_recover, :)'; \nay_pred_log      = struct.debug_slow.debug_slow_ay_pred_mps2.Data(idx_recover, :)'; \n\n% get linearization and target trajectory\nx_traj              = struct.debug_slow.debug_slow_x_traj_m.Data(idx_recover, :)'; \ny_traj              = struct.debug_slow.debug_slow_y_traj_m.Data(idx_recover, :)'; \npsi_traj            = struct.debug_slow.debug_slow_psi_traj_rad.Data(idx_recover, :)'; \nv_traj              = struct.debug_slow.debug_slow_v_traj_mps.Data(idx_recover, :)'; \nkappa_traj          = struct.debug_slow.debug_slow_kappa_traj_radpm.Data(idx_recover, :)'; \nax_diff_traj        = struct.debug_slow.debug_slow_ax_diff_traj_mps2m.Data(idx_recover, :)'; \nax_traj             = struct.debug_slow.debug_slow_ax_traj_mps2.Data(idx_recover, :)'; \nay_traj             = struct.debug_slow.debug_slow_ay_traj_mps2.Data(idx_recover, :)'; \nax_lim_mps2         = struct.debug_slow.debug_slow_ax_lim_mps2.Data(idx_recover, :)'; \nay_lim_mps2         = struct.debug_slow.debug_slow_ay_lim_mps2.Data(idx_recover, :)'; \nd_lim_ub_m          = struct.debug_slow.debug_slow_d_lim_ub_m.Data(idx_recover, :)'; \nd_lim_lb_m          = struct.debug_slow.debug_slow_d_lim_lb_m.Data(idx_recover, :)'; \nd_Target_m          = struct.debug_slow.debug_slow_d_Target_m.Data(idx_recover, :)'; \ndot_d_Target_mps    = struct.debug_slow.debug_slow_dot_d_Target_mps.Data(idx_recover, :)'; \nax_traj_old         = struct.debug_slow.debug_slow_ax_traj_mps2.Data(idx_recover-1, :)'; \nay_traj_old         = struct.debug_slow.debug_slow_ay_traj_mps2.Data(idx_recover-1, :)'; \nvx_lin_mps          = struct.debug_slow.debug_slow_vx_lin_mps.Data(idx_recover, :)'; \nkappa_lin_radpm     = struct.debug_slow.debug_slow_kappa_lin_radpm.Data(idx_recover, :)'; \nu_opt_total_sim     = struct.debug_slow.debug_slow_u_opt_total.Data(idx_recover, :)';\nu_opt_old_log       = struct.debug_slow.debug_slow_u_opt_total.Data(idx_recover-1, :)'; \n\n%% --------------------- SETUP INITIAL QP  ------------------------------ %% \n% Define problem data by reconstructing it using the sparsity pattern\n% init empty matrices\nP_help = zeros(sys.osqp_n, sys.osqp_n);\nA_help = zeros(sys.osqp_m, sys.osqp_n);\n% fill values according to sparsity pattern\nP_help(sys.P_i_lin) = sys.P_x_par;\n% NOTE THAT P IS STORED AS UPPER TRIANGULAR, however calculations require\n% FULL P MATRIX --> add transpose and substract diagonal elements\nP_help = P_help + P_help' - diag(diag(P_help));\nA_help(sys.A_i_lin) = sys.A_x_par;\nq = sys.osqp_qpar;\nl = sys.l_par;\nu = sys.u_par;\nP = sparse(P_help);\nA = sparse(A_help);\n% Create an OSQP object\nprob = osqp;\n% change settings\nsettings = prob.default_settings();\nsettings.alpha = 1.0;\nsettings.verbose = true;\nsettings.scaling = 0;  % number of scaling iterations\nsettings.max_iter = max_iter;\nsettings.warm_start = true; \nsettings.eps_abs = 1e-5;\nsettings.eps_rel = 1e-5;\n% Setup workspace, change alpha parameter and disable prints\nprob.setup(P, q, A, l, u, settings);\n\n%% ----------- CALL prepareOptimizationProblem TO RECOVER QP ----------------- %%\n[f, lb, ub, A_x, be_u_abs, be_l_abs, ~, error_state] =...\n    prepareOptimizationProblem(VehicleDynamicState, dot_d_numerical, PathPos, ...\n    v_traj, ax_diff_traj, ax_traj, ay_traj, ax_lim_mps2, ay_lim_mps2, ...\n    d_lim_ub_m, d_lim_lb_m, d_Target_m, dot_d_Target_mps, ...\n    vx_lin_mps, kappa_lin_radpm, UncertaintyTube, v_terminal_mps, ...\n    ax_traj_old, ay_traj_old, u_opt_old_log, ...\n    sys, P_VDC_VirtualController, drag_coefficient, roh_air, vehiclemass_kg, ...\n    P_VDC_PositiveAxLimScale, true, 0.9);\n\n%% --------------------- UPDATE AND SOLVE QP  ------------------------------ %% \n% update QP vectors\nprob.update('q', f, 'l', lb, 'u', ub);\nprob.update('Ax', A_x);\n% solve problem and get solution. two runs necessary to replicate warm start behavior of online\n% solution while running the car.\nres = prob.solve();\nu_opt_total = res.x;\n% meaning of status as in https://osqp.org/docs/interfaces/status_values.html\nstatus = res.info.status_val; \n\n% debug output\ndisp(['The problem has been solved during reoptimization with status: ' num2str(status)]); \ndisp(['It took ' num2str(res.info.iter) ' iterations and ' num2str(res.info.solve_time) ' seconds']); \n\n%% ----------- CALL transformMPCResult TO RECOVER OPTIMIZED TRAJ. AND PREDICTIONS ----------------- %%\n[u_opt_total, x_pred, y_pred, x_pred_left, y_pred_left, x_pred_right, y_pred_right, ...\n    vx_pred, d_pred, dot_d_pred, ~, ax_pred, ax_tire_pred, ay_pred, ~, ~]  ...\n    = transformMPCResult(status, u_opt_total, error_state,...\n    x_traj, y_traj, psi_traj, v_traj, ax_diff_traj, d_Target_m, ax_lim_mps2, ay_lim_mps2, ...\n    vx_lin_mps, kappa_lin_radpm, UncertaintyTube, ...\n    sys, drag_coefficient, roh_air, vehiclemass_kg, P_VDC_PositiveAxLimScale);\n\n%% plotting of optimization problem result\n\n% recalculate tubes\n[lb_v, ub_v] = calcBoundsPlot(zeros(sys.N_hor, 1), UncertaintyTube, false, P_VDC_VirtualController, sys.N_hor, repmat([1; 0; 0], 1, sys.N_hor));\n[lb_d, ub_d] = calcBoundsPlot(zeros(sys.N_hor, 1), UncertaintyTube, false, P_VDC_VirtualController, sys.N_hor, repmat([0; 1; 0], 1, sys.N_hor));\n[lb_dot_d, ub_dot_d] = calcBoundsPlot(zeros(sys.N_hor, 1), UncertaintyTube, false, P_VDC_VirtualController, sys.N_hor, repmat([0; 0; 1], 1, sys.N_hor));\n[~, ub_tire1] = calcBoundsPlot(zeros(sys.N_hor+1, 1), UncertaintyTube, true, ...\n    P_VDC_VirtualController, sys.N_hor+1, [1./(P_VDC_PositiveAxLimScale*ax_lim_mps2), 1./ay_lim_mps2]');\n[~, ub_tire2] = calcBoundsPlot(zeros(sys.N_hor+1, 1), UncertaintyTube, true, ...\n    P_VDC_VirtualController, sys.N_hor+1, [1./ax_lim_mps2, 1./ay_lim_mps2]');\n[~, ub_tire3] = calcBoundsPlot(zeros(sys.N_hor+1, 1), UncertaintyTube, true, ...\n    P_VDC_VirtualController, sys.N_hor+1, [-1./ax_lim_mps2, 1./ay_lim_mps2]');\n[~, ub_tire4] = calcBoundsPlot(zeros(sys.N_hor+1, 1), UncertaintyTube, true, ...\n    P_VDC_VirtualController, sys.N_hor+1, [-1./(P_VDC_PositiveAxLimScale*ax_lim_mps2), 1./ay_lim_mps2]');\n\n% calculate limits for ax depending on positive accelerations \nidx_pos = ax_traj > 0;\nax_lim_mps2_traj = ax_lim_mps2; \nax_lim_mps2_traj(idx_pos) = P_VDC_PositiveAxLimScale*ax_lim_mps2(idx_pos)'; \nidx_pos = ax_tire_pred > 0; \nax_lim_mps2_pred = ax_lim_mps2; \nax_lim_mps2_pred(idx_pos) = P_VDC_PositiveAxLimScale*ax_lim_mps2(idx_pos)'; \nidx_pos = ax_tire_pred_log > 0; \nax_lim_mps2_pred_log = ax_lim_mps2; \nax_lim_mps2_pred_log(idx_pos) = P_VDC_PositiveAxLimScale*ax_lim_mps2(idx_pos)' ;\n\nfigure; \ngrid on; hold on; \nplot(x_traj, y_traj); \nplot(x_pred, y_pred);\nplot(x_pred_log, y_pred_log, '*'); \nplot(x_pred_left, y_pred_left, 'k--'); \nplot(x_pred_right, y_pred_right, 'k--', 'HandleVisibility','off'); \ngrid on; axis equal; \nlegend('Target', 'Optimized', 'Logged', 'Tube'); \nxlabel('x East in m'); \nylabel('y North in m'); \n\n% compare target and reoptimized trajectory\nfigure; \nax11 = subplot(2, 2, 1); \ngrid on; hold on; \nplot(v_traj); \nplot(vx_pred); \nplot(vx_pred_log, '*'); \nplot(vx_pred(1:sys.N_hor) + ub_v', 'k--'); \nplot(vx_pred(1:sys.N_hor) + lb_v', 'k--', 'HandleVisibility','off'); \nplot([sys.N_hor+1, sys.N_hor+3], [be_u_abs(1), be_u_abs(1)], 'k'); \nplot([sys.N_hor+1, sys.N_hor+3], [be_l_abs(1), be_l_abs(1)], 'k', 'HandleVisibility','off'); \nplot(vx_lin_mps); \nxlabel('Discretization points'); \nylabel('Velocity in mps'); \nlegend('Target', 'Optimized', 'Logged', 'Tube', 'Terminal Set', 'Linearization'); \n\nax12 = subplot(2, 2, 2); \ngrid on; hold on; \nplot(ax_traj./ax_lim_mps2_traj + kappa_traj.*v_traj.^2./ay_lim_mps2); \nplot(ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2); \nplot(ax_tire_pred_log./ax_lim_mps2_pred_log + ay_pred_log./ay_lim_mps2, '*'); \nplot(ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2 + ub_tire1', 'k--'); \nplot(ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2 - ub_tire2', 'k--', 'HandleVisibility','off'); \nplot([0, sys.N_hor], [1, 1], 'k'); \nplot([0, sys.N_hor], [-1, -1], 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Acceleration constraint normalized'); \nlegend('Target', 'Optimized', 'Logged', 'Tube', 'Limit'); \n\nax13 = subplot(2, 2, 3); \ngrid on; hold on; \nplot(d_Target_m)\nplot(d_pred);  \nplot(d_pred_log, '*'); \nplot(d_pred(1:sys.N_hor) + ub_d', 'k--'); \nplot(d_pred(1:sys.N_hor) + lb_d', 'k--', 'HandleVisibility','off'); \nplot(d_lim_ub_m, 'k'); \nplot(d_lim_lb_m, 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Lateral deviation in m'); \nlegend('Target', 'Optimized', 'Logged', 'Tube', 'Limit'); \n\nax14 = subplot(2, 2, 4); \ngrid on; hold on; \nplot(-ax_traj./ax_lim_mps2 + kappa_traj.*v_traj.^2./ay_lim_mps2); \nplot(-ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2); \nplot(-ax_tire_pred_log./ax_lim_mps2_pred_log + ay_pred_log./ay_lim_mps2, '*'); \nplot(-ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2 - ub_tire3', 'k--'); \nplot(-ax_tire_pred./ax_lim_mps2_pred + ay_pred./ay_lim_mps2 + ub_tire4', 'k--', 'HandleVisibility','off'); \nplot([0, sys.N_hor], [1, 1], 'k'); \nplot([0, sys.N_hor], [-1, -1], 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Acceleration constraint normalized');\nlegend('Target', 'Optimized', 'Logged', 'Tube', 'Limit'); \n\nlinkaxes([ax11, ax12, ax13, ax14], 'x'); \n\nfigure; \nax21 = subplot(2, 3, 1); \ngrid on; hold on; \nplot(ax_traj); \nplot(ax_pred); \nplot(ax_pred_log, '*'); \nplot(-u_opt_total(1:2:2*(sys.N_hor+1))); \nplot(ax_lim_mps2, 'k'); \nplot(-ax_lim_mps2, 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Acceleration x in mps2'); \nlegend('Target', 'Optimized', 'Logged', 'delta ax', 'Limit'); \n\nax22 = subplot(2, 3, 2); \ngrid on; hold on; \nplot(kappa_traj.*v_traj.^2); \nplot(ay_pred); \nplot(ay_pred_log, '*'); \nplot(u_opt_total(2:2:2*(sys.N_hor+1))); \nplot(ay_lim_mps2, 'k'); \nplot(-ay_lim_mps2, 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Acceleration y in mps2'); \nlegend('Target', 'Optimized', 'Logged', 'delta ay', 'Limit'); \n\nax23 = subplot(2, 3, 3); \ngrid on; hold on; \nplot(dot_d_Target_mps)\nplot(dot_d_pred);  \nplot(dot_d_pred_log, '*'); \nplot(dot_d_pred_log(1:sys.N_hor) + ub_dot_d', 'k--'); \nplot(dot_d_pred_log(1:sys.N_hor) + lb_dot_d', 'k--', 'HandleVisibility','off'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Lateral deviation derivative in mps'); \nlegend('Target', 'Optimized', 'Logged', 'Tube'); \n\nax26 = subplot(2, 3, 4); \ngrid on; hold on; \nplot(u_opt_total(2*(sys.N_hor+1)+3:sys.n_slacks:end), 'b'); \nplot(u_opt_total_sim(2*(sys.N_hor+1)+3:sys.n_slacks:end), 'b*'); \nplot(u_opt_total(2*(sys.N_hor+1)+4:sys.n_slacks:end), 'c'); \nplot(u_opt_total_sim(2*(sys.N_hor+1)+4:sys.n_slacks:end), 'c*'); \nplot([0, sys.N_hor], [0, 0], 'k'); \nplot([0, sys.N_hor], [1.5, 1.5]/2, 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Slacks lateral'); \nlegend('Optimized upper', 'Logged upper', 'Optimized lower', 'Optimized lower', 'Limit'); \n\nax27 = subplot(2, 3, 5); \ngrid on; hold on; \nplot(u_opt_total(2*(sys.N_hor+1)+1:sys.n_slacks:end)); \nplot(u_opt_total_sim(2*(sys.N_hor+1)+1:sys.n_slacks:end), '*'); \nplot([0, sys.N_hor], [0, 0], 'k'); \nplot([0, sys.N_hor], [sys.slack_lim_rel, sys.slack_lim_rel], 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Slacks tire 1 lower'); \nlegend('Optimized upper', 'Logged', 'Limit'); \n\nax28 = subplot(2, 3, 6); \ngrid on; hold on; \nplot(u_opt_total(2*(sys.N_hor+1)+2:sys.n_slacks:end)); \nplot(u_opt_total_sim(2*(sys.N_hor+1)+2:sys.n_slacks:end), '*'); \nplot([0, sys.N_hor], [0, 0], 'k'); \nplot([0, sys.N_hor], [sys.slack_lim_rel, sys.slack_lim_rel], 'k'); \ngrid on; \nxlabel('Discretization points'); \nylabel('Slacks tire 2 lower'); \nlegend('Optimized', 'Logged', 'Limit'); \n\nlinkaxes([ax21, ax22, ax23, ax26, ax27, ax28], 'x'); \n\n%% store data in external file for further visualization\nif nargin > 3\n    save(file_name); \nend\n\nend\n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/control/scripts/recoverScenario.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24284860841756686}}
{"text": "function b = ContrastChange(img,level)\n\nimg = im2double(img)*255;\nimg= img*level;\nb = uint8(img);\nend", "meta": {"author": "xialeiliu", "repo": "RankIQA", "sha": "22ca65cd0156b5b428cecd55ed939366fb64d2e5", "save_path": "github-repos/MATLAB/xialeiliu-RankIQA", "path": "github-repos/MATLAB/xialeiliu-RankIQA/RankIQA-22ca65cd0156b5b428cecd55ed939366fb64d2e5/data/rank_tid2013/ContrastChange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2428486031636223}}
{"text": "function [mimgR,mimgG] = regRedGreenChannel(ops)\n\n% numPlanes = length(ops.planesToProcess);\n\n% build file list with red channel\n\nif (isfield(ops, 'SubDirsRed') && ~isempty(ops.SubDirsRed))\n    subDirsRed = ops.SubDirsRed;\nelse\n    if (isfield(ops, 'expred') && ~isempty(ops.expred))\n        for i = 1:length(ops.expred)\n            subDirsRed{i} = sprintf('%d', ops.expred(i));\n        end\n    else\n        warning('could not find red channel info, returning...')\n        return;\n    end\nend\n%\n% build file list\nfor i = 1:length(ops.expred)\n    fsRED = dir(fullfile(ops.RootDir, subDirsRed{i}, '*.tif'));\n    for k = 1:length(fsRED)\n        fsRED(k).name = fullfile(ops.RootDir, subDirsRed{i}, fsRED(k).name);\n    end\nend\n\nroot = ops.ResultsSavePath;\nfregops =  sprintf('regops_%s_%s.mat', ops.mouse_name, ops.date);\nif exist(fullfile(root, fregops), 'file')\n    load(fullfile(root, fregops))\nelse\n    ops1 = cell(ops.nplanes, 1);\n    for j = 1:ops.nplanes\n        \n        fname = sprintf('regops_%s_%s_plane%d.mat', ops.mouse_name, ops.date, j);\n        dat = load(fullfile(root, fname));\n        ops1{j} = dat.ops;\n        ops1{j}.useGPU = ops.useGPU;\n    end\nend\n\n%\nntf0 = 0;\nnumPlanes = ops.nplanes;\n%iplane0 = 1:1:ops.nplanes;\n\ntotFrames=0;\nfor k = 1:length(fsRED)\n    %iplane0 = mod(iplane0-1, numPlanes) + 1;\n    startPlane=((mod(totFrames+1,ops.nplanes*2)-1)/2)+1;\n    \n    nFr = nFramesTiff(fsRED(k).name);\n    totFrames=totFrames+nFr;\n    data = loadFramesBuff(fsRED(k).name, 1, nFr, 1, ops.temp_tiff);\n    \n    if ~exist('mimgR', 'var')\n        [Ly, Lx, ~] = size(data);\n        mimgR = zeros(Ly, Lx, ops.nplanes);\n    end\n    if ~exist('mimgG', 'var')\n        [Ly, Lx, ~] = size(data);\n        mimgG = zeros(Ly, Lx, ops.nplanes);\n    end\n    %\n    \n    \n    for iPlane=1:ops.nplanes\n      \n        idx0=mod((ops.nplanes-startPlane+iPlane)*2,ops.nplanes*2);\n        planesG=(idx0+1):(2*ops.nplanes):nFr;\n        planesR=(idx0+2):(2*ops.nplanes):nFr;\n        dataG0=data(:,:,planesG);\n        dataR0=data(:,:,planesR);\n        \n        BiDiPhase = ops1{iPlane}.BiDiPhase;\n        if abs(BiDiPhase) > 0\n            yrange = 2:2:Ly;\n            if BiDiPhase>0\n                dataG0(yrange,(1+BiDiPhase):Lx,:,:) = dataG0(yrange, 1:(Lx-BiDiPhase),:,:);\n                dataR0(yrange,(1+BiDiPhase):Lx,:,:) = dataR0(yrange, 1:(Lx-BiDiPhase),:,:);\n            else\n                dataG0(yrange,1:Lx+BiDiPhase,:,:)   = dataG0(yrange, 1-BiDiPhase:Lx,:,:);\n                dataR0(yrange,1:Lx+BiDiPhase,:,:)   = dataR0(yrange, 1-BiDiPhase:Lx,:,:);\n            end\n        end\n        \n        [ds, ~]  = regoffKriging(dataG0, ops1{iPlane}, 0);\n        %[ds, ~]  = registration_offsets(dataG0, ops1{iPlane}, 0);\n        \n        if k==1\n            ds(1,:) = 0;\n        end\n        dataR       = ...\n            register_movie(dataR0, ops1{iPlane}, ds);\n        dataG     = ...\n            register_movie(dataG0, ops1{iPlane}, ds);\n        \n        \n        mimgR(:,:,iPlane) = mimgR(:,:,iPlane) + mean(dataR, 3);\n        mimgG(:,:,iPlane) = mimgG(:,:,iPlane) + mean(dataG, 3);\n        \n    end\n    \n    ntf0 = ntf0 + 1;\n    \n    %iplane0 = iplane0 - nFr/ops.nchannels_red;\n    fprintf('processing tiff %d/%d\\n',k,length(fsRED))\nend\n\nmimgR = mimgR/ntf0;\nmimgG = mimgG/ntf0;", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/redChannel/regRedGreenChannel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24283530889206978}}
{"text": "classdef PTKVentilationMask < PTKPlugin\n    % PTKVentilationMask. Plugin for segmenting ventilation values from\n    %     hyperpolarised gas MRI\n    %\n    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using \n    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.\n    %     See PTKPlugin.m for more information on how to run plugins.\n    %\n    %     Plugins should not be run directly from your code.\n    %\n    %\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n    %     Author: Tom Doel, 2012.  www.tomdoel.com\n    %     Distributed under the GNU GPL v3 licence. Please see website for details.\n    %    \n    \n    properties\n        ButtonText = 'Ventilation <BR>Mask'\n        ToolTip = ''\n        Category = 'Lungs'\n\n        AllowResultsToBeCached = true\n        AlwaysRunPlugin = false\n        PluginType = 'ReplaceOverlay'\n        HidePluginInDisplay = false\n        FlattenPreviewImage = true\n        PTKVersion = '1'\n        ButtonWidth = 6\n        ButtonHeight = 2\n        GeneratePreview = true\n        Visibility = 'Developer'\n    end\n    \n    methods (Static)\n        function results = RunPlugin(dataset, reporting)\n            original_image = dataset.GetResult('PTKOriginalImage');\n            noise_roi = original_image.RawImage(1, 20:220, 10:60); % Kaushik et al\n            roi = dataset.GetResult('PTKLungROI');\n            std_noise = std(double(noise_roi(:)));\n            mean_signal = mean(double(noise_roi(:)));\n            threshold = mean_signal + 2*std_noise;\n            \n            threshold_image = logical(roi.RawImage >= threshold);\n            results = roi.BlankCopy;\n            results.ChangeRawImage(threshold_image);\n            \n            results.BinaryMorph(@imopen, 6);\n            \n            results.ChangeRawImage(3*uint8(results.RawImage));\n            \n            results.ImageType = PTKImageType.Colormap;\n        end\n    end\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Plugins/Registration/PTKVentilationMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.24278293208538607}}
{"text": "% =========================================================================\n% =========================================================================\n% ================================CHESS=================================\n% =========================================================================\n% =========================================================================\n% \n% Author:\n%   Muhammad Suleman Shafqat\n%   Started on:     19Jan, 2011 (1200hrs)\n%   Completed on:   20Jan, 2011 (1130hrs)\n% \n% Version:\n%   01\n% \n% ---Functions---------Used for\n%   Chess               main function\n%   playerturn          player's turn\n%   checkfp             check final position, it checks position and kills\n%   wholoses            to check who loses and if no body return (loses=0)\n%   reqmark             converts black to white backgrounds if necessary\n%   whichpiece          reads the selected piece and converts it from icon to integer\n% \n% ---Structures----------Used for \n% \n%   h                   structure for varialbes\n%   ha                  global for components of GUI\n% \n% ---Variables----------Used for \n% \n%   box                 to represent position of pieces\n%   ipr                 initial position in row\n%   ipc                 initial position in column\n%   fpr                 final position in row\n%   fpc                 final position in column\n%   r                   row number of selected button \n%   c                   column number of selected button\n%   background            to upload a background of board\n%   bg                  background image is uploaded here\n%   plrmark             an axis to show whose turn is this\n%   check               binary variable to check whether a turn is correct or not\n%   loses               checked after each turn, whether anybody loses or not\n%   plr                 player who needs to turn\n%   otherplr            other player\n%   ed                  eventdata\n% =========================================================================\n\n% simple chess:\n%       started on 19/1/2011 at 1200hrs\n%       ended on 20/1/2011 at 1130hrs\n% changing into symbols:\n%       started on 28/1/2011 and completed by 1230hrs\nfunction varargout = CHESS_on_MATLAB(varargin)\n% CHESS M-file for CHESS.fig\n% Last Modified by GUIDE v2.5 28-Jan-2011 12:16:36\n% Begin initialization code\ngui_Singleton = 1;\ngui_State = struct('gui_Name',       mfilename, ...\n                   'gui_Singleton',  gui_Singleton, ...\n                   'gui_OpeningFcn', @CHESS_OpeningFcn, ...\n                   'gui_OutputFcn',  @CHESS_OutputFcn, ...\n                   'gui_LayoutFcn',  [] , ...\n                   'gui_Callback',   []);\nif nargin && ischar(varargin{1})\n    gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n    gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code\n\n% --- Executes just before CHESS is made visible.\nfunction CHESS_OpeningFcn(hObj, ed, h, varargin)\n% Choose default command line output for CHESS\nh.output = hObj;\nglobal ha\nclc\n% initialization gui components\nha(1)  = h.plrturn;\nha(11) = h.box11;ha(12) = h.box12;ha(13) = h.box13;ha(14) = h.box14;\nha(15) = h.box15;ha(16) = h.box16;ha(17) = h.box17;ha(18) = h.box18;\nha(21) = h.box21;ha(22) = h.box22;ha(23) = h.box23;ha(24) = h.box24;\nha(25) = h.box25;ha(26) = h.box26;ha(27) = h.box27;ha(28) = h.box28;\nha(31) = h.box31;ha(32) = h.box32;ha(33) = h.box33;ha(34) = h.box34;\nha(35) = h.box35;ha(36) = h.box36;ha(37) = h.box37;ha(38) = h.box38;\nha(41) = h.box41;ha(42) = h.box42;ha(43) = h.box43;ha(44) = h.box44;\nha(45) = h.box45;ha(46) = h.box46;ha(47) = h.box47;ha(48) = h.box48;\nha(51) = h.box51;ha(52) = h.box52;ha(53) = h.box53;ha(54) = h.box54;\nha(55) = h.box55;ha(56) = h.box56;ha(57) = h.box57;ha(58) = h.box58;\nha(61) = h.box61;ha(62) = h.box62;ha(63) = h.box63;ha(64) = h.box64;\nha(65) = h.box65;ha(66) = h.box66;ha(67) = h.box67;ha(68) = h.box68;\nha(71) = h.box71;ha(72) = h.box72;ha(73) = h.box73;ha(74) = h.box74;\nha(75) = h.box75;ha(76) = h.box76;ha(77) = h.box77;ha(78) = h.box78;\nha(81) = h.box81;ha(82) = h.box82;ha(83) = h.box83;ha(84) = h.box84;\nha(85) = h.box85;ha(86) = h.box86;ha(87) = h.box87;ha(88) = h.box88;\n\n%uploading symbols of chess pieces to structure 'h'\nh.blackpawn1=imread(strcat('pieces\\blackpawn1','.png'));\nh.blackpawn2=imread(strcat('pieces\\blackpawn2','.png'));\nh.whitepawn1=imread(strcat('pieces\\whitepawn1','.png'));\nh.whitepawn2=imread(strcat('pieces\\whitepawn2','.png'));\nh.blackrook1=imread(strcat('pieces\\blackrook1','.png'));\nh.blackrook2=imread(strcat('pieces\\blackrook2','.png'));\nh.whiterook1=imread(strcat('pieces\\whiterook1','.png'));\nh.whiterook2=imread(strcat('pieces\\whiterook2','.png'));\nh.blackbishop1=imread(strcat('pieces\\blackbishop1','.png'));\nh.blackbishop2=imread(strcat('pieces\\blackbishop2','.png'));\nh.whitebishop1=imread(strcat('pieces\\whitebishop1','.png'));\nh.whitebishop2=imread(strcat('pieces\\whitebishop2','.png'));\nh.blackknight1=imread(strcat('pieces\\blackknight1','.png'));\nh.blackknight2=imread(strcat('pieces\\blackknight2','.png'));\nh.whiteknight1=imread(strcat('pieces\\whiteknight1','.png'));\nh.whiteknight2=imread(strcat('pieces\\whiteknight2','.png'));\nh.blackqueen1=imread(strcat('pieces\\blackqueen1','.png'));\nh.blackqueen2=imread(strcat('pieces\\blackqueen2','.png'));\nh.whitequeen1=imread(strcat('pieces\\whitequeen1','.png'));\nh.whitequeen2=imread(strcat('pieces\\whitequeen2','.png'));\nh.blackking1=imread(strcat('pieces\\blackking1','.png'));\nh.blackking2=imread(strcat('pieces\\blackking2','.png'));\nh.whiteking1=imread(strcat('pieces\\whiteking1','.png'));\nh.whiteking2=imread(strcat('pieces\\whiteking2','.png'));\nh.black=imread(strcat('pieces\\black','.png'));\nh.white=imread(strcat('pieces\\white','.png'));\n% deletion of extra rows and colomns\nh.blackpawn1(:,60,:)=[];\nh.blackpawn2(:,60,:)=[];\nh.whitepawn2(:,60,:)=[];\nh.blackrook1(:,60,:)=[];\nh.blackrook2(:,60,:)=[];\nh.whiterook1(:,60,:)=[];\nh.whiterook2(:,60,:)=[];\nh.blackbishop1(:,60,:)=[];\nh.blackbishop2(:,60,:)=[];\nh.whitebishop1(:,60,:)=[];\nh.whitebishop2(:,60,:)=[];\nh.blackknight2(:,60,:)=[];\nh.whiteknight2(:,60,:)=[];\nh.whitequeen2(:,60,:)=[];\nh.black(:,60,:)=[];\nh.blackrook1(60,:,:)=[];\nh.blackrook2(60,:,:)=[];\nh.whiterook1(60,:,:)=[];\nh.whiterook2(60,:,:)=[];\nh.blackbishop1(60,:,:)=[];\nh.blackbishop2(60,:,:)=[];\nh.whitebishop1(60,:,:)=[];\nh.whitebishop2(60,:,:)=[];\nh.blackknight1(60,:,:)=[];\nh.blackknight2(60,:,:)=[];\nh.whiteknight1(60,:,:)=[];\nh.whiteknight2(60,:,:)=[];\nh.blackqueen1(60,:,:)=[];\nh.whitequeen2(60,:,:)=[];\nh.blackking1(60,:,:)=[];\nh.blackking2(60,:,:)=[];\nh.whiteking1(60,:,:)=[];\nh.whiteking2(60,:,:)=[];\nh.black(60,:,:)=[];\nh.white(60,:,:)=[];\n\n% initializing box;  8x8 box\n% rook=2\n% horse=3\n% bishop=4\n% queen=5\n% king=10\n% pawn=1\nh.box=[ ...\n    2  3  4  5  10 4  3  2 ; ...\n    1  1  1  1  1  1  1  1 ; ...\n    0  0  0  0  0  0  0  0  ; ...\n    0  0  0  0  0  0  0  0  ; ...\n    0  0  0  0  0  0  0  0  ; ...\n    0  0  0  0  0  0  0  0  ; ...\n    -1 -1 -1 -1 -1 -1 -1 -1 ; ...\n    -2 -3 -4 -5 -10 -4 -3 -2  ];\n% position variables\nh.ipr=0;\nh.ipc=0;\nh.fpr=0;\nh.fpc=0;\nh.r=0;\nh.c=0;\n% showing whose turn......initially player one's turn it can be changed\nh.plr=1;\nset(ha(1),'CData',h.blackking2);\ni=2;\n% now initializing figure with player marks\nfor x=1:8\n    for y=1:8\n% required when to convert pieces from numbers to uploaded symbols\n        if h.box(x,y)==1\n            if i==1\n                mark=h.blackpawn1;\n                i=2;\n            elseif i==2\n                mark=h.blackpawn2;\n                i=1;\n            end\n        elseif h.box(x,y)==-1\n            if i==1\n                mark=h.whitepawn1;\n                i=2;\n            elseif i==2\n                mark=h.whitepawn2;\n                i=1;\n            end\n        elseif h.box(x,y)==2\n            if i==1\n                mark=h.blackrook1;\n                i=2;\n            elseif i==2\n                mark=h.blackrook2;\n                i=1;\n            end\n        elseif h.box(x,y)==-2\n            if i==1\n                mark=h.whiterook1;\n                i=2;\n            elseif i==2\n                mark=h.whiterook2;\n                i=1;\n            end\n        elseif h.box(x,y)==3\n            if i==1\n                mark=h.blackknight1;\n                i=2;\n            elseif i==2\n                mark=h.blackknight2;\n                i=1;\n            end\n        elseif h.box(x,y)==-3\n            if i==1\n                mark=h.whiteknight1;\n                i=2;\n            elseif i==2\n                mark=h.whiteknight2;\n                i=1;\n            end\n        elseif h.box(x,y)==4\n            if i==1\n                mark=h.blackbishop1;\n                i=2;\n            elseif i==2\n                mark=h.blackbishop2;\n                i=1;\n            end\n        elseif h.box(x,y)==-4\n            if i==1\n                mark=h.whitebishop1;\n                i=2;\n            elseif i==2\n                mark=h.whitebishop2;\n                i=1;\n            end\n        elseif h.box(x,y)==5\n            if i==1\n                mark=h.blackqueen1;\n                i=2;\n            elseif i==2\n                mark=h.blackqueen2;\n                i=1;\n            end\n        elseif h.box(x,y)==-5\n            if i==1\n                mark=h.whitequeen1;\n                i=2;\n            elseif i==2\n                mark=h.whitequeen2;\n                i=1;\n            end\n        elseif h.box(x,y)==10\n            if i==1\n                mark=h.blackking1;\n                i=2;\n            elseif i==2\n                mark=h.blackking2;\n                i=1;\n            end\n        elseif h.box(x,y)==-10\n            if i==1\n                mark=h.whiteking1;\n                i=2;\n            elseif i==2\n                mark=h.whiteking2;\n                i=1;\n            end\n        else\n            if i==1\n                mark=h.black;\n                i=2;\n            elseif i==2\n                mark=h.white;\n                i=1;\n            end\n        end\n        rc=x*10+y;\n        set(ha(rc),'CData',mark);\n    end\n%     first row starting from white next row starting from black\n    if i==1\n        i=2;\n    else i=1;\n    end\n\nend\n%set(CHESS,'Visible','on')\n% Update h structure\nguidata(hObj, h);\n\nfunction varargout = CHESS_OutputFcn(hObj, ed, h) \n% Get default command line output from h structure\nvarargout{1} = h.output;\n\n% --- Executes on button press in exit.\nfunction exit_Callback(hObj, ed, h)\n% used to close the game anytime\nclose(gcbf)\n\n% --- Executes during object creation, after setting all properties.\nfunction plrturn_CreateFcn(hObj, ed, h)\nif ispc && isequal(get(hObj,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n    set(hObj,'BackgroundColor','white');\nend\n\n% --- Executes on button press in concede.\nfunction concede_Callback(hObj, ed, h)\nif h.plr==2\n    msgbox('CHESS KING','Winner','custom',h.blackking2)\nelseif h.plr==1\n    msgbox('CHESS KING','Winner','custom',h.whiteking1)\nend\nclose(gcbf);\n\nfunction box11_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box12_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box13_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box14_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box15_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box16_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box17_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box18_Callback(hObj, ed, h)\nglobal ha\nh.r=1;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box21_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box22_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box23_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box24_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box25_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box26_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box27_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box28_Callback(hObj, ed, h)\nglobal ha\nh.r=2;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box31_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box32_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box33_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box34_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box35_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box36_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box37_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box38_Callback(hObj, ed, h)\nglobal ha\nh.r=3;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box41_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box42_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box43_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box44_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box45_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box46_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box47_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box48_Callback(hObj, ed, h)\nglobal ha\nh.r=4;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box51_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box52_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box53_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box54_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box55_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box56_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box57_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box58_Callback(hObj, ed, h)\nglobal ha\nh.r=5;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box61_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box62_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box63_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box64_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box65_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box66_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box67_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box68_Callback(hObj, ed, h)\nglobal ha\nh.r=6;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box71_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box72_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box73_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box74_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box75_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box76_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box77_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box78_Callback(hObj, ed, h)\nglobal ha\nh.r=7;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box81_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=1;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box82_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=2;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box83_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=3;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box84_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=4;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box85_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=5;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box86_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=6;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box87_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=7;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\nfunction box88_Callback(hObj, ed, h)\nglobal ha\nh.r=8;h.c=8;\nh=playerturn(ha,h);\nguidata(hObj,h);\n\n% ================================================================\n% ================================================================\n% ================================================================\n% ================================================================\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30594-chess-master/Chess Master/CHESS_on_MATLAB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24276019912445282}}
{"text": "\nfunction [IM_result]=display_clust_image(IM,input_mask,fig)\n% [IMseg]=display_clust_image(IM,input_mask,fig)\n% display image segmentation results:\n% input :\n%          IM = input image\n%          input_mask = segmentation mask\n%          fig = matlab figure number for display\n%\n%  output:\n%          IMseg = image with segments marked by different colors\n%\n%\n\n\nif( nargin < 3 )\n   fig = 0;\nend\n\n[height,width,colors] = size(IM);\nsegNum = max(max(input_mask));\n\nif( size(IM,3) == 1 )\n    IM = cat(3,IM,IM,IM);\nend\n\nmap = [0 0 255; 150 0 255; 255 0 255; 255 0 0; 0 255 255; 0 255 87; 255 255 0; ...\n        255 140 0; 128 0 0; 0 0 140; 255 196 125; 170 107 68]/255;\nif( size(map,1)<segNum )\n    map = hsv(segNum);\nend\nmap_yiq = rgb2ntsc(map);\n\nYIQ = rgb2ntsc(IM);\nY = YIQ(:,:,1);\nI = YIQ(:,:,2);\nQ = YIQ(:,:,3);\nIM_result = ntsc2rgb(cat(3,Y,I,Q));\n\n\nfor i=1:segNum,\n    mask = zeros(height,width);\n    ind = find(input_mask==i);\n    mask(ind) = 1;\n    mask = medfilt2(mask);\n    mask = medfilt2(mask);\n    mask = medfilt2(mask);\n    ind = find(mask);\n    %%% mark segment boundary in white\n    E = edge(mask);\n    se = strel('disk',2);\n    E = imdilate(E,se,'same');\n    ind = find(E);\n    %%% white\n    Y(ind) = 1;\n    I(ind) = 0;\n    Q(ind) = 0;\n    %%% green\n    Y(ind) = 0.587;\n    I(ind) = -0.2744;\n    Q(ind) = -0.5299;   \n    %%% red\n    Y(ind) = 0.2989;\n    I(ind) = 0.5959;\n    Q(ind) = 0.2115;\nend\nIM_result = ntsc2rgb(cat(3,Y,I,Q));\nif( fig>0 )\n    figure(fig);\n    clf;\n    imshow(IM_result);\nend\n\n\n\n \n \n ", "meta": {"author": "jwyang", "repo": "JULE.torch", "sha": "69bdfd82f9dfd431619a8ee25ac832da76a827e2", "save_path": "github-repos/MATLAB/jwyang-JULE.torch", "path": "github-repos/MATLAB/jwyang-JULE.torch/JULE.torch-69bdfd82f9dfd431619a8ee25ac832da76a827e2/matlab/approaches/sc-st/ZPclustering/display_clust_image_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24276019912445276}}
{"text": "% This is a stub with an example of how to attach voxel data, which will\n% trigger the calculation of derivatives (region averages)\n% This function will likely not be necessary, as the functions can be accomplished\n% with listeners - this is an example really.\n\n% img = fmri_data('/Users/torwager/Downloads/smoothed_residual.nii.gz')\n% b = brainpathway();\n\n% Resample image space of data to the atlas space\n% (We don't want to do it the other way around, because it will make it\n% difficult to have a consistent atlas definition and aggregate across\n% different datasets)\n\nimg_resampled = resample_space(img, b.region_atlas);\n\n% Assign the resampled data to the brainpathway object\n% This triggers several steps:\n% Updating node and region averages, and node and region connectivity\nb.voxel_dat = img_resampled.dat;\n\n% Plot the inter-region connectivity\n% plot_connectivity(b);\n\n% Load a different atlas instead, with a different parcellation:\n% This triggers updates of the regions and region connectivity\nb.region_atlas = load_atlas('yeo17networks');\n\nb = brainpathway(load_atlas('yeo17networks'));\nb.voxel_dat = img_resampled.dat;\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@brainpathway/attach_voxel_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.24275779955665344}}
{"text": "function test_bug2727\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY ft_clusterplot topoplot_common\n\n%%\n\nlabel = {\n  'MLC11'    'MLC12'    'MLC13'    'MLC14'    'MLC15'    'MLC21'    'MLC22'    'MLC23'    'MLC24'    'MLC31'    'MLC32'    'MLC33'    'MLC41'    'MLC42' ...\n  'MLC43'    'MLF11'    'MLF12'    'MLF21'    'MLF22'    'MLF23'    'MLF31'    'MLF32'    'MLF33'    'MLF34'    'MLF41'    'MLF42'    'MLF43'    'MLF44' ...\n  'MLF45'    'MLF51'    'MLF52'    'MLO11'    'MLO12'    'MLO21'    'MLO22'    'MLO31'    'MLO32'    'MLO33'    'MLO41'    'MLO42'    'MLO43'    'MLP11' ...\n  'MLP12'    'MLP13'    'MLP21'    'MLP22'    'MLP31'    'MLP32'    'MLP33'    'MLP34'    'MLT11'    'MLT12'    'MLT13'    'MLT14'    'MLT15'    'MLT16' ...\n  'MLT21'    'MLT22'    'MLT23'    'MLT24'    'MLT25'    'MLT26'    'MLT31'    'MLT32'    'MLT33'    'MLT34'    'MLT35'    'MLT41'    'MLT42'    'MLT43' ...\n  'MLT44'    'MRC11'    'MRC12'    'MRC13'    'MRC14'    'MRC15'    'MRC21'    'MRC22'    'MRC23'    'MRC24'    'MRC31'    'MRC32'    'MRC33'    'MRC41' ...\n  'MRC42'    'MRC43'    'MRF11'    'MRF12'    'MRF21'    'MRF22'    'MRF23'    'MRF31'    'MRF32'    'MRF33'    'MRF34'    'MRF41'    'MRF42'    'MRF43' ...\n  'MRF44'    'MRF45'    'MRF51'    'MRF52'    'MRO11'    'MRO12'    'MRO21'    'MRO22'    'MRO31'    'MRO32'    'MRO33'    'MRO41'    'MRO42'    'MRO43' ...\n  'MRP11'    'MRP12'    'MRP13'    'MRP21'    'MRP22'    'MRP31'    'MRP32'    'MRP33'    'MRP34'    'MRT11'    'MRT12'    'MRT13'    'MRT14'    'MRT15' ...\n  'MRT16'    'MRT21'    'MRT22'    'MRT23'    'MRT24'    'MRT25'    'MRT26'    'MRT31'    'MRT32'    'MRT33'    'MRT34'    'MRT35'    'MRT41'    'MRT42' ...\n  'MRT43'    'MRT44'    'MZC01'    'MZC02'    'MZF01'    'MZF02'    'MZF03'    'MZO01'    'MZO02'    'MZP01'    'MZP02'\n  };\n\nstat = [];\nstat.label = label;\nstat.prob = rand(151,1);\nstat.stat = stat.prob;\nstat.dimord = 'chan';\nstat.posclusterslabelmat = stat.prob<0.05;\nstat.posclusters(1).prob = 0;\n% stat.posclusters(1).clusterstat = nan;\n% stat.posclusters(1).stddev      = nan;\n% stat.posclusters(1).cirange     = nan;\n\nstatT = [];\nstatT.label = label;\nstatT.prob = rand(151,10);\nstatT.stat = statT.prob;\nstatT.time = (1:10)/10; % in seconds\nstatT.dimord = 'chan_time';\nstatT.posclusterslabelmat = statT.prob<0.05;\nstatT.posclusters(1).prob = 0;\n\nstatF = [];\nstatF.label = label;\nstatF.prob = rand(151,20);\nstatF.stat = statF.prob;\nstatF.freq = 1:20; % in Hz\nstatF.dimord = 'chan_freq';\nstatF.posclusterslabelmat = statF.prob<0.05;\nstatF.posclusters(1).prob = 0;\n\nstatTF = [];\nstatTF.label = label;\nstatTF.prob = rand(151,20,10);\nstatTF.stat = statTF.prob;\nstatTF.freq = 1:20; % in Hz\nstatTF.time = (1:10)/10; % in seconds\nstatTF.dimord = 'chan_freq_time';\nstatTF.posclusterslabelmat = statTF.prob<0.05;\nstatTF.posclusters(1).prob = 0;\n\nstatT1F = [];\nstatT1F.label = label;\nstatT1F.prob = rand(151,20,1);\nstatT1F.stat = statT1F.prob;\nstatT1F.freq = 1:20; % in Hz\nstatT1F.time = 0.5; % in seconds\nstatT1F.dimord = 'chan_freq_time';\nstatT1F.posclusterslabelmat = statT1F.prob<0.05;\nstatT1F.posclusters(1).prob = 0;\n\nstatTF1 = [];\nstatTF1.label = label;\nstatTF1.prob = rand(151,1,10);\nstatTF1.stat = statTF1.prob;\nstatTF1.freq = 1; % in Hz\nstatTF1.time = (1:10)/10; % in seconds\nstatTF1.dimord = 'chan_freq_time';\nstatTF1.posclusterslabelmat = statTF1.prob<0.05;\nstatTF1.posclusters(1).prob = 0;\n\n%%\n\ncfg = [];\ncfg.layout = 'CTF151.lay';\nft_clusterplot(cfg, stat);\nft_clusterplot(cfg, statT);\nft_clusterplot(cfg, statF);\nft_clusterplot(cfg, statTF1); % single frequency\nft_clusterplot(cfg, statT1F); % single latency\n\ntry\n  figure; ft_clusterplot(cfg, statTF);\n  failed = false;\ncatch\n  failed = true;\nend\nassert(failed==true, 'this should have failed');\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2727.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275779355327787}}
{"text": "function ROI(img, nroi)\n\n% 1) Goal: Draw & process multiple ROIs interactively within an image.\n%\n% 2) Usage: ROI(img, nroi), where 'img' is your image, and 'nroi' is a\n% total number to ROIs to be processed.  The opened image will be processed\n% BY DEFAULT.  A prefered procedure is as follows: a) img = imread(...); b)\n% imh = imshow(img) and c) ROI(img, nroi). \n% Alternatively, if there is no image in your WorkSpace, you MUST use\n% square brackets to occupy the argument space for img, such as, ROI([],5),\n% will let you open a new image and process with 5 ROIs.\n%\n% 3) Since getline('closed') is used to get the polygon interactively,\n% please click left mouse button to select, and right button to finish up a\n% ROI (Backspace to delete the lastest click). You may repeat this process\n% till all ROIs were processed.  For more infos, please may see help\n% getline. \n%\n% 4) Results: ROI statistics are displayed on screen or output to a text\n% file (optional).\n%\n% 5) The colors of line/text label are generated by 'jet' colormap,\n% therefore, certain color may be too close to tell, especially when you\n% select too many ROIs. In that case, you may need to edit the color after\n% ROI processing. For more infos, please see help jet. \n%\n% 6) For your convenience, you may use the following m-scripts to clear\n% your enviroments: 'dt', 'dl' and 'df' to delete all text characters,\n% lines and figures, respectively. \n%\n% 7) This package includes 5 m-files: 'ROI.m', 'MultiROI', 'df.m', 'dl.m' and 'dt.m'.\n%    MultiROI is similar to ROI. The only difference is that it uses spline\n%    interprate to smooth the ROI edge. \n%\n% Shanrong Zhang\n% Department of Radiology\n% University of Washington\n% 02/09/2004\n%\n% email: zhangs@u.washington.edu\n\nif nargin == 2\n  \n    imh = findobj(0, 'Type', 'Image');\n    \n    % if no image opened, open a new one\n    if isempty(imh)\n        if length(img) == 0\n            [infn inpn] = uigetfile('*.*','Please select an image file');\n            if infn ~= 0\n                img = imread([inpn infn]);\n                imh = imshow(img);\n                axis image; axis off;\n            else\n                disp('Cancel by user!')\n                return\n            end\n        else\n            imh = imshow(img);\n        end\n    end\n\n    [nrows, ncols, ncolors] = size(img);\n  \n    % Save ROIs to a file (optional)\n    SaveIt = questdlg('Do you want to save ROI outputs ?');\n    switch SaveIt\n        case 'Yes'\n            [outfn, outpn] = uiputfile('*', 'Select an output file');\n            if outfn == 0\n                disp('Cancel by user !');\n            else\n                fid = fopen([outpn outfn], 'w+');\n                fprintf(fid, '%20s\\t %-50s\\n', 'Date\\time = ', datestr(now));\n            end\n        otherwise\n            outfn = 0;\n    end\n    \n    % generate a jet colormap according to nroi\n    cmap = jet(nroi);\n    rndp = randperm(nroi);\n    \n    hold on;\n    \n    croi = 1;\n    \n    while croi <= nroi\n        [x,y] =getline('closed');\n        \n        XData = get(imh, 'XData');\n        YData = get(imh, 'YData');\n        xmingrid = max( XData(1), floor(min(x)) );\n        xmaxgrid = min( XData(2),  ceil(max(x)) );\n        ymingrid = max( YData(1), floor(min(y)) );\n        ymaxgrid = min( YData(2),  ceil(max(y)) );\n        xgrid = xmingrid : xmaxgrid;\n        ygrid = ymingrid : ymaxgrid;\n        [X, Y] = meshgrid(xgrid, ygrid);\n        k_inside = inpolygon(X, Y, x, y);\n        Xin = X(k_inside);\n        Yin = Y(k_inside);\n        \n        cdata = get(imh, 'CData');\n        smallcdata = double(cdata(ygrid, xgrid, :));\n        \n        roi.index = croi;\n        roi.area = polyarea(x,y);\n        roi.center =  [mean(Xin(:)), mean(Yin(:))];\n        \n        for i=1:ncolors\n            roicidata     = smallcdata(:, :, i);\n            roi.mean(i)   =   mean(roicidata(k_inside));\n            roi.std(i)    =    std(roicidata(k_inside));\n            roi.min(i)    =    min(roicidata(k_inside));\n            roi.max(i)    =    max(roicidata(k_inside));\n            roi.median(i) = median(roicidata(k_inside));\n        end;\n        \n        plot(x,y,'Color',cmap(rndp(croi), :));\n        text(roi.center(1), roi.center(2), num2str(croi), 'Color', cmap(rndp(croi), :), 'FontWeight','Bold');\n        \n        % write ROI statistics into file if necessary\n        if outfn ~= 0 \n            fprintf(fid, '\\n');\n            fprintf(fid, '%20s\\t %10.0f\\n', 'ROI Index = ', roi.index);  \n            \n            fprintf(fid, '%20s\\t ', 'area = '); \n            fprintf(fid, '%10.2f\\t', roi.area); \n            fprintf(fid, '\\n');\n            \n            fprintf(fid, '%20s\\t ', 'mean = ');  \n            fprintf(fid, '%10.2f\\t', roi.mean);  \n            fprintf(fid, '\\n');\n            \n            fprintf(fid, '%20s\\t ', 'std = ');  \n            fprintf(fid, '%10.2f\\t', roi.std);  \n            fprintf(fid, '\\n');  \n            \n            fprintf(fid, '%20s\\t ', 'min = ');  \n            fprintf(fid, '%10.2f\\t', roi.min);  \n            fprintf(fid, '\\n');  \n            \n            fprintf(fid, '%20s\\t ', 'max = ');  \n            fprintf(fid, '%10.2f\\t', roi.max);  \n            fprintf(fid, '\\n');  \n            \n            fprintf(fid, '%20s\\t ', 'median = ');  \n            fprintf(fid, '%10.2f\\t', roi.median);  \n            fprintf(fid, '\\n');\n                                \n            fprintf(fid, '%20s\\t ', 'roicenter = '); \n            fprintf(fid, '%10.2f\\t', roi.center); \n            fprintf(fid, '\\n'); \n        end\n\n        disp(' ');\n        disp(sprintf('%20s\\t %10.0f', 'ROI index = ', roi.index));\n        disp(sprintf('%20s\\t %10.2f', 'area = ', roi.area));\n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t %10.2f', 'mean = ', roi.mean) );  \n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t %10.2f', 'std = ',  roi.std) );  \n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t %10.2f', 'min = ', roi.min) );  \n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t %10.2f', 'max = ', roi.max) );   \n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t %10.2f', 'median = ', roi.median) );\n        disp(sprintf('%20s\\t %10.2f\\t %10.2f\\t', 'roicenter [x,y] = ', roi.center));\n        disp(' ');\n        \n        croi = croi + 1;\n        \n    end\n    \n    if outfn == 0\n        disp('Done, but ROI statistics were not saved !!!');\n        disp(' ' );\n    else\n        disp(['Done, ROI statistics been output to ', outfn]);\n        disp('But the image with ROI lines/labels was not saved yet !!!');\n        fclose(fid);\n    end\n    \nelse\n    disp(' ')\n    disp('  Number of arguments is incorrect !!!')\n    disp(' ')\n    help ROI\nend\n\n% end of code\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4462-roi/roi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275779355327787}}
{"text": "function acpc_aligned_nifti = mrAnatAutoAlignAcpcNifti(anatomical_in, anatomical_out)\n%\n%  acpc_aligned_nifti = mrAnatAutoAlignAcpcNifti(anatomical_in, [anatomical_out])\n% \n% Generate a ac-pc aligned nifti image using Talairach coordinates\n% converted to MNI space. \n%\n% INPUTS:\n%   anatomical_in:\tFull path to raw (unaligned) anatomical image\n%   anatomical_out:\t(optional) Full path for output file. Defaults to\n%                   <anatomical_in> + '_acpc.nii.gz'\n% \n% OUTPUTS:\n%   anatomical_out: Full path to the aligned nifti file. \n% \n% (C) Stanford Vista Lab, 2016\n% \n\n\n%% Handle I/O\n\nif ~exist('anatomical_in','var') || isempty(anatomical_in) || ~exist(anatomical_in, 'file')\n    error('No input file was defined.');\nend\n\n% If no output file was defined, set to input + '_acpc.nii.gz'\nif ~exist('anatomical_out','var') || isempty(anatomical_out) \n    base = strsplit(anatomical_in, '.nii');\n    [p, f] = fileparts(base{1}); \n    anatomical_out = fullfile(p, [f, '_acpc.nii.gz']);\nend\n\n\n%% Perform acpc alignment\n\n% The ACPC coordinates in Talairach\nACPC_COORDS = [0,0,0; 0,-16,0; 0,-8,40];\n\n% Read in the file\nni = niftiRead(anatomical_in);\n\n% Apply the cannonical transform\nni = niftiApplyCannonicalXform(ni);\n\n% Use the MNI_T1 template\ntemplate =  fullfile(mrDiffusionDir, 'templates', 'MNI_T1.nii.gz');\n\n% Compute the spatial normalization\nsn = mrAnatComputeSpmSpatialNorm(ni.data, ni.qto_xyz, template);\n\n% Get the iamge coordinates for the mid-line, ac, and pc\ncoords = mrAnatGetImageCoordsFromSn(sn, tal2mni(ACPC_COORDS)', true)';\n\n% Use the coords to generate acpc-aligned image\nmrAnatAverageAcpcNifti(ni, anatomical_out, coords, [], [], [], false);\n\n\n%% Check for anatomical_out file\n\nif ~exist(anatomical_out,'file')\n    warning('Auto AC-PC Alignment failed.');\nelse\n    acpc_aligned_nifti = anatomical_out;\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/VolumeUtilities/mrAnatAutoAlignAcpcNifti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275778754990232}}
{"text": "function outputs=run_benchmark(imnames, topchosen, topscores, sptextdir, regspimgdir, sbddir, categids, refineddir)\n\n%first compute all overlaps\noverlaps=cell(numel(imnames),1);\nfor i=1:numel(imnames)\n    if(rem(i-1,10)==0) fprintf('Computing overlaps:%d/%d\\n',i, numel(imnames)); end\n    %read the sprep\n    [sp, reg2sp]=read_sprep(fullfile(sptextdir, [imnames{i} '.txt']), fullfile(regspimgdir, [imnames{i} '.png']));\n    \n    %load gt\n    [cls, inst, categories]=load_gt(sbddir, imnames{i});\n\n    %for each category of interest\n    for j=1:numel(categids)\n        categ_reg2sp=reg2sp(:,topchosen{categids(j)}{i}); \n   \n\n\n        %if there is refined regions, read them\n        if(exist('refineddir', 'var') & ~isempty(topchosen{categids(j)}{i}))\n            tmp=load(fullfile(refineddir, int2str(categids(j)), [imnames{i} '.mat']));\n            categ_reg2sp=tmp.newreg2sp;\n        end\n    \n        %compute overlaps\n        [overlap, pprecision, precall]=get_gt_overlaps(logical(categ_reg2sp), sp, double(inst));\n\n        overlaps{j}{i}=overlap;\n    end    \n    gt{i}=categories;\n\n    \nend\n\n\n%now run the evaluation. This is relatively fast once overlaps are precomputed\nap_vol=zeros(9,numel(categids));\nfor j=1:numel(categids)\n    for t=1:9\n        outputs(t,j)=generalized_det_eval(imnames, topscores{categids(j)}, overlaps{j}, gt, categids(j), 0.1, 0.1*t);\n        ap_vol(t,j)=outputs(t,j).PR.ap;\n        fprintf('Evaluated threshold:%f for category:%d\\n', 0.1*t, categids(j));\n    end\nend\n\n%Print out ap_vol for all categories\ncateg_names_and_groups;\nfprintf('Category name \\t\\t | AP^r\\t | AP^r_{vol}\\n');\nfprintf('_______________________________________________________\\n');\nfor j=1:numel(categids)\n    fprintf('%s \\t\\t | %f\\t | %f\\n',categnames{categids(j)}, ap_vol(5,j), mean(ap_vol(:,j)));\nend\nfprintf('_______________________________________________________\\n');\nfprintf('Mean \\t\\t | %f\\t | %f\\n', mean(ap_vol(5,:)), mean(mean(ap_vol,2)));\n\n\n\n\n%we will only work with the 0.5 threshold now\n%produce the impact chart\nproduce_impact_chart_all(outputs(5,:));\noutput.ap_vol=ap_vol;\n \n", "meta": {"author": "bharath272", "repo": "sds_eccv2014", "sha": "3804648e3451040263ceeff938aab5873476cfc1", "save_path": "github-repos/MATLAB/bharath272-sds_eccv2014", "path": "github-repos/MATLAB/bharath272-sds_eccv2014/sds_eccv2014-3804648e3451040263ceeff938aab5873476cfc1/evaluation/run_benchmark.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.24264247970792563}}
{"text": "hb_setup();\n\nres = rproc.read('scoresroot', ...\n  fullfile(hb_path, 'matlab', 'scores', 'scores_all'));\n\nnorm_splits = {'c'};\nnorms_path = fullfile(hb_path, 'matlab', 'data', 'best_normalizations.csv');\nnorms = readtable(norms_path, 'delimiter', ',');\nnorms.Properties.RowNames = norms.descriptor;\n\n%%\noutpath = fullfile(hb_path, 'matlab', 'results', 'article');\nvl_xmkdir(outpath);\naddpath(fullfile(hb_path, '../matlab2tikz/src/'));\n\nsequences = utls.listdirs(fullfile(hb_path, 'data', 'hpatches-release'));\nillum_seq = cellfun(@(a) strcmp(a(1:2), 'i_'), sequences);\nviewp_seq = cellfun(@(a) strcmp(a(1:2), 'v_'), sequences);\n\ncategories = cellfun(@(a) a(1), res.matching.sequence, 'Uni', false);\nres.matching.category = categories;\n% Compute the matching scores averages\nres.matching_g = varfun(@mean, res.matching, ...\n  'GroupingVariables', {'descriptor', 'geom_noise', 'category'}, ...\n  'InputVariables', 'ap');\n\n%% Separate the normalisation type and split out of descriptor name\n\nres.verification_e = rproc.postproc_norm(res.verification);\nres.matching_ge = rproc.postproc_norm(res.matching_g);\nres.retrieval_e = rproc.postproc_norm(res.retrieval);\n\n\n%% Compute average over the norm splits\nres.verification_en = varfun(@mean, res.verification_e, ...\n  'GroupingVariables', {'descriptor', 'split', 'negs', 'geom_noise', 'method', 'norm_type'}, ...\n  'InputVariables', 'pr_ap');\n\nres.matching_gen = varfun(@mean, res.matching_ge, ...\n  'GroupingVariables', {'descriptor', 'geom_noise', 'category', 'norm_type'}, ...\n  'InputVariables', 'mean_ap');\n\nres.retrieval_en = varfun(@mean, res.retrieval_e, ...\n  'GroupingVariables', {'descriptor', 'split', 'geom_noise', 'method', 'norm_type'}, ...\n  'InputVariables', 'map');\n\n%%\n\nin_c = @(a, b) max(min(a.*b, 1), 0);\n\nnormname = 'none';\nbnames = {}; cip = 1;  ls = {'EdgeColor', [1, 1, 1] * 0.2};\nbnames{end+1} = struct('name', 'meanstd', 'printname', '\\meanstd', 'texname', 'MStd', ...\n  'color', in_c(utls.rgb('Silver'), cip), 'barargs', {ls}, ...\n  'dim', 2, 'isbin', false, 'psize', 65, 'pps', 72479, 'gpu', false, 'normname', normname);\nbnames{end+1} = struct('name', 'resize', 'printname', '\\resize', 'texname', 'Resz', ...\n  'color', in_c(utls.rgb('SlateGray'), cip), 'barargs', {ls}, ...\n  'dim', 36, 'isbin', false, 'psize', 65, 'pps', 2583, 'gpu', false, 'normname', normname);\n\nbnames{end+1} = struct('name', 'sift', 'printname', '\\sift', 'texname', 'SIFT', ...\n  'color', in_c(utls.rgb('SeaGreen'), cip), 'barargs', {ls}, ...\n  'dim', 128, 'isbin', false, 'psize', 65, 'pps', 2251, 'gpu', false, 'normname', normname);\nbnames{end+1} = struct('name', 'rootsift', 'printname', '\\rootsift', 'texname', 'RSIFT', ...\n  'color', in_c(utls.rgb('Olive'), cip), 'barargs', {ls}, ...\n  'dim', 128, 'isbin', false, 'psize', 65, 'pps', 2157, 'gpu', false, 'normname', normname);\n\nbnames{end+1} = struct('name', 'brief', 'printname', '\\brief', 'texname', 'BRIEF', ...\n  'color', in_c(utls.rgb('DarkCyan'), cip), 'barargs', {ls},...\n  'dim', 256, 'isbin', true, 'psize', 32, 'pps', 1./3e-6, 'gpu', false, 'normname', normname);\nbnames{end+1} = struct('name', 'binboost', 'printname', '\\binboost', 'texname', 'BBoost', ...\n  'color', in_c(utls.rgb('SteelBlue'), cip), 'barargs', {ls},...\n  'dim', 256, 'isbin', true, 'psize', 32, 'pps', 1./700e-6, 'gpu', false, 'normname', normname);\nbnames{end+1} = struct('name', 'orb', 'printname', '\\orb', 'texname', 'ORB', ...\n  'color', in_c(utls.rgb('SkyBlue'), cip), 'barargs', {ls}, ...\n  'dim', 256, 'isbin', true, 'psize', 32, 'pps', 1./3e-6, 'gpu', false, 'normname', normname);\n\nbnames{end+1} = struct('name', 'siam', 'printname', '\\dcsiam', 'texname', 'DC-S', ...\n  'color', in_c(utls.rgb('Salmon'), cip), 'barargs', {ls}, ...\n  'dim', 256, 'isbin', false, 'psize', 64, 'pps', 1./100e-6, 'gpu', true, 'normname', normname);\nbnames{end+1} = struct('name', 'siam2stream', 'printname', '\\dcsiamts', 'texname', 'DC-S2S', ...\n  'color', in_c(utls.rgb('LightSalmon'), cip), 'barargs', {ls},...\n    'dim', 512, 'isbin', false, 'psize', 64, 'pps', 1./200e-6, 'gpu', true, 'normname', normname);\nbnames{end+1} = struct('name', 'deepdesc', 'printname', '\\deepdesc', 'texname', 'DDesc', ...\n  'color', in_c(utls.rgb('BurlyWood'), cip), 'barargs', {ls}, ...\n  'dim', 128, 'isbin', false, 'psize', 64, 'pps', 1./500e-6, 'gpu', true, 'normname', normname);\n%bnames{end+1} = struct('name', 'tfeat-margin', 'printname', 'tfeat-margin');\nbnames{end+1} = struct('name', 'tfeat-margin-star', 'printname', '\\tfmargin', 'texname', 'TF-M', ...\n  'color', in_c(utls.rgb('Sienna'), cip), 'barargs', {ls}, ...\n  'dim', 128, 'isbin', false, 'psize', 32, 'pps', 1./10e-6, 'gpu', true, 'normname', normname);\n%bnames{end+1} = struct('name', 'tfeat-ratio', 'printname', 'tf-ratio');\nbnames{end+1} = struct('name', 'tfeat-ratio-star', 'printname', '\\tfratio', 'texname', 'TF-R', ...\n  'color', in_c(utls.rgb('Chocolate'), cip), 'barargs', {ls}, ...\n  'dim', 128, 'isbin', false, 'psize', 32, 'pps', 1./10e-6, 'gpu', true, 'normname', normname);\n\nbnames = cell2mat(bnames);\n\nbaselines = struct('name', {bnames.name}, 'printname', {bnames.printname}, ...\n  'color', {bnames.color}, ...\n  'bararg', {bnames.barargs}, 'normname', {bnames.normname});\n\n\nbaselines_chance = struct('name', 'chance', 'printname', '\\chance', ...\n  'color', in_c(utls.rgb('White'), cip), 'bararg', {ls});\nclear normname;\nbnames_pca = {}; cip = 1; ls = {'EdgeColor', [1, 1, 1] * 0, 'LineStyle', '--'};\n%bnames_pca{end+1} = struct('name', 'meanstd_norm', 'printname', '+meanstd');\n%bnames_pca{end+1} = struct('name', 'resize_norm', 'printname', '+resize');\nbnames_pca{end+1} = struct('name', 'sift', 'printname', '\\psift', 'texname', '+SIFT', ...\n  'color', in_c(utls.rgb('SeaGreen'), cip), 'barargs', {ls}, 'normname', norms{'sift', 'normstr'}{1});\nbnames_pca{end+1} = struct('name', 'rootsift', 'printname', '\\prootsift', 'texname', '+RSIFT', ...\n  'color', in_c(utls.rgb('Olive'), cip), 'barargs', {ls}, ...\n  'normname', norms{'rootsift', 'normstr'}{1});\n\nbnames_pca{end+1} = struct('name', 'siam', 'printname', '\\pdcsiam', 'texname', '+DC-S', ...\n  'color', in_c(utls.rgb('Salmon'), cip), 'barargs',{ls}, ...\n  'normname', norms{'siam', 'normstr'}{1});\nbnames_pca{end+1} = struct('name', 'siam2stream', ...\n  'printname', '\\pdcsiamts', 'texname', '+DC-S2S', ...\n  'color', in_c(utls.rgb('LightSalmon'), cip), 'barargs', {ls}, ...\n  'normname', norms{'siam2stream', 'normstr'}{1});\n%bnames_pca{end+1} = struct('name', 'siam2stream_norm', 'printname', '+dc-siam2stream');\nbnames_pca{end+1} = struct('name', 'deepdesc', ...\n  'printname', '\\pdeepdesc', 'texname', '+DDesc', ...\n  'color', in_c(utls.rgb('BurlyWood'), cip), 'barargs', {ls}, ...\n  'normname', norms{'deepdesc', 'normstr'}{1});\n%bnames_pca{end+1} = struct('name', 'tfeat-margin_norm', 'printname', '+tf-margin');\nbnames_pca{end+1} = struct('name', 'tfeat-margin-star', ...\n  'printname', '\\ptfmargin', 'texname', '+TF-M', ...\n  'color', in_c(utls.rgb('Sienna'), cip), 'barargs', {ls}, ...\n  'normname', norms{'tfeat-margin-star', 'normstr'}{1});\n%bnames_pca{end+1} = struct('name', 'tfeat-ratio_norm', 'printname', '+tf-ratio');\nbnames_pca{end+1} = struct('name', 'tfeat-ratio-star', 'printname', '\\ptfratio', 'texname', '+TF-R', ...\n  'color', in_c(utls.rgb('Chocolate'), cip), 'barargs', {ls}, ...\n  'normname', norms{'tfeat-ratio-star', 'normstr'}{1});\nbnames_pca = cell2mat(bnames_pca);\n\nbaselines_pca = struct('name', {bnames_pca.name}, 'printname', {bnames_pca.printname}, ...\n  'color', {bnames_pca.color}, ...\n  'bararg', {bnames_pca.barargs}, 'normname', {bnames_pca.normname});\n\ndet_sets = {};\n\n%det_sets{end+1}.dets = baselines;\n%det_sets{end}.detnames = {bnames.printname};\n%det_sets{end}.name = 'baselines';\n\n%det_sets{end+1}.dets = baselines_pca;\n%det_sets{end}.detnames = {bnames_pca.printname};\n%det_sets{end}.name = 'baselines-pca';\n\ndet_sets{end+1}.dets = [baselines, baselines_pca];\ndet_sets{end}.detnames = [{bnames.printname}, {bnames_pca.printname}];\ndet_sets{end}.name = 'baselines-all';\n\n%det_sets{end+1}.dets = [baselines, baselines_pca, baselines_chance];\n%det_sets{end}.detnames = [{bnames.printname}, {bnames_pca.printname}, {baselines_chance.printname}];\n%det_sets{end}.name = 'baselines-all-chance';\n\ndet_sets = cell2mat(det_sets);\n\ntask_clrs = [0,136,55; 94,60,153; 202,0,32] ./ 256;\n%cl_tasks = {'full_diffseq_easy', 'full_diffseq_hard', 'full_diffseq_tough', 'full_sameseq_easy', 'full_sameseq_hard', 'full_sameseq_tough'};\nmarker_opts = {'LineWidth', 0.5, 'MarkerSize', 3};\nmop = 1; mfp = 0.4;\ncl_tasks = {...\n  struct('filter', struct('split', 'full', 'negs', 'inter', 'geom_noise', 'easy', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', '*', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}}}), ... % full_diffseq_easy\n  struct('filter', struct('split', 'full', 'negs', 'inter', 'geom_noise', 'hard', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', '*', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}}}), ... % full_diffseq_hard\n  struct('filter', struct('split', 'full', 'negs', 'inter', 'geom_noise', 'tough', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', '*', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}}}), ... % full_diffseq_tough\n  struct('filter', struct('split', 'full', 'negs', 'intra', 'geom_noise', 'easy', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', 'd', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}, 'MarkerSize', 1.5}}), ... % full_sameseq_easy\n  struct('filter', struct('split', 'full', 'negs', 'intra', 'geom_noise', 'hard', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', 'd', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}, 'MarkerSize', 1.5}}), ... % full_sameseq_hard\n  struct('filter', struct('split', 'full', 'negs', 'intra', 'geom_noise', 'tough', 'method', 'imbalanced'), 'style', ...\n    {{'Marker', 'd', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}, 'MarkerSize', 1.5}})  ... % full_sameseq_tough\n};\ncl_tasks = cell2mat(cl_tasks);\nmarker_opts = {'LineWidth', 0.5, 'MarkerSize', 4};\n\n%m_tasks = {...\n%  'full_easy_illum', 'full_easy_viewpoint', 'full_hard_illum', 'full_hard_viewpoint', ...\n%  'full_tough_illum', 'full_tough_viewpoint'};\nm_tasks = {...\n  struct('filter', struct('geom_noise', 'easy', 'category', 'i'), 'style', ...\n    {{'Marker', 'x', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}}}), ... % full_easy_illum\n  struct('filter', struct('geom_noise', 'easy', 'category', 'v'), 'style', ...\n    {{'Marker', '<', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}}}), ... % full_easy_viewpoint\n  struct('filter', struct('geom_noise', 'hard', 'category', 'i'), 'style', ...\n    {{'Marker', 'x', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}}}), ... % full_hard_illum\n  struct('filter', struct('geom_noise', 'hard', 'category', 'v'), 'style', ...\n    {{'Marker', '<', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}}}), ... % full_hard_viewpoint\n  struct('filter', struct('geom_noise', 'tough', 'category', 'i'), 'style', ...\n    {{'Marker', 'x', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}}}), ... % full_tough_illum\n  struct('filter', struct('geom_noise', 'tough', 'category', 'v'), 'style', ...\n    {{'Marker', '<', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}}})  ... % full_tough_viewpoint\n  };\nm_tasks = cell2mat(m_tasks);\n\nmarker_opts = {'LineWidth', 0.5, 'MarkerSize', 3};\n%r_tasks = {'full_easy_5s', 'full_easy_40s', ...\n%  'full_hard_5s', 'full_hard_40s', 'full_tough_5s', 'full_tough_40s'};\nmethod = 'removequery';\n%method = 'keepquery';\n\nr_tasks = {...\n%  struct('filter', struct('split', 'small', 'geom_noise', 'easy', 'method', method), 'style', ...\n%    {{'Marker', '.', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}, 'MarkerSize', 4}}), ... % full_easy_5s\n  struct('filter', struct('split', 'full', 'geom_noise', 'easy', 'method', method), 'style', ...\n    {{'Marker', 'o', 'Color', in_c(task_clrs(1, :), mop), 'MarkerFaceColor', in_c(task_clrs(1, :), mfp), marker_opts{:}, 'MarkerSize', 3}}), ... % full_easy_40s\n%  struct('filter', struct('split', 'small', 'geom_noise', 'hard', 'method', method), 'style', ...\n%    {{'Marker', '.', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}, 'MarkerSize', 4}}), ... % full_hard_5s\n  struct('filter', struct('split', 'full', 'geom_noise', 'hard', 'method', method), 'style', ...\n    {{'Marker', 'o', 'Color', in_c(task_clrs(2, :), mop), 'MarkerFaceColor', in_c(task_clrs(2, :), mfp), marker_opts{:}, 'MarkerSize', 3}}), ... % full_hard_40s\n%  struct('filter', struct('split', 'small', 'geom_noise', 'tough', 'method', method), 'style', ...\n%    {{'Marker', '.', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}, 'MarkerSize', 4}}), ... % full_tough_5s\n  struct('filter', struct('split', 'full', 'geom_noise', 'tough', 'method', method), 'style', ...\n    {{'Marker', 'o', 'Color', in_c(task_clrs(3, :), mop), 'MarkerFaceColor', in_c(task_clrs(3, :), mfp), marker_opts{:}, 'MarkerSize', 3}})  ... % full_tough_40s\n  };\n\nr_tasks = cell2mat(r_tasks);\n%% Export the Figures\n\n% Verification\nps = 2;\nfor dsi = 1:numel(det_sets)\n  figure(101); clf;\n  detnames = det_sets(dsi).detnames;\n  rproc.bar_plot(res.verification_en, 'mean_pr_ap', ...\n    cl_tasks, det_sets(dsi).dets, 'detnames', detnames, ...\n    'legend', false);\n  xlabel('Patch Verification mAP [%]');\n  %set(gcf, 'Position', get(0, 'Screensize')); % Maximize figure.\n  drawnow;\n  vl_printsize(ps);\n  out_im_path = fullfile(outpath, sprintf('verif_%s.png', ...\n      det_sets(dsi).name));\n  %print('-dpng', out_im_path, '-r200');\n  matlab2tikz(fullfile(outpath, sprintf('verif_%s.tikz', ...\n      det_sets(dsi).name)), 'showInfo', false, ...\n      'width', '\\figW', 'height', '\\figH', 'interpretTickLabelsAsTex', false);\nend\n\n%% Matching\n\nfor dsi = 1:numel(det_sets)\n  figure(102); clf;\n  detnames = det_sets(dsi).detnames;\n  rproc.bar_plot(res.matching_gen, 'mean_mean_ap', ...\n    m_tasks, det_sets(dsi).dets, 'detnames', detnames, ...\n    'legend', false);\n  xlabel('Image Matching mAP [%]');\n  drawnow;\n  vl_printsize(ps);\n  out_im_path = fullfile(outpath, sprintf('matching_%s.png', ...\n    det_sets(dsi).name));\n  %print('-dpng', out_im_path, '-r200');\n  matlab2tikz(fullfile(outpath, sprintf('matching_%s.tikz', ...\n    det_sets(dsi).name)), 'showInfo', false, ...\n    'width', '\\figW', 'height', '\\figH', 'interpretTickLabelsAsTex', false);\nend\n\n%% Retrieval\nfor dsi = 1:numel(det_sets)\n  figure(103); clf; \n  detnames = det_sets(dsi).detnames;\n  rproc.bar_plot(res.retrieval_en, 'mean_map', ...\n    r_tasks, det_sets(dsi).dets, 'detnames', detnames, ...\n    'legend', false);\n  xlabel('Patch Retrieval mAP [%]');\n  drawnow;\n  vl_printsize(ps);\n  out_im_path = fullfile(outpath, ...\n    sprintf('retr_patch_%s.png', det_sets(dsi).name));\n  %print('-dpng', out_im_path, '-r200');\n  matlab2tikz(fullfile(outpath, sprintf('retr_patch_%s.tikz', ...\n    det_sets(dsi).name)), 'showInfo', false, ...\n    'width', '\\figW', 'height', '\\figH', 'interpretTickLabelsAsTex', false);\nend\n\n", "meta": {"author": "hpatches", "repo": "hpatches-benchmark", "sha": "d5bde9d4520a037e8efc839bd1b6fc70edca82ed", "save_path": "github-repos/MATLAB/hpatches-hpatches-benchmark", "path": "github-repos/MATLAB/hpatches-hpatches-benchmark/hpatches-benchmark-d5bde9d4520a037e8efc839bd1b6fc70edca82ed/matlab/res_article.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2425397026294272}}
{"text": "% Shear Waves And Critical Angle Reflection Example\n%\n% This example illustrates Snell's law for elastic media using a weakly\n% focused ultrasound transducer incident on a soft-tissue / bone interface.\n% It builds on the Explosive Source In A Layered Medium and Snell's Law And\n% Critical Angle Reflection examples.\n%\n% author: Bradley Treeby\n% date: 14th Nov 2013\n% last update: 15th February 2014\n%  \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see <http://www.gnu.org/licenses/>. \n\nclear all;\n\n% =========================================================================\n% SIMULATION PARAMETERS\n% =========================================================================\n\n% change scale to 2 to reproduce the higher resolution figures used in the\n% help file\nscale = 1;\n\n% create the computational grid\nPML_size = 10;               % size of the PML in grid points\nNx = 128*scale - 2*PML_size; % number of grid points in the x direction\nNy = 192*scale - 2*PML_size; % number of grid points in the y direction\ndx = 0.1e-3/scale;           % grid point spacing in the x direction [m]\ndy = 0.1e-3/scale;           % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the medium properties\ncp1 = 1540;         % compressional wave speed [m/s]\ncs1 = 0;            % shear wave speed [m/s]\nrho1 = 1000;        % density [kg/m^3]\nalpha0_p1 = 0.1;    % compressional wave absorption [dB/(MHz^2 cm)]\nalpha0_s1 = 0.1;    % shear wave absorption [dB/(MHz^2 cm)]\n\ncp2 = 3000;         % compressional wave speed [m/s]\ncs2 = 1400;         % shear wave speed [m/s]\nrho2 = 1850;        % density [kg/m^3]\nalpha0_p2 = 1;      % compressional wave absorption [dB/(MHz^2 cm)]\nalpha0_s2 = 1;      % shear wave absorption [dB/(MHz^2 cm)]\n\n% create the time array\ncfl   = 0.1;\nt_end = 12e-6;\nkgrid.t_array= makeTime(kgrid, cp1, cfl, t_end);\n\n% define position of heterogeneous slab\nslab = zeros(Nx, Ny);\nslab(Nx/2:Nx, :) = 1;\n\n% define the source properties\nsource_freq = 2e6;              % [Hz]\nsource_strength = 1e6;          % [Pa]\nsource_cycles = 3;              % number of tone burst cycles\nsource_focus_dist = 5*scale;    % position of focus inside slab [grid points]\nsource_slab_dist = 5*scale;     % distance between source and slab [grid points]\nsource_mask = makeCircle(Nx, Ny, Nx/2 + source_focus_dist, Ny/2, 50*scale, pi/3);\nsource_mask(Nx/2 - source_slab_dist:end, :) = 0;\n\n% define the sensor to record the maximum particle velocity everywhere\nsensor.record = {'u_max_all'};\n\n% set the input arguments\ninput_args = {'PMLSize', PML_size, 'PMLAlpha', 2, 'PlotPML', false, ...\n    'PMLInside', false, 'PlotScale', [-1, 1]*source_strength, ...\n    'DisplayMask', 'off', 'DataCast', 'single'};\n\n% =========================================================================\n% FLUID SIMULATION\n% =========================================================================\n\n% assign the medium properties\nmedium.sound_speed            = cp1*ones(Nx, Ny);\nmedium.sound_speed(slab == 1) = cp2;\nmedium.density                = rho1*ones(Nx, Ny);\nmedium.density(slab == 1)     = rho2;\nmedium.alpha_coeff            = alpha0_p1*ones(Nx, Ny);\nmedium.alpha_coeff(slab == 1) = alpha0_p2;\nmedium.alpha_power            = 2;\n\n% assign the source\nsource.p_mask = source_mask;\nsource.p = source_strength*toneBurst(1/kgrid.dt, source_freq, source_cycles);\n\n% run the fluid simulation\nsensor_data_fluid = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% ELASTIC SIMULATION\n% =========================================================================\n\n% define the medium properties\nclear medium\nmedium.sound_speed_compression            = cp1*ones(Nx, Ny);\nmedium.sound_speed_compression(slab == 1) = cp2;\nmedium.sound_speed_shear                  = cs1*ones(Nx, Ny);\nmedium.sound_speed_shear(slab == 1)       = cs2;\nmedium.density                            = rho1*ones(Nx, Ny);\nmedium.density(slab == 1)                 = rho2;\nmedium.alpha_coeff_compression            = alpha0_p1*ones(Nx, Ny);\nmedium.alpha_coeff_compression(slab == 1) = alpha0_p2;\nmedium.alpha_coeff_shear                  = alpha0_s1*ones(Nx, Ny);\nmedium.alpha_coeff_shear(slab == 1)       = alpha0_s2;\n\n% assign the source\nclear source\nsource.s_mask = source_mask;\nsource.sxx = -source_strength*toneBurst(1/kgrid.dt, source_freq, source_cycles);\nsource.syy = source.sxx;\n\n% run the elastic simulation\nsensor_data_elastic = pstdElastic2D(kgrid, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% define plot vector\nx_vec = kgrid.x_vec(1 + PML_size:end - PML_size)*1e3;\ny_vec = kgrid.y_vec(1 + PML_size:end - PML_size)*1e3;\n\n% calculate square of velocity magnitude\nu_e = sensor_data_elastic.ux_max_all.^2 + sensor_data_elastic.uy_max_all.^2;\nu_f = sensor_data_fluid.ux_max_all.^2 + sensor_data_fluid.uy_max_all.^2;\n\n% plot layout\nfigure;\nimagesc(y_vec, x_vec, double(source_mask | slab));\nxlabel('y [mm]');\nylabel('x [mm]');\naxis image;\ncolormap(flipud(gray));\n\n% plot beam patterns\nfigure;\nsubplot(2, 1, 1);\nimagesc(y_vec, x_vec, 20*log10(u_f./max(u_f(:))));\nxlabel('y [mm]');\nylabel('x [mm]');\naxis image;\ncolorbar;\ncaxis([-50, 0]);\ntitle('Fluid Model');\n\nsubplot(2, 1, 2);\nimagesc(y_vec, x_vec, 20*log10(u_e./max(u_e(:))));\nxlabel('y [mm]');\nylabel('x [mm]');\naxis image;\ncolorbar;\ncaxis([-50, 0]);\ntitle('Elastic Model');\ncolormap(jet(256));", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_ewp_shear_wave_snells_law.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24253970262942712}}
{"text": "function [VO,M] = pm_segment(VF,PG,flags)\n% Segment an MR image into Gray, White & CSF.\n%\n% FORMAT VO = pm_segment(PF,PG,flags)\n% PF    - name(s) of image(s) to segment (must have same dimensions).\n% PG    - name(s) of template image(s) for realignment.\n%       - or a 4x4 transformation matrix which maps from the image to\n%         the set of templates.\n% flags - a structure normally based on defaults.segment\n% VO    - optional output volume\n% M     - affine transformation between template and image to segment\n%\n%                      The algorithm is four step:\n%\n% 1) Determine the affine transform which best matches the image with a\n%    template image. If the name of more than one image is passed, then\n%    the first image is used in this step. This step is not performed if\n%    no template images are specified.\n%\n% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori\n%    information about the likelihoods of each voxel being one of a\n%    number of different tissue types. If more than one image is passed,\n%    then they they are all assumed to be in register, and the voxel\n%    values are fitted to multi-normal distributions.\n%\n% 3) Perform morphometric operations on the grey and white partitions\n%    in order to more accurately identify brain tissue. This is then used\n%    to clean up the grey and white matter segments. \n%\n% 4) If no or 2 output arguments is/are specified, then the segmented \n%    images are written to disk. The names of these images have \"c1\", \n%    \"c2\" & \"c3\" appended to the name of the first image passed. The \n%    'brainmask' is also created with \"BrMsk_\" as an appendix.\n%\n%_______________________________________________________________________\n% Refs:\n%\n% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and\n% Partitioning - a Unified Framework. NeuroImage 6:209-217\n%\n%_______________________________________________________________________\n%\n% The template image, and a-priori likelihood images are modified\n% versions of those kindly supplied by Alan Evans, MNI, Canada\n% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).\n%_______________________________________________________________________\n% \n% This is a renamed version of the original spm_segment which has been\n% removed from the main spm distribution, but copied into the FieldMap\n% toolbox where it is still used.\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: pm_segment.m 4873 2012-08-30 19:06:26Z john $\n\n% Create some suitable default values\n%-----------------------------------------------------------------------\n\ndr = fileparts(mfilename('fullpath'));\ndef_flags.estimate.priors = char(...\n        fullfile(dr,'grey.nii'),...\n        fullfile(dr,'white.nii'),...\n        fullfile(dr,'csf.nii'));\ndef_flags.estimate.reg    = 0.01;\ndef_flags.estimate.cutoff = 30;\ndef_flags.estimate.samp   = 3;\ndef_flags.estimate.bb     =  [[-88 88]' [-122 86]' [-60 95]'];\ndef_flags.estimate.affreg.smosrc = 8;\ndef_flags.estimate.affreg.regtype = 'mni';\ndef_flags.estimate.affreg.weight = '';\ndef_flags.write.cleanup   = 1;\ndef_flags.write.wrt_cor   = 1;\ndef_flags.write.wrt_brV   = 0;\ndef_flags.graphics        = 1;\n\nif nargin<3, flags = def_flags; end;\nif ~isfield(flags,'estimate'),        flags.estimate        = def_flags.estimate;        end;\nif ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;\nif ~isfield(flags.estimate,'reg'),    flags.estimate.reg    = def_flags.estimate.reg;    end;\nif ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;\nif ~isfield(flags.estimate,'samp'),   flags.estimate.samp   = def_flags.estimate.samp;   end;\nif ~isfield(flags.estimate,'bb'),     flags.estimate.bb     = def_flags.estimate.bb;     end;\nif ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;\nif ~isfield(flags.estimate.affreg,'smosrc'),\n    flags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;\nend;\nif ~isfield(flags.estimate.affreg,'regtype'),\n    flags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;\nend;\nif ~isfield(flags.estimate.affreg,'weight'),\n    flags.estimate.affreg.weight = def_flags.estimate.affreg.weight;\nend;\nif ~isfield(flags,'write'),         flags.write         = def_flags.write;         end;\nif ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;\nif ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;\nif ~isfield(flags.write,'wrt_brV'), flags.write.wrt_brV = def_flags.write.wrt_brV; end;\nif ~isfield(flags,'graphics'),      flags.graphics      = def_flags.graphics;      end;\n\n%-----------------------------------------------------------------------\n\nif ischar(VF), VF= spm_vol(VF); end;\n\nSP         = init_sp(flags.estimate,VF,PG);\n[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);\nBP         = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);\nCP         = init_cp(VF,x3);\nsums       = zeros(8,1);\n\nfor pp=1:length(x3),\n    [raw,msk] = get_raw(VF,x1,x2,x3(pp));\n    s         = get_sp(SP,x1,x2,x3(pp));\n    CP        = update_cp_est(CP,s,raw,msk,pp);\n    sums      = sums + reshape(sum(sum(s,1),2),8,1);\nend;\nsums = sums/sum(sums);\nCP   = shake_cp(CP);\n\n[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);\n\n%save segmentation_results.mat CP BP SP VF sums\n\n[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);\nif flags.write.cleanup, [g,w,c,b] = clean_gwc(g,w,c); end;\n\n% Create the segmented images + the brain mask.\n%-----------------------------------------------------------------------\n%offs  = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));\n%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];\n[pth,nm,xt] = fileparts(deblank(VF(1).fname));\n\nif flags.write.wrt_brV\n    Nwrt = 4;\nelse\n    Nwrt = 3;\nend\nfor j=1:Nwrt,\n    tmp   = fullfile(pth,['c', num2str(j), nm, xt]);\n    if j==4, tmp = fullfile(pth,['BrMsk_', nm  xt]); end\n\n    VO(j) = struct(...\n        'fname',tmp,...\n        'dim',    VF(1).dim(1:3),...\n        'dt',     [spm_type('uint8'), spm_platform('bigend')],...\n        'mat',    VF(1).mat,...\n        'pinfo',  [1/255 0 0]',...\n        'descrip','Segmented image');\nend;\n\nif nargout==0 || nargout==2,\n    VO = spm_create_vol(VO);\n\n    spm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');\n    for pp=1:VF(1).dim(3),\n        VO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);\n        VO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);\n        VO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);\n        if flags.write.wrt_brV\n            VO(4) = spm_write_plane(VO(4),double(b(:,:,pp))/255,pp);\n        end\n        spm_progress_bar('Set',pp);\n    end;\n    spm_progress_bar('Clear');\nend;\n\nVO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);\nVO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);\nVO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);\nif flags.write.wrt_brV\n    VO(4).dat = b; VO(4).pinfo = VO(4).pinfo(1:2,:);\nend\nif nargout==2\n    M = SP.MM/VF(1).mat;\nend\n\nif flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [y1,y2,y3] = affine_transform(x1,x2,x3,M)\n    y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\n    y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\n    y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction display_graphics(VF,VS,mn,cv,mg)\n% Do the graphics\nnb = 3;\nspm_figure('Clear','Graphics');\nfg = spm_figure('FindWin','Graphics');\nif ~isempty(fg),\n    % Show some text\n    %-----------------------------------------------------------------------\n    ax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);\n    text(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...\n        'HorizontalAlignment','center','Parent',ax);\n\n    text(0,0.65, ['Image:  ' spm_file(VF(1).fname,'short50')],...\n        'FontSize',14,'FontWeight','Bold','Parent',ax);\n\n    text(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);\n    text(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);\n    text(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);\n    for j=1:nb,\n        text((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...\n            'FontSize',12,'FontWeight','Bold',...\n            'HorizontalAlignment','center','Parent',ax);\n        text((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...\n            'FontSize',12,'FontWeight','Bold',...\n            'HorizontalAlignment','center','Parent',ax);\n        text((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...\n            'FontSize',12,'FontWeight','Bold',...\n            'HorizontalAlignment','center','Parent',ax);\n    end;\n    if length(VF) > 1,\n        text(0,0.10,...\n        'Note: only means and variances for the first image are shown',...\n        'Parent',ax,'FontSize',12);\n    end;\n\n    M1 = VS(1).mat;\n    M2 = VF(1).mat;\n    for i=1:5,\n        M   = spm_matrix([0 0 i*VF(1).dim(3)/6]);\n        img = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);\n        img(1,1) = eps;\n        ax = axes('Position',...\n            [0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n            'Visible','off','Parent',fg);\n        imagesc(rot90(img), 'Parent', ax);\n        set(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n\n        for j=1:3,\n            img = spm_slice_vol(VS(j),M2\\M1*M,VF(1).dim(1:2),1);\n            ax  = axes('Position',...\n                [0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n                'Visible','off','Parent',fg);\n            image(rot90(img*64), 'Parent', ax);\n            set(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n        end;\n    end;\n\n    spm_print;\n    drawnow;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction M = get_affine_mapping(VF,VG,aflags)\n\nif ~isempty(VG) && ischar(VG), VG = spm_vol(VG); end;\n\nif ~isempty(VG) && isstruct(VG),\n    % Affine registration so that a priori images match the image to\n    % be segmented.\n    %-----------------------------------------------------------------------\n\n    VFS = spm_smoothto8bit(VF(1),aflags.smosrc);\n\n    % Scale all images approximately equally\n    % ---------------------------------------------------------------\n    for i=1:length(VG),\n        VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));\n    end;\n    VFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));\n\n    spm_plot_convergence('Init','Affine Registration','Mean squared difference','Iteration');\n    flags     = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);\n    M         = eye(4);\n    [M,scal]  = spm_affreg(VG, VFS, flags, M);\n\n    if ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;\n\n    flags.sep = aflags.smosrc/2;\n    M         = spm_affreg(VG, VFS, flags, M,scal);\n    spm_plot_convergence('Clear');\n\nelseif all(size(VG) == [4 4])\n    % Assume that second argument is a matrix that will do the job\n    %-----------------------------------------------------------------------\n    M = VG;\nelse\n    % Assume that image is normalized\n    %-----------------------------------------------------------------------\n    M = eye(4);\nend\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)\n% Voxels to sample during the cluster analysis\n%-----------------------------------------------------------------------\n\n% A bounding box for the brain in Talairach space.\n%bb = [ [-88 88]' [-122 86]' [-60 95]'];\n%c = [bb(1,1) bb(1,2) bb(1,3) 1\n%     bb(1,1) bb(1,2) bb(2,3) 1\n%     bb(1,1) bb(2,2) bb(1,3) 1\n%     bb(1,1) bb(2,2) bb(2,3) 1\n%     bb(2,1) bb(1,2) bb(1,3) 1\n%     bb(2,1) bb(1,2) bb(2,3) 1\n%     bb(2,1) bb(2,2) bb(1,3) 1\n%     bb(2,1) bb(2,2) bb(2,3) 1]';\n%tc = MM\\c;\n%tc = tc(1:3,:)';\n%mx = max(tc);\n%mn = min(tc);\n%bb = [mn ; mx];\n%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n%samp = round(max(abs([4 4 4]./vx), [1 1 1]));\n%x1 = bb(1,1):samp(1):bb(2,1);\n%x2 = bb(1,2):samp(2):bb(2,2);\n%x3 = bb(1,3):samp(3):bb(2,3);\n%return;\n\n% A bounding box for the brain in Talairach space.\nif nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;\n\n% A mapping from a unit radius sphere to a hyper-ellipse\n% that is just enclosed by the bounding box in Talairach\n% space.\nM0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];\n\n% The mapping from voxels to Talairach space is MM,\n% so the ellipse in the space of the image becomes:\nM0 = MM\\M0;\n\n% So to work out the bounding box in the space of the\n% image that just encloses the hyper-ellipse.\ntmp = M0(1:3,1:3);\ntmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));\nbb  = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';\nbb  = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);\n\n% Want to sample about every 3mm\ntmp  = sqrt(sum(VF(1).mat(1:3,1:3).^2))';\nsamp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));\n\nx1 = bb(1,1):samp(1):bb(2,1);\nx2 = bb(1,2):samp(2):bb(2,2);\nx3 = bb(1,3):samp(3):bb(2,3);\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)\noll = -Inf;\nspm_plot_convergence('Init','Segmenting','Log-likelihood','Iteration #');\n\nfor iter = 1:64,\n    ll= 0;\n    for pp = 1:length(x3), % Loop over planes\n        bf        = get_bp(BP,x1,x2,x3(pp));\n        [raw,msk] = get_raw(VF,x1,x2,x3(pp));\n        s         = get_sp(SP,x1,x2,x3(pp));\n        cor       = bf.*raw;\n        [P,ll0]   = get_p(cor,msk,s,sums,CP,bf);\n        ll        = ll + ll0;\n        CP        = update_cp_est(CP,P,cor,msk,pp);\n        BP        = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));\n    end;\n\n    BP = update_bp(BP);\n    if iter>1, spm_plot_convergence('Set',ll); end;\n    %fprintf('\\t%g\\n', ll);\n\n    % Stopping criterion\n    %-----------------------------------------------------------------------\n    if iter == 2,\n        ll2 = ll;\n    elseif iter > 2 && abs((ll-oll)/(ll-ll2)) < 0.0001\n        break;\n    end;\n    oll = ll;\nend;\nspm_plot_convergence('Clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = init_bp(VF,co,reg)\nm        = length(VF);\ntmp      = sqrt(sum(VF(1).mat(1:3,1:3).^2));\nBP.nbas  = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);\nBP.B1    = spm_dctmtx(VF(1).dim(1),BP.nbas(1));\nBP.B2    = spm_dctmtx(VF(1).dim(2),BP.nbas(2));\nBP.B3    = spm_dctmtx(VF(1).dim(3),BP.nbas(3));\n\nnbas     = BP.nbas;\nif prod(BP.nbas)>1,\n    % Set up a priori covariance matrix\n    vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n    kx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;\n    ky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;\n    kz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;\n\n    % Cost function based on sum of squares of 4th derivatives\n    IC0 =  (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...\n            1*kron(kz.^0,kron(ky.^4,kx.^0)) +...\n            1*kron(kz.^0,kron(ky.^0,kx.^4)) +...\n            4*kron(kz.^3,kron(ky.^1,kx.^0)) +...\n            4*kron(kz.^3,kron(ky.^0,kx.^1)) +...\n            4*kron(kz.^1,kron(ky.^3,kx.^0)) +...\n            4*kron(kz.^0,kron(ky.^3,kx.^1)) +...\n            4*kron(kz.^1,kron(ky.^0,kx.^3)) +...\n            4*kron(kz.^0,kron(ky.^1,kx.^3)) +...\n            6*kron(kz.^2,kron(ky.^2,kx.^0)) +...\n            6*kron(kz.^2,kron(ky.^0,kx.^2)) +...\n            6*kron(kz.^0,kron(ky.^2,kx.^2)) +...\n           12*kron(kz.^2,kron(ky.^1,kx.^1)) +...\n           12*kron(kz.^1,kron(ky.^2,kx.^1)) +...\n           12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;\n\n    %IC0(1) = max(IC0);\n    BP.IC0 = diag(IC0(2:end));\n\n    % Initial estimate for intensity modulation field\n    BP.T   = zeros(nbas(1),nbas(2),nbas(3),length(VF));\n    %-----------------------------------------------------------------------\nelse\n    BP.T   = zeros([1 1 1 length(VF)]);\n    BP.IC0 = [];\nend;\nBP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);\nBP.Beta  = zeros(prod(BP.nbas(1:3)),m);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor j=1:size(BP.Alpha,3),\n    cr  = cor(:,:,j);\n    w1 = zeros(size(cr));\n    w2 = zeros(size(cr));\n    for i=[1 2 3 4 5 6 7 8],\n        tmp = p(:,:,i)*CP.cv(j,j,i)^(-1);\n        w1  = w1 + tmp.*(CP.mn(j,i) - cr);\n        w2  = w2 + tmp;\n    end;\n    wt1       = 1 + cr.*w1;\n    wt2       = cr.*(cr.*w2 - w1);\n    wt1(~msk) = 0;\n    wt2(~msk) = 0;\n\n    BP.Beta(:,j)    = BP.Beta(:,j)    + kron(B3',spm_krutil(wt1,B1,B2,0));\n    BP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction BP = update_bp(BP)\nif prod(BP.nbas)<=1, return; end;\nfor j=1:size(BP.Alpha,3),\n    x     = BP.T(:,:,:,j);\n    x     = x(:);\n    x     = x(2:end);\n    Alpha = BP.Alpha(2:end,2:end,j);\n    Beta  = BP.Beta(2:end,j);\n    x     = (Alpha + BP.IC0)\\(Alpha*x + Beta);\n\n    BP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));\n    BP.Alpha      = zeros(size(BP.Alpha));\n    BP.Beta       = zeros(size(BP.Beta));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction bf = get_bp(BP,x1,x2,x3)\nbf = ones(length(x1),length(x2),size(BP.Alpha,3));\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor i=1:size(BP.Alpha,3),\n    t = reshape(reshape(BP.T(:,:,:,i),...\n        BP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));\n    bf(:,:,i) = exp(B1*t*B2');\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [dat,msk] = get_raw(VF,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\nfor i=1:length(VF),\n    [Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\\VF(1).mat);\n    dat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);\nend;\nmsk = all(dat,3) & all(isfinite(double(dat)),3);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = init_cp(VF,x3)\nn = 8;\nm = length(VF);\np = length(x3);\nCP.mom0 = zeros(1,n,p)+eps;\nCP.mom1 = zeros(m,n,p);\nCP.mom2 = zeros(m,m,n,p)+eps;\n\n% Occasionally the dynamic range of the images is such that many voxels\n% all have the same intensity.  Adding cv0 is an attempt to improve the\n% stability of the algorithm if this occurs. The value 0.083 was obtained\n% from var(rand(1000000,1)).  It prbably isn't the best way of doing\n% things, but it appears to work.\nCP.cv0 = zeros(m,m);\nfor i=1:m,\n    if spm_type(VF(i).dt(1),'intt'),\n        CP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));\n    end;\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = shake_cp(CP)\nCP.mom0(:,5,:)   = CP.mom0(:,1,:);\nCP.mom0(:,6,:)   = CP.mom0(:,2,:);\nCP.mom0(:,7,:)   = CP.mom0(:,3,:);\nCP.mom1(:,5,:)   = CP.mom1(:,1,:);\nCP.mom1(:,6,:)   = CP.mom1(:,2,:);\nCP.mom1(:,7,:)   = CP.mom1(:,3,:);\nCP.mom1(:,8,:)   = 0;\nCP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);\nCP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);\nCP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = update_cp_est(CP,P,dat,msk,p)\nm   = size(dat,3);\nd   = size(P);\nP   = reshape(P,[d(1)*d(2),d(3)]);\ndat = reshape(dat,[d(1)*d(2),m]);\nP(~msk(:),:)   = [];\ndat(~msk(:),:) = [];\nfor i=1:size(CP.mom0,2),\n    CP.mom0(1,i,p)   = sum(P(:,i));\n    CP.mom1(:,i,p)   = sum((P(:,i)*ones(1,m)).*dat)';\n    CP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;\nend;\n\nfor i=1:size(CP.mom0,2),\n    CP.mg(1,i)   = sum(CP.mom0(1,i,:),3);\n    CP.mn(:,i)   = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);\n\n    tmp          = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';\n    tmp          = tmp-eye(size(tmp))*eps*1e6;\n    CP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;\nend;\nCP.mg   = CP.mg/sum(CP.mg);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [p,ll] = get_p(cor,msk,s,sums,CP,bf)\nd   = [size(cor) 1 1];\nn   = size(CP.mg,2);\ncor = reshape(cor,d(1)*d(2),d(3));\ncor = cor(msk,:);\np   = zeros(d(1)*d(2),n);\nif ~any(msk), p  = reshape(p,d(1),d(2),n); ll=0; return; end;\n\nfor i=1:n,\n    amp       = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));\n    dst       = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));\n    dst       = sum(dst.*dst,2);\n    tmp       = s(:,:,i);\n    p(msk,i)  = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;\nend;\nsp = sum(p,2);\nll = sum(log(sp(msk).*bf(msk)+eps));\nsp(~msk) = Inf;\nfor i=1:n, p(:,i) = p(:,i)./sp; end;\np  = reshape(p,d(1),d(2),n);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction SP = init_sp(flags,VF,PG)\nSP.VB       = spm_vol(flags.priors);\nMM          = get_affine_mapping(VF,PG,flags.affreg);\n%VF          = spm_vol(PF);\nSP.MM       = MM*VF(1).mat;\nSP.w        = 0.98;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction s = get_sp(SP,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\n[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\\SP.MM);\nw1  = SP.w;\nw2  = (1-w1)/2;\ns   = zeros([size(Y1),4]);\nfor i=1:3,\n    s(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;\nend;\ns(:,:,4:8)   = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)\n\nif wc,\n    VC = VF;\n    for j=1:length(VF),\n        [pth,nm,xt,vr] = spm_fileparts(deblank(VF(j).fname));\n        VC(j).fname    = fullfile(pth,['m' nm xt vr]);\n        VC(j).descrip  = 'Bias corrected image';\n    end;\n    VC = spm_create_vol(VC);\nend;\n\nspm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');\nx1 = 1:VF(1).dim(1);\nx2 = 1:VF(1).dim(2);\nx3 = 1:VF(1).dim(3);\n\ng = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nw = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nc = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\n\nfor pp=1:length(x3),\n    bf        = get_bp(BP,x1,x2,x3(pp));\n    [raw,msk] = get_raw(VF,x1,x2,x3(pp));\n    cor       = raw.*bf;\n    if wc,\n        for j=1:length(VC),\n            VC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);\n        end;\n    end;\n    s         = get_sp(SP,x1,x2,x3(pp));\n    p         = get_p(cor,msk,s,sums,CP,bf);\n    g(:,:,pp) = uint8(round(p(:,:,1)*255));\n    w(:,:,pp) = uint8(round(p(:,:,2)*255));\n    c(:,:,pp) = uint8(round(p(:,:,3)*255));\n\n    spm_progress_bar('Set',pp);\nend;\nspm_progress_bar('Clear');\n\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c,b] = clean_gwc(g,w,c)\nb    = w;\nb(1) = w(1);\n\n% Build a 3x3x3 seperable smoothing kernel\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\n% Erosions and conditional dilations\n%-----------------------------------------------------------------------\nniter = 32;\nspm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');\nfor j=1:niter,\n    if j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.\n    for i=1:size(b,3),\n        gp = double(g(:,:,i));\n        wp = double(w(:,:,i));\n        bp = double(b(:,:,i))/255;\n        bp = (bp>th).*(wp+gp);\n        b(:,:,i) = uint8(round(bp));\n    end;\n    spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n    spm_progress_bar('Set',j);\nend;\nth = 0.05;\nfor i=1:size(b,3),\n    gp       = double(g(:,:,i))/255;\n    wp       = double(w(:,:,i))/255;\n    cp       = double(c(:,:,i))/255;\n    bp       = double(b(:,:,i))/255;\n    bp       = ((bp>th).*(wp+gp))>th;\n    g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));\n    w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));\n    c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));\n    b(:,:,i) = uint8(round(255*bp));\nend;\nspm_progress_bar('Clear');\nreturn;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/FieldMap/pm_segment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.2424586677063918}}
{"text": "function [norm] = electroderealign(cfg);\n\n% ELECTRODEREALIGN rotates and translates electrode positions to\n% template electrode positions or towards the head surface. It can\n% either perform a rigid body transformation, in which only the\n% coordinate system is changed, or it can apply additional deformations\n% to the input electrodes.\n%\n% Use as\n%   [elec] = electroderealign(cfg)\n%\n% Three different methods for aligning the input electrodes are implemented:\n% based on a warping method, based on the fiducials or interactive with a\n% graphical user interface. Each of these approaches is described below.\n%\n% 1) You can apply a spatial deformation method (i.e. 'warp') that\n% automatically minimizes the distance between the electrodes and the\n% averaged standard. The warping methods use a non-linear search to\n% optimize the error between input and template electrodes or the\n% head surface.\n%\n% 2) You can apply a rigid body realignment based on three fiducial locations.\n% Realigning using the fiducials only ensures that the fiducials (typically\n% nose, left and right ear) are along the same axes in the input electrode\n% set as in the template electrode set.\n%\n% 3) You can display the electrode positions together with the skin surface,\n% and manually (using the graphical user interface) adjust the rotation,\n% translation and scaling parameters, so that the two match.\n%\n% The configuration can contain the following options\n%   cfg.method         = different methods for aligning the electrodes\n%                        'rigidbody'       apply a rigid-body warp\n%                        'globalrescale'   apply a rigid-body warp with global rescaling\n%                        'traditional'     apply a rigid-body warp with individual axes rescaling\n%                        'nonlin1'         apply a 1st order non-linear warp\n%                        'nonlin2'         apply a 2nd order non-linear warp\n%                        'nonlin3'         apply a 3rd order non-linear warp\n%                        'nonlin4'         apply a 4th order non-linear warp\n%                        'nonlin5'         apply a 5th order non-linear warp\n%                        'realignfiducial' realign the fiducials\n%                        'interactive'     manually using graphical user interface\n%   cfg.channel        = Nx1 cell-array with selection of channels (default = 'all'),\n%                        see CHANNELSELECTION for details\n%   cfg.fiducial       = cell-array with the name of three fiducials used for\n%                        realigning (default = {'nasion', 'lpa', 'rpa'})\n%   cfg.casesensitive  = 'yes' or 'no', determines whether string comparisons\n%                        between electrode labels are case sensitive (default = 'yes')\n%   cfg.feedback       = 'yes' or 'no' (default = 'no')\n%\n% The electrode set that will be realigned is specified as\n%   cfg.elecfile       = string with filename, or alternatively\n%   cfg.elec           = structure with electrode definition\n%\n% If you want to align the electrodes to a single template electrode set\n% or to multiple electrode sets (which will be averaged), you should\n% specify the template electrode sets as\n%   cfg.template       = single electrode set that serves as standard\n% or\n%   cfg.template{1..N} = list of electrode sets that are averaged into the standard\n% The template electrode sets can be specified either as electrode\n% structures (i.e. when they are already read in memory) or as electrode\n% files.\n%\n% If you want to align the electrodes to the head surface as obtained from\n% an anatomical MRI (using one of the warping methods), you should specify\n% the head surface\n%   cfg.headshape      = a filename containing headshape, a structure containing a\n%                        single triangulated boundary, or a Nx3 matrix with surface\n%                        points\n%\n% In case you only want to realign the fiducials, the template electrode\n% set only has to contain the three fiducials, e.g.\n%   cfg.template.pnt(1,:) = [110 0 0]  % location of the nose\n%   cfg.template.pnt(2,:) = [0  90 0]  % left ear\n%   cfg.template.pnt(3,:) = [0 -90 0]  % right ear\n%   cfg.template.label    = {''nasion', 'lpa', 'rpa'}\n%\n% See also READ_FCDC_ELEC, VOLUMEREALIGN\n\n% Copyright (C) 2005-2006, Robert Oostenveld\n%\n% $Log: electroderealign.m,v $\n% Revision 1.1  2009/01/30 04:02:02  arno\n% *** empty log message ***\n%\n% Revision 1.6  2007/08/06 09:20:14  roboos\n% added support for bti_hs\n%\n% Revision 1.5  2007/07/26 08:00:09  roboos\n% also deal with cfg.headshape if specified as surface, set of points or ctf_hs file.\n% the construction of the tri is now done consistently for all headshapes if tri is missing\n%\n% Revision 1.4  2007/02/13 15:12:51  roboos\n% removed cfg.plot3d option\n%\n% Revision 1.3  2006/12/12 11:28:33  roboos\n% moved projecttri subfunction into seperate function\n%\n% Revision 1.2  2006/10/04 07:10:07  roboos\n% updated documentation\n%\n% Revision 1.1  2006/09/13 07:20:06  roboos\n% renamed electrodenormalize to electroderealign, added \"deprecated\"-warning to the old function\n%\n% Revision 1.10  2006/09/13 07:09:24  roboos\n% Implemented support for cfg.method=interactive, using GUI for specifying and showing transformations. Sofar only for electrodes+headsurface.\n%\n% Revision 1.9  2006/09/12 15:26:06  roboos\n% implemented support for aligning electrodes to the skin surface, extended and improved documentation\n%\n% Revision 1.8  2006/04/20 09:58:34  roboos\n% updated documentation\n%\n% Revision 1.7  2006/04/19 15:42:53  roboos\n% replaced call to warp_pnt with new function name warp_optim\n%\n% Revision 1.6  2006/03/14 08:16:00  roboos\n% changed function call to warp3d into warp_apply (thanks to Arno)\n%\n% Revision 1.5  2005/05/17 17:50:37  roboos\n% changed all \"if\" occurences of & and | into && and ||\n% this makes the code more compatible with Octave and also seems to be in closer correspondence with Matlab documentation on shortcircuited evaluation of sequential boolean constructs\n%\n% Revision 1.4  2005/03/21 15:49:43  roboos\n% added cfg.casesensitive for string comparison of electrode labels\n% added cfg.feedback and cfg.plot3d option for debugging\n% changed output: now ALL electrodes of the input are rerurned, after applying the specified transformation\n% fixed small bug in feedback regarding distarnce prior/after realignfiducials)\n% added support for various warping strategies, a.o. traditional, rigidbody, nonlin1-5, etc.\n%\n% Revision 1.3  2005/03/16 09:18:56  roboos\n% fixed bug in fprintf feedback, instead of giving mean squared distance it should give mean distance before and after normalization\n%\n% Revision 1.2  2005/01/18 12:04:39  roboos\n% improved error handling of missing fiducials\n% added other default fiducials\n% changed debugging output\n%\n% Revision 1.1  2005/01/17 14:56:06  roboos\n% new implementation\n%\n\n% set the defaults\nif ~isfield(cfg, 'channel'),       cfg.channel = 'all';       end\nif ~isfield(cfg, 'feedback'),      cfg.feedback = 'no';       end\nif ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end\nif ~isfield(cfg, 'headshape'),     cfg.headshape = [];        end\nif ~isfield(cfg, 'template'),      cfg.template = [];         end\n\n% this is a common mistake which can be accepted\nif strcmp(cfg.method, 'realignfiducials')\n  cfg.method = 'realignfiducial';\nend\n\nif strcmp(cfg.method, 'warp')\n  % rename the default warp to one of the method recognized by the warping toolbox\n  cfg.method = 'traditional';\nend\n\nif strcmp(cfg.feedback, 'yes')\n  % use the global fb field to tell the warping toolbox to print feedback\n  global fb\n  fb = 1;\nelse\n  global fb\n  fb = 0;\nend\n\nusetemplate  = isfield(cfg, 'template')  && ~isempty(cfg.template);\nuseheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);\n\nif usetemplate\n  % get the template electrode definitions\n  if ~iscell(cfg.template)\n    cfg.template = {cfg.template};\n  end\n  Ntemplate = length(cfg.template);\n  for i=1:Ntemplate\n    if isstruct(cfg.template{i})\n      template(i) = cfg.template{i};\n    else\n      template(i) = read_fcdc_elec(cfg.template{i});\n    end\n  end\nelseif useheadshape\n  % get the surface describing the head shape\n  if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')\n    % use the headshape surface specified in the configuration\n    headshape = cfg.headshape;\n  elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3\n    % use the headshape points specified in the configuration\n    headshape.pnt = cfg.headshape;\n  elseif ischar(cfg.headshape) && filetype(cfg.headshape, 'ctf_shape')\n    % read the headshape from file\n    headshape = read_ctf_shape(cfg.headshape);\n  elseif ischar(cfg.headshape) && filetype(cfg.headshape, '4d_hs')\n    % read the headshape from file\n    headshape     = []; \n    headshape.pnt = read_bti_hs(cfg.headshape);\n  else\n    error('cfg.headshape is not specified correctly')\n  end\n  if ~isfield(headshape, 'tri')\n    % generate a closed triangulation from the surface points\n    headshape.tri = projecttri(headshape.pnt);\n  end\nelse\n  error('you should either specify template electrode positions, template fiducials or a head shape');\nend\n\n% get the electrode definition that should be warped\nif isfield(cfg, 'elec')\n  elec = cfg.elec;\nelse\n  elec = read_fcdc_elec(cfg.elecfile);\nend\n\n% remember the original electrode locations and labels\norig = elec;\n\n% convert all labels to lower case for string comparisons\n% this has to be done AFTER keeping the original labels and positions\nif strcmp(cfg.casesensitive, 'no')\n  for i=1:length(elec.label)\n    elec.label{i} = lower(elec.label{i});\n  end\n  for j=1:length(template)\n    for i=1:length(template(j).label)\n      template(j).label{i} = lower(template(j).label{i});\n    end\n  end\nend\n\nif strcmp(cfg.feedback, 'yes')\n  % create an empty figure, continued below...\n  figure\n  axis equal\n  axis vis3d\n  hold on\n  xlabel('x')\n  ylabel('y')\n  zlabel('z')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif usetemplate && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % determine electrode selection and overlapping subset for warping\n  cfg.channel = channelselection(cfg.channel, elec.label);\n  for i=1:Ntemplate\n    cfg.channel = channelselection(cfg.channel, template(i).label);\n  end\n\n  % make subselection of electrodes\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label = elec.label(datsel);\n  elec.pnt   = elec.pnt(datsel,:);\n  for i=1:Ntemplate\n    [cfgsel, datsel] = match_str(cfg.channel, template(i).label);\n    template(i).label = template(i).label(datsel);\n    template(i).pnt   = template(i).pnt(datsel,:);\n  end\n\n  % compute the average of the template electrode positions\n  all = [];\n  for i=1:Ntemplate\n    all = cat(3, all, template(i).pnt);\n  end\n  avg    = mean(all,3);\n  stderr = std(all, [], 3);\n\n  fprintf('warping electrodes to template... '); % the newline comes later\n  [norm.pnt, norm.m] = warp_optim(elec.pnt, avg, cfg.method);\n  norm.label = elec.label;\n\n  dpre  = mean(sqrt(sum((avg - elec.pnt).^2, 2)));\n  dpost = mean(sqrt(sum((avg - norm.pnt).^2, 2)));\n  fprintf('mean distance prior to warping %f, after warping %f\\n', dpre, dpost);\n\n  if strcmp(cfg.feedback, 'yes')\n    % plot all electrodes before warping\n    my_plot3(elec.pnt, 'r.');\n    my_plot3(elec.pnt(1,:), 'r*');\n    my_plot3(elec.pnt(2,:), 'r*');\n    my_plot3(elec.pnt(3,:), 'r*');\n    my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');\n    my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');\n    my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');\n\n    % plot all electrodes after warping\n    my_plot3(norm.pnt, 'm.');\n    my_plot3(norm.pnt(1,:), 'm*');\n    my_plot3(norm.pnt(2,:), 'm*');\n    my_plot3(norm.pnt(3,:), 'm*');\n    my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');\n    my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');\n    my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm');\n\n    % plot the template electrode locations\n    my_plot3(avg,      'b.');\n    my_plot3(avg(1,:), 'b*');\n    my_plot3(avg(2,:), 'b*');\n    my_plot3(avg(3,:), 'b*');\n    my_text3(avg(1,:), norm.label{1}, 'color', 'b');\n    my_text3(avg(2,:), norm.label{2}, 'color', 'b');\n    my_text3(avg(3,:), norm.label{3}, 'color', 'b');\n\n    % plot lines connecting the input/warped electrode locations with the template locations\n    my_line3(elec.pnt, avg, 'color', 'r');\n    my_line3(norm.pnt, avg, 'color', 'm');\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif useheadshape && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % determine electrode selection and overlapping subset for warping\n  cfg.channel = channelselection(cfg.channel, elec.label);\n\n  % make subselection of electrodes\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label = elec.label(datsel);\n  elec.pnt   = elec.pnt(datsel,:);\n\n  fprintf('warping electrodes to head shape... '); % the newline comes later\n  [norm.pnt, norm.m] = warp_optim(elec.pnt, headshape, cfg.method);\n  norm.label = elec.label;\n\n  dpre  = warp_error([],     elec.pnt, headshape, cfg.method);\n  dpost = warp_error(norm.m, elec.pnt, headshape, cfg.method);\n  fprintf('mean distance prior to warping %f, after warping %f\\n', dpre, dpost);\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'realignfiducial')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  % try to determine the fiducials automatically if not specified\n  option1 = {'nasion' 'left' 'right'};\n  option2 = {'nasion' 'lpa' 'rpa'};\n  option3 = {'nz' 'lpa' 'rpa'};\n  if ~isfield(cfg, 'fiducial')\n    if length(match_str(elec.label, option1))==3\n      cfg.fiducial = option1;\n    elseif length(match_str(elec.label, option2))==3\n      cfg.fiducial = option2;\n    elseif length(match_str(elec.label, option3))==3\n      cfg.fiducial = option3;\n    else\n      error('could not determine three fiducials, please specify cfg.fiducial')\n    end\n  end\n  fprintf('using fiducials {''%s'', ''%s'', ''%s''}\\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});\n\n  % determine electrode selection\n  cfg.channel = channelselection(cfg.channel, elec.label);\n  [cfgsel, datsel] = match_str(cfg.channel, elec.label);\n  elec.label = elec.label(datsel);\n  elec.pnt   = elec.pnt(datsel,:);\n\n  if length(cfg.fiducial)~=3\n    error('you must specify three fiducials');\n  end\n\n  % do case-insensitive search for fiducial locations\n  nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));\n  if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1\n    error('not all fiducials were found in the electrode set');\n  end\n  elec_nas = elec.pnt(nas_indx,:);\n  elec_lpa = elec.pnt(lpa_indx,:);\n  elec_rpa = elec.pnt(rpa_indx,:);\n\n  % find the matching fiducials in the template and average them\n  templ_nas = [];\n  templ_lpa = [];\n  templ_rpa = [];\n  for i=1:Ntemplate\n    nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1}));\n    lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2}));\n    rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3}));\n    if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1\n      error(sprintf('not all fiducials were found in template %d', i));\n    end\n    templ_nas(end+1,:) = template(i).pnt(nas_indx,:);\n    templ_lpa(end+1,:) = template(i).pnt(lpa_indx,:);\n    templ_rpa(end+1,:) = template(i).pnt(rpa_indx,:);\n  end\n  templ_nas = mean(templ_nas,1);\n  templ_lpa = mean(templ_lpa,1);\n  templ_rpa = mean(templ_rpa,1);\n\n  % realign both to a common coordinate system\n  elec2common  = headcoordinates(elec_nas, elec_lpa, elec_rpa);\n  templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa);\n\n  % compute the combined transform and realign the electrodes to the template\n  norm       = [];\n  norm.m     = elec2common * inv(templ2common);\n  norm.pnt   = warp_apply(norm.m, elec.pnt, 'homogeneous');\n  norm.label = elec.label;\n\n  nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));\n  dpre  = mean(sqrt(sum((elec.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));\n  nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));\n  lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));\n  rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));\n  dpost = mean(sqrt(sum((norm.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));\n  fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\\n', dpre, dpost);\n\n  if strcmp(cfg.feedback, 'yes')\n    % plot the first three electrodes before transformation\n    my_plot3(elec.pnt(1,:), 'r*');\n    my_plot3(elec.pnt(2,:), 'r*');\n    my_plot3(elec.pnt(3,:), 'r*');\n    my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');\n    my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');\n    my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');\n\n    % plot the template fiducials\n    my_plot3(templ_nas, 'b*');\n    my_plot3(templ_lpa, 'b*');\n    my_plot3(templ_rpa, 'b*');\n    my_text3(templ_nas, ' nas', 'color', 'b');\n    my_text3(templ_lpa, ' lpa', 'color', 'b');\n    my_text3(templ_rpa, ' rpa', 'color', 'b');\n\n    % plot all electrodes after transformation\n    my_plot3(norm.pnt, 'm.');\n    my_plot3(norm.pnt(1,:), 'm*');\n    my_plot3(norm.pnt(2,:), 'm*');\n    my_plot3(norm.pnt(3,:), 'm*');\n    my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');\n    my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');\n    my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm');\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif strcmp(cfg.method, 'interactive')\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % open a figure\n  fig = figure;\n  % add the data to the figure\n  set(fig, 'CloseRequestFcn', @cb_close);\n  setappdata(fig, 'elec', elec);\n  setappdata(fig, 'transform', eye(4));\n  if useheadshape\n    setappdata(fig, 'surf', headshape);\n  end\n  if usetemplate\n    % FIXME interactive realigning to template electrodes is not yet supported\n    % this requires a consistent handling of channel selection etc.\n    setappdata(fig, 'template', template);\n  end\n  % add the GUI elements\n  cb_creategui(gca);\n  cb_redraw(gca);\n  rotate3d on\n  waitfor(fig);\n  % get the data from the figure that was left behind as global variable\n  global norm\n  tmp = norm;\n  clear global norm\n  norm = tmp;\n  clear tmp\n\nelse\n  error('unknown method');\nend\n\n% apply the spatial transformation to all electrodes, and replace the\n% electrode labels by their case-sensitive original values\nif any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))\n  norm.pnt   = warp_apply(norm.m, orig.pnt, cfg.method);\nelse\n  norm.pnt   = warp_apply(norm.m, orig.pnt, 'homogenous');\nend\nnorm.label = orig.label;\n\n% add version information to the configuration\ntry\n  % get the full name of the function\n  cfg.version.name = mfilename('fullpath');\ncatch\n  % required for compatibility with Matlab versions prior to release 13 (6.5)\n  [st, i] = dbstack;\n  cfg.version.name = st(i);\nend\ncfg.version.id = '$Id: electroderealign.m,v 1.1 2009/01/30 04:02:02 arno Exp $';\n\n% remember the configuration\nnorm.cfg = cfg;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% some simple SUBFUNCTIONs that facilitate 3D plotting\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction h = my_plot3(xyz, varargin)\nh = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});\nfunction h = my_text3(xyz, varargin)\nh = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});\nfunction my_line3(xyzB, xyzE, varargin)\nfor i=1:size(xyzB,1)\n  line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION to layout a moderately complex graphical user interface\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction h = layoutgui(fig, geometry, position, style, string, value, tag, callback);\nhoripos  = geometry(1); % lower left corner of the GUI part in the figure\nvertpos  = geometry(2); % lower left corner of the GUI part in the figure\nwidth    = geometry(3); % width  of the GUI part in the figure\nheight   = geometry(4); % height of the GUI part in the figure\nhoridist = 0.05;\nvertdist = 0.05;\noptions  = {'units', 'normalized', 'HorizontalAlignment', 'center'}; %  'VerticalAlignment', 'middle'\nNrow     = size(position,1);\nh        = cell(Nrow,1);\nfor i=1:Nrow\n  if isempty(position{i})\n    continue;\n  end\n  position{i} = position{i} ./ sum(position{i});\n  Ncol = size(position{i},2);\n  ybeg = (Nrow-i  )/Nrow + vertdist/2;\n  yend = (Nrow-i+1)/Nrow - vertdist/2;\n  for j=1:Ncol\n    xbeg    = sum(position{i}(1:(j-1))) + horidist/2;\n    xend    = sum(position{i}(1:(j  ))) - horidist/2;\n    pos(1) = xbeg*width  + horipos;\n    pos(2) = ybeg*height + vertpos;\n    pos(3) = (xend-xbeg)*width;\n    pos(4) = (yend-ybeg)*height;\n    h{i}{j} = uicontrol(fig, ...\n      options{:}, ...\n      'position', pos, ...\n      'style',    style{i}{j}, ...\n      'string',   string{i}{j}, ...\n      'tag',      tag{i}{j}, ...\n      'value',    value{i}{j}, ...\n      'callback', callback{i}{j} ...\n      );\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cb_creategui(hObject, eventdata, handles);\n% define the position of each GUI element\nposition = {\n  [2 1 1 1]\n  [2 1 1 1]\n  [2 1 1 1]\n  [1]\n  [1]\n  [1]\n  [1]\n  [1 1]\n  };\n\n% define the style of each GUI element\nstyle = {\n  {'text' 'edit' 'edit' 'edit'}\n  {'text' 'edit' 'edit' 'edit'}\n  {'text' 'edit' 'edit' 'edit'}\n  {'pushbutton'}\n  {'pushbutton'}\n  {'toggle'}\n  {'toggle'}\n  {'text' 'edit'}\n  };\n\n% define the descriptive string of each GUI element\nstring = {\n  {'rotate'    0 0 0}\n  {'translate' 0 0 0}\n  {'scale'     1 1 1}\n  {'redisplay'}\n  {'apply'}\n  {'toggle grid'}\n  {'toggle axes'}\n  {'alpha' 0.7}\n  };\n\n% define the value of each GUI element\nvalue = {\n  {[] [] [] []}\n  {[] [] [] []}\n  {[] [] [] []}\n  {[]}\n  {[]}\n  {0}\n  {0}\n  {[] []}\n  };\n\n% define a tag for each GUI element\ntag = {\n  {'' 'rx' 'ry' 'rz'}\n  {'' 'tx' 'ty' 'tz'}\n  {'' 'sx' 'sy' 'sz'}\n  {''}\n  {''}\n  {'toggle grid'}\n  {'toggle axes'}\n  {'' 'alpha'}\n  };\n\n% define the callback function of each GUI element\ncallback = {\n  {[] @cb_redraw @cb_redraw @cb_redraw}\n  {[] @cb_redraw @cb_redraw @cb_redraw}\n  {[] @cb_redraw @cb_redraw @cb_redraw}\n  {@cb_redraw}\n  {@cb_apply}\n  {@cb_redraw}\n  {@cb_redraw}\n  {[] @cb_redraw}\n  };\n\nfig = get(hObject, 'parent');\nlayoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cb_redraw(hObject, eventdata, handles);\nfig = get(hObject, 'parent');\nsurf = getappdata(fig, 'surf');\nelec = getappdata(fig, 'elec');\ntemplate = getappdata(fig, 'template');\n% get the transformation details\nrx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));\nry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));\nrz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));\ntx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));\nty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));\ntz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));\nsx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));\nsy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));\nsz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));\nR = rotate   ([rx ry rz]);\nT = translate([tx ty tz]);\nS = scale    ([sx sy sz]);\nH = S * T * R;\nelec.pnt = warp_apply(H, elec.pnt);\naxis vis3d; cla\nxlabel('x')\nylabel('y')\nzlabel('z')\nif ~isempty(surf)\n  triplot(surf.pnt, surf.tri,  [], 'faces_skin');\n  alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));\nend\nif ~isempty(template)\n  triplot(template.pnt, [], [], 'nodes_blue')\nend\ntriplot(elec.pnt, [], [], 'nodes');\nif isfield(elec, 'line')\n  triplot(elec.pnt, elec.line, [], 'edges');\nend\nif get(findobj(fig, 'tag', 'toggle axes'), 'value')\n  axis on\nelse\n  axis off\nend\nif get(findobj(fig, 'tag', 'toggle grid'), 'value')\n  grid on\nelse\n  grid off\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cb_apply(hObject, eventdata, handles);\nfig = get(hObject, 'parent');\nelec      = getappdata(fig, 'elec');\ntransform = getappdata(fig, 'transform');\n% get the transformation details\nrx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));\nry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));\nrz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));\ntx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));\nty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));\ntz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));\nsx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));\nsy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));\nsz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));\nR = rotate   ([rx ry rz]);\nT = translate([tx ty tz]);\nS = scale    ([sx sy sz]);\nH = S * T * R;\nelec.pnt = warp_apply(H, elec.pnt);\ntransform = H * transform;\nset(findobj(fig, 'tag', 'rx'), 'string', 0);\nset(findobj(fig, 'tag', 'ry'), 'string', 0);\nset(findobj(fig, 'tag', 'rz'), 'string', 0);\nset(findobj(fig, 'tag', 'tx'), 'string', 0);\nset(findobj(fig, 'tag', 'ty'), 'string', 0);\nset(findobj(fig, 'tag', 'tz'), 'string', 0);\nset(findobj(fig, 'tag', 'sx'), 'string', 1);\nset(findobj(fig, 'tag', 'sy'), 'string', 1);\nset(findobj(fig, 'tag', 'sz'), 'string', 1);\nsetappdata(fig, 'elec', elec);\nsetappdata(fig, 'transform', transform);\ncb_redraw(hObject);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cb_close(hObject, eventdata, handles);\n% make the current transformation permanent and subsequently allow deleting the figure\ncb_apply(gca);\n% get the updated electrode from the figure\nfig    = hObject;\n% hmmm, this is ugly\nglobal norm\nnorm   = getappdata(fig, 'elec');\nnorm.m = getappdata(fig, 'transform');\nset(fig, 'CloseRequestFcn', @delete);\ndelete(fig);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/electroderealign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24240790002681212}}
{"text": "function output = calllindo_nlp(interfacedata)\n\nglobal MY_LICENSE_FILE\n\npersistent iEnv\n\n% Instead of calling lindo, we define the parameters we need. This is\n% needed to speed up repeated calls\n%lindo\nLSERR_NO_ERROR                                               = 0000;\nLS_IPARAM_NLP_PRINTLEVEL                                     = 203;\nLS_IPARAM_NLP_SOLVER                                         = 201;\nLS_IPARAM_NLP_MAXLOCALSEARCH                                 = 221;\nLS_STATUS_OPTIMAL                                            = 1;\nLS_STATUS_BASIC_OPTIMAL                                      = 2;\nLS_STATUS_INFEASIBLE                                         = 3;\nLS_STATUS_UNBOUNDED                                          = 4;\nLS_STATUS_FEASIBLE                                           = 5;\nLS_STATUS_INFORUNB                                           = 6;\nLS_STATUS_NEAR_OPTIMAL                                       = 7;\nLS_STATUS_LOCAL_OPTIMAL                                      = 8;\nLS_STATUS_LOCAL_INFEASIBLE                                   = 9;\nLS_STATUS_CUTOFF                                             = 10;\nLS_STATUS_NUMERICAL_ERROR                                    = 11;\nLS_STATUS_UNKNOWN                                            = 12;\nLS_STATUS_UNLOADED                                           = 13;\nLS_STATUS_LOADED                                             = 14;\nLS_METHOD_FREE                                               = 0;\nLS_METHOD_PSIMPLEX                                           = 1;\nLS_METHOD_DSIMPLEX                                           = 2;\nLS_METHOD_BARRIER                                            = 3;\nLS_METHOD_NLP                                                = 4;\nLS_NMETHOD_FREE                                              = 4;\nLS_NMETHOD_CONOPT                                            = 7;\nLS_NMETHOD_MSW_GRG                                           = 9;\n\nif isempty(iEnv)\n    % This call is mighty slow, so we do it only once, unless uses clears\n    % everything\n    [MY_LICENSE_KEY,Err] = mxlindo('LSloadLicenseString',MY_LICENSE_FILE);\n    [iEnv,nErr]=mxlindo('LScreateEnv',MY_LICENSE_KEY);\n    if nErr ~= LSERR_NO_ERROR;output = returnempty(-5); return; end;\nend\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc       = interfacedata.c;\nK       = interfacedata.K;\nx0      = interfacedata.x0;\nQ       = interfacedata.Q;\nlb      = interfacedata.lb;\nub      = interfacedata.ub;\nmonomtable = interfacedata.monomtable;\n\n% Do some pre-calc to be used in callbacks\nnonlinearindicies = find(interfacedata.variabletype~=0);\nnonlinearindicies = unionstripped(nonlinearindicies,interfacedata.evalVariables);\nlinearindicies    = find(interfacedata.variabletype==0);\nlinearindicies    = setdiff1D(linearindicies,nonlinearindicies);\ninterfacedata.nonlinearindicies = nonlinearindicies;\ninterfacedata.linearindicies    = linearindicies;\n\n% % Move nonlinear bounds to constraints\nif ~isempty(lb)\n    finite = find(~isinf(lb(nonlinearindicies)));\n    if ~isempty(finite)\n        temp = F_struc(1:K.f,:);\n        F_struc(1:K.f,:) = [];\n        n = length(c);\n\n        for i = 1:length(finite)\n            j = nonlinearindicies(i);\n            F_struc = [-lb(j) sparse(1,j,1,1,n);F_struc];\n        end\n        K.l = K.l + length(finite);\n        F_struc = [temp;F_struc];\n        interfacedata.K = K;\n        interfacedata.F_struc = F_struc;\n    end\nend\nif ~isempty(ub)\n    finite = find(~isinf(ub(nonlinearindicies)));\n    if ~isempty(finite)\n        temp = F_struc(1:K.f,:);\n        F_struc(1:K.f,:) = [];\n        n = length(c);\n\n        for i = 1:length(finite)\n            j = nonlinearindicies(i);\n            F_struc = [ub(j) -sparse(1,j,1,1,n);F_struc];\n        end\n        K.l = K.l + length(finite);\n        F_struc = [temp;F_struc];\n        interfacedata.K = K;\n        interfacedata.F_struc = F_struc;\n    end\nend\n% \n% Init model size\nm  = K.l + K.f;\nn  = length(c);\n\n% Specifying variable types...\nvtype = repmat('C',1,length(c(linearindicies)));\nvtype(interfacedata.integer_variables) = 'I';\n\noshift = interfacedata.f;\n\nif m == 0\n    interfacedata.F_struc = [1e6 -ones(1,length(c))];\n    K.l = 1;\n    F_struc = [1e6 -ones(1,length(c))];\n    m = 1;\n    csense = [repmat('E',1,K.f) repmat('L',1,K.l)];\nend\n\n[Nbegcol,Nlencol,Nrowndx,Nobjcnt,Nobjndx,Apatt] = jacSparsity(interfacedata);\nA = -F_struc(:,1+linearindicies);\nb = full(F_struc(:,1));\ncsense = [repmat('E',1,K.f) repmat('L',1,K.l)];\nA = A.*(~Apatt);\nb(any(Apatt,2)) = 0;\n\n\n%[MY_LICENSE_KEY,nErr] = mxlindo('LSloadLicenseString',MY_LICENSE_FILE);\n\n%[iEnv,nErr]=mxlindo('LScreateEnv',MY_LICENSE_KEY);\n%if nErr ~= LSERR_NO_ERROR;output = returnempty(-5); return; end;\n[iModel,nErr]=mxlindo('LScreateModel',iEnv);\nif nErr ~= LSERR_NO_ERROR;output = returnempty(11); return; end;\nconstant_data = setup_fmincon_params(interfacedata);\nconstant_data.F_struc = F_struc;\nlindo_fun([],[],[],[],[],[],constant_data);\n[nErr] = mxlindo('LSsetFuncalc', iModel, 'lindo_fun',constant_data);\nif nErr ~= LSERR_NO_ERROR;output = returnempty(11); return; end;\n[nErr] = mxlindo('LSsetModelIntParameter', iModel, LS_IPARAM_NLP_PRINTLEVEL, options.verbose+1);\nif nErr ~= LSERR_NO_ERROR;output = returnempty(11); return; end;\n\n% Set NLP solver\n[nErr] = mxlindo('LSsetModelIntParameter', iModel, LS_IPARAM_NLP_SOLVER, eval(options.lindo.LS_IPARAM_NLP_SOLVER));\n[nErr] = mxlindo('LSsetModelIntParameter', iModel, LS_IPARAM_NLP_MAXLOCALSEARCH,options.lindo.LS_IPARAM_NLP_MAXLOCALSEARCH);\n\n% Load the LP portion of  model\n[nErr] = mxlindo('LSXloadLPData', iModel, 1, 0, c(linearindicies), b, csense,sparse(A), lb(linearindicies), ub(linearindicies));\nif nErr ~= LSERR_NO_ERROR;output = createoutput(11); return; end;\n\nnErr = mxlindo('LSloadVarType',iModel,vtype);\nif nErr ~= LSERR_NO_ERROR;output = createoutput(11); return; end;\n\n% Load the NLP portion of the model\n[nErr] = mxlindo('LSloadNLPData', iModel, Nbegcol, Nlencol,[], Nrowndx, Nobjcnt,Nobjndx,[]);\nif nErr ~= LSERR_NO_ERROR;output = createoutput(11); return; end;\n\n% Optimize model\nsolvertime = tic;\n\nif isempty(interfacedata.integer_variables)\n    solver = 2;\nelse\n    solver = 1;\nend\nsolvertime = tic;\nswitch solver\n    case 1\n        [solstat,nErr] = mxlindo('LSsolveMIP', iModel);\n        if ~ismember(solstat,[2009 LS_STATUS_INFEASIBLE])\n            [x,nErr] = mxlindo('LSgetMIPPrimalSolution',iModel);\n        else\n            x = zeros(length(linearindicies),1);\n        end\n    case 2\n        [solstat,nErr] = mxlindo('LSoptimize', iModel, eval(options.lindo.LS_METHOD));\n        if ~ismember(solstat,[2009 LS_STATUS_INFEASIBLE])\n            [x,nErr] = mxlindo('LSgetPrimalSolution',iModel);\n        else\n            x = zeros(length(linearindicies),1);\n        end\n    case 3\n        [solStatus,nErr] = mxlindo('LSsolveGOP', iModel);\n        [x,nErr] = mxlindo('LSgetPrimalSolution',iModel);\n    otherwise\nend\nsolvertime = toc(solvertime);\n\nw = zeros(length(c),1);w(linearindicies) =x;\ny = [];\n\n%[nErr]=mxlindo('LSdeleteEnv',iEnv);\n[nErr]=mxlindo('LSdeleteModel',iModel);\n\nswitch solstat\n    case {LS_STATUS_OPTIMAL,LS_STATUS_BASIC_OPTIMAL,7,8}\n        problem = 0;\n    case {LS_STATUS_INFEASIBLE,LS_STATUS_LOCAL_INFEASIBLE}\n        problem = 1;\n    case {LS_STATUS_UNBOUNDED}\n        problem = 2;\n    otherwise\n        problem = 11;\nend\ninfostr = yalmiperror(problem,'LINDO-QP');\n\n% Save all data sent to solver?\nif options.savesolverinput\n    solverinput.solstat = solstat;\n    solverinput.nErr = nErr;\n    solverinput.x = x;\nelse\n    solverinput = [];\nend\n\n% Save all data from the solver?\nif options.savesolveroutput\n    solveroutput.x = x;\n    solveroutput.fmin = fmin;\n    solveroutput.flag = flag;\n    solveroutput.output=output;\n    solveroutput.lambda=lambda;\nelse\n    solveroutput = [];\nend\n\n% Standard interface\noutput = createoutput(w,y,[],problem,'LINDO',solverinput,solveroutput,solvertime);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/calllindo_nlp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24240789467756008}}
{"text": "% Run this in order to construct the results table for the CE-CLM paper\nExtract_table_results_68;\n\nfile_out = fopen('results/300W_68.txt', 'w');\n\nfprintf(file_out, 'Errors with outline (68 points)\\n');\nfprintf(file_out, '------------------------------\\n');\nfprintf(file_out, 'Method\\tcomm\\tdiff\\n');\nfprintf(file_out, 'CLNF\\t%.2f\\t%.2f\\n', median(clnf_error_comm)*100, median(clnf_error_ibug)*100);\nfprintf(file_out, 'CFAN\\t--- \\t%.2f\\n', median(cfan_error_ibug)*100);\nfprintf(file_out, 'DRMF\\t%.2f\\t%.2f\\n', median(drmf_error_comm)*100, median(drmf_error_ibug)*100);\nfprintf(file_out, 'CFSS\\t%.2f\\t%.2f\\n', median(cfss_error_comm)*100, median(cfss_error_ibug)*100);\nfprintf(file_out, 'TCDCN\\t%.2f\\t%.2f\\n', median(tcdcn_error_comm)*100, median(tcdcn_error_ibug)*100);\nfprintf(file_out, '3DDFA\\t%.2f\\t%.2f\\n', median(error_3ddfa_comm)*100, median(error_3ddfa_ibug)*100);\nfprintf(file_out, '------------------------------\\n');\nfprintf(file_out, 'CE-CLM\\t%.2f\\t%.2f\\n', median(ceclm_error_comm)*100, median(ceclm_error_ibug)*100);\nfclose(file_out);\n\nExtract_table_results_49;\nfile_out = fopen('results/300W_49.txt', 'w');\n\nfprintf(file_out, 'Errors without outline (49 points)\\n');\nfprintf(file_out, '------------------------------\\n');\nfprintf(file_out, 'Method\\tcomm\\tdiff\\n');\nfprintf(file_out, 'CLNF\\t%.2f\\t%.2f\\n', median(clnf_error_comm)*100, median(clnf_error_ibug)*100);\nfprintf(file_out, 'SDM \\t%.2f\\t%.2f\\n', median(sdm_error_comm)*100, median(sdm_error_ibug)*100);\nfprintf(file_out, 'CFAN\\t--- \\t%.2f\\n', median(cfan_error_ibug)*100);\nfprintf(file_out, 'DRMF\\t%.2f\\t%.2f\\n', median(drmf_error_comm)*100, median(drmf_error_ibug)*100);\nfprintf(file_out, 'CFSS\\t%.2f\\t%.2f\\n', median(cfss_error_comm)*100, median(cfss_error_ibug)*100);\nfprintf(file_out, 'TCDCN\\t%.2f\\t%.2f\\n', median(tcdcn_error_comm)*100, median(tcdcn_error_ibug)*100);\nfprintf(file_out, '3DDFA\\t%.2f\\t%.2f\\n', median(error_3ddfa_comm)*100, median(error_3ddfa_ibug)*100);\nfprintf(file_out, '------------------------------\\n');\nfprintf(file_out, 'CE-CLM\\t%.2f\\t%.2f\\n', median(ceclm_error_comm)*100, median(ceclm_error_ibug)*100);\n\nfclose(file_out);", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/experiments_300W/Construct_error_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.24238178604150776}}
{"text": "% function [Results, Gt, F1, Fs2, Fs3, Ft2, Ft3] = GenerativeTriTL(Train_Data,Test_Data,Parameter_Setting)\nfunction [Results, pzd_t] = GenerativeTriTL(TrainData, TestData, TrainLabel, TestLabel, numIdentical, numAlike, numDistinct, numIter, numSource, numTrain, numTarget, numTest)\n% function [Results, pz_d] = TriTL(Train_Data,Test_Data,Parameter_Setting)\n\n% The common program for CD_PLSA, which can deal with multiple classes,\n% multiple source domains and multiple target domains\n\n%%%% Input:\n% The parameter Train_data stores the file pathes of training data and the\n% corresponding labels\n% The parameter Test_data stores the file pathes of test data and the\n% corresponding labels\n% The parameter Parameterfile stores the parameter setting information\n\n%%%% Output\n% The variable Results is a matrix with size numIteration x numTarget, where\n% numIteration is the number of iterations, numTarget is the number of\n% target domains. Results record the detailed results of each iteration.\n\n% The variable pz_d is a matrix with size n x c, where n is the number of\n% instances in all target domains, specifically, n = n_1 + ... + nt (n_t is\n% the number of instances in t-th target domain), c is the number of\n% classes\n%\n% Note that if you want to deal with large data set, you should set larget\n% memory for Matlab. You can set it in the file C:\\boot.ini (This may not\n% be true in your system), change '/fastdetect' to '/fastdetect /3GB'.\n%\n% Be good luck for your research, if you have any questions, you can\n% contact the email: zhuangfz@ics.ict.ac.cn\n\n%read the parameters\nnumK_1 = double(numIdentical);\nnumK_2 = double(numAlike);\nnumK_3 = double(numDistinct);\nnumIteration = double(numIter);\n\nTrainX = TrainData;\nTrainY = TrainLabel;\nTestX = TestData;\nTestY = TestLabel;\nlabelset = union(TestY,[]);\n\nnumC = length(labelset);\nnumFeature = size(TestX,1);\n\nstart = 1;\n% if numK_3 == 0\n%     start = 0;\n% end\nif start == 1\n    DataSetX = [TrainX TestX];\n    Learn.Verbosity = 1;\n    Learn.Max_Iterations = 20;\n    Learn.heldout = .1; % for tempered EM only, percentage of held out data\n    Learn.Min_Likelihood_Change = 1;\n    Learn.Folding_Iterations = 20; % for TEM only: number of fiolding in iterations\n    Learn.TEM = 0; %tempered or not tempered\n    [Pw_z,Pz_d,Pd,Li,perp,eta] = pLSA(DataSetX,[],numK_1+numK_2,Learn); %start PLSA\n    %xlswrite(strcat('pwz_','common_selected','.xls'),Pw_z);\n    csvwrite(strcat('pzw_','common_selected','.plsa'),Pw_z);\nend\n%pwy = xlsread(strcat('pwz_','common_selected','.xls'));\n\n%% Following are Initializaitons\npzw = csvread(strcat('pzw_','common_selected','.plsa'));\npwy_a = pzw(:,1:numK_1); % the common topics using the same words\npwy_b_s = []; % the common topics using different words\npwy_b_t = []; % the common topics using different words\nfor i = 1:numSource\n    pwy_b_s = [pwy_b_s, pzw(:,1+numK_1:numK_1+numK_2)];\nend\nfor i = 1:numTarget\n    pwy_b_t = [pwy_b_t, pzw(:,1+numK_1:numK_1+numK_2)];\nend\n% pwy_c_s = []; % different topics using different words\n% pwy_c_t = []; % different topics using different words\npwy_c_s = ones(numFeature,numK_3*numSource)/numFeature;\npwy_c_t = ones(numFeature,numK_3*numTarget)/numFeature;\nclear pzw;\npdz_s = zeros(sum(numTrain),numC);\nfor i = 1:size(pdz_s,1)\n    pdz_s(i,TrainY(i)) = 1;\nend\nfor i = 1:numSource\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTrain(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    for j = 1:numC\n        pdz_s(pos+1:pos+numTrain(i),j) = pdz_s(pos+1:pos+numTrain(i),j)/sum(pdz_s(pos+1:pos+numTrain(i),j));\n    end\nend\n\n% In our paper, pdz_t is assigned as the predicted results by supervised\n% classifiers\n% The initialization of the target-domain label\npdz_t = zeros(sum(numTest),numC);\nflag = 1;\nif flag == 1\n    w_models = [];\n    for i = 1:numSource\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTrain(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        TempTrainX = TrainX(:,pos+1:pos+numTrain(i));\n        TempTrainY = TrainY(:,pos+1:pos+numTrain(i));\n        for v = 1:length(TempTrainY)\n            if TempTrainY(v) > 1\n                TempTrainY(v) = -1;\n            end\n        end\n        \n        TempTrainXY = scale_cols(TempTrainX,TempTrainY);\n        fprintf('.....................................\\n');\n        w00 = zeros(size(TempTrainXY,1),1);\n        lambda = exp(linspace(-0.5,6,20));\n        wbest = [];\n        f1max = -inf;\n        for j = 1:length(lambda)\n            w_0 = train_cg(TempTrainXY,w00,lambda(j));\n            f1 = logProb(TempTrainXY,w_0);\n            if f1 > f1max\n                f1max = f1;\n                wbest = w_0;\n                %se_lambda = lambda(j);\n            end\n        end\n        w_models = [w_models wbest];\n        clear TempTrainX;\n        clear TempTrainY;\n        clear TempTrainXY;\n    end\n%     csvwrite(strcat('lg_models/','model_lg.model'),w_models);\nend\n\nTempGt = zeros(size(pdz_t));\n% w_models = csvread(strcat('lg_models/','model_lg.model'));\nfor i = 1:numTarget\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTest(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    TempTestX = TestX(:,pos+1:pos+numTest(i));\n    for j = 1:numSource\n        wbest = w_models(:,j);\n        ptemp = 1./(1 + exp(-wbest'*TempTestX));\n    end\n    TempGt(pos+1:pos+numTest(i),:) = TempGt(pos+1:pos+numTest(i),:) + [(ptemp'+0.5)/2 ((1-ptemp)'+0.5)/2];    \n    clear TempTestX;\nend\nTempGt = TempGt/numSource;\npdz_t = TempGt; % not yet normalize\n%% The initialization pyz\npyz_a = ones(numK_1,numC)/numK_1;\npyz_b = ones(numK_2,numC)/numK_2;\npyz_c_s = ones(numK_3,numC*numSource)/numK_3;\npyz_c_t = ones(numK_3,numC*numTarget)/numK_3;\n\n%% the initial accuracy\niter_results = [];\nfor i = 1:numTarget\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTest(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    pzd = pdz_t(pos+1:pos+numTest(i),:);\n    nCorrect = 0;\n    for j = 1:size(pzd,1)\n        [va vi] = max(pzd(j,:));\n        if labelset(vi) == TestY(pos+j)\n            nCorrect = nCorrect + 1;\n        end\n    end\n    iter_results(1,i+1) = nCorrect/(numTest(i));\n    iter_results(1,1) = 0;\nend\n\n% the normalization of pdz_t\nfor i = 1:numTarget\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTest(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    for j = 1:numC\n        pdz_t(pos+1:pos+numTest(i),j) = pdz_t(pos+1:pos+numTest(i),j)/sum(pdz_t(pos+1:pos+numTest(i),j));\n    end\nend\n\npzr_s = ones(1,numC*numSource)/numC;\npzr_t = ones(1,numC*numTarget)/numC;\npr = ones(1,numSource+numTarget)/(numSource+numTarget);\n\nfor i = 1:numSource\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTrain(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    pr(i) = sum(sum(TrainX(:,pos+1:pos+numTrain(i))));\nend\nfor i = 1:numTarget\n    pos = 0;\n    if i > 1\n        for t = 1:i-1\n            pos = pos + numTest(t);\n        end\n    end\n    if i == 1\n        pos = 0;\n    end\n    pr(numSource+i) = sum(sum(TestX(:,pos+1:pos+numTest(i))));\nend\npr = pr/sum(pr);\n%% stepLen\nstepLen = 1000;\n% fprintf('the 0 iteration,the value of objective is %g\\n',fvalue);\n%% Start to interate\n% update all variables \n% pwy_a; pwy_b_s; pwy_b_t; pwy_c_s; pwy_c_t; pdz_s; pdz_t; \n% pyz_a; pyz_b; pyz_c_s; pyz_c_t; pzr_s; pzr_t; pr;\nfor iterID = 1:numIteration\n    \n    % update pwy_a; pwy_b_s; pwy_b_t; pwy_c_s; pwy_c_t;\n    temp_pwy_a = zeros(size(pwy_a));\n    temp_pwy_b_s = [];\n    temp_pwy_b_t = [];\n    temp_pwy_c_s = [];\n    temp_pwy_c_t = [];    \n    % update pdz_t; \n    temp_pdz_t = [];    \n    % update pzr_s; pzr_t; pr\n    temp_pzr_s = [];\n    temp_pzr_t = [];\n    temp_pr = [];\n    for i = 1:numSource\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTrain(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        A = pyz_a;\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_s(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_a*A*pdz_s(pos+1:pos+numTrain(i),:)';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pwy_a = temp_pwy_a + pwy_a.*(MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen)*A'*pr(i));\n        I = sum(MatrixProduce(pwy_a',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen),stepLen).*pyz_a)*pr(i);\n        \n        %%-----------------%%\n        A = pyz_b;\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_s(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_b_s(:,(i-1)*numK_2+1:i*numK_2)*A*pdz_s(pos+1:pos+numTrain(i),:)';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pwy_b_s(:,(i-1)*numK_2+1:i*numK_2).*(MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen)*A'*pr(i));\n        temp_pwy_b_s = [temp_pwy_b_s B];\n        I = I + sum(MatrixProduce(pwy_b_s(:,(i-1)*numK_2+1:i*numK_2)',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen),stepLen).*pyz_b)*pr(i);\n        \n        A = pyz_c_s(:,(i-1)*numC+1:i*numC);\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_s(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_c_s(:,(i-1)*numK_3+1:i*numK_3)*A*pdz_s(pos+1:pos+numTrain(i),:)';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pwy_c_s(:,(i-1)*numK_3+1:i*numK_3).*(MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen)*A'*pr(i));\n        temp_pwy_c_s = [temp_pwy_c_s B];   \n        I = I + sum(MatrixProduce(pwy_c_s(:,(i-1)*numK_3+1:i*numK_3)',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,pdz_s(pos+1:pos+numTrain(i),:),stepLen),stepLen).*pyz_c_s(:,(i-1)*numC+1:i*numC))*pr(i);\n        temp_pzr_s = [temp_pzr_s I]; \n        temp_pr = [temp_pr sum(I)];\n    end\n    for i = 1:numTarget\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTest(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        A = pyz_a;\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_t(1,j+(i-1)*numC);\n        end        \n        \n        tempsum2 = pwy_a*A*pdz_t(pos+1:pos+numTest(i),:)';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pwy_a = temp_pwy_a + pwy_a.*(MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen)*A'*pr(numSource+i));\n        H = (MatrixProduce([TestX(:,pos+1:pos+numTest(i))./tempsum2]',pwy_a,stepLen)*A*pr(numSource+i));\n        I = sum(MatrixProduce(pwy_a',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen),stepLen).*pyz_a)*pr(numSource+i);\n        %%-----------------%%\n        A = pyz_b;\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_t(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_b_t(:,(i-1)*numK_2+1:i*numK_2)*A*pdz_t(pos+1:pos+numTest(i),:)';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pwy_b_t(:,(i-1)*numK_2+1:i*numK_2).*(MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen)*A'*pr(numSource+i));\n        temp_pwy_b_t = [temp_pwy_b_t B];\n        H = H + (MatrixProduce([TestX(:,pos+1:pos+numTest(i))./tempsum2]',pwy_b_t(:,(i-1)*numK_2+1:i*numK_2),stepLen)*A*pr(numSource+i));\n        I = I + sum(MatrixProduce(pwy_b_t(:,(i-1)*numK_2+1:i*numK_2)',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen),stepLen).*pyz_b)*pr(numSource+i);\n                \n        A = pyz_c_t(:,(i-1)*numC+1:i*numC);\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_t(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_c_t(:,(i-1)*numK_3+1:i*numK_3)*A*pdz_t(pos+1:pos+numTest(i),:)';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pwy_c_t(:,(i-1)*numK_3+1:i*numK_3).*(MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen)*A'*pr(numSource+i));\n        temp_pwy_c_t = [temp_pwy_c_t B];\n        H = H + (MatrixProduce([TestX(:,pos+1:pos+numTest(i))./tempsum2]',pwy_c_t(:,(i-1)*numK_3+1:i*numK_3),stepLen)*A*pr(numSource+i));\n        H = pdz_t(pos+1:pos+numTest(i),:).*H;\n        temp_pdz_t = [temp_pdz_t; H];\n        I = I + sum(MatrixProduce(pwy_c_t(:,(i-1)*numK_3+1:i*numK_3)',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,pdz_t(pos+1:pos+numTest(i),:),stepLen),stepLen).*pyz_c_t(:,(i-1)*numC+1:i*numC))*pr(numSource+i);\n        temp_pzr_t = [temp_pzr_t I]; \n        temp_pr = [temp_pr sum(I)];\n    end    \n    \n    % update pyz_a; pyz_b; pyz_c_s; pyz_c_t;\n    temp_pyz_a = zeros(size(pyz_a));\n    temp_pyz_b = zeros(size(pyz_b));\n    temp_pyz_c_s = [];\n    temp_pyz_c_t = [];\n    for i = 1:numSource\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTrain(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        A = pdz_s(pos+1:pos+numTrain(i),:);\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_s(1,j+(i-1)*numC);\n        end\n        \n        tempsum2 = pwy_a*pyz_a*A';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pyz_a = temp_pyz_a + pyz_a.*(MatrixProduce(pwy_a',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,A,stepLen),stepLen)*pr(i));\n        \n        %%-----------------%%\n        tempsum2 = pwy_b_s(:,(i-1)*numK_2+1:i*numK_2)*pyz_b*A';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pyz_b = temp_pyz_b + pyz_b.*(MatrixProduce(pwy_b_s(:,(i-1)*numK_2+1:i*numK_2)',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,A,stepLen),stepLen)*pr(i));\n        \n        tempsum2 = pwy_c_s(:,(i-1)*numK_3+1:i*numK_3)*pyz_c_s(:,(i-1)*numC+1:i*numC)*A';\n        tempsum2 = tempsum2*pr(i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pyz_c_s(:,(i-1)*numC+1:i*numC).*(MatrixProduce(pwy_c_s(:,(i-1)*numK_3+1:i*numK_3)',MatrixProduce(TrainX(:,pos+1:pos+numTrain(i))./tempsum2,A,stepLen),stepLen)*pr(i));\n        temp_pyz_c_s = [temp_pyz_c_s B];\n    end\n    for i = 1:numTarget\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTest(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        A = pdz_t(pos+1:pos+numTest(i),:);\n        for j = 1:numC\n            A(:,j) = A(:,j)*pzr_t(1,j+(i-1)*numC);\n        end\n        tempsum2 = pwy_a*pyz_a*A';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pyz_a = temp_pyz_a + pyz_a.*(MatrixProduce(pwy_a',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,A,stepLen),stepLen)*pr(numSource+i));\n        \n        %%-----------------%%\n        tempsum2 = pwy_b_t(:,(i-1)*numK_2+1:i*numK_2)*pyz_b*A';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        temp_pyz_b = temp_pyz_b + pyz_b.*(MatrixProduce(pwy_b_t(:,(i-1)*numK_2+1:i*numK_2)',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,A,stepLen),stepLen)*pr(numSource+i));\n        \n        tempsum2 = pwy_c_t(:,(i-1)*numK_3+1:i*numK_3)*pyz_c_t(:,(i-1)*numC+1:i*numC)*A';\n        tempsum2 = tempsum2*pr(numSource+i);\n        [xs ys] = find(tempsum2 < 10^(-20));\n        for q = 1:size(xs,1)\n            tempsum2(xs(q,1),ys(q,1)) = 1;\n        end\n        B = pyz_c_t(:,(i-1)*numC+1:i*numC).*(MatrixProduce(pwy_c_t(:,(i-1)*numK_3+1:i*numK_3)',MatrixProduce(TestX(:,pos+1:pos+numTest(i))./tempsum2,A,stepLen),stepLen)*pr(numSource+i));\n        temp_pyz_c_t = [temp_pyz_c_t B];\n    end    \n     \n    % normalize all the variables\n    pwy_a = temp_pwy_a;\n    pwy_b_s = temp_pwy_b_s; \n    pwy_b_t = temp_pwy_b_t; \n    pwy_c_s = temp_pwy_c_s; \n    pwy_c_t = temp_pwy_c_t; \n    % pdz_s = temp_pdz_s; \n    pdz_t = temp_pdz_t; \n    pyz_a = temp_pyz_a; \n    pyz_b = temp_pyz_b; \n    pyz_c_s = temp_pyz_c_s; \n    pyz_c_t = temp_pyz_c_t; \n    pzr_s = temp_pzr_s; \n    pzr_t = temp_pzr_t; \n    pr = temp_pr;\n    \n    for t = 1:numK_1\n        pwy_a(:,t) = pwy_a(:,t)/sum(pwy_a(:,t));\n    end\n    for t = 1:numC\n        pyz_a(:,t) = pyz_a(:,t)/sum(pyz_a(:,t));\n        pyz_b(:,t) = pyz_b(:,t)/sum(pyz_b(:,t));\n    end\n    pr = pr/sum(pr);\n    for t = 1:numK_2*numSource\n        pwy_b_s(:,t) = pwy_b_s(:,t)/sum(pwy_b_s(:,t));\n    end\n    for t = 1:numK_3*numSource\n        pwy_c_s(:,t) = pwy_c_s(:,t)/sum(pwy_c_s(:,t));\n    end\n    for t = 1:numC*numSource\n        pyz_c_s(:,t) = pyz_c_s(:,t)/sum(pyz_c_s(:,t));\n    end\n    for t = 1:numK_2*numTarget\n        pwy_b_t(:,t) = pwy_b_t(:,t)/sum(pwy_b_t(:,t));\n    end\n    for t = 1:numK_3*numTarget\n        pwy_c_t(:,t) = pwy_c_t(:,t)/sum(pwy_c_t(:,t));\n    end\n    for t = 1:numC*numTarget\n        pyz_c_t(:,t) = pyz_c_t(:,t)/sum(pyz_c_t(:,t));\n    end\n    for i = 1:numTarget\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTest(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        for t = 1:numC\n            pdz_t(pos+1:pos+numTest(i),t) = pdz_t(pos+1:pos+numTest(i),t)/sum(pdz_t(pos+1:pos+numTest(i),t));\n        end\n    end    \n    for i = 1:numSource\n        pzr_s(1,(i-1)*numC+1:i*numC) = pzr_s(1,(i-1)*numC+1:i*numC)/sum(pzr_s(1,(i-1)*numC+1:i*numC));\n    end\n    for i = 1:numTarget\n        pzr_t(1,(i-1)*numC+1:i*numC) = pzr_t(1,(i-1)*numC+1:i*numC)/sum(pzr_t(1,(i-1)*numC+1:i*numC));\n    end\n    \n    %%%%%% The output results\n    pzd_t = [];\n    for i = 1:numTarget\n        A = pdz_t(pos+1:pos+numTest(i),:);\n        for t = 1:numC\n            A(:,t) = A(:,t)*pzr_t(1,(i-1)*numC+t);\n        end\n        A = A*pr(numSource+i);\n        pzd_t = [pzd_t; A];\n    end\n    iter_results(iterID+1,1) = iterID;\n    for i = 1:numTarget\n        pos = 0;\n        if i > 1\n            for t = 1:i-1\n                pos = pos + numTest(t);\n            end\n        end\n        if i == 1\n            pos = 0;\n        end\n        pzd = pzd_t(pos+1:pos+numTest(i),:);\n        nCorrect = 0;\n        for j = 1:size(pzd,1)\n            [va vi] = max(pzd(j,:));\n            if labelset(vi) == TestY(pos+j)\n                nCorrect = nCorrect + 1;\n            end\n        end\n        iter_results(iterID+1,i+1) = nCorrect/(numTest(i));\n    end\nend\n%% output\nResults = iter_results\nend\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/HIDC/GenerativeTriTL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24238177988240542}}
{"text": "function fx = jdfunc (jdin)\n\n% objective function for tdb2utc\n\n% input\n\n%  jdin = current value for UTC julian date\n\n% output\n\n%  fx = delta julian date\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal jdsaved\n\ntai_utc = findleap(jdin);\n\nfx = utc2tdb (jdin, tai_utc) - jdsaved;\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43173-a-matlab-script-for-predicting-orbital-events-of-the-planets/jdfunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2423817798824054}}
{"text": "function [displacements,rois_dic,seedinfo,outstate] = ncorr_alg_dicanalysis(imgs,radius,spacing,cutoff_diffnorm,cutoff_iteration,total_threads,enabled_stepanalysis,subsettrunc,num_img,total_imgs,pos_parent,params_init)\n% This function performs RG-DIC.\n%\n% Inputs -----------------------------------------------------------------%\n%   imgs - struct; Contains struct('imginfo',{},'roi',{}). Contains the \n%   reference and current images packaged together. The imginfo field\n%   contains an ncorr_class_img and the ROI field contains an ncorr_class_roi.\n%   radius - integer; subset radius\n%   spacing - integer; subset spacing\n%   cutoff_diffnorm - double; cutoff for the norm of difference vector\n%   cutoff_iteration - integer; cutoff for the number of IC-GN iterations\n%   total_threads - integer; total number of threads\n%   enabled_stepanalysis - logical; if true, then process as many seeds as\n%   possible. If false, process all the seeds.\n%   subsettrunc - logical; if true, then subset truncation is enabled\n%   num_img - integer; reference image number\n%   total_imgs - integer; total number of images\n%   pos_parent - integer array; this is the position of the parent figure\n%   which determines where to position this figure\n%   params_init - struct; contains struct('paramvector',{},'num_region',{},\n%   'num_thread',{},'computepoints',{}). If its not empty, it contains last \n%   set of seeds used for the previous iteration\n%\n% Outputs ----------------------------------------------------------------%\n%   displacements - struct; contains\n%   struct('plot_u',{},'plot_v',{},'plot_corrcoef',{},'plot_validpoints',{}) \n%   rois_dic - ncorr_class_img; ROIs after being unioned with reference roi \n%   and validpoints from DIC analysis.\n%   seedinfo - struct; contains struct('paramvector',{},'num_region',{},\n%   'num_thread',{},'computepoints',{})\n%   outstate - integer; returns either out.cancelled, out.failed, or\n%   out.success.\n%\n% outstate will only return failed if ncorr_alg_rgdic throws an exception.\n\n    % Initialize outputs\n    outstate = out.cancelled;\n    displacements = struct('plot_u',{},'plot_v',{},'plot_corrcoef',{},'plot_validpoints',{});    \n    rois_dic = ncorr_class_roi.empty;\n    seedinfo = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});\n    \n    % --------------------------------------------------------------------%\n    % Get Seeds ----------------------------------------------------------%\n    % --------------------------------------------------------------------%\n    \n    if (isempty(params_init))\n        % Get new seeds manually through GUI. outstate_seeds will either be\n        % success or cancelled.\n        [seedinfo_prelim,threaddiagram,outstate_seeds] = ncorr_gui_seedanalysis(imgs(1).imginfo, ...\n                                                                                [imgs(2:end).imginfo], ...\n                                                                                imgs(1).roi, ...\n                                                                                radius, ...\n                                                                                spacing, ...\n                                                                                cutoff_diffnorm, ...\n                                                                                cutoff_iteration, ...\n                                                                                total_threads, ...\n                                                                                enabled_stepanalysis, ...\n                                                                                subsettrunc, ...\n                                                                                num_img, ...\n                                                                                total_imgs, ...\n                                                                                pos_parent);\n        % See if analysis was cancelled\n        if (outstate_seeds ~= out.success)\n            return;\n        end            \n    else\n        % Use params init to place seeds directly               \n        % Initialize seedinfo_prelim\n        seedinfo_prelim = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});\n            \n        % Initialize Thread diagram buffers - some buffers are unused\n        ref_reduced = imgs(1).imginfo.reduce(spacing); % Unused\n        roi_reduced = imgs(1).roi.reduce(spacing); % Unused\n        preview_threaddiagram = zeros(size(roi_reduced.mask)); % Unused\n        threaddiagram_buffer = -ones(size(roi_reduced.mask));\n        threaddiagram = -ones(size(roi_reduced.mask)); % This must be negative 1\n        \n        % Calculate seeds - cycle over regions\n        num_imgs_success = inf; % Initialize to impossibly high value\n        manualseed = false; % Set this parameter true if there is trouble. This causes the user to reselect the seeds manually through a GUI.\n        % Cycle over regions\n        for i = 0:size(params_init,2)-1 \n            % Get updated seed positions based on seed locations of the\n            % last successfully seeded image for this region\n            % Initialize\n            pos_seed = zeros(size(params_init,1),2);\n            % Cycle over threads\n            for j = 0:size(params_init,1)-1\n                % Must round displacements so that the updated position\n                % lies properly on \"spaced grid\" - THIS IS IMPORTANT!!!\n                pos_seed(j+1,1) = params_init(j+1,i+1,end).paramvector(1) + round(params_init(j+1,i+1,end).paramvector(3)/(spacing+1))*(spacing+1);\n                pos_seed(j+1,2) = params_init(j+1,i+1,end).paramvector(2) + round(params_init(j+1,i+1,end).paramvector(4)/(spacing+1))*(spacing+1);\n            end\n            \n            % Get num_region - just use seed from the first thread\n            num_region = params_init(1,i+1,end).num_region;\n            \n            % Make sure seed positions are within the ROI and are unique.\n            % If they arent then prompt the user and have them replace the\n            % seeds manually.\n            regionmask = roi_reduced.get_regionmask(num_region); \n            if (size(pos_seed,1) == size(unique(pos_seed,'rows'),1) && ...\n                all(pos_seed(:,1)./(spacing+1) >= 0) && all(pos_seed(:,1)./(spacing+1) < size(regionmask,2)) && ...\n                all(pos_seed(:,2)./(spacing+1) >= 0) && all(pos_seed(:,2)./(spacing+1) < size(regionmask,1)) && ...\n                all(regionmask(sub2ind(size(regionmask),pos_seed(:,2)/(spacing+1)+1,pos_seed(:,1)/(spacing+1)+1))))\n                % Get seeds - outstate will be successful if at least one\n                % image is seeded\n                [seedinfo_buffer,convergence_buffer,outstate_seeds] = ncorr_alg_seedanalysis(imgs(1).imginfo, ...\n                                                                                             [imgs(2:end).imginfo], ...\n                                                                                             imgs(1).roi, ...\n                                                                                             num_region, ...\n                                                                                             pos_seed, ...\n                                                                                             radius, ...\n                                                                                             cutoff_diffnorm, ...\n                                                                                             cutoff_iteration, ...\n                                                                                             enabled_stepanalysis, ...\n                                                                                             subsettrunc, ...\n                                                                                             num_img, ...\n                                                                                             total_imgs); %#ok<ASGLU>\n                % See if analysis was cancelled\n                if (outstate_seeds == out.cancelled)\n                    return;\n                end\n                \n                % See if analysis was successful or failed\n                if (outstate_seeds == out.success)     \n                    % Form thread diagram for these seeds\n                    ncorr_alg_formthreaddiagram(threaddiagram_buffer,preview_threaddiagram,int32(pos_seed/(spacing+1)),regionmask,ref_reduced.formatted());\n\n                    % Get compute points\n                    for j = 0:size(seedinfo_buffer,3)-1\n                        for k = 0:size(seedinfo_buffer,1)-1\n                            seedinfo_buffer(k+1,1,j+1).computepoints = length(find(threaddiagram_buffer == k));\n                        end\n                    end    \n                else\n                    % Seed analysis failed. Alert user and then ask him/her\n                    % to manually place seeds.\n                    h_error = errordlg('Not a single image was seeded correctly; please replace seeds manually.','Error','modal');\n                    uiwait(h_error);\n                    \n                    manualseed = true;\n                end\n            else\n                % Alert user\n                h_error = errordlg('One or more seeds went outside of the ROI **OR** converged on top of each other, please replace manually. If this happens often then dont place seeds near each other or near the boundary.','Error','modal');\n                uiwait(h_error);\n                manualseed = true;\n            end            \n            \n            if (~manualseed)            \n                % Take minimum of num_imgs_success and\n                % seedinfo. Buffer can be more or less than\n                % num_imgs_success\n                num_imgs_success = min(num_imgs_success, size(seedinfo_buffer,3));\n\n                % Clear out other images in buffer and prelim\n                if (~isempty(seedinfo_prelim))\n                    seedinfo_prelim = seedinfo_prelim(:,:,1:num_imgs_success);\n                end\n                seedinfo_buffer = seedinfo_buffer(:,:,1:num_imgs_success);\n\n                % Append seedinfo_buffer - append along 2nd dimension \n                seedinfo_prelim = horzcat(seedinfo_prelim,seedinfo_buffer); %#ok<AGROW>  \n\n                % Merge threaddiagram from previous iteration\n                threaddiagram(threaddiagram_buffer ~= -1) = threaddiagram_buffer(threaddiagram_buffer ~= -1);\n            else\n                % If there's a problem, just ask user to manually reset\n                % seeds. Outstate will either be success or cancelled.\n                [seedinfo_prelim,threaddiagram,outstate_seeds] = ncorr_gui_seedanalysis(imgs(1).imginfo, ...\n                                                                                        [imgs(2:end).imginfo], ...\n                                                                                        imgs(1).roi, ...\n                                                                                        radius, ...\n                                                                                        spacing, ...\n                                                                                        cutoff_diffnorm, ...\n                                                                                        cutoff_iteration, ...\n                                                                                        total_threads, ...\n                                                                                        enabled_stepanalysis, ...\n                                                                                        subsettrunc, ...\n                                                                                        num_img, ...\n                                                                                        total_imgs, ...\n                                                                                        pos_parent);\n                                                                                    \n                % Check if analysis was cancelled\n                if (outstate_seeds ~= out.success)\n                    return;\n                end\n                \n                % Break since seeds for all regions are placed in GUI.\n                break;\n            end\n        end\n        \n        % Debug ----------------------------------------------------------%\n        %{\n        figure, imshow(threaddiagram,[]); hold on;\n        for i = 0:size(seedinfo_prelim,2)-1\n            for j = 0:size(seedinfo_prelim,1)-1\n                plot(seedinfo_prelim(j+1,i+1,1).paramvector(1)/(spacing+1),seedinfo_prelim(j+1,i+1,1).paramvector(2)/(spacing+1),'ro');\n            end\n        end\n        hold off;\n        %}\n        % ----------------------------------------------------------------%\n    end                                                                     \n                                        \n    % --------------------------------------------------------------------%\n    % Perform DIC Analysis -----------------------------------------------%\n    % --------------------------------------------------------------------%\n    \n    % Format Seeds ---------------------------------------------------%\n    seedinfo_prelim_f = seedinfo_prelim;\n    for i = 0:size(seedinfo_prelim,1)-1\n        for j = 0:size(seedinfo_prelim,2)-1\n            for k = 0:size(seedinfo_prelim,3)-1\n                seedinfo_prelim_f(i+1,j+1,k+1).num_region = int32(seedinfo_prelim(i+1,j+1,k+1).num_region);\n                seedinfo_prelim_f(i+1,j+1,k+1).num_thread = int32(seedinfo_prelim(i+1,j+1,k+1).num_thread);\n                seedinfo_prelim_f(i+1,j+1,k+1).computepoints = int32(seedinfo_prelim(i+1,j+1,k+1).computepoints);\n            end\n        end\n    end    \n\n    % Begin DIC analysis ---------------------------------------------%\n    displacements_prelim = struct('plot_u',{},'plot_v',{},'plot_corrcoef',{},'plot_validpoints',{});    \n    rois_dic_prelim = ncorr_class_roi.empty;\n    for i = 0:size(seedinfo_prelim,3)-1\n        % Put in try block because DIC can run\n        % out of memory                                \n        try\n            tic\n            % No need to send in the number of regions or total number\n            % of threads because this is encoded in the size of the\n            % seeds. \n            % FYI: seeinfo_prelim(i,j,k) where i refers to the thread\n            % number, j refers to the region, and k refers to the image.\n            % ncorr_alg_rgdic will either return success or cancelled or\n            % return an exception.\n            [displacements_prelim(i+1),outstate_dic] = ncorr_alg_rgdic(imgs(1).imginfo.formatted(), ...\n                                                                       imgs(i+2).imginfo.formatted(), ...\n                                                                       imgs(1).roi.formatted(), ...\n                                                                       seedinfo_prelim_f(:,:,i+1), ...\n                                                                       int32(threaddiagram), ...\n                                                                       int32(radius), ...\n                                                                       int32(spacing), ...\n                                                                       cutoff_diffnorm, ...\n                                                                       int32(cutoff_iteration), ...\n                                                                       logical(subsettrunc), ...\n                                                                       int32(num_img+i), ...\n                                                                       int32(total_imgs));       \n            toc\n        catch %#ok<CTCH>\n            % Only time an exception is returned is either if rgdic has\n            % incorrect inputs, ran out of memory, or there is a bug in \n            % the code. The first option never happens if rgdic\n            % is called through the program. The second option can \n            % happen and is thus the only real handleable exception \n            % which will get thrown by rgdic. The last case was not\n            % intended, so it is not handled here.\n            h_error = errordlg('Ncorr most likely ran out of memory while performing DIC. Please clear memory in workspace, restart Ncorr, or crop/use smaller images before doing analysis.','Error','modal');\n            uiwait(h_error);\n            return;\n        end  \n\n        % See if analysis was cancelled\n        if (outstate_dic ~= out.success)\n            return;\n        end\n\n        % Take union of reference ROI with validpoints to get the new\n        % ROI.\n        rois_dic_prelim(i+1) = imgs(1).roi.get_union(displacements_prelim(i+1).plot_validpoints,spacing);\n    end\n\n    % Set outputs\n    for i = 0:length(displacements_prelim)-1\n        displacements(i+1) = displacements_prelim(i+1);\n        rois_dic(i+1) = rois_dic_prelim(i+1);\n    end\n    for i = 0:size(seedinfo_prelim,1)-1\n        for j = 0:size(seedinfo_prelim,2)-1\n            for k = 0:size(seedinfo_prelim,3)-1\n                seedinfo(i+1,j+1,k+1) = seedinfo_prelim(i+1,j+1,k+1);\n            end\n        end\n    end\n    outstate = out.success;\nend\n", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_ext/ncorr_2D_matlab-master/ncorr_alg_dicanalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2423817798824054}}
{"text": " function xs = wls_pscd(x, G, yi, dqi, wi, dj, niter)\n% Runs one iteration of coordinate descent in the style suitable\n% for the inner part of paraboloidal surrogates coordinate descent updates\n% cost function: J(x) = ?\n% Output\n%\tx [np,1]\tupdated image\n%\n% This is for TESTING ONLY.\n% IT IS NOT USEFUL because it is unregularized and slow\n%\n% Copyright Aug 2000, Jeff Fessler, The University of Michigan\n\nNOT DONE!\n\nif nargin < 3, ir_usage, end\n\nif ~isvar('wi') || isempty(wi)\n\twi = ones(size(yi));\nend\nif ~isvar('niter') || isempty(niter)\n\tniter = 1;\nend\n\n% backproject curvatures for denominator\nif ~isvar('dj') || isempty(dj)\n\tdj = wi(:)' * G.^2;\nend\n\n%\n% now we are minimizing the quadratic function:\n% J(x) = \\sum_k q_i([Gx]_i)\n%\twhere q_i(l) = doth' (l-l0) - 1/2 (l-l0)' D(n) (l-l0)\n% ?\n% d/dli P(l;l0) = dothi - ni (li-l0i)\n% Q(x) == doth' G (x-x0) - 1/2 (x-x0)' G' D(n) G (x-x0)\n% ??? d/dx_j Q(x) = \\sumi \\gij \\dothi - \\sumi \\gij \\ni [G(x-x0)]_i\n% d/dx_j Q(x) = \\sumi \\gij [d/dli P(l;l0)]\n% -d^2/dx_j^2 Q(x) = \\sumi \\gij^2 \\ni\n%\ndqi = doth(:);\t% initial surrogate derivatives\n\nxs = zeros(length(x), nsubiter);\nxs(:,1) = x;\n\n%\n% loop over subiterations of paraboloid\n%\nfor it=1:niter\n\n\t%\n\t% loop over pixels\n\t%\n\tfor jj=1:numel(x)\n\t\tg = G(:,jj);\n\t\tx0j = x(jj);\n\t\tx(jj) = x0j + (dqi' * g) / dj(jj);\n\t\tx(jj) = max(x(jj),0);\n\t\tdqi = dqi - wi .* (g * (x(jj) - x0j));\n\n\tend\n\txs(:,it) = x;\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/wls_pscd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.2423394230128936}}
{"text": "% OverlayRegCheck: shell for mrAlign3 to compare inplanes for a session\n%                  with interpolated inplanes, given the bestrotvol.\n%                   This is intended as an update for regCheckRotAll.\n%\n%\n%\n% (regCheckRotAll)- Script that interpolates the inplanes corresponding\n%                to the estimated rotation (rot) and translation (trans)\n%                and displays slice by slice the original inplanes, the\n%                interpolated inplanes and a mosaic of both.\n%\n%  Oscar Nestares - 5/99\n%  Rory Sayres - 8/04, updated to use the overlayVol interface.\n\n% Size of the original inplanes\n[NyI NxI NzI] = size(INPLANE.anat);\ninp = INPLANE.anat;\n\n\n% interpolating the inplanes\nhmsgbox = msgbox('Wait while interpolating the inplanes...'); drawnow\ninpMf = regInplanes(reshape(volume,[sagSize, numSlices]),...\n                    NxI, NyI, NzI, scaleFac, rot, trans);\n\n% Correct intensity (selecting 'No' doesn't do anything useful)\nfprintf('Correcting intensity...\\n');\nLimit = 4;\nIntFunc = 'regEstFilIntGrad'; PbyPflag = 0;\ninp = regCorrMeanInt(inp);\n% intensity estimation\n[Int Noise] = feval(IntFunc, inp, PbyPflag); \n% intensity normalization\ninp = regCorrIntGradWiener(inp, Int, Noise);\n% robust mean and contrast normalization\ninp = regCorrContrast(inp,Limit); \n% intensity estimation\n[IntM NoiseM] = feval(IntFunc, inpMf, PbyPflag);\n% intensity normalization\ninpMf = regCorrIntGradWiener(inpMf, IntM, NoiseM);\n% robust mean and contrast normalization\n[inpMf, pM] = regCorrContrast(inpMf,Limit); \n\nclose(hmsgbox);\n\n% ensure inplanes and interp inplanes are same size\nif size(inp) ~= size(inpMf)\n    for i = 1:size(inp,3)\n        tmp(:,:,i) = imresize(inp(:,:,i),size(inpMf(:,:,i)));\n    end\n    inp = tmp;\nend\n\n% call external overlay interface\nFF = overlayVolumes(inp,inpMf);\n\n% % checking the alignment\n% FF = figure;\n% SS = get(0,'ScreenSize');\n% set(FF,'Position', [1 -40 SS(3)/3  SS(4)-80])\n% for k=1:size(inpMf,3)\n%    figure(FF)\n%    subplot(3,1,1)\n%    imagesc(inp(:,:,k));\n%    axis('image'); colormap('gray'); axis('off');\n%    subplot(3,1,2)\n%    imagesc(regMosaic(regNormal(inpMf(:,:,k),0,1),...\n%                      regNormal(inp(:,:,k),0,1)));\n%    axis('image'); colormap('gray'); axis('off');\n%    subplot(3,1,3)\n%    imagesc(inpMf(:,:,k));\n%    axis('image'); colormap('gray'); axis('off');\n%    disp('Press a key to continue...')\n%    pause\n% end\n% \n% close(FF)\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/OverlayRegCheck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.2423035668412238}}
{"text": "% RunMCMCSimForBPHMM\n%  Generic harness for running many iterations of MCMC,\n%   allows sensible reporting/saving of samples and diagnostics\n%USAGE\n%  Usually called from more \"user-friendly\" function \"runBPHMM\"\n%  but if specific data and initial configuration Psi are available,\n%  >> RunMCMCForBPHMM( data, Psi, algP, outP )\n%INPUT\n%  data : SeqData object, defining a collection of sequences to fit model\n%  Psi  : initial model state\n%           usually generated by a function in the \"init\" folder\n%  algParams : specifies MCMC behavior (# iterations, proposal distribs)\n%           see defaults/defaultMCMCParams_BPHMM.m for details\n%  outParams : specifies MCMC output behavior\n%           how often to save samples, write to disk, etc.\n%           see defaults/defaultOutputParams_BPHMM.m for details\n%OUTPUT\n%  Markov Chain state variables saved at preset frequency to hard drive\n%     at filepath location specified in outParams.saveDir\n\nfunction [ChainHist] = RunTimedMCMCSimForBPHMM( data, Psi, algParams, outParams, model )\ntic;\n\nif isfield( Psi, 'F' )\n    % Stating chain from scratch\n    n = 0;\n    logPr = calcJointLogPr_BPHMMState( Psi, data );\n    ChainHist = recordMCMCHistory_BPHMM( 0, outParams, [], Psi, logPr  );\n\n    fprintf( 'Initial Config: \\n' );\n    printTimedMCMCSummary_BPHMM( 0, Psi, logPr, algParams); \nelse\n    ChainHist = Psi;\n    Psi = unpackBPHMMState(  ChainHist.Psi(end), data, model );\n    logPr = calcJointLogPr_BPHMMState( Psi, data );\n    n = ChainHist.iters.Psi(end );\n    fprintf( 'Resumed Config: \\n' );\n    printTimedMCMCSummary_BPHMM( 0, Psi, logPr, algParams); \nend\n\nfprintf( 'Running MCMC Sampler %d : %d ... \\n', outParams.jobID, outParams.taskID );\n\nwhile toc < algParams.TimeLimit\n    n = n + 1;\n    Psi.iter = n;\n\n    % Perform 1 iteration of MCMC, moving to next Markov state!\n    [Psi, Stats] = BPHMMsample( Psi, data, algParams );\n    \n    % Diagnose convergence by calculating joint log pr. of all sampled vars\n    if n == 1 || rem(n, outParams.logPrEvery)==0\n        % NB: not passing \"data\" as arg means Psi stores all X suff stats\n        logPr = calcJointLogPr_BPHMMState( Psi );\n    end\n    \n    %Record current sampler state\n    %  NB: internally only records at preset frequency\n    ChainHist = recordMCMCHistory_BPHMM( n, outParams, ChainHist, Psi, logPr, Stats );\n    \n    doSaveToDisk = n==1 || rem(n, outParams.saveEvery)==0 || toc > algParams.TimeLimit;\n    if doSaveToDisk\n        filename = fullfile( outParams.saveDir,  'SamplerOutput.mat' );\n        save(filename, '-struct', 'ChainHist');\n    end\n    \n    if n == 1 || rem(n, outParams.printEvery)==0\n       printTimedMCMCSummary_BPHMM( n, Psi, logPr, algParams); \n    end\n    \nend % loop over sampler iterations\n\nfprintf( '<<<<< --------------------------------------------------- \\n');\n\nend % main function\n\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/RunTimedMCMCSimForBPHMM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24230356684122376}}
{"text": "function add_header_to_bin(bin_filename, fc_requested, fc_programmed, fs_requested, fs_programmed)\n\n[fc_requested_exist, fc_programmed_exist, fs_requested_exist, fs_programmed_exist] = read_header_from_bin(bin_filename);\nif fc_requested_exist ~= inf\n    disp('There is already a header! Just return.');\n    disp(['fc_requested ' num2str(fc_requested_exist) ' fc_programmed ' num2str(fc_programmed_exist)  ' fs_requested ' num2str(fs_requested_exist)  ' fs_programmed ' num2str(fs_programmed_exist) ]);\n    return;\nend\n\nfid = fopen(bin_filename, 'r');\n\nif fid==-1\n    disp('add_header_to_bin: Can not open file for read!');\n    return;\nend\n\ntmp_store = fread(fid, inf, 'uint8');\nfclose(fid);\n\nfc_requested_magic = 73492.215;\nfc_programmed_magic = -0.7923597;\nfs_requested_magic = -189978508;\nfs_programmed_magic = 93.126712;\n\nreserve1_magic = -53243.129;\nreserve2_magic = 0.0008123898;\nreserve3_magic = -6.0098321;\nreserve4_magic = 237.09983;\n\nfid = fopen(bin_filename, 'w');\n\nif fid==-1\n    disp('add_header_to_bin: Can not open file for write!');\n    return;\nend\n\nfwrite(fid, fc_requested_magic, 'double');\nfwrite(fid, fc_requested, 'uint64');\n\nfwrite(fid, fc_programmed_magic, 'double');\nfwrite(fid, fc_programmed, 'uint64');\n\nfwrite(fid, fs_requested_magic, 'double');\nfwrite(fid, fs_requested, 'uint64');\n\nfwrite(fid, fs_programmed_magic, 'double');\nfwrite(fid, fs_programmed, 'uint64');\n\nfwrite(fid, reserve1_magic, 'double');\nfwrite(fid, 0, 'uint64');\n\nfwrite(fid, reserve2_magic, 'double');\nfwrite(fid, 0, 'uint64');\n\nfwrite(fid, reserve3_magic, 'double');\nfwrite(fid, 0, 'uint64');\n\nfwrite(fid, reserve4_magic, 'double');\nfwrite(fid, 0, 'uint64');\n\nfwrite(fid, tmp_store, 'uint8');\n\nfclose(fid);\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/add_header_to_bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24221613356740065}}
{"text": "% function calvinNNDetection()\n%\n% Copyright by Holger Caesar, 2016\n\n% Global variables\nglobal glDatasetFolder glFeaturesFolder;\nassert(~isempty(glDatasetFolder) && ~isempty(glFeaturesFolder));\n\n%%% Settings\n% Dataset\nvocYear = 2010;\ntrainName = 'train';\ntestName  = 'val';\n\n% Specify paths\nvocName = sprintf('VOC%d', vocYear);\ndatasetDir = [fullfile(glDatasetFolder, vocName), '/'];\noutputFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'FRCN', vocName, sprintf('%s-testRelease', vocName));\nnetPath = fullfile(glFeaturesFolder, 'CNN-Models', 'matconvnet', 'imagenet-vgg-verydeep-16.mat');\nlogFilePath = fullfile(outputFolder, 'log.txt');\n\n% Fix randomness\nrandSeed = 42;\nrng(randSeed);\n\n% Setup dataset specific options and check validity\nsetupDataOpts(vocYear, testName, datasetDir);\nglobal DATAopts;\nassert(~isempty(DATAopts), 'Error: Dataset not initialized properly!');\n\n% Task-specific\nnnOpts.testFn = @testDetection;\nnnOpts.misc.overlapNms = 0.3;\nnnOpts.derOutputs = {'objective', 1, 'regressObjective', 1};\n\n% General\nnnOpts.batchSize = 2;\nnnOpts.numSubBatches = nnOpts.batchSize; % 1 image per sub-batch\nnnOpts.weightDecay = 5e-4;\nnnOpts.momentum = 0.9;\nnnOpts.numEpochs = 16;\nnnOpts.learningRate = [repmat(1e-3, 12, 1); repmat(1e-4, 4, 1)];\nnnOpts.misc.netPath = netPath;\nnnOpts.expDir = outputFolder;\nnnOpts.gpus = 1; % for automatic selection use: SelectIdleGpu();\n\n% Create outputFolder\nif ~exist(outputFolder, 'dir')\n    mkdir(outputFolder);\nend\n\n% Start logging\ndiary(logFilePath);\n\n%%% Setup\n% Start from pretrained network\nnet = load(nnOpts.misc.netPath);\n\n% Setup imdb\nimdb = setupImdbDetection(trainName, testName, net);\n\n% Create calvinNN CNN class\n% By default, network is transformed into fast-rcnn with bbox regression\ncalvinn = CalvinNN(net, imdb, nnOpts);\n\n%%% Train\ncalvinn.train();\n\n%%% Test\nstats = calvinn.test();\n\n%%% Eval\nevalDetection(testName, imdb, stats, nnOpts);\n", "meta": {"author": "nightrome", "repo": "matconvnet-calvin", "sha": "42d7e80bac56741d39404b6646a0866c10aad021", "save_path": "github-repos/MATLAB/nightrome-matconvnet-calvin", "path": "github-repos/MATLAB/nightrome-matconvnet-calvin/matconvnet-calvin-42d7e80bac56741d39404b6646a0866c10aad021/matconvnet-calvin/examples/frcn/calvinNNDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24221613356740065}}
{"text": "function vw = computeResStdMap(vw, scanList, forceSave)\n%\n% vw = computeResStdMap(vw, [scanList], [forceSave])\n%\n% Cycles through tSeries, computing the residual std of the\n% functional images.  Puts them together into a parameter map and\n% calls setParameterMap to set vw.map = stdMap.\n% Residual time series have the harmonics of freq removed\n%\n% scanList: \n%   0 - do all scans\n%   number or list of numbers - do only those scans\n%   default - prompt user via selectScans dialog\n%\n% forceSave: 1 = true (overwrite without dialog)\n%            0 = false (query before overwriting)\n%           -1 = do not save\n%\n%\n% If you change this function make parallel changes in:\n%    computeCorAnal, computeStdMap, computeMeanMap\n%\n% rmk, 05/05/99\n% djh 2/2001, mrLoadRet-3.0\n\nif notDefined('forceSave'),   forceSave = 0;   end\n\nnScans = viewGet(vw,'numScans');\n\nif strcmp(vw.mapName,'resStdMap')\n    % If exists, initialize to existing map\n    map=vw.map;\nelse\n    % Otherwise, initialize empty cell array\n    map = cell(1,nScans);\nend\n\n% (Re-)set scanList\nif ~exist('scanList','var')\n    scanList = selectScans(vw);\nelseif scanList == 0\n    scanList = 1:nScans;\nend\nif isempty(scanList)\n  error('Analysis aborted');\nend\n\n% Compute it\nwaitHandle = mrvWaitbar(0,'Computing res std images from the tSeries.  Please wait...');\nncScans = length(scanList);\nfor iScan = 1:ncScans\n    scan    = scanList(iScan);\n    dims    = viewGet(vw, 'sliceDims', scanNum);\n    nCycles = viewGet(vw, 'numcycles', scanNum);\n    datasz  = viewGet(vw, 'dataSize',  scanNum);\n    \n    map{scan} = NaN*ones(datasz);\n    for slice = sliceList(vw,scan)\n        resStd = computeTSResStd(vw,scan,slice,nCycles);\n        map{scan}(:,:,slice) = reshape(resStd,dims);\n    end\n    mrvWaitbar(scan/ncScans)\nend\nclose(waitHandle);\n\n% Set parameter map\nvw = setParameterMap(vw,map,'resStdMap');\n\n% Save file\nif forceSave >= 0, saveParameterMap(vw, [], forceSave); end\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/BlockAnalysis/computeResStdMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150961329051}}
{"text": "function [y,swp]=mvk2(a,x,eps,nswp,z,rmax,varargin)\n%Two-sided DMRG fast matrix-by-vector product\n%   [Y,SWP]=MVK2(A,X,EPS,[NSWP],[Y],[RMAX],[OPTIONS]) Two-sided DMRG (mvk\n%   is one-sided). Matrix-by-vector product of a TT-matrix A\n%   by a TT-tensor X with accuracy EPS. Also, one can specify the number of\n%   sweeps NSWP, initial approximation Z and the maximal TT-rank RMAX (if\n%   they become too large)\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\nn=a.n;\nm=a.m;\natt=a.tt;\ncorea=att.core;\npsa=att.ps;\nra=att.r;\nd=att.d;\n%start_val='fast_mv'; \nstart_val='rough_mv';\n%start_val='random';\nrmax_loc=8; %For the \"rough\" matrix-by-vector product\nif ( nargin <= 5 || isempty(rmax) )\n   rmax=1000;\nend\nif ( nargin <= 4 || isempty(z) )\n    \n    if ( strcmp(start_val,'random') )\n    rz1=rank(a,1)*rank(x,1);\n    rzd=rank(a,d+1)*rank(x,d+1);\n    kf=5;\n    rz=[rz1;kf*ones(d-1,1);rzd];\n    z=tt_rand(n,ndims(x),rz);\n    elseif (strcmp(start_val,'rough_mv'))\n        rmax_loc=8; % \n        xloc=round(x,0,rmax_loc);\n        aloc=round(a,0,rmax_loc);\n        z=round(aloc*xloc,eps); \n        %z=aloc*xloc;\n    elseif (strcmp(start_val,'fast_mv') )\n         rz1=rank(a,1)*rank(x,1);\n      rzd=rank(a,d+1)*rank(x,d+1);\n      kf=5;\n      rz=[rz1;kf*ones(d-1,1);rzd];\n      z=tt_rand(n,ndims(x),rz);\n       z=mvk2(a,x,max(eps,1e-2),10,z,rmax); %First, do it with bad accuracy\n    end\nend\nif ( nargin <= 3 || isempty(nswp) )\n  nswp = 40;\nend\ny=z;\n\n%Parameters section\nkick_rank=6;\nverb=false;\n\n%Warmup is to orthogonalize Y from right-to-left and compute psi-matrices\n%for Ax\npsi=cell(d+1,1); %Psi-matrices \n%psi{d+1}=1; psi{1}=1;\npsi{d+1}=eye(rank(y,d+1)); \npsi{1}=eye(rank(y,1));\n%Here we will add convergence test\n%Warmup: right-to-left QR + computation of psi matrices \n\ncorex=x.core;\npsx=x.ps;\nrx=x.r;\n\nswp=1;\nconverged=false;\nwhile (swp <= nswp && ~converged)  \npsy=y.ps;\n  ry=y.r;\n  corey=y.core;\n     pos1=psy(d+1);\ncr1=corey(psy(d):psy(d+1)-1);\n\nfor i=d:-1:2  \n   cr2=corey(psy(i-1):psy(i)-1);\n   cr1=reshape(cr1,[ry(i),n(i)*ry(i+1)]);\n   cr2=reshape(cr2,[ry(i-1)*n(i-1),ry(i)]);\n   cr1=cr1.';\n   [q,rm]=qr(cr1,0); rn=size(q,2); rm=rm.';\n   q=q.'; \n   ry(i)=rn;\n   corey(pos1-ry(i+1)*n(i)*ry(i):pos1-1)=q(:);\n   %Convolution is now performed for psi(i) using psi(i+1) and corea, and\n   %(new) core q\n   cra=corea(psa(i):psa(i+1)-1); cra=reshape(cra,[ra(i),n(i),m(i),ra(i+1)]);\n   cry=reshape(conj(q),[ry(i),n(i),ry(i+1)]);\n   crx=corex(psx(i):psx(i+1)-1); crx=reshape(crx,[rx(i),m(i),rx(i+1)]);\n   pscur=psi{i+1}; pscur=reshape(pscur,[ra(i+1),rx(i+1),ry(i+1)]); %ra,rx,ry\n   %First, convolve over rx(i+1) \n   crx=reshape(crx,[rx(i)*m(i),rx(i+1)]);\n   pscur=permute(pscur,[2,1,3]); pscur=reshape(pscur,[rx(i+1),ra(i+1)*ry(i+1)]);\n   pscur=crx*pscur; %pscur is now rx(i)*m(i)*ra(i+1)*ry(i+1)\n   %Convolve over m(i),ra(i+1),n(i),ry(i+1)\n    pscur=reshape(pscur,[rx(i),m(i)*ra(i+1),ry(i+1)]);\n    pscur=permute(pscur,[1,3,2]); \n    pscur=reshape(pscur,[rx(i)*ry(i+1),m(i)*ra(i+1)]);\n    cra=reshape(cra,[ra(i)*n(i),m(i)*ra(i+1)]); cra=cra.';  \n    pscur=pscur*cra; \n    %pscur is now rx(i)*ry(i+1)*ra(i)*n(i), it is left to convolve over \n    %n(i)*ry(i+1)\n    pscur=reshape(pscur,[rx(i),ry(i+1),ra(i),n(i)]);\n    pscur=permute(pscur,[3,1,4,2]);\n    pscur=reshape(pscur,[rx(i)*ra(i),n(i)*ry(i+1)]);\n    cry=reshape(cry,[ry(i),n(i)*ry(i+1)]); cry=cry.';\n    pscur=pscur*cry;\n    psi{i}=pscur;\n   %End of psi-block\n   pos1=pos1-ry(i+1)*n(i)*ry(i);\n   cr1=cr2*rm;\n   \nend\ncorey(pos1-ry(2)*n(1)*ry(1):pos1-1)=cr1(:);\npos1=pos1-ry(2)*n(1)*ry(1);\ncorey=corey(pos1:numel(corey)); %Truncate unused elements\n\n  \n\n  %left-to-right dmrg sweep \n  pos1=1;\n  cry_old=corey;\n  psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n  converged=true;\n  ermax=0;\n  for i=1:d-1\n     %We care for two cores, with number i & number i+1, and use\n     %psi(i) and psi(i+2) as a basis; also we will need to recompute\n     %psi(i+1)\n     ps1=psi{i}; ps2=psi{i+2};\n     cra1=corea(psa(i):psa(i+1)-1); cra2=corea(psa(i+1):psa(i+2)-1);\n     crx1=corex(psx(i):psx(i+1)-1); crx2=corex(psx(i+1):psx(i+2)-1);\n     %our convolution is\n     %ps1(ra(i),rx(i),ry(i))*cra1(ra(i),n(i),m(i),ra(i+1))*\n     %cra2(ra(i+1),n(i+1),m(i+1),ra(i+2))*\n     %*ps2(ra(i+2),rx(i+2),ry(i+2))\n     %*crx1(rx(i),m(i),rx(i+1))*cr2x(rx(i+1)*m(i+1)*rx(i+2))\n     %Scheme ps1*crx1 over rx(i)\n     \n     ps1=reshape(ps1,[ra(i),rx(i),ry(i)]); \n     ps1=permute(ps1,[1,3,2]); ps1=reshape(ps1,[ra(i)*ry(i),rx(i)]);\n     crx1=reshape(crx1,[rx(i),m(i)*rx(i+1)]);\n     ps1=ps1*crx1; %ps1 is now ra(i)*ry(i)*m(i)*rx(i+1)\n     %Now convolve with matrix A over ra(i)*m(i)\n     ps1=reshape(ps1,[ra(i),ry(i),m(i),rx(i+1)]);\n     ps1=permute(ps1,[2,4,1,3]);\n     ps1=reshape(ps1,[ry(i)*rx(i+1),ra(i)*m(i)]);\n     cra1=reshape(cra1,[ra(i),n(i),m(i),ra(i+1)]);\n     cra1=permute(cra1,[1,3,2,4]); \n     cra1=reshape(cra1,[ra(i)*m(i),n(i)*ra(i+1)]);\n     ps1=ps1*cra1; %ps1 is now ry(i)*rx(i+1)*n(i)*ra(i+1)\n     %Then the ``same'' convolution is carried over for second pair of\n     %cores\n     ps2=reshape(ps2,[ra(i+2),rx(i+2),ry(i+2)]);\n     ps2=permute(ps2,[2,1,3]);\n     ps2=reshape(ps2,[rx(i+2),ra(i+2)*ry(i+2)]);\n     crx2=reshape(crx2,[rx(i+1)*m(i+1),rx(i+2)]);\n     ps2=crx2*ps2; %ps2 is now rx*(i+1)*m(i+1)*ra(i+2)*ry(i+2)\n     %Convolve over m(i+1)*ra(i+2)\n     ps2=reshape(ps2,[rx(i+1),m(i+1)*ra(i+2),ry(i+2)]);\n     ps2=permute(ps2,[2,1,3]);\n     ps2=reshape(ps2,[m(i+1)*ra(i+2),rx(i+1)*ry(i+2)]);\n     cra2=reshape(cra2,[ra(i+1)*n(i+1),m(i+1)*ra(i+2)]);\n     ps2=cra2*ps2; \n     %ps2 is now ra(i+1)*n(i+1)*rx(i+1)*ry(i+2)\n     %Now form superblock by contraction ps1 & ps2\n     %over ra(i+1)*rx(i+1)\n     ps0=reshape(ps1,[ry(i),rx(i+1),n(i),ra(i+1)]);\n     ps0=permute(ps0,[1,3,2,4]);\n     ps0=reshape(ps0,[ry(i)*n(i),rx(i+1)*ra(i+1)]);\n     ps2=reshape(ps2,[ra(i+1),n(i+1),rx(i+1),ry(i+2)]);\n     ps2=permute(ps2,[3,1,2,4]); \n     ps2=reshape(ps2,[rx(i+1)*ra(i+1),n(i+1)*ry(i+2)]);\n     super_core=ps0*ps2; %super_core is ry(i)*n(i)*n(i+1)*ry(i+2)\n    if ( i > 1 )\n     %Compute previous supercore\n        cr1=corey(pos1:pos1+ry(i)*n(i)*ry(i+1)-1);\n        cr2=cry_old(psy(i+1):psy(i+2)-1); \n        cr1=reshape(cr1,[ry(i)*n(i),ry(i+1)]);\n        cr2=reshape(cr2,[ry(i+1),n(i+1)*ry(i+2)]);\n         super_core_old=cr1*cr2; \n         er=norm(super_core_old(:)-super_core(:))/norm(super_core(:));\n     \n        if ( er > eps ) \n            converged=false;\n        end\n        ermax=max(er,ermax);\n     %if ( verb )\n     %  fprintf('i=%d er=%3.2e \\n',i,er);\n     %end \n     end\n     [u,s,v]=svd(super_core,'econ');\n     s=diag(s); \n     r=my_chop2(s,eps/sqrt(d-1)*norm(s)); r=min(r,rmax);\n     u=u(:,1:r); s=s(1:r); v=v(:,1:r); v=v*diag(s);\n     \n     %Kick rank\n     \n     ur=randn(size(u,1),kick_rank);\n     %Orthogonalize ur to u by Golub-Kahan reorth\n     u=reort(u,ur);\n     radd=size(u,2)-r; \n     if ( radd > 0 )\n        vr=zeros(size(v,1),radd);\n        v=[v,vr];\n     end\n     r=size(u,2);\n     \n     \n     ry(i+1)=r;\n     %u is ry(i)*n(i)*ry(i+1)\n     %core_new(pos1:pos1+ry(i)*n(i)*ry(i+1)-1)=u(:); \n     corey(pos1:pos1+ry(i)*n(i)*ry(i+1)-1)=u(:); \n     \n     u=reshape(u,[ry(i),n(i),ry(i+1)]);\n\n     %Compute new psi\n     %ps1 is ry(i)*rx(i+1)*n(i)*ra(i+1) with u over ry(i)*n(i)\n     u=conj(u);\n     ps1=reshape(ps1,[ry(i),rx(i+1),n(i),ra(i+1)]);\n     ps1=permute(ps1,[4,2,1,3]);\n     ps1=reshape(ps1,[ra(i+1)*rx(i+1),ry(i)*n(i)]);\n     u=reshape(u,[ry(i)*n(i),ry(i+1)]);\n     ps1=ps1*u;\n     psi{i+1}=ps1;\n     %Compute (?) new v\n     pos1=pos1+ry(i)*n(i)*ry(i+1);\n     v=v';\n     %v=reshape(v,[ry(i+1),n(i+1),ry(i+2)]);\n     corey(pos1:pos1+ry(i+1)*n(i+1)*ry(i+2)-1)=v(:);\n  end\n  psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\ny.core=corey;\ny.r=ry;\ny.ps=psy;\nswp=swp+1;\nif ( verb )\nfprintf('swp=%d er=%3.2e trunk=%3.2e \\n',swp,ermax,eps/sqrt(d-1));\nend\nend\nif ( swp == nswp ) \n  fprintf('mvk2 warning: error is not fixed for maximal number of sweeps %d\\n', swp); \nend%end\n%p1=tt_mvdot(core(a),core(x),y0);\n%p2=dot(y,tt_tensor(y0));\n%abs(p1-p2)/abs(p1)\n%keyboard;\n\n\n  \n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_matrix/mvk2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24221508947713932}}
{"text": "function [res] = mne_ex_evoked_grad_amp(inname,bmin,bmax,outname)\n%\n%   function [res] = mne_ex_evoked_grad_amp(inname,bmin,bmax,outname)\n%\n%   Compute the magnitude of the tangential gradient at each\n%   sensor location using the planar gradiometer data and\n%   optionally output the result to a fif file.\n%\n%   inname      The input file name. All average data sets are\n%               read and processed\n%   bmin,bmax   Baseline limits in seconds\n%   outname     Optional output file name\n%\n%\n%   Function returns the data which was or would have been written\n%   to the file\n%\n\n%\n%   Author : Matti Hamalainen, MGH Martinos Center\n%   License : BSD 3-clause\n%\n\nme='MNE:mne_ex_evoked_grad_amp';\n\nglobal FIFF;\nif isempty(FIFF)\n    FIFF = fiff_define_constants();\nend\n\nif nargin == 1\n    do_baseline = false;\nelseif (nargin == 3 || nargin == 4)\n    do_baseline = true;\nelse\n    error(me,'Wrong number of arguments');\nend\n%\n%   Read the data\n%\ndata = fiff_read_evoked_all(inname);\n%\n%   Figure out the planar gradiometer pairs\n%\npairs = zeros(data.info.nchan,2);\nnpair = 0;\nk = 1;\nwhile k < data.info.nchan\n    %\n    %   First check the coil types\n    %\n    coil1 = data.info.chs(k).coil_type;\n    coil2 = data.info.chs(k+1).coil_type;\n    if (coil1 == coil2 && ...\n            (coil1 == 2 || coil1 == 3012 || coil1 == 3013))\n        one = data.info.ch_names{k};\n        two = data.info.ch_names{k+1};\n        lastone = one(length(one));\n        lasttwo = two(length(two));\n        %\n        %   Then the channel names\n        %\n        if (strcmp(one(1:3),'MEG') && strcmp(one(1:3),'MEG'))\n            if (strcmp(one(1:(length(one)-1)),two(1:(length(two)-1))) && ...\n                    ((lastone == '2' && lasttwo == '3') || ...\n                    (lastone == '3' && lasttwo == '2')))\n                npair = npair + 1;\n                pairs(npair,1) = k;\n                pairs(npair,2) = k+1;\n                k = k + 1;\n            end\n        end\n    end\n    k = k + 1;\nend\n\nif npair == 0\n    error(me,'No planar gradiometers in these data');\nend\n%\n%   Compute the amplitudes\n%\nfprintf(1,'Computing the amplitudes');\nif do_baseline\n    fprintf(1,' (Baseline = %7.1f ... %7.1f ms)',1000*bmin,1000*bmax);\nend\nfprintf(1,'...');\nfor k = 1:length(data.evoked)\n    epochs = data.evoked(k).epochs;\n    %\n    %  Setup baseline limits\n    %\n    if do_baseline\n        b1 = double(data.info.sfreq*bmin - data.evoked(k).first);\n        b2 = double(data.info.sfreq*bmax - data.evoked(k).first);\n        if b1 < 1\n            b1 = 1;\n        end\n        if b2 > size(epochs,2)\n            b2 = size(epochs,2)\n        end\n    else\n        b1 = 1;\n        b2 = 1;\n    end\n    %\n    %   Go through all pairs\n    %\n    for p = 1:npair\n        one = pairs(p,1);\n        two = pairs(p,2);\n        if b2 > b1\n            base1 = sum(epochs(one,b1:b2))/(b2-b1);\n            base2 = sum(epochs(two,b1:b2))/(b2-b1);\n            epochs(one,:) = sqrt((epochs(one,:)-base1).*(epochs(one, ...\n                :)-base1)+(epochs(two,:)-base2).*(epochs(two,:)-base2));\n        else\n            epochs(one,:) = sqrt(epochs(one,:).*epochs(one, ...\n                :)+epochs(two,:).*epochs(two,:));\n        end\n    end\n    data.evoked(k).epochs = epochs;\n    fprintf(1,'.');\nend\nfprintf(1,'[done]\\n');\n%\n%   Compose the selection name list\n%\npairs = pairs(1:npair,:);\nfor k = 1:npair\n    ch_sel_names{k} = data.info.ch_names{pairs(k,1)};\nend\n%\n%   Omit MEG channels but include others\n%\nfor p = 1:data.info.nchan\n    if (data.info.chs(p).kind ~= FIFF.FIFFV_MEG_CH)\n        k = k + 1;\n        ch_sel_names{k} = data.info.ch_names{p};\n    end\nend\n%\n%   Modify the bad channel list\n%\nif ~isempty(data.info.bads)\n    nbad = length(data.info.bads);\n    for k = 1:npair\n        one = data.info.ch_names{pairs(k,1)};\n        two = data.info.ch_names{pairs(k,2)};\n        %\n        %   If one channel of the planar gradiometer is marked bad,\n        %   add the other to the bad channel list\n        %\n        if (~isempty(strmatch(one,data.info.bads)) && ...\n                isempty(strmatch(two,data.info.bads)))\n            nbad = nbad + 1;\n            data.info.bads{nbad} = two;\n        elseif (isempty(strmatch(one,data.info.bads)) && ...\n                ~isempty(strmatch(two,data.info.bads)))\n            nbad = nbad + 1;\n            data.info.bads{nbad} = one;\n        end\n    end\nend\n%\n%   Do the picking\n%\nres = fiff_pick_channels_evoked(data,ch_sel_names);\n%\n%   Optionally write an output file\n%\nif nargin == 4\n    fiff_write_evoked(outname,res);\n    fprintf(1,'Wrote %s\\n',outname);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/mne/mne_ex_evoked_grad_amp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24221508947713932}}
{"text": "function [rgb,ucs,status,RGB,UCS] = maxdistcolor_view(N,fun,varargin)\n% Create a figure for interactive generation and display of MAXDISTCOLOR colors.\n%\n% (c) 2017-2020 Stephen Cobeldick\n%\n% This function has exactly the same inputs and outputs as MAXDISTCOLOR.\n% See MAXDISTCOLOR for descriptions of the required and optional arguments.\n%\n% See also MAXDISTCOLOR MAXDISTCOLOR_DEMO SRGB_TO_CAM02UCS SRGB_TO_CIELAB\n% SRGB_TO_OSAUCS COLORNAMES COLORMAP RGBPLOT AXES SET LINES PLOT\n\n%% New Figure %%\n%\nfigH = figure('Units','pixels', 'ToolBar','figure', 'NumberTitle','off',...\n\t'HandleVisibility','off', 'Name',mfilename(), 'Visible','on');\nfigP = get(figH, 'Position');\nfigY = get(figH, 'Pointer');\nset(figH, 'Pointer','watch')\n%\niniH = uicontrol(figH, 'Units','pixels', 'Style','text', 'HitTest','off',...\n\t'Visible','on',\t'String','Initializing the figure... please wait.');\niniX = get(iniH,'Extent');\nset(iniH,'Position',[figP(3:4)/2-iniX(3:4)/2,iniX(3:4)])\n%\ndrawnow()\n%\n% First call to check input arguments and define all output arguments:\n[bgr,ucs,status,RGB,UCS] = maxdistcolor(N,fun,varargin{:});\n%\nopts = status.options;\n%\ninw = true;\nohm = pow2([opts.bitR,opts.bitG,opts.bitB])-1;\n%\nif isempty(opts.exc)\n\topts.exc = nan(0,3);\nend\nif isempty(opts.inc)\n\topts.inc = nan(0,3);\nend\n%\ndelete(iniH)\n%\n%% Parameters %%\n%\ngap = 7;\n% UI colors:\n[R,G,B] = ndgrid(0:1/8:1);\nsmp = [R(:),G(:),B(:)];\nclear R G B\ntxc = [0.7,0.3,0.2];\nbgd = [];\nfgd = [];\nfBackFore(false)\n% Slider steps:\nbStp = [1,2]; % bits\ncStp = [0.005,0.1]; % chroma\nlStp = [0.005,0.1]; % lightness\n% Number properties:\nnRng = [1,64];\nnStp = [1,5];\nnFun = @(n) max(nRng(1),min(nRng(2),n));\n% Table properties:\ntTxt = {'exc'; 'inc'};\n% Menu properties:\nmTxt = {'plot'; 'sort'; 'path'; 'disp'};\nmSrt = {{'none','farthest','hue','zip','lightness','a','b'},{'maxmin','minmax','longest','shortest'}};\nmStr = {''; [mSrt{:}]; {'open','closed'}; {'off','time','summary','verbose'}};\n% Slider properties:\nsTxt = {'Cmax'; 'Cmin'; 'Lmax'; 'Lmin'; 'bitR'; 'bitG'; 'bitB'; 'start'};\nsInt = [ false;  false;  false;  false;   true;   true;   true;   false];\nsRng = [   0,1;    0,1;    0,1;    0,1;    1,8;    1,8;    1,8;   0,360];\nsStp = [  cStp;   cStp;   lStp;   lStp;   bStp;   bStp;   bStp;    1,10];\nsTwo = [    +1;     -1;     +2;     -2;      0;      0;      0;       0];\nsFun = @(n,k) max(sRng(k,1),min(sRng(k,2),n));\nsStr = @(x) sprintf('%.4g',round(1000*x)/1000);\n% Colorspace axes:\nf2s = upper(regexp(func2str(fun),'(?<=_to_)\\w+','match','once'));\ntmp = struct('CAM02UCS',{'J''','a''','b'''}, 'CIELAB',{'L*','a*','b*'},...\n\t'DIN99',{'L_{99}','a_{99}','b_{99}'}, 'OSAUCS',{'L','j','g'});\nif isfield(tmp,f2s)\n\tzyx = {tmp.(f2s)};\nelse\n\tzyx = {'L?','a?','b?'};\n\tf2s = '???';\nend\n% Maximum chroma:\ntmp = fun(smp);\nmxc = max(max(abs(tmp(:,2:3))));\n%\n%% 3D Axes %%\n%\naz = [];\nel = [];\n%\n%% Interactive Graphics Objects %%\n%\n% Get text width:\ncnc = {'Red','Green','Blue'};\ntmp = uicontrol(figH, 'Style','text', 'Units','pixels', 'String',cnc);\ntxw = get(tmp,'Extent');\ntxh = txw(4)/numel(cnc);\ntxw = num2cell(ones(1,3)*(7+txw(3)));\ndelete(tmp)\n% Add drop-down menus:\nmTxN = numel(mTxt);\nmAxH = axes('Parent',figH, 'Units','pixels', 'Visible','off', 'View',[0,90],...\n\t'HitTest','off', 'Xlim',[0,1], 'Ylim',[0,2*mTxN]);\nmTxH = text(zeros(1,mTxN),2*mTxN-1:-2:1, mTxt, 'parent',mAxH, 'Color',txc,...\n\t'VerticalAlignment','bottom','HorizontalAlignment','left');\nset(mTxH(1),'Color',txc([3,2,1]));\nfor k = mTxN:-1:1\n\tif k>1\n\t\tidm = find(strcmpi(opts.(mTxt{k}),mStr{k}));\n\telse\n\t\tidm = 1;\n\tend\n\tmUiH(k) = uicontrol(figH, 'Style','popupmenu', 'Units','pixels',...\n\t\t'String',mStr{k}, 'Callback',{@fOptMenu,k}, 'Value',idm);\nend\n% Add horizontal sliders:\nsTxN = numel(sTxt);\nfor k = sTxN:-1:1\n\tval = opts.(sTxt{k});\n\tsTxH(k) = uicontrol(figH, 'Units','pixels', 'Style','text',...\n\t\t'String',sTxt{k}, 'HorizontalAlignment','left', 'ForegroundColor',txc);\n\tsVaH(k) = uicontrol(figH, 'Units','pixels', 'Style','edit',...\n\t\t'String',sStr(val), 'HorizontalAlignment','left', 'Callback',{@fOptEdit,k});\n\tsUiH(k) = uicontrol(figH, 'Units','pixels', 'Style','slider', 'Value',1,...\n\t\t'Min',sRng(k,1), 'Max',sRng(k,2), 'Value',sFun(val,k),...\n\t\t'SliderStep',sStp(k,:)./diff(sRng(k,:)), 'Callback',@fUpDtMap);\n\taddlistener(sUiH(k), 'Value', 'PostSet',@(o,e)fOptSlide(o,e,k));\nend\n% Add tables:\ntTxN = numel(tTxt);\nfor k = tTxN:-1:1\n\ttmp = opts.(tTxt{k});\n\ttmp(end+1:N,:) = NaN;\n\ttUiH(k) = uitable(figH, 'Units','pixels', 'Data',tmp, 'ColumnWidth',txw,...\n\t\t'ColumnName',cnc, 'ColumnEditable',true, 'CellEditCallback',{@fCellEdit,k});\n\ttTxH(k) = uicontrol(figH, 'Style','text', 'Units','pixels','ForegroundColor',txc,...\n\t\t'String',tTxt{k}, 'HorizontalAlignment','left');\n\ttCbH(k) = uicontrol(figH, 'Style','checkbox', 'Units','pixels','String','X',...\n\t\t'Callback',{@fCheckBox,k});\nend\n% Add colorbar:\nbAxH = axes('Parent',figH, 'Units','pixels', 'Visible','off',...\n\t'HitTest','off', 'Xlim',[0.5,1.4], 'Ylim',[0,N]+0.5, 'View',[0,90],...\n\t'YDir','normal', 'XTick',[], 'YTick',1:N, 'Box','off');\nbImH = image('CData',permute(bgr,[1,3,2]), 'Parent',bAxH);\n% Add number slider:\nnVaH = uicontrol(figH, 'Units','pixels', 'Style','edit', 'String',sprintf('%d',N),...\n\t'HorizontalAlignment','center', 'Callback',@fNumEdit);\nnUiH = uicontrol(figH, 'Units','pixels', 'Style','slider', 'Value',nFun(N),...\n\t'Min',nRng(1), 'Max',nRng(2), 'SliderStep',nStp./diff(nRng), 'Callback',@fUpDtMap);\naddlistener(nUiH, 'Value', 'PostSet',@fNumSlide);\n% Add EVAL button:\neUiH = uicontrol(figH, 'Units','pixels', 'Style','pushbutton',...\n\t'String','pause', 'ForegroundColor',txc([3,2,1]), 'Callback',@fEvalFun);\neUiX = true;\neUiC = get(eUiH,'BackgroundColor');\n%\n%% Main Plot Objects %%\n%\nndx = 'Colormap Index';\neds = sprintf('Euclidean Distance (%s)',f2s);\n%\naxp = {'Units','normalized', 'NextPlot','replacechildren', 'Clipping','off',...\n\t'Color','none', 'XColor',fgd, 'YColor',fgd, 'ZColor',fgd, 'UserData'};\npnp = {figH, 'Units','pixels', 'BorderType','none', 'Title','', 'BackgroundColor',bgd};\n%\npAxH(10) = axes('Parent',uipanel(pnp{:}), axp{:},4);\npAxS(10) = struct('title','RGB Gamut (alphashape) [slow]',...\n\t'X',zyx{3}, 'Y',zyx{2}, 'Z',zyx{1}, 'fun',@fAlphaTry);\n%\npAxH(9) = axes('Parent',uipanel(pnp{:}), axp{:},3);\npAxS(9) = struct('title','RGB Gamut (point cloud) [fast]',...\n\t'X',zyx{3}, 'Y',zyx{2}, 'Z',zyx{1}, 'fun',@fPointCloud);\n%\npAxH(8) = axes('Parent',uipanel(pnp{:}), axp{:},3);\npAxS(8) = struct('title','Colors with RGB Cube',...\n\t'X',zyx{3}, 'Y',zyx{2}, 'Z',zyx{1}, 'fun',@fCubeRGB);\n%\npAxH(7) = axes('Parent',uipanel(pnp{:}), axp{:},3);\npAxS(7) = struct('title','Colors with Sort Path',...\n\t'X',zyx{3}, 'Y',zyx{2}, 'Z',zyx{1}, 'fun',@fSortPath);\n%\npAxH(6) = axes('Parent',uipanel(pnp{:}), axp{:},2, 'Visible','off');\npAxS(6) = struct('title','Matrix Scatter Plot',...\n\t'X','', 'Y','', 'Z','', 'fun',@fScatterMat);\n%\npAxH(5) = axes('Parent',uipanel(pnp{:}), axp{:},2);\npAxS(5) = struct('title','Adjacent Color Matrix',...\n\t'X',ndx, 'Y',ndx, 'Z','', 'fun',@fAdjaNode);\n%\npAxH(4) = axes('Parent',uipanel(pnp{:}), axp{:},2, 'XTick',[]);\npAxS(4) = struct('title','Bands with RGB Values',...\n\t'X','', 'Y',ndx, 'Z','', 'fun',@fRgbValues);\n%\npAxH(3) = axes('Parent',uipanel(pnp{:}), axp{:},2, 'XTick',[]);\npAxS(3) = struct('title','Bands with Color Names',...\n\t'X','', 'Y',ndx, 'Z','', 'fun',@fBandName);\n%\npAxH(2) = axes('Parent',uipanel(pnp{:}), axp{:},3);\npAxS(2) = struct('title','Euclidean Distance (3D Plot)',...\n\t'X',ndx, 'Y',ndx, 'Z',eds, 'fun',@fEuclDist);\n%\npAxH(1) = axes('Parent',uipanel(pnp{:}), axp{:},2);\npAxS(1) = struct('title','Euclidean Distance (2D Plot)',...\n\t'X',ndx, 'Y',eds, 'Z','', 'fun',@fEuclDist);\n%\npPnH = get(pAxH,'Parent');\npPnH = [pPnH{:}];\npScH = [];\n%\nfor k = 1:numel(pAxH)\n\txlabel(pAxH(k), pAxS(k).X, 'Color',fgd)\n\tylabel(pAxH(k), pAxS(k).Y, 'Color',fgd)\n\tzlabel(pAxH(k), pAxS(k).Z, 'Color',fgd)\n\ttitle( pAxH(k), pAxS(k).title, 'Color',fgd, 'Visible','on')\n\tif get(pAxH(k), 'UserData')>2\n\t\t% Axes 3D view:\n\t\tview(pAxH(k),3)\n\t\t% Zlabel orientation for short strings:\n\t\tif numel(pAxS(k).Z)<7\n\t\t\tset(get(pAxH(k), 'ZLabel'), 'Rotation',0, 'HorizontalAlignment','right')\n\t\tend\n\tend\nend\n%\n% Optional linking of 3D axes:\nxud = cellfun(@(m)isequal(m,zyx{3}),{pAxS.X});\nlinkprop(pAxH(xud), 'View');\n%\n%% Initialize GUI %%\n%\nrgb2str = @(f,d,m)cellfun(@(v)sprintf(f,v),reshape(num2cell(round(m*d)/d,2),1,[]),'uni',0);\narrayfun(@(s,a) s.fun(a), pAxS, pAxH)\nset(pPnH(:), 'Visible','off', 'HitTest','off')\nset(pPnH(1), 'Visible','on', 'HitTest','on')\nset(mUiH(1), 'String',{pAxS.title})\nset(figH, 'Pointer',figY, 'ResizeFcn',@fSizeObj)\nfNumTick()\nfSizeObj()\n%\n%% Main Plot Functions %%\n%\n\tfunction fOrient3D(axh,az,el)\n\t\taxis(axh,'equal')\n\t\tgrid(axh,'on')\n\t\tview(axh,az,el)\n\t\tmat = fun([0,0,0;1,1,1]);\n\t\tset(axh, 'XGrid','on', 'YGrid','on', 'ZGrid','on',...\n\t\t\t'XLim',[-mxc,mxc], 'YLim',[-mxc,mxc], 'ZLim',[mat(1),mat(2)])\n\tend\n%\n\tfunction fAlphaTry(~) % ALPHASHAPE is slow, run only on demand.\n\t\tplv = get(mUiH(strcmpi('plot',mTxt)), 'Value');\n\t\tif eUiX && inw && 4==get(pAxH(plv), 'UserData')\n\t\t\tset(figH, 'Pointer','watch')\n\t\t\tdrawnow()\n\t\t\tfAlphaRGB(pAxH(plv))\n\t\t\tset(figH, 'Pointer',figY)\n\t\t\tinw = false;\n\t\tend\n\tend\n\tfunction fAlphaRGB(axh) % Show the RGB gamut using alphashape.\n\t\tdelete(get(axh, 'Children'))\n\t\t[az,el] = view(axh);\n\t\t% Get gamut boundary:\n\t\tnrw = size(UCS,1);\n\t\tmxn = 1e4; % max elements for ALPHASHAPE: more elements -> slower runtime.\n\t\tstp = ceil(nrw/mxn);\n\t\tvec = [];\n\t\tfor idk = 1:stp\n\t\t\tidu = idk:stp:nrw;\n\t\t\ttry\n\t\t\t\tbnd = fGetBound(idu);\n\t\t\tcatch %#ok<CTCH>\n\t\t\t\ttext(0.5, 0.5, 0.5,...\n\t\t\t\t\t{'ALPHASHAPE not found','(requires R2014b or later)'},...\n\t\t\t\t\t'Parent',axh, 'HorizontalAlignment','center',...\n\t\t\t\t\t'FontWeight','bold', 'Color',fgd)\n\t\t\t\treturn\n\t\t\tend\n\t\t\tvec = union(vec,idu(bnd(:)));\n\t\tend\n\t\tbnd = fGetBound(vec);\n\t\t% Show RGB gamut:\n\t\tpatch('Faces',bnd, 'Vertices',UCS(vec,[3,2,1]), 'Parent',axh,...\n\t\t\t'EdgeColor','none', 'FaceColor','interp', 'FaceVertexCData',RGB(vec,:));\n\t\t% Show color nodes:\n\t\thold(axh,'on')\n\t\tscatter3(ucs(:,3),ucs(:,2),ucs(:,1), 13, fgd, 'filled', 'Parent',axh)\n\t\t% Orient axes:\n\t\tfOrient3D(axh,az,el)\n\tend\n\tfunction bnd = fGetBound(idu) % Get boundary of the node cloud.\n\t\tshp = alphaShape(UCS(idu,[3,2,1]),Inf); % requires R2014b or later.\n\t\tshp.Alpha = shp.criticalAlpha('all-points');\n\t\tbnd = shp.boundaryFacets();\n\tend\n%\n\tfunction fPointCloud(axh) % Show the RGB gamut using a point cloud.\n\t\tdelete(get(axh, 'Children'))\n\t\t[az,el] = view(axh);\n\t\t% Plot point cloud:\n\t\tnpt = 1e4;\n\t\tI = unique(round(linspace(1,size(UCS,1),npt)));\n\t\tscatter3(UCS(I,3),UCS(I,2),UCS(I,1), 3, RGB(I,:), 'filled', 'Parent', axh)\n\t\thold(axh,'on')\n\t\tscatter3(ucs(:,3),ucs(:,2),ucs(:,1), 13, fgd, 'filled', 'Parent',axh)\n\t\t% Orient axes:\n\t\tfOrient3D(axh,az,el)\n\tend\n%\n\tfunction fSortPath(axh) % Colors shown in UCS space, with path.\n\t\tdelete(get(axh, 'Children'))\n\t\t[az,el] = view(axh);\n\t\t% Show color nodes:\n\t\tn2s = cellstr(strjust(num2str((1:N).'),'left'));\n\t\tscatter3(ucs(:,3),ucs(:,2),ucs(:,1), 256, bgr, 'filled', 'Parent',axh)\n\t\ttext(ucs(:,3),ucs(:,2),ucs(:,1), n2s, 'Parent',axh,...\n\t\t\t'Color',fgd, 'HorizontalAlignment','center')\n\t\thold(axh,'on')\n\t\t% Show path:\n\t\tipc = strcmpi(opts.path,'closed');\n\t\tmat = ucs([1:N,1:+ipc],:);\n\t\tplot3(mat(:,3),mat(:,2),mat(:,1),'-', 'Parent',axh, 'Color',fgd)\n\t\t% Show distances:\n\t\tvec = sqrt(sum(diff(mat,1,1).^2,2));\n\t\t[mxv,mxi] = max(vec);\n\t\t[mnv,mni] = min(vec);\n\t\tmxp = mean(mat(mxi:mxi+1,:),1);\n\t\tmnp = mean(mat(mni:mni+1,:),1);\n\t\ttext(mxp(3),mxp(2),mxp(1), sprintf('max:%.5g',mxv), 'Parent',axh, 'Color',fgd)\n\t\ttext(mnp(3),mnp(2),mnp(1), sprintf('min:%.5g',mnv), 'Parent',axh, 'Color',fgd)\n\t\t% Orient axes:\n% \t\taxis(axh,'equal')\n% \t\tview(axh,az,el)\n\t\tfOrient3D(axh,az,el)\n\tend\n%\n\tfunction fCubeRGB(axh) % Colors shown in UCS space, with RGB cube.\n\t\tdelete(get(axh, 'Children'))\n\t\t[az,el] = view(axh);\n\t\t% Show color nodes:\n\t\tn2s = cellstr(strjust(num2str((1:N).'),'left'));\n\t\tscatter3(ucs(:,3),ucs(:,2),ucs(:,1), 256, bgr, 'filled', 'Parent',axh)\n\t\ttext(ucs(:,3),ucs(:,2),ucs(:,1), n2s, 'Parent',axh,...\n\t\t\t'Color',fgd, 'HorizontalAlignment','center')\n\t\t% Show excluded nodes:\n\t\tif isinteger(opts.exc)\n\t\t\texc = bsxfun(@rdivide,double(opts.exc),ohm);\n\t\telse\n\t\t\texc = opts.exc;\n\t\tend\n\t\tcxe = fun(exc);\n\t\thold(axh,'on')\n\t\tscatter3(cxe(:,3),cxe(:,2),cxe(:,1), 256, exc, 'filled', 'Parent',axh)\n\t\ttext(cxe(:,3),cxe(:,2),cxe(:,1), 'X', 'Parent',axh,...\n\t\t\t'Color',fgd, 'HorizontalAlignment','center')\n\t\t% Show outline of RGB cube:\n\t\tM = 23;\n\t\t[X,Y,Z] = ndgrid(linspace(0,1,M),0:1,0:1);\n\t\tmat = fun([X(:),Y(:),Z(:);Y(:),Z(:),X(:);Z(:),X(:),Y(:)]);\n\t\tX = reshape(mat(:,3),M,[]);\n\t\tY = reshape(mat(:,2),M,[]);\n\t\tZ = reshape(mat(:,1),M,[]);\n\t\tline(X,Y,Z, 'Color',fgd, 'Parent',axh)\n\t\t% Orient axes:\n% \t\taxis(axh,'equal')\n% \t\tview(axh,az,el)\n\t\tfOrient3D(axh,az,el)\n\tend\n%\n\tfunction fScatterMat(axh) % Matrix scatter plot.\n\t\tuih = get(axh, 'Parent');\n\t\tise = isempty(pScH);\n\t\tfor rr = 3:-1:1\n\t\t\tfor cc = 3:-1:1\n\t\t\t\tif ise\n\t\t\t\t\tpos = [rr-1,(3-cc)*0.93,1,0.93]./3;\n\t\t\t\t\tpScH(rr,cc) = axes('Parent',uih, 'Visible','on',...\n\t\t\t\t\t\t'Units','normalized', 'OuterPosition',pos,...\n\t\t\t\t\t\t'NextPlot','replacechildren',...\n\t\t\t\t\t\t'Color','none', 'XColor',fgd, 'YColor',fgd); %#ok<LAXES>\n\t\t\t\telse\n\t\t\t\t\tdelete(get(pScH(rr,cc), 'Children'))\n\t\t\t\tend\n\t\t\t\tif rr==cc\n\t\t\t\t\ttext(0.5,0.5, zyx{rr}, 'Parent',pScH(rr,cc),...\n\t\t\t\t\t\t'FontWeight','bold', 'Color',fgd)\n\t\t\t\telse\n\t\t\t\t\tscatter(pScH(rr,cc), ucs(:,rr),ucs(:,cc), 32, bgr, 'filled');%, 'Parent',axh)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t%set(pScH, 'XLimMode','auto', 'YLimMode','auto')\n\t\tset(pScH([1,5,9]), 'XLim',0:1, 'YLim',0:1, 'Visible','off')\n\t\tset(pScH, 'XColor',fgd, 'YColor',fgd, 'ZColor',fgd)\n\tend\n%\n\tfunction fAdjaNode(axh) % Show matrix with all colors adjacent.\n\t\tdelete(get(axh, 'Children'))\n\t\t[idr,idc] = ndgrid(0:N);\n\t\tF = (1:N*(N+1)).';\n\t\tF(N+1:N+1:end) = [];\n\t\timage('Parent',axh, 'CData',repmat(permute(bgr,[1,3,2]),[1,N,1]));\n\t\tpatch('Parent',axh, 'Faces',[F,F+N+1,F+N+2], 'Vertices',0.5+[idr(:),idc(:)],...\n\t\t\t'FaceColor','flat', 'FaceVertexCData',bgr(mod(F,N+1),:), 'EdgeColor','none');\n\tend\n%\n\tfunction fBandName(axh) % Show bands with colornames (if COLORNAMES is available).\n\t\tdelete(get(axh, 'Children'))\n\t\timage(permute(bgr,[1,3,2]), 'Parent',axh)\n\t\ttry\n\t\t\tcnm = colornames('CSS',bgr);\n\t\tcatch %#ok<CTCH>\n\t\t\tcnm = repmat({'COLORNAMES not found: download FEX #48155'},1,N);\n\t\tend\n\t\ttext(ones(1,N), 1:N, cnm, 'Parent',axh, 'Color',fgd,...\n\t\t\t'BackgroundColor',bgd, 'HorizontalAlignment','center')\n\tend\n%\n\tfunction fRgbValues(axh) % Show bands with RGB values (floating point and integer).\n\t\tdelete(get(axh, 'Children'))\n\t\timage(permute(bgr,[1,3,2]), 'Parent',axh)\n\t\t% Integer:\n\t\tcnm = rgb2str('[%d,%d,%d] =',1,bsxfun(@times,bgr,ohm));\n\t\ttext(ones(1,N), 1:N, cnm, 'Parent',axh, 'Color',fgd,...\n\t\t\t'BackgroundColor',bgd, 'HorizontalAlignment','right')\n\t\t% Normalized:\n\t\tcnm = rgb2str(' [%.5g,%.5g,%.5g]',1e5,bgr);\n\t\ttext(ones(1,N), 1:N, cnm, 'Parent',axh, 'Color',fgd,...\n\t\t\t'BackgroundColor',bgd, 'HorizontalAlignment','left')\n\tend\n%\n\tfunction fEuclDist(axh) % Show Euclidean distances (2D or 3D).\n\t\tdelete(get(axh, 'Children'))\n\t\taud = get(axh, 'UserData');\n\t\tsgc = {'Parent',axh, 'LineWidth',2.8, 'Marker','o'};\n\t\tfor idk = 1:N\n\t\t\tdst = sqrt(sum(bsxfun(@minus,ucs,ucs(idk,:)).^2,2));\n\t\t\tswitch aud\n\t\t\t\tcase 2\n\t\t\t\t\tscatter(1:N, dst, 123, bgr,...\n\t\t\t\t\t\tsgc{:}, 'MarkerFaceColor',bgr(idk,:), 'Parent',axh);\n\t\t\t\tcase 3\n\t\t\t\t\tscatter3(idk*ones(1,N), 1:N, dst, 123, bgr,...\n\t\t\t\t\t\tsgc{:}, 'MarkerFaceColor',bgr(idk,:), 'Parent',axh);\n\t\t\t\totherwise\n\t\t\t\t\terror('SC:maxdistcolor_view:TooManyDimensions',...\n\t\t\t\t\t\t'Sorry, I don''t know how to plot %d dimensions.',aud)\n\t\t\tend\n\t\t\thold(axh,'on')\n\t\tend\n\t\t%\n\t\tif aud==2\n\t\t\tdst = status.minDistOutput;\n\t\t\ttext(N+0.5,dst,sprintf(' %#.5g',dst), 'Parent',axh,...\n\t\t\t\t'Color',fgd, 'BackgroundColor','none')\n\t\tend\n\tend\n%\n%% Callback Functions %%\n%\n\tfunction fEvalFun(obj,~) % Turn evaluation on and off.\n\t\teUiX = ~eUiX;\n\t\tif eUiX % eval\n\t\t\tset(obj,'String','pause', 'BackgroundColor',eUiC)\n\t\telse % paused\n\t\t\tset(obj,'String','eval', 'BackgroundColor',[1,1,0])\n\t\tend\n\t\tfUpDtMap()\n\tend\n\tfunction fUpDtMap(~,~) % Update colormap using options structure.\n\t\tif eUiX\n\t\t\t% Generate colormap:\n\t\t\tset(figH, 'Pointer','watch')\n\t\t\tdrawnow()\n\t\t\t[bgr,ucs,status,RGB,UCS] = maxdistcolor(N,fun,opts);\n\t\t\tset(figH, 'Pointer',figY)\n\t\t\tinw = true;\n\t\t\tohm = pow2([opts.bitR,opts.bitG,opts.bitB])-1;\n\t\t\t% Update colorbar:\n\t\t\tset(bImH, 'CData',permute(bgr,[1,3,2]))\n\t\t\t% Update main plots:\n\t\t\tarrayfun(@(s,h) s.fun(h), pAxS, pAxH)\n\t\tend\n\tend\n%\n\tfunction fNumEdit(obj,~) % Number edit box callback.\n\t\tstr = get(obj, 'String');\n\t\tif all(isstrprop(str,'digit')) && sscanf(str,'%d')\n\t\t\tN = sscanf(str,'%d');\n\t\t\tset(nUiH, 'Value',nFun(N))\n\t\t\tfNumTick()\n\t\t\tfUpDtMap()\n\t\telse\n\t\t\tset(obj,'String',sprintf('%d',N))\n\t\tend\n\tend\n\tfunction fNumSlide(~,evt) % Number slider listener callback.\n\t\ttry\n\t\t\tN = round(get(evt,'NewValue'));\n\t\tcatch %#ok<CTCH>\n\t\t\tN = round(evt.AffectedObject.Value);\n\t\tend\n\t\tset(nVaH, 'String',sprintf('%d',N))\n\t\tfNumTick()\n\tend\n\tfunction fNumTick() % Number adjust limits and tickmarks.\n\t\tfPermSort()\n\t\t% Colorbar limits:\n\t\tset(bAxH, 'Ylim',[0,N]+0.5, 'YTick',1:N)\n\t\t% Table sizes:\n\t\tfor idk = 1:tTxN\n\t\t\tnew = get(tUiH(idk), 'Data');\n\t\t\tnew(end+1:N,:) = NaN;\n\t\t\tnew(N+1:end,:) = [];\n\t\t\tset(tUiH(idk), 'Data',new)\n\t\tend\n\t\t% Main plot axes limits:\n\t\tfor idk = 1:numel(pAxH)\n\t\t\tfor idc = 'XYZ'\n\t\t\t\tif strcmpi(pAxS(idk).(idc),ndx)\n\t\t\t\t\tset(pAxH(idk), [idc,'Lim'],[0,N]+0.5, [idc,'Tick'],1:N);\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n%\n\tfunction fOptEdit(obj,~,idk) % Options edit box callback.\n\t\tstr = get(obj, 'String');\n\t\tnew = str2double(str);\n\t\tif ~isreal(new) || (sInt(idk) && fix(new)~=new) || new<sRng(idk,1) || new>sRng(idk,2)\n\t\t\tnew = NaN;\n\t\tend\n\t\tif isnan(new)\n\t\t\tset(obj, 'String',sStr(opts.(sTxt{idk})))\n\t\telse\n\t\t\topts.(sTxt{idk}) = new;\n\t\t\tset(sUiH(idk), 'Value',new)\n\t\t\tfUpDtMap()\n\t\tend\n\tend\n\tfunction fOptSlide(~,evt,idk) % Options slider listener callback.\n\t\ttry\n\t\t\tnew = get(evt,'NewValue');\n\t\tcatch %#ok<CTCH>\n\t\t\tnew = evt.AffectedObject.Value;\n\t\tend\n\t\tif sInt(idk)\n\t\t\tnew = round(new);\n\t\t\tset(sUiH(idk), 'Value',new)\n\t\tend\n\t\topts.(sTxt{idk}) = new;\n\t\tset(sVaH(idk), 'String',sStr(new))\n\t\t% Move paired slider:\n\t\tif sTwo(idk)\n\t\t\tidt = setdiff(find(abs(sTwo)==abs(sTwo(idk))),idk);\n\t\t\told = get(sUiH(idt), 'Value');\n\t\t\tif ((new-old) * diff(sign(sTwo([idt,idk])))) < 0\n\t\t\t\tset(sUiH(idt), 'Value',new)\n\t\t\tend\n\t\tend\n\tend\n%\n\tfunction fOptMenu(obj,~,idk) % Options menu callback.\n\t\tidv = get(obj,'Value');\n\t\tif idk>1\n\t\t\topts.(mTxt{idk}) = mStr{idk}{idv};\n\t\t\tfUpDtMap()\n\t\telse\n\t\t\tset(pPnH,     'Visible','off', 'HitTest','off')\n\t\t\tset(pPnH(idv),'Visible','on',  'HitTest','on')\n\t\tend\n\t\tfAlphaTry()\n\tend\n%\n\tfunction fCellEdit(obj,~,idk) % Options table cell callback.\n\t\tnew = get(obj,'Data');\n\t\tisn = sum(isnan(new),2);\n\t\tidz = isn==0;\n\t\tif all(idz|(isn==3))\n\t\t\tnew = new(idz,:);\n\t\t\tif get(tCbH(idk),'Value') % uint\n\t\t\t\tpwr = pow2(max(3,ceil(log2(max(log2(ohm+1))))));\n\t\t\t\tnew = cast(new,sprintf('uint%d',pwr));\n\t\t\tend\n\t\t\topts.(tTxt{idk}) = new;\n\t\t\tfBackFore(true)\n\t\t\tfUpDtMap()\n\t\tend\n\tend\n\tfunction fCheckBox(obj,~,idk) % Options table checkbox callback.\n\t\told = get(tUiH(idk),'Data');\n\t\tif get(obj,'Value')\n\t\t\t% float->uint\n\t\t\tnew = round(bsxfun(@times,old,ohm));\n\t\telse\n\t\t\t% uint->float\n\t\t\tnew = bsxfun(@rdivide,old,ohm);\n\t\tend\n\t\tset(tUiH(idk),'Data',new);\n\tend\n%\n\tfunction fPermSort() % No permutation sorting if N>9.\n\t\tids = strcmpi('sort',mTxt);\n\t\tidn = get(mUiH(ids), 'Value');\n\t\tif N>9\n\t\t\tif idn > numel(mSrt{1})\n\t\t\t\tidn = 1;\n\t\t\tend\n\t\t\topts.sort = mSrt{1}{idn};\n\t\t\tset(mUiH(ids), 'String',mSrt{1}, 'Value',idn)\n\t\telse\n\t\t\tset(mUiH(ids), 'String',mStr{ids})\n\t\tend\n\tend\n%\n\tfunction fBackFore(chg) % Background and Foreground colors.\n\t\tif isempty(opts.exc)\n\t\t\tbgd = [1,1,1];\n\t\t\tfgd = [0,0,0];\n\t\telse\n\t\t\tnew = opts.exc(1,:);\n\t\t\tif isfloat(new)\n\t\t\t\tbgd = double(new);\n\t\t\telse\n\t\t\t\tbgd = double(new) ./ ohm;\n\t\t\tend\n\t\t\t% Define forground as farthest color from background:\n\t\t\t[~,idf] = max(sum(bsxfun(@minus,fun(bgd),fun(smp)).^2,2));\n\t\t\tfgd = smp(idf,:);\n\t\tend\n\t\tif chg\n\t\t\tuih = get(pAxH, 'Parent');\n\t\t\tset([uih{:}], 'BackgroundColor',bgd)\n\t\t\tuih = get(pAxH, 'Title');\n\t\t\tset([uih{:}], 'Color',fgd)\n\t\t\tset(pAxH, 'XColor',fgd, 'YColor',fgd, 'ZColor',fgd)\n\t\tend\n\tend\n%\n\tfunction fSizeObj(~,~) % Resize the figure contents.\n\t\tdrawnow()\n\t\ttry\n\t\t\tfigP = get(figH, 'Position');\n\t\tcatch %#ok<CTCH>\n\t\t\treturn\n\t\tend\n\t\t% Ensure minimum virtual figure size:\n\t\tadj = max(figP(3:4),[425,254]);\n\t\tpFg = [figP(1:2)+min(0,figP(3:4)-adj),adj];\n\t\t% Get object sizes:\n\t\tmUiX = cell2mat(get(mUiH, 'Extent'));\n\t\tsTxX = cell2mat(get(sTxH, 'Extent'));\n\t\ttCbX = cell2mat(get(tCbH, 'Extent'));\n\t\ttUiX = cell2mat(get(tUiH, 'Extent'));\n\t\ttTxX = cell2mat(get(tTxH, 'Extent'));\n\t\t% Group widths and heights:\n\t\ttWd = max(tUiX(:,3))+21; % table width\n\t\tbWd = 36; % colorbar axes width\n\t\taWd = pFg(3)-tWd-bWd-gap*4; % main axes width\n\t\tmHt = max(mUiX(:,4)); % menu height\n\t\t% Menu UI positions:\n\t\tmUiP = mUiX;\n\t\tmUiP(:,1) = aWd+bWd+3*gap;\n\t\tmUiP(:,2) = gap+2*mHt*(mTxN-1:-1:0)+3;\n\t\tmUiP(:,3) = tWd;\n\t\tmUiP(:,4) = mHt;\n\t\tset(mUiH,{'Position'},num2cell(mUiP,2))\n\t\t% Menu text positions:\n\t\tmAxP = mUiP(end,:);\n\t\tmAxP(:,4) = 2*mTxN*mHt;\n\t\tset(mAxH,'Position',mAxP)\n\t\t% Horizontal slider text positions:\n\t\tsHt = (2*mTxN*mHt)/sTxN;\n\t\tsTxP = sTxX;\n\t\tsTxP(:,1) = gap;\n\t\tsTxP(:,2) = gap+sHt*(sTxN-1:-1:0);\n\t\tsTxP(:,3) = max(sTxX(:,3));\n\t\tsTxP(:,4) = sHt;\n\t\tset(sTxH,{'Position'},num2cell(sTxP,2))\n\t\t% Horizontal slider value positions:\n\t\tsVaP = sTxP;\n\t\tsVaP(:,1) = sum(sTxP(:,[1,3]),2);\n\t\tset(sVaH,{'Position'},num2cell(sVaP,2))\n\t\t% Horizontal slider UI positions:\n\t\tsUiP = sVaP;\n\t\tsUiP(:,1) = sum(sVaP(:,[1,3]),2);\n\t\tsUiP(:,3) = aWd-sTxP(:,3)-sVaP(:,3);\n\t\tset(sUiH,{'Position'},num2cell(sUiP,2))\n\t\t% Table UI positions:\n\t\tbHt = pFg(4)-2*mTxN*mHt-3*gap;\n\t\ttUiP = tUiX;\n\t\ttUiP(:,1) = aWd+bWd+3*gap;\n\t\ttUiP(:,2) = 2*mTxN*mHt+2*gap+[bHt/2;0];\n\t\ttUiP(:,3) = tWd;\n\t\ttUiP(:,4) = bHt/2;\n\t\tset(tUiH,{'Position'},num2cell(tUiP,2))\n\t\t% Table text positions:\n\t\ttTxP = tTxX;\n\t\ttTxP(:,1) = tUiP(:,1)+3;\n\t\ttTxP(:,2) = tUiP(:,2)+bHt/2-tTxX(:,4);\n\t\ttTxP(:,4) = tTxX(:,4)-3;\n\t\tset(tTxH,{'Position'},num2cell(tTxP,2))\n\t\t% Table checkbox UI positions:\n\t\ttCbP = tCbX(:,[1,2,4,4]);\n\t\ttCbP(:,1) = tUiP(:,1)+tUiP(:,3)-21;\n\t\ttCbP(:,2) = tUiP(:,2)+tUiP(:,4)-21;\n\t\tset(tCbH,{'Position'},num2cell(tCbP,2))\n\t\t% Colorbar axes position:\n\t\tbAxP = tUiP(end,:);\n\t\tbAxP(1) = aWd+gap*2;\n\t\tbAxP(3) = bWd;\n\t\tbAxP(4) = bHt;\n\t\tset(bAxH,'Position',bAxP)\n\t\t% Number slider UI position:\n\t\tnUiP = bAxP;\n\t\tnUiP(2) = gap;\n\t\tnUiP(4) = 2*mTxN*mHt-txh-gap-mHt;\n\t\tset(nUiH,'Position',nUiP)\n\t\t% Number slider value position:\n\t\tnVaP = nUiP;\n\t\tnVaP(2) = gap+nUiP(4);\n\t\tnVaP(4) = txh;\n\t\tset(nVaH,'Position',nVaP)\n\t\t% Eval button UI position:\n\t\teUiP = nVaP;\n\t\teUiP(2) = 2*mTxN*mHt-mHt+gap;\n\t\teUiP(4) = mHt;\n\t\tset(eUiH,'Position',eUiP)\n\t\t% Main plots uipanel position:\n\t\tpPnP = bAxP;\n\t\tpPnP(1) = gap;\n\t\tpPnP(3) = aWd;\n\t\tset(pPnH,'Position',pPnP)\n\tend\n%\nif nargout\n\twaitfor(figH)\n\trgb = bgr;\nend\n%\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%maxdistcolor_view", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/extern/maxdistcolor/maxdistcolor_view.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24221508947713932}}
{"text": "function rinds = APPspInds2RegionInds(map, sinds)\n% rinds = APPspInds2RegionInds(map, sinds)\n% Gets the sp in each region\n%\n% Copyright(C) Derek Hoiem, Carnegie Mellon University, 2005\n% Permission granted to non-commercial enterprises for\n% modification/redistribution under GNU GPL.  \n% Current Version: 1.0  09/30/2005\n\nnr = max(map);\nrinds = cell(nr, 1);\nfor r = 1:nr\n    count = 0;\n    rs = find(map==r);\n    for k = 1:length(rs)\n        count = count + length(sinds{rs(k)});\n    end         \n    rinds{r} = zeros(count, 1);\n    \n    count = 0;\n    for k = 1:length(rs) \n        rinds{r}(count+1:count+length(sinds{rs(k)})) = sinds{rs(k)};\n        count = count + length(sinds{rs(k)});\n    end\nend", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/geom/APPspInds2regionInds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150894771393}}
{"text": "function plotPredictionResults_VASARI(pathResults,nameOutcome,fSetNames,metric,maxOrder,pathFig)\n% -------------------------------------------------------------------------\n% function plotPredictionResults_VASARI(pathResults,nameOutcome,fSetNames,metrics,maxOrder)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function plots prediction performance estimation results for all the\n% different feature set types entered as inputs in the LGG study.\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathResults: Full path to the 'RESULTS' folder where prediction results\n%                 are saved.\n%                 --> Ex: '/myProject/WORKSPACE/VASARI/RESULTS'\n% 2. nameOutcome: String specifying the name of the outcome being displayed\n%                 --> Ex: 'progression'\n% 3. fSetNames: Cell of strings specifying the name of the type of feature \n%               set analyzed.\n%               --> Ex: {'VASARI'}\n% 4. metric: String specifying the metric to display.\n%            --> 'AUC632'\n% 5. maxOrder: Integer specifying the maximal multivariable model order.\n%              --> Ex: 10\n% 6. pathFig: (optional).  Full path to where figure is saved without\n%             displaying it. Put '' for displaying the figure and not \n%             saving it to 'pathFig' (default).\n%             --> Ex: ''\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nif nargin < 6\n    pathFig = '';\nend\n\nstartpath = pwd;\ncd(pathResults)\n\nsigns = {'-r',':b','--g','-.y'};\nnFSET = numel(fSetNames);\n\nmaxOrderChosen = maxOrder;\n\nif isempty(pathFig)\n    figure\nelse\n    h = figure('visible','off');\nend\nfor i = 1:nFSET\n    fSET = fSetNames{i};\n    results = load(['RESULTS_',fSET,'_',nameOutcome]); results = struct2cell(results); results = results{1};\n    nOrders = numel(fieldnames(results));\n    if nOrders < maxOrderChosen\n        maxOrder = nOrders;\n    else\n        maxOrder = maxOrderChosen;\n    end\n    val = zeros(maxOrder,1);\n    val_SE = zeros(maxOrder,1);\n    for j = 1:maxOrder\n        orderName = ['Order',num2str(j)];\n        val(j,1) = results.(orderName).(metric);\n        val_SE(j,1) = results.(orderName).(['SE_',metric]);\n    end\n    errorbar(1:maxOrder,val(:,1),val_SE(:,1),signs{i},'LineWidth',3,'MarkerFaceColor',signs{i}(end),'MarkerSize',6)\n    hold on\nend\nset(gca,'FontSize',20)\nxlabel('Model Order','FontSize',24)\nylabel('Prediction performance','FontSize',24)\nind = strfind(metric,'632');\nif ~isempty(ind)\n    metric = [metric,'+'];\nend\nmetric = [metric(1:ind-1),'_{',metric(ind:end),'}'];\nind = strfind(nameOutcome,'Death');\nif ~isempty(ind)\n    nameOutcome(ind:ind+4) = [];\n    nameOutcome = ['Survival',nameOutcome];\nend\ntitleName = [nameOutcome,'(VASARI) -- ',metric];\ntitle(titleName,'FontSize',30,'FontWeight','bold')\nlegend(fSetNames,'Location','SouthEast')\naxis([0 maxOrderChosen+1 0.5 1])\nset(gca,'XTick',[1 2 3 4 5 6 7 8 9 10])\n\nif ~isempty(pathFig)\n    cd(pathFig)\n    saveas(h,titleName,'fig')\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/plotPredictionResults_VASARI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.2422150894771392}}
{"text": "% Read all images and extract point coordinates.\n%\n% All information needed are stored and retrieved\n% from the function CONFIGDATA\n\n% $Author: svoboda $\n% $Revision: 2.6 $\n% $Id: im2points.m,v 2.6 2005/05/23 16:26:03 svoboda Exp $\n% $State: Exp $\n\nclear all;\n\n% add path to config data\naddpath ../../CommonCfgAndIO\n% add path for graphical output if needed\naddpath ../OutputFunctions\n\nSHOWFIG\t  = 0; % show images during point extraction\nSTEP4STAT = 1; % step for computing average and std images, if 1 then all images taken\n\n% Read configuration from whatever is specified on command-line (via --config=FILENAME)\nconfig = read_configuration();\n\nim.dir = config.paths.img;\nim.ext = config.files.imgext;\n\nNoCams = size(config.files.idxcams,2);\t% number of cameras\n\n% load image names\nfor i=1:NoCams,\n  seq(i).camId = config.files.idxcams(i);\n  if seq(i).camId > -1\n\tif strfind(config.expname,'oscar')\n\t  seq(i).data = dir([sprintf(im.dir,seq(i).camId),config.files.imnames,'*.',im.ext]);\n\telse\n\t  seq(i).data = dir([sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]);\n\tend\n  else\n\tseq(i).data = dir([im.dir,sprintf(config.files.imnames),im.ext]);\n  end\n  seq(i).size = size(seq(i).data,1);\n  if seq(i).size<4\n\terror('Not enough images found. Wrong image path or name pattern?');\n  end\nend\n\n\n% create an occupancy matrix for image frames\noccmat=1; try config.files.maxid; catch occmat=0; end\nif occmat,\n\tNoPoints = config.files.maxid;\n\tFrameMat = zeros(config.files.maxid,NoCams);\n\tfor i=1:NoCams,\n\t\tseq(i).imgidx = zeros(size(1:NoPoints));\n\t\tfor j=1:size(seq(i).data,1)\n\t\t\tFrameMat(str2num(seq(i).data(j).name(config.files.posid)),i)=j;\n\t\tend\n\tend\nelse\n\tNoPoints = min([seq.size]);\n\tFrameMat = zeros(NoPoints,NoCams);\n\tfor i=1:NoCams,\n\t\tFrameMat(:,i) = [1:NoPoints]';\n\tend\nend\n\n% In fact, some frames might be without any calibration point\n\n% Becouse of non-consistent stopping of capturing, the sequences might\n% have different number of images, select the minimal value as the right one\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% beginning of the findings\n\nt = cputime;\nfor i=1:NoCams,\n  if ~exist(sprintf(config.files.avIM,seq(i).camId)),\n\tdisp(sprintf('The average image of the camera %d is being computed',seq(i).camId));\n\tavIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tpointIdx = 1:STEP4STAT:seq(i).size;\n\tfor j=pointIdx,\n\t  IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t  avIM = avIM + double(IM);\n\tend\n\tavIM = uint8(round(avIM./size(pointIdx,2)));\n\timwrite(avIM,sprintf(config.files.avIM,seq(i).camId));\n  else\tdisp('Average file already exists');\n  end\nend\ndisp(sprintf('Elapsed time for computation of average images: %4.2f [sec]',cputime-t))\n% compute the standard deviations images that will be used for finding LEDs\n% if not already computed\nt = cputime;\nfor i=1:NoCams,\n  if ~exist(sprintf(config.files.stdIM,seq(i).camId)),\n\tavIM = double(imread(sprintf(config.files.avIM,seq(i).camId)));\n\tdisp(sprintf('The image of standard deviations of the camera %d is being computed',seq(i).camId));\n\tstdIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tpointIdx = 1:STEP4STAT:seq(i).size;\n\tfor j=pointIdx,\n\t  IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t  stdIM = stdIM + (double(IM)-avIM).^2;\n\tend\n\tstdIM = uint8(round(sqrt(stdIM./(size(pointIdx,2)-1))));\n\timwrite(stdIM,sprintf(config.files.stdIM,seq(i).camId));\n  else\n\tdisp('Image of standard deviations already exists')\n  end\nend\n\ndisp(sprintf('Elapsed time for computation of variance images: %4.2f [sec]',cputime-t))\n\n% find points in the images\nWs    = [];\t  % joint image matrix\nRes\t  = [];\t  % resolution of cameras\n% UsableFramesIdx = find(sum(FrameMat')>2);\nIdMat = ones(NoCams,NoPoints);\n% IdMat is very important for Martinec&Pajdla filling [ECCV2002]\n% it is a NoCams x NoPoints matrix,\n% IdMat(i,j) = 0 -> no j-th point in i-th\n% IdMat(i,j) = 1 -> point successfully detected\n\n\ndisp('*********************************************')\ndisp('Finding points (laser projections) in cameras')\ndisp(sprintf('Totally %d cameras, %d images for each cam', NoCams, NoPoints'))\ndisp('*********************************************')\nfor i=1:NoCams,\n  t1 = cputime;\n  disp(sprintf('Finding points in camera No: %0.2d',config.files.idxcams(i)))\n  Points = [];\n  avIM  = imread(sprintf(config.files.avIM,seq(i).camId));\n  stdIM\t= imread(sprintf(config.files.stdIM,seq(i).camId));\n  for j=1:NoPoints,\n\t  fprintf(1,'\\b\\b\\b\\b\\b\\b %5d',j);\n\t  idx2data = FrameMat(j,i);\n\t  if idx2data\n\t\t  [pos,err] = getpoint([sprintf(im.dir,seq(i).camId),seq(i).data(idx2data).name], SHOWFIG, config.imgs, avIM, stdIM);\n\t  else\n\t\t  err = 1;\n\t  end\n\tif err\n\t  IdMat(i,j) = 0;\n\t  Points = [Points, [NaN; NaN; NaN]];\n\telse\n\t  Points = [Points, [pos; 1]];\n\tend\n  end\n  Ws = [Ws; Points];\n  Res= [Res; size(avIM,2), size(avIM,1)];\n  t2 = cputime;\n  disp(sprintf('\\nElapsed time for finding points in one camera: %d minutes %d seconds',floor((t2-t1)/60), round(mod((t2-t1),60))))\n  disp(sprintf('%4d points found in camera No: %0.2d',sum(Points(3,:)>0),config.files.idxcams(i)));\nend\n\n%%% End of the findings\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strfind(config.expname,'oscar')\n  % needs special care for handling projector data\n  ProjPoints = load(config.files.projdata,'-ASCII');\n  Ws = [Ws; ProjPoints(:,end-1:end)'; ones(size(ProjPoints(:,1)'))];\n  IdMat = [IdMat; ones(size(ProjPoints(:,1)'))];\n  Res\t= [Res; config.imgs.projres];\nend\n\nsave(config.files.points, 'Ws','-ASCII')\nsave(config.files.Res, 'Res', '-ASCII')\nsave(config.files.IdMat, 'IdMat', '-ASCII')\n\n% display the overall statistics\ndisp('Overall statistics from im2points:  ************************  ')\ndisp(sprintf('Total number of frames (possible 3D points): %d',NoPoints))\ndisp(sprintf('Total number of cameras %d', NoCams))\ndisp('More important statistics: *********************************  ')\ndisp(sprintf('Detected 3D points:                    %d', sum(sum(IdMat)>0)))\ndisp(sprintf('Detected 3D points in at least 3 cams: %d', sum(sum(IdMat)>2)))\ndisp(sprintf('Detected 3D points in ALL cameras:     %d', sum(sum(IdMat)==NoCams)))\n\n\n\n\n\n\n\n\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/FindingPoints/im2points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}}
{"text": "function vw = nifti2ROI(vw, mappth)\n%   Convert a nifti label file into a mrVista format ROI \n%\n% vw = nifti2ROI([vw], [mappth])\n%\n% vw:       mrVista view structure (must be gray view) \n%               [default = current Gray view]               \n% mappth:   path to nifti file with map to convert; \n%               [default = dialog]\n%\n% Notes: the nifti format map is a 3D matrix. The mrVista parameter map is\n% a vector, indexed to the gray coords. The main steps of the routine are:\n%   1) Convert the nifti format 3D map to a vector and 3xN coordinate\n%           matrix\n%   2) Transform the coordinates to the space of the t1-weighted anatomy\n%       (using header information in the two files)       \n%   3) Transform the coordinates to mrAnat conventions\n%\n% Example:  Convert a class file into ROIs\n% vw = nifti2ROI(vw, viewGet(vw, 'class file', 'right'))\n%\n%   JW, 4/27/2015\n%\n\nmrGlobals;\n\n% Variable check\nif notDefined('vw'), vw = getSelectedGray; end\n\nif ~exist('mappth', 'var') || ~exist(mappth, 'file') \n    mappth = getPathStrDialog(dataDir(vw),'Choose nifti parameter map','*.nii.gz');\nend\n\n% read a nifti file with map to be converted to ROIs\nni = niftiRead(mappth);\n\n% apply our canonical transform to ensure orientation is matched to t1;\nni   = niftiApplyCannonicalXform(ni);\n\n% This is the map data\ndata = niftiGet(ni, 'data');\ndata = nifti2mrVistaAnat(data);\ndata = round(data);\n% ensure data are integers\nassert(isequal(data, round(data)));\n\n% define ROIs\nlabels = setdiff(unique(data(:)),0);\n\nfprintf('[%s]: Creating %d ROIs from file %s\\n', mfilename, length(labels), mappth);\n\nfor ii = 1:length(labels)\n   [x, y, z] = ind2sub(size(data), find(data == labels(ii)));\n   coords = [x y z]';\n   comments = sprintf('ROI defined by label %d in map %s', labels(ii), mappth);\n   name = sprintf('ROI_%03d', labels(ii));\n   fprintf('.');drawnow();\n   vw = newROI(vw,name,1,'k',coords, comments);\nend\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/XformView/nifti2ROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2418989115528129}}
{"text": "function flag=istfraff(method);\n% flag=istfr2(method) returns true is method is an affine\n% time frequency representation.\n%\tSee also istfr1, istfr2.\n\n%\tF. Auger, may 98\n%\tCopyright (c) CNRS - France 1998. \n%\n%  This program is free software; you can redistribute it and/or modify\n%  it under the terms of the GNU General Public License as published by\n%  the Free Software Foundation; either version 2 of the License, or\n%  (at your option) any later version.\n%\n%  This program is distributed in the hope that it will be useful,\n%  but WITHOUT ANY WARRANTY; without even the implied warranty of\n%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%  GNU General Public License for more details.\n%\n%  You should have received a copy of the GNU General Public License\n%  along with this program; if not, write to the Free Software\n%  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nmethod=upper(method);\nif strcmp(method,'TFRASPW' ) | strcmp(method,'TFRSCALO') | ...\n   strcmp(method,'TFRDFLA' ) | strcmp(method,'TFRSPAW' ) | ...\n   strcmp(method,'TFRUNTER') | strcmp(method,'TFRBERT' ) | ...\n   strcmp(method,'TFRSPBK' ),\n flag=1;\nelse\n flag=0;\nend;\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/istfraff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24187998375596864}}
{"text": "function [y,fs,bits]=wavread(fn,n)\n%WAVREAD  Legacy MATLAB function to read .WAV file [Y,FS,BITS]=(FILENAME,NMAX)\n% wavread supports multichannel data, with up to 32 bits per sample, and supports reading 24- and 32-bit .wav files.\n%\n% Usage:\n% y = wavread('filename')               loads a WAVE file specified by the string filename, returning\n%                                       the sampled data in y. The .wav extension is appended if no\n%                                       extension is given. Amplitude values are in the range [-1,+1].\n% [y,Fs,bits] = wavread('filename')     returns the sample rate (Fs) in Hertz and the number of bits\n%                                       per sample (bits) used to encode the data in the file.\n% [...] = wavread('filename',N)         returns only the first N samples from each channel in the file.\n% [...] = wavread('filename',[N1 N2])   returns only samples N1 through N2 from each channel in the file.\n% siz = wavread('filename','size')      returns the size of the audio data contained in the file in place\n%                                       of the actual audio data, returning the vector siz = [samples channels].\n\n%\t   Copyright (C) Mike Brookes 2018\n%      Version: $Id: wavread.m 10865 2018-09-21 17:22:45Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<2\n    [y,fs,wm,fx]=v_readwav(fn);\nelseif ischar(n)\n    if strcmp(n,'size')\n        [y,fs,wm,fx]=v_readwav(fn,'',0);\n        y=fx(4:5); % number of samples and channels\n    else\n        error('%s is invalid option',n);\n    end\nelseif length(n)<2\n    [y,fs,wm,fx]=v_readwav(fn,'',n);\nelse\n    [y,fs,wm,fx]=v_readwav(fn,'',n(2)-n(1)+1,n(1)-1);\nend\nbits=fx(7); % bits precision", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/wavread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24187998375596864}}
{"text": "function []=anim8_DIC3DPP_faceMeasureDirection(DIC3DPPresults,faceMeasureString,RBMlogic,varargin)\n%% function for plotting 3D-DIC results of face measures as color + direction as arrows in STEP4.\n% plotting 3D surfaces from camera pairs, animation changing\n% with time, and the faces colored according to faceMeasureString \n% this function is called in plotMultiDICPairResults\n%\n% Options:\n% anim8_DIC3DPP_faceMeasureDirection(DIC_3Dallpairs_results,faceMeasureString)\n% anim8_DIC3DPP_faceMeasureDirection(DIC_3Dallpairs_results,faceMeasureString,optStruct)\n% \n% Inputs:\n% * DIC3DAllPairsResults\n% * faceMeasureString: can be any of the following:\n%   'Epc1','Epc2','epc1','epc2','Lamda1','Lamda2', or a combination of two  in a cell array to plot side by side\n% * optStruct: optional structure for plotting options which may include any of the following fields:\n%   - smoothLogic: logical variable for smoothing (true)/not smoothing (false) the face measure \n%   - FaceAlpha: transparacy of the faces (scalar between 0 and 1, where zero is transparent and 1 is opaque) \n%   - colorBarLimits: a 2x1 scalar vector for the colobar limits. if not set, it's automatic\n%   - dataLimits: a 2x1 scalar vector for the data limits of the face measure. if a face measure is outside these limits, it is set to NaN. if not set no face is set to NaN\n%   - colorMap\n%   - zDirection: 1 for z up and -1 for z down\n%   - lineColor: line color for the mesh. can be for example 'b','k','none',etc...\n%   - supTitleString=faceMeasureString;\n\n%% Assign plot options\nNarg=numel(varargin);\nswitch Narg\n    case 1\n        optStruct=varargin{1};\n    case 0\n        optStruct=struct;\n    otherwise\n        ('wrong number of input arguments');\nend\n\n% complete the struct fields\nif ~isfield(optStruct,'smoothLogic')\n    optStruct.smoothLogic=0;\nend\nif ~isfield(optStruct,'FaceAlpha')\n    optStruct.FaceAlpha=1;\nend\nif ~isfield(optStruct,'dataLimits')\n    optStruct.dataLimits=[-inf inf];\nend\nif ~isfield(optStruct,'zDirection') % 1 or -1\n    optStruct.zDirection=1;\nend\nif ~isfield(optStruct,'lineColor') % 'none' or 'k'\n    optStruct.lineColor='none';\nend\nif ~isfield(optStruct,'maxCorrCoeff')\n    optStruct.maxCorrCoeff=[];\nend\nif ~isfield(optStruct,'quiverScaleFactor')\n    optStruct.quiverScaleFactor=20;\nend\n%%\nnFrames=numel(DIC3DPPresults.Points3D);\n\n[xl,yl,zl]=axesLimits(DIC3DPPresults.Points3D);\nmeanEdgeLength=nanmean(patchEdgeLengths(DIC3DPPresults.Faces,DIC3DPPresults.Points3D{1}));\n\n%% Assign the right face measure into FC\n\nif iscell(faceMeasureString)\n    faceMeasureCell=faceMeasureString;\n    nStrains=numel(faceMeasureString);\n    switch nStrains\n        case 1\n            FC=cell(nFrames,nStrains);\n            D=cell(nFrames,nStrains);\n            Ds=cell(nFrames,nStrains);\n            Vc=cell(nFrames,nStrains);\n        case 2\n            FC=cell(nFrames,nStrains);\n            D=cell(nFrames,nStrains);\n            Ds=cell(nFrames,nStrains);\n            Vc=cell(nFrames,nStrains);\n        otherwise\n            error('wrong number of cells in faceMeasureString cell array (must be 1 or 2)');\n    end\nelseif ischar(faceMeasureString)\n    nStrains=1;\n    faceMeasureCell=cell(1);\n    faceMeasureCell{1}=faceMeasureString;\n    FC=cell(nFrames,1);\n    D=cell(nFrames,1);\n    Ds=cell(nFrames,1);\n    Vc=cell(nFrames,1);\nelse\n    error('wrong face measure (second input variable)');\nend\n\ndirectionStringCell=cell(nStrains,1);\nfor is=1:nStrains\n    switch faceMeasureCell{is}\n        case 'Epc1'\n            directionStringCell{is}='Epc1vecCur';\n            optStruct.supTitleString{is}='1st principal Lagrangian strain';\n        case 'Epc2'\n            directionStringCell{is}='Epc2vecCur';\n            optStruct.supTitleString{is}='2nd principal Lagrangian strain';\n        case 'epc1'\n            directionStringCell{is}='epc1vec';\n            optStruct.supTitleString{is}='1st principal Eulerian strain';\n        case 'epc2'\n            directionStringCell{is}='epc2vec';\n            optStruct.supTitleString{is}='2nd principal Eulerian strain';\n        case 'Lamda1'\n            directionStringCell{is}='Epc1vecCur';\n            optStruct.supTitleString{is}='1st principal stretch';\n        case 'Lamda2'\n            directionStringCell{is}='Epc2vecCur';\n            optStruct.supTitleString{is}='2nd principal stretch';\n        otherwise\n            error('unexpected face measure string. plots not created');\n    end\n    for it=1:nFrames\n        if RBMlogic\n            FC{it,is}=DIC3DPPresults.Deform_ARBM.(faceMeasureCell{is}){it}; % face color (strain)\n            D{it,is}=DIC3DPPresults.Deform_ARBM.(directionStringCell{is}){it}; % direction (unit vector)\n            \n            switch faceMeasureCell{is}\n                case {'Epc1','Epc2','epc1','epc2'}\n                    Ds{it,is}=optStruct.quiverScaleFactor*FC{it,is}.*D{it,is}; % direction with magnitude (scaled vector)\n                    DsLengths=sqrt((sum(Ds{it,is}.^2,2)));\n                    LogicTooLong=DsLengths>meanEdgeLength;\n                    Ds{it,is}(LogicTooLong,:)=meanEdgeLength*Ds{it,is}(LogicTooLong,:)./DsLengths(LogicTooLong);        \n                case {'Lamda1','Lamda2'}\n                    Ds{it,is}=optStruct.quiverScaleFactor*(FC{it,is}-1).*D{it,is}; % direction with magnitude (scaled vector)\n                    DsLengths=sqrt((sum(Ds{it,is}.^2,2)));\n                    LogicTooLong=DsLengths>meanEdgeLength;\n                    Ds{it,is}(LogicTooLong,:)=meanEdgeLength*Ds{it,is}(LogicTooLong,:)./DsLengths(LogicTooLong);\n            end\n            Vc{it,is}=DIC3DPPresults.FaceCentroids_ARBM{it}-.5*Ds{it,is};\n        else\n            FC{it,is}=DIC3DPPresults.Deform.(faceMeasureCell{is}){it}; % face color (strain)\n            D{it,is}=DIC3DPPresults.Deform.(directionStringCell{is}){it}; % direction (unit vector)\n            \n            switch faceMeasureCell{is}\n                case {'Epc1','Epc2','epc1','epc2'}\n                    Ds{it,is}=optStruct.quiverScaleFactor*FC{it,is}.*D{it,is}; % direction with magnitude (scaled vector)\n                    DsLengths=sqrt((sum(Ds{it,is}.^2,2)));\n                    LogicTooLong=DsLengths>meanEdgeLength;\n                    Ds{it,is}(LogicTooLong,:)=meanEdgeLength*Ds{it,is}(LogicTooLong,:)./DsLengths(LogicTooLong);                    \n                case {'Lamda1','Lamda2'}\n                    Ds{it,is}=optStruct.quiverScaleFactor*(FC{it,is}-1).*D{it,is}; % direction with magnitude (scaled vector)\n                    DsLengths=sqrt((sum(Ds{it,is}.^2,2)));\n                    LogicTooLong=DsLengths>meanEdgeLength;\n                    Ds{it,is}(LogicTooLong,:)=meanEdgeLength*Ds{it,is}(LogicTooLong,:)./DsLengths(LogicTooLong);                    \n            end\n            Vc{it,is}=DIC3DPPresults.FaceCentroids{it}-.5*Ds{it,is};\n        end\n\n        if ~isempty(optStruct.maxCorrCoeff)\n            corrNow=DIC3DPPresults.FaceCorrComb{it};\n            FC{it,is}(corrNow>optStruct.maxCorrCoeff,:)=NaN;\n            D{it,is}(corrNow>optStruct.maxCorrCoeff,:)=NaN;\n            Vc{it,is}(corrNow>optStruct.maxCorrCoeff,:)=NaN;\n        end        \n\n    end\nend\nFCmat = cell2mat(FC);\nif ~isfield(optStruct,'colorBarLimits')\n    switch faceMeasureCell{is}\n        case {'Epc1','Epc2','epc1','epc2'}\n            Emax=max(abs(FCmat(:)));\n            optStruct.colorBarLimits=[-Emax Emax];\n        case {'Lamda1','Lamda2'}\n            Lmax=max(abs(FCmat(:)-1));\n            if Lmax>1\n                optStruct.colorBarLimits=[0 2];\n            else\n                optStruct.colorBarLimits=[1-prctile(abs(FCmat(:)-1),100) 1+prctile(abs(FCmat(:)-1),100)];\n            end\n    end\nend\ncolorBarLogic=1;\nif ~isfield(optStruct,'colorMap')\n    optStruct.colorMap=.8*coldwarm;\nend\n\n\n%% Plot\n\nanimStruct=struct;\n\nhf=cFigure;\nhf.Units='normalized'; hf.OuterPosition=[.05 .05 .9 .9]; hf.Units='pixels';\n\nfor is=1:nStrains\n    subplot(1,nStrains,is);\n    \n    axisGeom;     \n    ax=gca;     \n    ax.CameraUpVector=[0 0 optStruct.zDirection];\n    colormap(optStruct.colorMap);\n    if colorBarLogic\n        colorbar;\n        caxis(optStruct.colorBarLimits);\n    end\n    \n    title(optStruct.supTitleString{is});\n%     axis off\n    % camlight headlight\n    \n    it=1;\n    Fnow=DIC3DPPresults.Faces;\n    if RBMlogic\n        Pnow=DIC3DPPresults.Points3D_ARBM{it};\n    else\n        Pnow=DIC3DPPresults.Points3D{it};   \n    end\n    \n    Vnow=Vc{it,is};\n    FCnow=FC{it,is};\n    Dnow=Ds{it,is};\n    if optStruct.smoothLogic\n        smoothPar.lambda=0.5;\n        smoothPar.n=2;\n        [FCnow]=patchSmoothFaceMeasure(Fnow,Pnow,FCnow,smoothPar);\n    end\n    FCnow(FCnow<optStruct.dataLimits(1))=NaN;\n    FCnow(FCnow>optStruct.dataLimits(2))=NaN;\n\n    hp(is)=gpatch(Fnow,Pnow,FCnow,optStruct.lineColor,optStruct.FaceAlpha); hold on\n    hq(is)=quiver3(Vnow(:,1),Vnow(:,2),Vnow(:,3),Dnow(:,1),Dnow(:,2),Dnow(:,3),0,'Color',.2*[1 1 1],'ShowArrowHead','off','AutoScale','off'); hold on;\n%         \n    h_ax=gca;\n    h_ax.XLim = xl; h_ax.YLim = yl; h_ax.ZLim = zl;\n    \nend\n\n%% fill in the animstruct\n\nanimStruct.Time=1:nFrames;\nanimStruct.Handles=cell(1,nFrames);\nanimStruct.Props=cell(1,nFrames);\nanimStruct.Set=cell(1,nFrames);\n\n\nfor it=1:nFrames\n    animStruct.Handles{it}=[];\n    animStruct.Props{it}=cell(1,8*nStrains);\n    animStruct.Set{it}=cell(1,8*nStrains);\n\n    \n    for is=1:nStrains\n        if RBMlogic\n            Pnow=DIC3DPPresults.Points3D_ARBM{it};\n        else\n            Pnow=DIC3DPPresults.Points3D{it};\n        end\n        Fnow=DIC3DPPresults.Faces;\n        FCnow=FC{it,is};\n        if optStruct.smoothLogic\n            [FCnow]=patchSmoothFaceMeasure(Fnow,Pnow,FCnow,smoothPar);\n        end\n        FCnow(FCnow<optStruct.dataLimits(1))=NaN;\n        FCnow(FCnow>optStruct.dataLimits(2))=NaN;\n        \n        Vnow=Vc{it,is};\n        Dnow=Ds{it,is};\n    \n        animStruct.Handles{it}=[animStruct.Handles{it} hp(is) hp(is) hq(is) hq(is) hq(is) hq(is) hq(is) hq(is)]; %Handles of objects to animate (add one every pair)\n        \n        animStruct.Props{it}{1+8*(is-1)}='CData';\n        animStruct.Props{it}{2+8*(is-1)}='Vertices'; %Properties of objects to animate\n        animStruct.Props{it}{3+8*(is-1)}='XData'; %Properties of objects to animate\n        animStruct.Props{it}{4+8*(is-1)}='YData'; %Properties of objects to animate\n        animStruct.Props{it}{5+8*(is-1)}='ZData'; %Properties of objects to animate\n        animStruct.Props{it}{6+8*(is-1)}='UData'; %Properties of objects to animate\n        animStruct.Props{it}{7+8*(is-1)}='VData'; %Properties of objects to animate\n        animStruct.Props{it}{8+8*(is-1)}='WData'; %Properties of objects to animate\n        \n        animStruct.Set{it}{1+8*(is-1)}=FCnow;\n        animStruct.Set{it}{2+8*(is-1)}=Pnow; %Property values for to set in order to animate\n        animStruct.Set{it}{3+8*(is-1)}=Vnow(:,1); %Property values for to set in order to animate\n        animStruct.Set{it}{4+8*(is-1)}=Vnow(:,2); %Property values for to set in order to animate\n        animStruct.Set{it}{5+8*(is-1)}=Vnow(:,3); %Property values for to set in order to animate\n        animStruct.Set{it}{6+8*(is-1)}=Dnow(:,1); %Property values for to set in order to animate\n        animStruct.Set{it}{7+8*(is-1)}=Dnow(:,2); %Property values for to set in order to animate\n        animStruct.Set{it}{8+8*(is-1)}=Dnow(:,3); %Property values for to set in order to animate\n        \n        h_ax.XLim = xl; h_ax.YLim = yl; h_ax.ZLim = zl;\n        \n    end\nend\n\nanim8(hf,animStruct);\n\naddColorbarLimitsButton(hf);\naddColormapButton(hf);\naddEdgeColorButton(hf);\naddFaceAlphaButton(hf);\naddLightButton(hf);\naddAmbientStrengthButton(hf);\naddDiffuseStrengthButton(hf);\naddSpecularStrengthButton(hf);\naddQuiverFactorButton(hf);\naddFaceLightingButton(hf);\n\nend\n\n%% \n% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation\n% \n% License: <https://github.com/MultiDIC/MultiDIC/blob/master/LICENSE.txt>\n% \n% Copyright (C) 2018  Dana Solav\n% % \n% If you use the toolbox/function for your research, please cite our paper:\n% <https://engrxiv.org/fv47e>", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_MultiDIC/anim8_DIC3DPP_faceMeasureDirection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24187997671630362}}
{"text": "function bnet = mk_dbn(intra, inter, node_sizes, varargin)\n% MK_DBN Make a Dynamic Bayesian Network.\n%\n% BNET = MK_DBN(INTRA, INTER, NODE_SIZES, ...) makes a DBN with arcs\n% from i in slice t to j in slice t iff intra(i,j) = 1, and \n% from i in slice t to j in slice t+1 iff inter(i,j) = 1,\n% for i,j in {1, 2, ..., n}, where n = num. nodes per slice, and t >= 1.\n% node_sizes(i) is the number of values node i can take on.\n% The nodes are assumed to be in topological order. Use TOPOLOGICAL_SORT if necessary.\n% See also mk_bnet.\n%\n% Optional arguments [default in brackets]\n% 'discrete' - list of discrete nodes [1:n]\n% 'observed' - the list of nodes which will definitely be observed in every slice of every case [ [] ]\n% 'eclass1' - equiv class for slice 1 [1:n]\n% 'eclass2' - equiv class for slice 2 [tie nodes with equivalent parents to slice 1]\n%    equiv_class1(i) = j means node i in slice 1 gets its parameters from bnet.CPD{j},\n%    i.e., nodes i and j have tied parameters.\n% 'intra1' - topology of first slice, if different from others\n% 'names' - a cell array of strings to be associated with nodes 1:n [{}]\n%    This creates an associative array, so you write e.g.\n%     'evidence(bnet.names{'bar'}) = 42' instead of  'evidence(2} = 42' \n%     assuming names = { 'foo', 'bar', ...}.\n%    \n% For backwards compatibility with BNT2, arguments can also be specified as follows\n%   bnet = mk_dbn(intra, inter, node_sizes, dnodes, eclass1, eclass2, intra1)\n%\n% After calling this function, you must specify the parameters (conditional probability\n% distributions) using bnet.CPD{i} = gaussian_CPD(...) or tabular_CPD(...) etc.\n\n\nn = length(intra);\nss = n;\nbnet.nnodes_per_slice = ss;\nbnet.intra = intra;\nbnet.inter = inter;\nbnet.intra1 = intra;\ndag = zeros(2*n);\ndag(1:n,1:n) = bnet.intra1;\ndag(1:n,(1:n)+n) = bnet.inter;\ndag((1:n)+n,(1:n)+n) = bnet.intra;\nbnet.dag = dag;\nbnet.names = {};\n\ndirected = 1;\nif ~acyclic(dag,directed)\n  error('graph must be acyclic')\nend\n\n\nbnet.eclass1 = 1:n;\n%bnet.eclass2 = (1:n)+n;\nbnet.eclass2 = bnet.eclass1;\nfor i=1:ss\n  if isequal(parents(dag, i+ss), parents(dag, i)+ss)\n    %fprintf('%d has isomorphic parents, eclass %d\\n', i, bnet.eclass2(i))\n  else\n    bnet.eclass2(i) = max(bnet.eclass2) + 1;\n    %fprintf('%d has non isomorphic parents, eclass %d\\n', i, bnet.eclass2(i))\n  end\nend\n\ndnodes = 1:n;\nbnet.observed = [];\n\nif nargin >= 4\n  args = varargin;\n  nargs = length(args);\n  if ~isstr(args{1})\n    if nargs >= 1, dnodes = args{1}; end\n    if nargs >= 2, bnet.eclass1 = args{2}; end\n    if nargs >= 3, bnet.eclass2 = args{3}; end\n    if nargs >= 4, bnet.intra1 = args{4}; end\n  else\n    for i=1:2:nargs\n      switch args{i},\n       case 'discrete', dnodes = args{i+1}; \n       case 'observed', bnet.observed = args{i+1}; \n       case 'eclass1',  bnet.eclass1 = args{i+1}; \n       case 'eclass2',  bnet.eclass2 = args{i+1}; \n       case 'intra1',  bnet.intra1 = args{i+1}; \n       %case 'ar_hmm',  bnet.ar_hmm = args{i+1};  % should check topology\n       case 'names',  bnet.names = assocarray(args{i+1}, num2cell(1:n)); \n       otherwise,  \n\terror(['invalid argument name ' args{i}]);       \n      end\n    end\n  end\nend\n\n\nbnet.observed = sort(bnet.observed); % for comparing sets\nns = node_sizes;\nbnet.node_sizes_slice = ns(:)';\nbnet.node_sizes = [ns(:) ns(:)];\n\ncnodes = mysetdiff(1:n, dnodes);\nbnet.dnodes_slice = dnodes;\nbnet.cnodes_slice = cnodes;\nbnet.dnodes = [dnodes dnodes+n];\nbnet.cnodes = [cnodes cnodes+n];\n\nbnet.equiv_class = [bnet.eclass1(:) bnet.eclass2(:)];\nbnet.CPD = cell(1,max(bnet.equiv_class(:)));\neclass = bnet.equiv_class(:);\nE = max(eclass);\nbnet.rep_of_eclass = zeros(1,E);\nfor e=1:E\n  mems = find(eclass==e);\n  bnet.rep_of_eclass(e) = mems(1);\nend\n\nss = n;\nonodes = bnet.observed;\nhnodes = mysetdiff(1:ss, onodes);\nbnet.hidden_bitv = zeros(1,2*ss);\nbnet.hidden_bitv(hnodes) = 1;\nbnet.hidden_bitv(hnodes+ss) = 1;\n\nbnet.parents = cell(1, 2*ss);\nfor i=1:ss\n  bnet.parents{i} = parents(bnet.dag, i);\n  bnet.parents{i+ss} = parents(bnet.dag, i+ss);\nend\n\nbnet.auto_regressive = zeros(1,ss);\n% ar(i)=1 means (observed) node i depends on i in the  previous slice\nfor o=bnet.observed(:)'\n  if any(bnet.parents{o+ss} <= ss)\n    bnet.auto_regressive(o) = 1;\n  end\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/general/mk_dbn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "% EASY3\t  Read RINEX navigation file, version 3.03, and reformat\n%             into a Matlab Eph matrix. Open a RINEX observation file,\n%             version 3.03, analyse the header and identify observation\n%             types. The call fgetl finds the information for the epoch time.\n%             Next we read observations line  by line. Finally recpo_ls\n%             estimates the  (stand alone) receiver position.\n\n% Kai Borre 31-10-2001\n% Copyright (c) by Kai Borre\n% $Revision: 1.0 $  $Date: 2001/10/31  $\n% Total revision 2.0, February 13, 2016\n\n% RINEX version 3.03\n\n\n% Read RINEX ephemerides file and convert to internal Matlab format\nrinexe('log_24h.15n','eph.dat');\n% rinexe('D:\\Work\\Laboratory\\Trana\\rec\\r302_long\\Bas_log_2016_05_07_12.00.00.16N','eph.dat');\nEph = get_eph('eph.dat');\n\n% Open the observation file\nofile2 = 'log_r.15o'; % log_24h.15o\n% ofile2 = 'D:\\Work\\Laboratory\\Trana\\rec\\r302_long\\Bas_log_2016_05_07_12.00.00.16o';\nfid2 = fopen(ofile2,'rt');\n\n% The selection of observation type is set\nss = 'C1W'%;\nlinjer = 0;\n\nwhile 1\t\t\t   % Gobbling the header\n    linjer = linjer +1;\n    line = fgetl(fid2);\n    answer = strfind(line,'END OF HEADER');\n    if  ~isempty(answer), break; end;\n    if (line == -1), eof = 1; break; end;\n    answer = strfind(line,'ANT # / TYPE');\n    if ~isempty(answer)\n        delta = textscan(fid2,'%6.4f','Delimiter','\\n');\n        delt = delta{1};\n        delx = delt(1,1);\n        dely = delt(2,1);\n        delz = delt(3,1);\n    end\n    \n    answer = strfind(line,'SYS / # / OBS TYPES');\n    if ~isempty(answer)\n        tline1 = strsplit(line);\n        line = fgetl(fid2);\n        tline2 = strsplit(line);\n        tt = horzcat(tline1,tline2);\n        i = strcmp(tt,ss); % if tt equals ss, i =1, else 0\n        ii = find(i == 1) ;\n        ii = ii-2;\n        if ii > 15,  ii = ii-7; end;\n        % the cell array of strings tline1 originally contains two strings\n        % which describe the system and number of observation types.\n        % Both tline1 and tline2 terminates with six additional strings.\n        % An extra string appears at  the start of tline2; it originates\n        % from concatenation of  the two lines. The indexing does not\n        % change, even if you empty the cells. They remain empty\n        % cells and keep a place\n        obs_col = ii%;\n    end;\n    answer = strfind(line,'INTERVAL');\n    if ~isempty(answer)\n        interval = strtok(line);\n        int = str2double(interval);\n    end;\nend % end reading header\n\n% the string arrays for the tline1 and tline2 contain an integer after the\n% carrier phase observation. We account for this by the following\n% correctional table\nif         strcmp(ss(2:3), '1C'), obs_col = obs_col +1;\nelseif   strcmp(ss(2:3), '1W'), obs_col = obs_col+2;\nelseif  strcmp(ss(2:3), '2X'), obs_col = obs_col +3;\nelse    strcmp(ss(2:3), '2W'), obs_col = obs_col +4;\nend\n\nPos = [];\nepoch = 0;\ndt = [];\nTline = [];\n\nwhile ~feof(fid2)\n    epoch = epoch +1;\n    %time = 0;\n    sats = [];\n    sats0 = [];\n    \n    % We read the first line in every  epoch and get sow and\n    % number of SVs.\n    [time,post] = textscan(fid2,'%s %d8','Delimiter','\\n');\n    tid = time{1}{1};\n    year = str2double(tid(3:6));\n    month = str2double(tid(8:9));\n    day = str2double(tid(11:12));\n    hour = str2double(tid(14:15));\n    minute = str2double(tid(17:18));\n    second = str2double(tid(20:29));\n    static = str2double(tid(31:32));\n    NoSvs = str2double(tid(34:36));\n    dte  = str2double(tid(38:56));\n    dt = [dt dte];\n    h = hour+minute/60+second/3600;\n    jd = julday(year, month, day, h);\n    [~, sec_of_week] = gps_time(jd);\n    time = sec_of_week; % sow\n    \n    Obs = zeros(NoSvs,length(obs_col));\n    for i = 1:NoSvs\n        obs = textscan(fid2,'%s %d8','Delimiter','\\n');\n        obsy = obs{1}{1};\n        obs = strsplit(obsy);\n        sat = obs{1};\n        sats(i,:) = str2double(sat(2:3));\n        Obs(i,1) = str2double(obs(obs_col));\n    end\n    \n    % Next we test if all observed sats have an ephemeris.\n    % sats contains the SVs as read in the observation lines.\n    % The intersect command delivers Sats in sorted order!\n    % Therefore we must be careful in the follwing manipulations\n    Sats = intersect(sats,Eph(1,:));\n    \n    %The command ismember does not change the sequence of entries in sats\n    lia = ismember(sats,Sats);\n    % A 0 (zero) in lia indicates that a SV has been deleted. We delete the\n    % corresponding row in the observations\n    sats(lia==0) = [];\n    Obs(lia==0) = [];\n    % All book-keeping has prepared the data so that we can nake the call\n    % for a  final position computation\n    pos = recpo_ls(Obs,sats,time,Eph);\n    Pos = [Pos pos];\nend % while\nfclose(fid2);\n\nme = mean(Pos,2);\nfprintf('\\n\\nMean Position as Computed From %d Epochs:', epoch)\nfprintf('\\n\\nX: %12.3f  Y: %12.3f  Z: %12.3f\\n\\n', me(1,1), me(2,1), me(3,1))\n\nfigure(1);\nplot(1:epoch,(Pos(1,:)-Pos(1,1)*ones(1,epoch))','-',...\n    1:epoch,(Pos(2,:)-Pos(2,1)*ones(1,epoch))','-.',...\n    1:epoch,(Pos(3,:)-Pos(3,1)*ones(1,epoch))','--','linewidth',.25)\ntitle('Positions over time','fontsize',16)\nlegend('X','Y','Z')\nxlabel('Epochs [1 s interval]','fontsize',16)\nylabel('Changes in {\\itX}, {\\itY}, {\\itZ} since the first epoch [m]','fontsize',16)\nset(gca,'fontsize',16)\nlegend\nprint -dpdf easy31\n\nfigure(2);\nplot(1:epoch,dt*10^6')\nylabel('Receiver clock off-set in {\\mu}s','fontsize',16),\nxlabel('Epochs [1 s interval]','fontsize',16)\nprint -dpdf  easy32\n\n% transformation from (X, Y, Z) to geographical coordinates\n[phi, lambda, h] = cart2geo(me(1,1), me(2,1), me(3,1), 5)\n%%%%%%%%%%%%%%%%%%%%% end easy3.m %%%%%%%%%%%%%%%\n\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/easy3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186161955178428}}
{"text": "% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix\nfunction make(opt)\nfprintf('=> Building liblinear.\\n');\nif nargin < 1\n    try\n        % This part is for OCTAVE\n        if(exist('OCTAVE_VERSION', 'builtin'))\n            % Use -std=c++11 for newer versions of Octave\n            if ispc\n                setenv('CFLAGS','-std=gnu99 -O3')\n                setenv('CC','gcc')\n            else\n                setenv('CFLAGS','-O3 -fstack-protector-strong -Wformat -Werror=format-security')\n            end\n            %mex libsvmread.c\n            %mex libsvmwrite.c\n            mex -I.. -O3 svmtrain.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n            mex -I.. -O3 svmpredict.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n            delete *.o\n            % This part is for MATLAB\n            % Add -largeArrayDims on 64-bit machines of MATLAB\n        else\n            if ispc\n                %mex COMPFLAGS=\"\\$COMPFLAGS -std=c99 -O3\" -largeArrayDims libsvmread.c\n                %mex COMPFLAGS=\"\\$COMPFLAGS -std=c99 -O3\" -largeArrayDims libsvmwrite.c\n                mex COMPFLAGS=\"\\$COMPFLAGS -O3\" -I.. -largeArrayDims svmtrain.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n                mex COMPFLAGS=\"\\$COMPFLAGS -O3\" -I.. -largeArrayDims svmpredict.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n            else\n                %mex CFLAGS=\"\\$CFLAGS -std=c99\" -largeArrayDims libsvmread.c\n                %mex CFLAGS=\"\\$CFLAGS -std=c99\" -largeArrayDims libsvmwrite.c\n                mex CFLAGS=\"\\$CFLAGS\" -I.. -largeArrayDims svmtrain.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n                mex CFLAGS=\"\\$CFLAGS\" -I.. -largeArrayDims svmpredict.cpp linear_model_matlab.cpp ../linear.cpp ../tron.cpp ../blas/daxpy.c ../blas/ddot.c ../blas/dnrm2.c ../blas/dscal.c\n            end\n        end\n    catch err\n        fprintf('Error: %s failed (line %d)\\n', err.stack(1).file, err.stack(1).line);\n        disp(err.message);\n        fprintf('=> Please check README for detailed instructions.\\n');\n    end\nelseif nargin == 1\n    switch lower(opt)\n        case 'clean'\n            delete *.o\n        case 'cleanall'\n            delete *.o\n            delete *.mexa64\n        otherwise\n            error('make option \"%s\" not recognized', opt)\n    end\nend\n", "meta": {"author": "ayrna", "repo": "orca", "sha": "eaa629e687d04d73628782e16e92d330acb43faf", "save_path": "github-repos/MATLAB/ayrna-orca", "path": "github-repos/MATLAB/ayrna-orca/orca-eaa629e687d04d73628782e16e92d330acb43faf/src/Algorithms/liblinear-2.20/matlab/make.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24181873129329282}}
{"text": "% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).\n% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)\n% Copyright: ETH Zurich, 2014\n% Author: Romano Cicchetti\n\n% Returns a threshold that defines whether\n% the specified appliance is in state 'on' or 'off'\nfunction [threshold] = getThresholdDiffOnOff(applianceID) \n    \nthreshold_vector = [\n        15;  % fridge\n        15;  % freezer\n        500; % microwave\n        500; % dishwasher\n        15;  % entertainment\n        500; % kettle\n        500; % stove\n        15;  % coffee machine\n        500; % washing machine\n        300; % dryer\n        15;  % lamp\n        15;  % PC\n        15;  % laptop\n        15;  % TV\n        15;  % Stereo\n        5;   % Tablet\n        5;   % Router\n        5;   % Illuminated fountain\n    ]; % stereo\n\n     threshold = threshold_vector(applianceID,1);\nend\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/config/getThresholdDiffOnOff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24179552457053302}}
{"text": "function [uOutput] = import_harvard(nFunction, sFilename)\n% [uOutput] = harvardcmt_imp(nFunction, sFilename);\n% ----------------------------------------------------------\n% Imports Harvard CMT data of a selfmade ASCII-file.\n% Use 'getharvardcatalog' in the importfilters/harvard directory.\n% See import_harvard_doc.html for more information.\n%\n% D. Schorlemmer; schorlemmer@sed.ethz.ch\n%\n% 17.05.2005\n\n% Filter function switchyard\nif nFunction == FilterOp.getDescription\n  uOutput = 'Harvard CMT catalog';\nelseif nFunction == FilterOp.getWebpage\n  uOutput = 'import_harvard_doc.html';\nelseif nFunction == FilterOp.importCatalog\n  % Read formated data\n  mData = textread(sFilename, '%s', 'delimiter', '\\n', 'whitespace', '');\n  % Create empty catalog\n  uOutput = zeros(length(mData), 10);\n  % Loop thru all lines of catalog and convert them\n  for i = 1:length(mData)\n    if rem(i,100) == 0 ; disp([ num2str(i) ' of ' num2str(length(mData)) ' events processed']); end\n    try\n      uOutput(i,1) = str2num(mData{i}(28:34));      % Longitude (PDE)\n      uOutput(i,2) = str2num(mData{i}(21:25));      % Latitude  (PDE)\n      uOutput(i,3) = str2num(mData{i}(1:2));        % Year\n      if uOutput(i,3) < 76\n        uOutput(i,3) = uOutput(i,3)+2000;\n      else\n        uOutput(i,3) = uOutput(i,3)+1900;\n      end\n      uOutput(i,4) = str2num(mData{i}(4:5));        % Month\n      uOutput(i,5) = str2num(mData{i}(7:8));        % Day\n      uOutput(i,6) = str2num(mData{i}(82:85));      % Magnitude Mw\n      uOutput(i,7) = str2num(mData{i}(36:40));      % Depth (PDE)\n      uOutput(i,8) = str2num(mData{i}(10:11));      % Hour\n      uOutput(i,9) = str2num(mData{i}(13:14));      % Minute\n      uOutput(i,10) = str2num(mData{i}(16:19));     % Second\n      uOutput(i,11) = nan;                          % Reserved for cross-section values\n\n      uOutput(i,12) = str2num(mData{i}(87:89));     % Strike (Plane 1)\n      uOutput(i,13) = uOutput(i,12) + 90;           % Dip direction (Plane 1)\n      uOutput(i,13) = mod(uOutput(i,13) + 360, 360);\n      uOutput(i,14) = str2num(mData{i}(91:92));     % Dip (Plane 1)\n      uOutput(i,15) = str2num(mData{i}(94:97));     % Rake (Plane 1)\n\n      uOutput(i,16) = str2num(mData{i}(99:101));    % Strike (Plane 2)\n      uOutput(i,17) = uOutput(i,16) + 90;           % Dip direction (Plane 2)\n      uOutput(i,17) = mod(uOutput(i,17) + 360, 360);\n      uOutput(i,18) = str2num(mData{i}(103:104));   % Dip (Plane 2)\n      uOutput(i,19) = str2num(mData{i}(106:109));   % Rake (Plane 2)\n\n      uOutput(i,20) = str2num(mData{i}(42:44));     % Magnitude mb\n      uOutput(i,21) = str2num(mData{i}(46:48));     % Magnitude Ms\n      uOutput(i,22) = str2num(mData{i}(50:55));     % Latitude (HAV)\n      uOutput(i,23) = str2num(mData{i}(57:63));     % Longitude (HAV)\n      uOutput(i,24) = str2num(mData{i}(65:69));     % Depth (HAV)\n      uOutput(i,25) = str2num(mData{i}(72:75));     % Cen_time\n      uOutput(i,26) = str2num(mData{i}(77:80));     % Half Duration\n      % Create decimal year\n      uOutput(i,3) = decyear([uOutput(i,3) uOutput(i,4) uOutput(i,5) uOutput(i,8) uOutput(i,9) uOutput(i,16)]);\n    catch\n      msg.dbfprintf('Import: Problem in line %d of %s. Line ignored.\\n',i, sFilename);\n    end\n  end\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/importfilters/import_harvard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.241795524570533}}
{"text": "%==========================================================================\n% This is the testing code of a special case of SRMD (scale factor = 1) for real image <denoising & deblurring>.\n% There are two models, \"SRMDx1_gray.mat\" for grayscale image, \"SRMDx1_color.mat\"\n% for color image. The models can do:\n%   1. Deblurring. (The kernel is assumed to be Gaussian-like!!! For other kernels, you should re-train the model!)\n%      there are two types of kernels,\n%      including isotropic Gaussian (width range: [0.1, 3]),\n%      anisotropic Gaussian ([0.5, 8]).\n%   2. Denoising. the noise level range is [0, 75].\n%      For denoising only, set \"kerneltype = 1; kernelwidth = 0.1.\" (i.e., delta kernel)\n%\n%==========================================================================\n% The basic idea of SRMD is to learn a CNN to infer the MAP of general SISR (with special case of sf=1), i.e.,\n% solve x^ = arg min_x 1/(2 sigma^2) ||kx - y||^2 + lamda \\Phi(x)\n% via x^ = CNN(y,k,sigma;\\Theta) or x^ = CNN(y,kernel,noiselevel;\\Theta).\n%\n% There involves two important factors, i.e., blur kernel (k; kernel) and noise\n% level (sigma; nlevel).\n%\n% For more information, please refer to the following paper.\n%    @article{zhang2017learningsrmd,\n%    title={Learning a Single Convolutional Super-Resolution Network for Multiple Degradations},\n%    author={Kai, Zhang and Wangmeng, Zuo and Lei, Zhang},\n%    year={2017},\n%    }\n%\n% If you have any question, please feel free to contact with <Kai Zhang (cskaizhang@gmail.com)>.\n%\n% This code is for research purpose only.\n%\n% by Kai Zhang (Nov, 2017)\n%==========================================================================\n\n% clear; clc;\nformat compact;\n\naddpath('utilities');\nimageSets    = {'hanzi','starsL','Audrey_Hepburn','flowersL','frog','Nami','Set5','Set14'}; % testing dataset\n\n%%======= ======= ======= degradation parameter settings ======= ======= =======\n% For real image 'starsL', some examples of degradation setting are given as follows.\n% sf = 1; nlevel = 20; kerneltype = 1; kernelwidth =   0.1;  % denoising\n\n% For real image 'Audrey_Hepburn', some examples of degradation setting are given as follows.\n% sf = 1; nlevel = 10; kerneltype = 1; kernelwidth =   0.1;  % denoising\n\n% For real image 'flowersL', some examples of degradation setting are given as follows.\n% sf = 1; nlevel = 65; kerneltype = 1; kernelwidth =   0.1;  % denoising\n\n% For real image 'frog', some examples of degradation setting are given as follows.\n% sf = 1; nlevel = 15; kerneltype = 1; kernelwidth =   0.1;  % denoising\n\n% For real image 'Nami', some examples of degradation setting are given as follows.\n% sf = 1; nlevel = 10; kerneltype = 1; kernelwidth =   1;   % denoising and deblurring\n\n%%=======  ======= ======= ======= ======= ======= ======= ======= ======= =======\n\n\n%% select testing dataset, use GPU or not, ...\nsetTest      = imageSets([5]); %\nshowResult   = 1; % 1; show results; 2; save restored images\npauseTime    = 1;\nuseGPU       = 1; % 1 or 0, true or false\nmethod       = 'SRMD';\nfolderTest   = 'testsets';\nfolderResult = 'results';\nif ~exist(folderResult,'file')\n    mkdir(folderResult);\nend\n\n%% scale factor (it is fixed to 1)\n\nsf          = 1; %{1}\n\n%% load model with scale factor sf\nfolderModel = 'models';\nload(fullfile(folderModel,['SRMDx',int2str(sf),'_color.mat']));\n%net.layers = net.layers(1:end-1);\nnet = vl_simplenn_tidy(net);\nif useGPU\n    net = vl_simplenn_move(net, 'gpu') ;\nend\n\n%% degradation parameter (noise level and kernel) setting\n%############################# noise level ################################\n% noise level, from a range of [0, 75]\n\nnlevel     = 15;  % [0, 75]\n\nkerneltype = 1;  % {1, 2}\n\n%############################### kernel ###################################\n% there are tree types of kernels, including isotropic Gaussian,\n% anisotropic Gaussian, and estimated kernel k_b for isotropic Gaussian k_d\n% under direct downsampler (x2 and x3 only).\n\nif kerneltype == 1\n    % type 1, isotropic Gaussian---although it is a special case of anisotropic Gaussian.\n    kernelwidth = 0.1; % from a range of [0.1, 3]. set kernelwidth from (0.001, 0.2) to generate delta kernel (no blur)\n    kernel = fspecial('gaussian',15, kernelwidth); % Note: the kernel size is fixed to 15X15.\n    tag    = ['_',method,'_x',num2str(sf),'_itrG_',int2str(kernelwidth*10),'_nlevel_',int2str(nlevel)];\n    \nelseif kerneltype == 2\n    % type 2, anisotropic Gaussian\n    nk     = randi(size(net.meta.AtrpGaussianKernel,4)); % randomly select one\n    kernel = net.meta.AtrpGaussianKernel(:,:,:,nk);\n    tag    = ['_',method,'_x',num2str(sf),'_atrG_',int2str(nk),'_nlevel_',int2str(nlevel)];\n    \nend\n\n\n%##########################################################################\n\nsurf(kernel) % show kernel\nview(45,55);\ntitle('Assumed kernel');\nxlim([1 15]);\nylim([1 15]);\npause(2)\nclose;\n\n%% for degradation maps\nglobal degpar;\ndegpar = single([net.meta.P*kernel(:); nlevel(:)/255]);\n\n\nfor n_set = 1 : numel(setTest)\n    \n    %% search images\n    setTestCur = cell2mat(setTest(n_set));\n    disp('--------------------------------------------');\n    disp(['    ----',setTestCur,'-----Super-Resolution-----']);\n    disp('--------------------------------------------');\n    folderTestCur = fullfile(folderTest,setTestCur);\n    ext                 =  {'*.jpg','*.png','*.bmp'};\n    filepaths           =  [];\n    for i = 1 : length(ext)\n        filepaths = cat(1,filepaths,dir(fullfile(folderTestCur, ext{i})));\n    end\n    \n    %% prepare results\n    folderResultCur = fullfile(folderResult, [setTestCur,tag]);\n    if ~exist(folderResultCur,'file')\n        mkdir(folderResultCur);\n    end\n    \n    %% perform denoising or/and deblurring (only support Gaussian-like kernel)\n    for i = 1 : length(filepaths)\n        \n        label  = imread(fullfile(folderTestCur,filepaths(i).name));\n        %label  = modcrop(label, 2);\n        [h,w,C]   = size(label);\n        if C == 1\n            label = cat(3,label,label,label);\n        end\n        \n        input = label;\n        [~,imageName,ext] = fileparts(filepaths(i).name);\n        \n        input = im_pad(input);\n        %tic\n        if useGPU\n            input = gpuArray(im2single(input));\n        end\n        res = vl_srmd(net, input,[],[],'conserveMemory',true,'mode','test','cudnn',true);\n        %res = vl_srmd_concise(net, input); % a concise version of \"vl_srmd\".\n        %res = vl_srmd_matlab(net, input); % When use this, you should also set \"useGPU = 0;\" and comment \"net = vl_simplenn_tidy(net);\"\n        \n        output = im2uint8(gather(res(end).x));\n        \n        output = im_crop(output,h,w);\n        input  = im_crop(input,h,w);\n        %toc;\n        %         a = 0.1;%0.15-nlevel/700;\n        %         output2 = (1-a)*output + a*label; % add noise and structure back to make the output more visually plausible. or GAN?\n        disp([setTestCur,'    ',int2str(i),'    ',filepaths(i).name]);\n        \n        if showResult\n            imshow(cat(2,label,output));\n            drawnow;\n            title(['Denoising and Gaussian deblurring   ',filepaths(i).name],'FontSize',12)\n            pause(pauseTime)\n            imwrite(output,fullfile(folderResultCur,[imageName,'_x',int2str(sf),'.png']));% save results\n            \n        end\n        \n    end\n    \nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "cszn", "repo": "SRMD", "sha": "c83995140baecd43f9f426710bf6330b3678746f", "save_path": "github-repos/MATLAB/cszn-SRMD", "path": "github-repos/MATLAB/cszn-SRMD/SRMD-c83995140baecd43f9f426710bf6330b3678746f/Demo_real_application_denoising_and_deblurring_color.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24179552457053297}}
{"text": "% STD_CENTROID - compute cluster centroid in EEGLAB dataset STUDY.\n%                  Compute and store the centroid(s) (i.e., mean(s)) \n%                  for some combination of six measures on specified\n%                  clusters in a STUDY. Possible measures include: scalp\n%                  maps, ERPs, spectra, ERSPs, ITCs, dipole_locations\n% Usage:    \n%        >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG, ...\n%                                              clusters, measure1, measure2, ...);\n%\n% Inputs:\n%   STUDY        - STUDY set \n%   ALLEEG       - ALLEEG dataset vector (else an EEG dataset) containing the STUDY\n%                  datasets, typically created using LOAD_ALLEEG.\n%   clusters     - [vector] of cluster indices. Computes measure means for the \n%                  specified clusters. {deffault|[]: compute means for all \n%                  STUDY clusters} \n%   measure(s)   - ['erp'|'spec'|'scalp'|'dipole'|'itc'|'ersp'].   \n%                  The measures(s) for which to calculate the cluster centroid(s):\n%                     'erp'    ->  mean ERP of each cluster.\n%                     'dipole' ->  mean dipole of each cluster.\n%                     'spec'   ->  mean spectrum of each cluster (baseline removed).\n%                     'scalp'  ->  mean topoplot scalp map of each cluster.\n%                     'ersp'   ->  mean ERSP of each cluster. \n%                     'itc'    ->  mean ITC of each cluster. \n%                  If [], re-compute the centroid for whichever centroids \n%                  have previously been computed.\n% Outputs:\n%   STUDY        - input STUDY structure with computed centroids added. \n%                  If the requested centroids already exist, overwrites them. \n%   centroid     - cell array of centroid structures, each cell corrasponding \n%                  to a different cluster requested in 'clusters' (above).\n%                  fields of 'centroid' may include centroid.erp, centroid.dipole,\n%                  etc. (as above). The structure is similar as the output\n%                  of the STD_READDATA function (with some fields\n%                  about the cluster name and index missing).\n% Examples:\n%\n%   >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,[], 'scalp'); \n%   % For each of the clusters in STUDY, compute a mean scalp map.\n%   % The centroids are saved in the STUDY structure as entries in array\n%   % STUDY.cluster(k).centroid.scalp. The centroids are also returned in \n%   % a cell array the size of the clusters (i.e., in: centroid(k).scalp).\n%\n%   >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,5,'spec','scalp'); \n%   % Same as above, but now compute only two centroids for Cluster 5. \n%   % The returned 'centroid' has two fields: centroid.scalp and centroid.spec\n%\n% Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, Feb 03, 2005\n\n% Copyright (C) Hilit Serby, SCCN, INC, UCSD, Feb 03, 2005, hilit@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% Coding notes: Useful information on functions and global variables used.\n\nfunction [STUDY, centroid] = std_centroid(STUDY,ALLEEG, clsind, varargin);\n\n if nargin < 3\n     help std_centroid;\n     return\n end\n \n if isempty(clsind)\n     for k = 2: length(STUDY.cluster) %don't include the ParentCluster\n         if ~strncmpi('Notclust',STUDY.cluster(k).name,8) \n             % don't include 'Notclust' clusters\n             clsind = [clsind k];\n         end\n     end\n end\n %default values\nerpC =0;\nspecC =0 ;\nscalpC = 0;\ndipoleC = 0;\nitcC = 0;\nerspC = 0;\n \ncommands = {};\nif isempty(varargin)\n    if isfield(STUDY.cluster(clsind(1)).centroid,'scalp')\n        commands{end+1} = 'scalp';\n    end\n    if isfield(STUDY.cluster(clsind(1)).centroid,'spec')\n        commands{end+1} = 'spec';\n    end\n    if isfield(STUDY.cluster(clsind(1)).centroid,'erp')\n        commands{end+1} = 'erp';\n    end\n    if isfield(STUDY.cluster(clsind(1)).centroid,'ersp')\n        commands{end+1} = 'ersp';\n    end\n    if isfield(STUDY.cluster(clsind(1)).centroid,'itc')\n        commands{end+1} = 'itc';\n    end\n    if isfield(STUDY.cluster(clsind(1)).centroid,'dipole')\n        commands{end+1} = 'dipole';\n    end\nelse\n    commands = varargin;\nend\n\nNcond = length(STUDY.condition);\nif Ncond == 0\n    Ncond = 1;\nend \ncentroid = cell(length(clsind),1);\nfprintf('Computing ');\nfor k = 1:length(clsind)\n    for l = 1:Ncond \n        for ind = 1:length(commands)\n            ctr = commands{ind};\n            switch ctr\n                case 'scalp'\n                    centroid{k}.scalp = 0; \n                    scalpC = 1;\n                    if (l ==1) && (k ==1)\n                        fprintf('scalp ');\n                    end\n                case 'erp'\n                    centroid{k}.erp{l} = 0; \n                    erpC = 1;\n                    if (l ==1) && (k ==1)\n                        fprintf('erp ');\n                    end\n                case 'spec'\n                    centroid{k}.spec{l} = 0; \n                    specC = 1;\n                    if (l ==1) && (k ==1)\n                        fprintf('spectrum ');\n                    end\n                case 'ersp'\n                    centroid{k}.ersp{l} = 0; \n                    centroid{k}.ersp_limits{l} = 0;\n                    erspC =1;\n                    if (l ==1) && (k ==1)\n                        fprintf('ersp ');\n                    end\n                case 'itc'\n                    centroid{k}.itc{l} = 0; \n                    centroid{k}.itc_limits{l} = 0;\n                    itcC = 1;\n                    if (l ==1) && (k ==1)\n                        fprintf('itc ');\n                    end                    \n                case 'dipole'\n                    dipoleC =1;\n                    if (l ==1) && (k ==1)\n                        fprintf('dipole ');\n                    end\n            end\n        end\n    end\nend   \nfprintf('centroid (only done once)\\n');\nif itcC || erspC || specC || erpC || scalpC\n    for clust = 1:length(clsind) %go over all requested clusters\n        for cond = 1:Ncond %compute for all conditions\n            for k = 1:length(STUDY.cluster(clsind(clust)).comps) % go through all components\n                comp  = STUDY.cluster(clsind(clust)).comps(k);\n                abset = STUDY.cluster(clsind(clust)).sets(cond,k);\n                if scalpC && cond == 1  %scalp centroid, does not depend on condition \n                    grid = std_readtopo(ALLEEG, abset, comp);\n                    if isempty(grid)\n                        return;\n                    end\n                    centroid{clust}.scalp = centroid{clust}.scalp + grid;\n                end\n                if erpC %erp centroid\n                    [erp, t] = std_readerp(ALLEEG, abset, comp, STUDY.preclust.erpclusttimes);\n                    fprintf('.');\n                    if isempty(erp)\n                        return;\n                    end\n                    if (cond==1) && (k==1)\n                        all_erp = zeros(length(erp),length(STUDY.cluster(clsind(clust)).comps));\n                    end\n                    all_erp(:,k) = erp';\n                    if k == length(STUDY.cluster(clsind(clust)).comps)\n                        [all_erp pol] = std_comppol(all_erp);\n                        centroid{clust}.erp{cond} = mean(all_erp,2);\n                        centroid{clust}.erp_times = t;\n                    end\n                end\n                if specC %spec centroid\n                    [spec, f] = std_readspec(ALLEEG, abset, comp, STUDY.preclust.specclustfreqs);\n                    fprintf('.');\n                    if isempty(spec)\n                        return;\n                    end\n                    centroid{clust}.spec{cond} = centroid{clust}.spec{cond} + spec;\n                    centroid{clust}.spec_freqs = f;\n                end\n                if erspC %ersp centroid\n                    fprintf('.');\n                    if cond == 1\n                        tmpabset = STUDY.cluster(clsind(clust)).sets(:,k);\n                        [ersp, logfreqs, timevals] = std_readersp(ALLEEG, tmpabset, comp, STUDY.preclust.erspclusttimes, ...\n                                                                STUDY.preclust.erspclustfreqs );\n                        if isempty(ersp)\n                            return;\n                        end\n                        for m = 1:Ncond\n                            centroid{clust}.ersp{m} = centroid{clust}.ersp{m} + ersp(:,:,m);\n                            centroid{clust}.ersp_limits{m} = max(floor(max(max(abs(ersp(:,:,m))))), centroid{clust}.ersp_limits{m});\n                        end\n                        centroid{clust}.ersp_freqs  = logfreqs;\n                        centroid{clust}.ersp_times = timevals;\n                    end\n                end\n                if itcC %itc centroid\n                    fprintf('.');\n                    [itc, logfreqs, timevals] = std_readitc(ALLEEG, abset, comp, STUDY.preclust.erspclusttimes, ...\n                                                                STUDY.preclust.erspclustfreqs );\n                    if isempty(itc)\n                        return;\n                    end\n                    centroid{clust}.itc{cond} = centroid{clust}.itc{cond} + itc;\n                    centroid{clust}.itc_limits{cond} = max(floor(max(max(abs(itc)))), centroid{clust}.itc_limits{cond}); %ersp image limits \n                    centroid{clust}.itc_freqs  = logfreqs;\n                    centroid{clust}.itc_times = timevals;\n                end\n            end\n        end\n        if ~scalpC\n            fprintf('\\n');\n        end\n\tend\nend\n\nif dipoleC %dipole centroid\n    for clust = 1:length(clsind)\n        max_r = 0;\n        len = length(STUDY.cluster(clsind(clust)).comps);\n        tmppos = 0;\n        tmpmom = 0;\n        tmprv = 0;\n        ndip = 0;\n        for k = 1:len \n            fprintf('.');\n            comp  = STUDY.cluster(clsind(clust)).comps(k);\n            abset = STUDY.cluster(clsind(clust)).sets(1,k);\n            if ~isfield(ALLEEG(abset), 'dipfit')\n               warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole');\n               return;\n            end\n            if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz)\n                ndip = ndip +1;\n                tmppos = tmppos + ALLEEG(abset).dipfit.model(comp).posxyz;\n                tmpmom = tmpmom + ALLEEG(abset).dipfit.model(comp).momxyz;\n                tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv;\n                if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n                   if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n                       load('-mat', ALLEEG(abset).dipfit.hdmfile);\n                       max_r = max(max_r, max(vol.r));\n                   else % old version of dipfit\n                       max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));\n                   end\n               end\n            end\n        end\n        centroid{clust}.dipole.posxyz =  tmppos/ndip;\n        centroid{clust}.dipole.momxyz =  tmpmom/ndip;\n        centroid{clust}.dipole.rv =  tmprv/ndip;\n        if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') && (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit\n            centroid{clust}.dipole.maxr = max_r;\n        end\n        STUDY.cluster(clsind(clust)).centroid.dipole = centroid{clust}.dipole;\n   end\nend\n\n%update STUDY\nfor clust =  1:length(clsind) %go over all requested clusters\n    for cond  = 1:Ncond\n        ncomp = length(STUDY.cluster(clsind(clust)).comps);\n        if scalpC && cond == 1%scalp centroid\n            centroid{clust}.scalp  = centroid{clust}.scalp/ncomp;\n            STUDY.cluster(clsind(clust)).centroid.scalp = centroid{clust}.scalp ;\n        end\n        if erpC\n            STUDY.cluster(clsind(clust)).centroid.erp{cond} = centroid{clust}.erp{cond};\n\t\t    STUDY.cluster(clsind(clust)).centroid.erp_times = centroid{clust}.erp_times;\n        end\n\t\tif specC\n            centroid{clust}.spec{cond} = centroid{clust}.spec{cond}/ncomp;\n            STUDY.cluster(clsind(clust)).centroid.spec{cond} = centroid{clust}.spec{cond};\n\t\t    STUDY.cluster(clsind(clust)).centroid.spec_freqs = centroid{clust}.spec_freqs;\n        end\n        if erspC %ersp centroid\n            centroid{clust}.ersp{cond} = centroid{clust}.ersp{cond}/ncomp;\n            STUDY.cluster(clsind(clust)).centroid.ersp{cond} = centroid{clust}.ersp{cond};\n            STUDY.cluster(clsind(clust)).centroid.ersp_limits{cond} = floor(0.75*centroid{clust}.ersp_limits{cond}); \n            %[round(0.9*min(cell2mat({centroid{clust}.ersp_limits{cond,:}})))  round(0.9*max(cell2mat({centroid{clust}.ersp_limits{cond,:}})))];\n            STUDY.cluster(clsind(clust)).centroid.ersp_freqs = centroid{clust}.ersp_freqs;\n            STUDY.cluster(clsind(clust)).centroid.ersp_times = centroid{clust}.ersp_times;\n        end\n        if itcC\n            centroid{clust}.itc{cond} = centroid{clust}.itc{cond}/ncomp;\n            STUDY.cluster(clsind(clust)).centroid.itc{cond} = centroid{clust}.itc{cond} ;\n            STUDY.cluster(clsind(clust)).centroid.itc_limits{cond} = floor(0.75*centroid{clust}.itc_limits{cond});%round(0.9*max(cell2mat({centroid{clust}.itc_limits{cond,:}})));\n            STUDY.cluster(clsind(clust)).centroid.itc_freqs = centroid{clust}.itc_freqs;\n            STUDY.cluster(clsind(clust)).centroid.itc_times = centroid{clust}.itc_times;\n        end\n        \n    end\nend\nfprintf('\\n');\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_centroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2417955184813386}}
{"text": "%%*************************************************************************\n%% sqlp: main solver \n%%\n%%*************************************************************************\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*************************************************************************\n\n  function [obj,X,y,Z,info,runhist] = sqlpmain(blk,At,C,b,par,parbarrier,X0,y0,Z0);\n\n   global spdensity smallblkdim  printlevel msg\n   global solve_ok  use_LU  exist_analytic_term numpertdiagschur  \n   global schurfun  schurfun_par \n%%\n   randstate = rand('state');  randnstate = randn('state');\n   rand('state',0);   randn('state',0);\n%%\n   vers          = par.vers;\n   predcorr      = par.predcorr;\n   gam           = par.gam; \n   expon         = par.expon;\n   gaptol        = par.gaptol;\n   inftol        = par.inftol;\n   steptol       = par.steptol;\n   maxit         = par.maxit;\n   printlevel    = par.printlevel;\n   stoplevel     = par.stoplevel;\n   scale_data    = par.scale_data;\n   spdensity     = par.spdensity;\n   rmdepconstr   = par.rmdepconstr;\n   smallblkdim   = par.smallblkdim;\n   schurfun      = par.schurfun;\n   schurfun_par  = par.schurfun_par;\n   ublksize      = par.ublksize; \n%%\n   tstart = clock; \n   X = X0; y = y0; Z = Z0; \n   for p = 1:size(blk,1)\n      if strcmp(blk{p,1},'u'); Z{p} = zeros(blk{p,2},1); end\n   end\n%%\n%%-----------------------------------------\n%% convert unrestricted blk to linear blk. \n%%-----------------------------------------\n%%\n   convertlen = 0; \n   [blk,At,C,X,Z,u2lblk,ublkidx] = sqlpu2lblk(blk,At,C,X,Z,par,convertlen);\n   for p = 1:size(blk,1) \n      pblk = blk(p,:); \n      if (u2lblk(p) == 1) \n         n = 2*blk{p,2}; \n         blk{p,1} = 'l';  blk{p,2} = n;\n         parbarrier{p} = zeros(1,n);\n         At{p} = [At{p}; -At{p}];  \n         tau = max(1,norm(C{p})); \n         C{p} = [C{p}; -C{p}]; \n         msg = 'convert ublk to lblk'; \n         if (printlevel); fprintf(' *** %s',msg); end\n         b2 = 1 + abs(b');  \n         normCtmp = 1+norm(C{p});\n         normAtmp = 1+sqrt(sum(At{p}.*At{p}));\n         if (n > 1000)\n            const = sqrt(n); \n         else\n\t    const = n; \n         end\n         if (par.startpoint == 1)\n            X{p} = const* max([1,b2./normAtmp]) *ones(n,1); \n            Z{p} = const* max([1,normAtmp/sqrt(n),normCtmp/sqrt(n)]) *ones(n,1);\n            X{p} = X{p}.*(1+1e-10*rand(n,1)); \n            Z{p} = Z{p}.*(1+1e-10*rand(n,1)); \n\t else\n            const = max(abs(X{p})) + 100; \n            X{p} = [X{p}+const; const*ones(n/2,1)]; \n            %%old: const = 100; Z{p} = [const*ones(n/2,1); const*ones(n/2,1)];\n            Z{p} = [abs(Z0{p}); abs(Z0{p})] + 1e-4; \n         end\n      end\n   end\n%%-----------------------------------------\n%% check whether {A1,...,Am} is \n%% linearly independent. \n%%-----------------------------------------\n%%\n   m0 = length(b); \n   [At,b,y,indeprows,par.depconstr,feasible,par.AAt] = ...\n    checkdepconstr(blk,At,b,y,rmdepconstr);\n   if (~feasible)\n      obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1); \n      runhist = [];      \n      msg = 'SQLP is not feasible'; \n      if (printlevel); fprintf('\\n %s \\n',msg); end\n      return;\n   end\n   par.normAAt = norm(par.AAt,'fro'); \n%%\n%%-----------------------------------------\n%% scale SQLP data. Note: must be done only \n%% after checkdepconstr\n%%-----------------------------------------\n%%\n   normA2 = 1+ops(At,'norm'); \n   normb2 = 1+norm(b); \n   normC2 = 1+ops(C,'norm'); \n   normX0 = 1+ops(X0,'norm'); \n   normZ0 = 1+ops(Z0,'norm'); \n   if (scale_data)\n      [At,C,b,normA,normC,normb,X,y,Z] = scaling(blk,At,C,b,X,y,Z);\n   else\n      normA = 1; normC = 1; normb = 1; \n   end \n%%\n%%-----------------------------------------\n%% find the combined list of non-zero \n%% elements of Aj, j = 1:k, for each k. \n%% IMPORTANT NOTE: Ak, C are permuted.\n%%-----------------------------------------\n%% \n   par.numcolAt = length(b); \n   [At,C,X,Z,par.permA,par.permZ] = sortA(blk,At,C,b,X,Z);\n   [par.isspA,par.nzlistA,par.nzlistAsum,par.isspAy,par.nzlistAy] = nzlist(blk,At,par);\n%%\n%%-----------------------------------------\n%% create an artifical non-negative block \n%% for a purely log-barrier problem\n%%-----------------------------------------\n%%\n   numblkold = size(blk,1);  \n   nn = 0; \n   for p = 1:size(blk,1);\n      pblk = blk(p,:);  \n      idx = find(parbarrier{p}==0); \n      if ~isempty(idx); \n         if strcmp(pblk{1},'l') \n            nn = nn + length(idx); \n         elseif strcmp(pblk{1},'s') | strcmp(pblk{1},'q')   \n            nn = nn + sum(pblk{2}(idx)); \n         end\n      end\n   end\n   if (nn==0)\n      analytic_prob = 1; \n      numblk = size(blk,1)+1; \n      blk{numblk,1} = 'l'; blk{numblk,2} = 1; \n      At{numblk,1} = sparse(1,length(b)); \n      C{numblk,1} = 1; \n      X{numblk,1} = 1e3; \n      Z{numblk,1} = 1e3;\n      parbarrier{numblk,1} = 0; \n      u2lblk(numblk,1) = 0;\n      nn = nn + 1; \n   else\n      analytic_prob = 0;       \n   end\n%%\n   exist_analytic_term = 0; \n   for p = 1:size(blk,1);\n      idx = find(parbarrier{p} > 0); \n      if ~isempty(idx); \n         exist_analytic_term = 1; \n      end\n   end\n%%-----------------------------------------\n%% initialization\n%%-----------------------------------------\n%%\n   EE = ops(blk,'identity');\n   normE2 = ops(EE,'norm'); Zpertold = 1; \n   for p = 1:size(blk,1) \n      normCC(p) = 1+ops(C(p),'norm');\n      normEE(p) = 1+ops(EE(p),'norm'); \n   end\n   [Xchol,indef(1)] = blkcholfun(blk,X); \n   [Zchol,indef(2)] = blkcholfun(blk,Z); \n   if any(indef)\n      msg = 'stop: X or Z not positive definite'; \n      if (printlevel); fprintf('\\n  %s\\n',msg); end\n      info.termcode = -3;\n      info.msg1 = msg;\n      obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1); \n      runhist = [];      \n      return;\n   end \n   AX = AXfun(blk,At,par.permA,X); \n   rp = b-AX;\n   ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n   ZpATynorm = ops(ZpATy,'norm');\n   Rd = ops(C,'-',ZpATy);\n   objadd0 = 0; \n   if (scale_data)\n      for p = 1:size(blk,1)\n         pblk = blk(p,:); \n         objadd0 = objadd0 + sum(parbarrier{p}.*pblk{2})*log(normA{p}); \n      end\n   end\n   objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0;\n   obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;      \n   gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd); \n   relgap = gap/(1+sum(abs(obj)));\n   prim_infeas = norm(rp)/normb2;\n   dual_infeas = ops(Rd,'norm')/normC2;\n   infeas = max(prim_infeas,dual_infeas); \n   if (scale_data)\n      infeas_org(1) = prim_infeas*normb;\n      infeas_org(2) = dual_infeas*normC;\n   else\n      infeas_org = [0,0]; \n   end\n   trXZ = blktrace(blk,X,Z,parbarrier); \n   if (nn > 0); mu  = trXZ/nn; else; mu = gap/ops(X,'getM'); end\n   normX = ops(X,'norm'); \n%%   \n   termcode = 0; restart = 0; \n   pstep = 1; dstep = 1; pred_convg_rate = 1; corr_convg_rate = 1;\n   prim_infeas_min  = prim_infeas; \n   dual_infeas_min  = dual_infeas; \n   prim_infeas_best = prim_infeas; \n   dual_infeas_best = dual_infeas; \n   infeas_best = infeas; \n   relgap_best = relgap; \n   homRd = inf; homrp = inf; dy = zeros(length(b),1);    \n   msg = []; msg2 = []; msg3 = [];\n   runhist.pobj    = obj(1);\n   runhist.dobj    = obj(2); \n   runhist.gap     = gap;\n   runhist.relgap  = relgap;\n   runhist.pinfeas = prim_infeas;\n   runhist.dinfeas = dual_infeas;\n   runhist.infeas  = infeas;  \n   runhist.step    = 0; \n   runhist.normX   = normX; \n   runhist.cputime = etime(clock,tstart); \n   ttime.preproc   = runhist.cputime; \n   ttime.pred = 0; ttime.pred_pstep = 0; ttime.pred_dstep = 0; \n   ttime.corr = 0; ttime.corr_pstep = 0; ttime.corr_dstep = 0; \n   ttime.pchol = 0; ttime.dchol = 0; ttime.misc = 0; \n%%\n%%-----------------------------------------\n%% display parameters and initial info\n%%-----------------------------------------\n%%\n   if (printlevel >= 2)\n      fprintf('\\n********************************************');\n      fprintf('***********************\\n');\n      fprintf('   SDPT3: Infeasible path-following algorithms'); \n      fprintf('\\n********************************************');\n      fprintf('***********************\\n');\n      [hh,mm,ss] = mytime(ttime.preproc); \n      if (printlevel>=3)       \n         fprintf(' version  predcorr  gam  expon  scale_data\\n');\n         if (vers == 1); fprintf('   HKM '); elseif (vers == 2); fprintf('    NT '); end\n         fprintf('     %1.0f      %4.3f',predcorr,gam);\n         fprintf('   %1.0f        %1.0f    %1.0f\\n',expon,scale_data); \n         fprintf('\\nit pstep dstep pinfeas dinfeas  gap')\n         fprintf('      mean(obj)   cputime\\n');\n         fprintf('------------------------------------------------');\n         fprintf('-------------------\\n');\n         fprintf('%2.0f|%4.3f|%4.3f|%2.1e|%2.1e|',0,0,0,prim_infeas,dual_infeas);\n         fprintf('%2.1e|%- 7.6e| %s:%s:%s|',gap,mean(obj),hh,mm,ss);\n      end\n   end\n%%\n%%---------------------------------------------------------------\n%% start main loop\n%%---------------------------------------------------------------\n%%\n   param.termcode    = termcode; \n   param.iter        = 0; \n   param.obj         = obj;\n   param.relgap      = relgap; \n   param.prim_infeas = prim_infeas;   param.dual_infeas = dual_infeas;    \n   param.homRd       = homRd;         param.homrp       = homrp; \n   param.AX          = AX;            param.ZpATynorm   = ZpATynorm;\n   param.normA       = normA;  \n   param.normb       = normb;         param.normC       = normC;\n   param.normX0      = normX0;        param.normZ0      = normZ0; \n   param.m0          = m0;            param.indeprows   = indeprows;\n   param.prim_infeas_bad = 0;         \n   param.dual_infeas_bad = 0; \n   param.prim_infeas_min = prim_infeas; \n   param.dual_infeas_min = dual_infeas; \n   param.gaptol      = gaptol;\n   param.inftol      = inftol; \n   param.maxit       = maxit;\n   param.scale_data  = scale_data;\n   param.printlevel  = printlevel; \n   param.ublksize    = ublksize; \n   Xbest = X; ybest = y; Zbest = Z; \n%%\n   for iter = 1:maxit;\n      tstart  = clock;  \n      timeold = tstart;\n      update_iter = 0; breakyes = 0; \n      pred_slow = 0; corr_slow = 0; step_short = 0; \n      par.parbarrier = parbarrier; \n      par.iter    = iter; \n      par.obj     = obj; \n      par.relgap  = relgap; \n      par.pinfeas = prim_infeas; \n      par.dinfeas = dual_infeas;\n      par.rp      = rp; \n      par.y       = y; \n      par.dy      = dy; \n      par.normX   = normX; \n      par.ZpATynorm = ZpATynorm; \n      %%if (printlevel > 2); fprintf(' %2.1e',par.normX); end\n      if (iter == 1 | restart); Cpert = min(1,normC2/ops(EE,'norm')); end\n      if (runhist.dinfeas(1) > 1e-3) & (~exist_analytic_term) ...\n         & (relgap > 1e-4) \n         if (par.normX > 5e3 & iter < 20)\n            Cpert = Cpert*0.5; \n         elseif (par.normX > 5e2 & iter < 20); \n            Cpert = Cpert*0.3; \n         else; \n            Cpert = Cpert*0.1; \n         end\n         Rd = ops(Rd,'+',EE,Cpert); \n         %%if (printlevel > 2); fprintf('|%2.1e',Cpert); end\n      end\n%%---------------------------------------------------------------\n%% predictor step.\n%%---------------------------------------------------------------\n%%\n      if (predcorr)\n         sigma = 0; \n      else \n         sigma = 1-0.9*min(pstep,dstep); \n         if (iter == 1); sigma = 0.5; end; \n      end\n      sigmu = cell(size(blk,1),1);\n      for p = 1:size(blk,1)\n         sigmu{p} = max(sigma*mu, parbarrier{p}');  \n      end\n      invXchol = cell(size(blk,1),1); \n      invZchol = ops(Zchol,'inv'); \n      if (vers == 1);\n         [par,dX,dy,dZ,coeff,L,hRd] = ...\n          HKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol);\n      elseif (vers == 2);\n         [par,dX,dy,dZ,coeff,L,hRd] = ...\n          NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);\n      end\n      if (solve_ok <= 0)\n         msg = 'stop: difficulty in computing predictor directions'; \n         if (printlevel); fprintf('\\n  %s',msg); end\n         runhist.pinfeas(iter+1) = runhist.pinfeas(iter); \n         runhist.dinfeas(iter+1) = runhist.dinfeas(iter); \n         runhist.relgap(iter+1)  = runhist.relgap(iter); \n         runhist.cputime(iter+1) = etime(clock,tstart); \n         termcode = -4;\n         break; %% do not ues breakyes = 1\n      end\n      timenew = clock;\n      ttime.pred = ttime.pred + etime(timenew,timeold); timeold = timenew; \n%%\n%%-----------------------------------------\n%% step-lengths for predictor step\n%%-----------------------------------------\n%%\n      if (gam == 0) \n         gamused = 0.9 + 0.09*min(pstep,dstep); \n      else\n         gamused = gam;\n      end \n      [Xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol); \n      pstep = min(1,gamused*full(Xstep));\n      timenew = clock; \n      ttime.pred_pstep = ttime.pred_pstep + etime(timenew,timeold); timeold = timenew;\n      Zstep = steplength(blk,Z,dZ,Zchol,invZchol); \n      dstep = min(1,gamused*full(Zstep));\n      trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...\n                 + dstep*blktrace(blk,X,dZ,parbarrier) ...\n                 + pstep*dstep*blktrace(blk,dX,dZ,parbarrier);\n      if (nn > 0); mupred  = trXZnew/nn; else; mupred = 1e-16; end\n      mupredhist(iter) = mupred;\n      timenew = clock;        \n      ttime.pred_dstep = ttime.pred_dstep + etime(timenew,timeold); timeold = timenew;\n%%\n%%-----------------------------------------\n%%  stopping criteria for predictor step.\n%%-----------------------------------------\n%%\n      if (min(pstep,dstep) < steptol) & (stoplevel) & (iter > 10)\n         msg = 'stop: steps in predictor too short';\n         if (printlevel) \n            fprintf('\\n  %s',msg);\n            fprintf(': pstep = %3.2e,  dstep = %3.2e\\n',pstep,dstep);\n         end\n         runhist.cputime(iter+1) = etime(clock,tstart); \n         termcode = -2; \n         breakyes = 1; \n      end\n      if (~predcorr)\n         if (iter >= 2) \n            idx = [max(2,iter-2) : iter];\n            pred_slow = all(mupredhist(idx)./mupredhist(idx-1) > 0.4);\n            idx = [max(2,iter-5) : iter];\n            pred_convg_rate = mean(mupredhist(idx)./mupredhist(idx-1));\n            pred_slow = pred_slow + (mupred/mu > 5*pred_convg_rate);\n         end \n         if (max(mu,infeas) < 1e-6) & (pred_slow) & (stoplevel)\n            msg = 'stop: lack of progress in predictor'; \n            if (printlevel) \n               fprintf('\\n  %s',msg);\n               fprintf(': mupred/mu = %3.2f, pred_convg_rate = %3.2f.',...\n               mupred/mu,pred_convg_rate);\n            end\n            runhist.cputime(iter+1) = etime(clock,tstart); \n            termcode = -2; \n            breakyes = 1;\n         else \n            update_iter = 1; \n         end\n      end\n%%---------------------------------------------------------------\n%% corrector step.\n%%---------------------------------------------------------------\n%%\n      if (predcorr) & (~breakyes)\n         step_pred = min(pstep,dstep);\n         if (mu > 1e-6)\n            if (step_pred < 1/sqrt(3)); \n               expon_used = 1; \n            else\n               expon_used = max(expon,3*step_pred^2); \n            end\n         else \n            expon_used = max(1,min(expon,3*step_pred^2)); \n         end \n         if (nn==0)\n             sigma = 0.2; \n         elseif (mupred < 0) \n             sigma = 0.8; \n         else\n            sigma = min(1, (mupred/mu)^expon_used);\n         end\n         sigmu = cell(size(blk,1),1); \n         for p = 1:size(blk,1)\n            sigmu{p} = max(sigma*mu, parbarrier{p}'); \n         end\t \n         if (vers == 1)\n            [dX,dy,dZ] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n             dX,dZ,coeff,L,X,Z);\n         elseif (vers == 2)\n            [dX,dy,dZ] = NTcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n             dX,dZ,coeff,L,X,Z); \n         end\n         if (solve_ok <= 0)\n            msg = 'stop: difficulty in computing corrector directions'; \n            if (printlevel); fprintf('\\n  %s',msg); end\n            runhist.pinfeas(iter+1) = runhist.pinfeas(iter); \n            runhist.dinfeas(iter+1) = runhist.dinfeas(iter); \n            runhist.relgap(iter+1)  = runhist.relgap(iter); \n            runhist.cputime(iter+1) = etime(clock,tstart); \n            termcode = -4;\n            break; %% do not ues breakyes = 1\n         end\n         timenew = clock;\n         ttime.corr = ttime.corr + etime(timenew,timeold); timeold = timenew; \n%%\n%%-----------------------------------\n%% step-lengths for corrector step\n%%-----------------------------------\n%%\n         if (gam == 0) \n            gamused = 0.9 + 0.09*min(pstep,dstep); \n         else\n            gamused = gam;\n         end            \n         Xstep = steplength(blk,X,dX,Xchol,invXchol);\n         pstep = min(1,gamused*full(Xstep));\n         timenew = clock;\n         ttime.corr_pstep = ttime.corr_pstep+etime(timenew,timeold); timeold = timenew;\n         Zstep = steplength(blk,Z,dZ,Zchol,invZchol);\n         dstep = min(1,gamused*full(Zstep));\n         trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...\n                    + dstep*blktrace(blk,X,dZ,parbarrier)...\n                    + pstep*dstep*blktrace(blk,dX,dZ,parbarrier); \n         if (nn > 0); mucorr  = trXZnew/nn; else; mucorr = 1e-16; end\n         timenew = clock;\n         ttime.corr_dstep = ttime.corr_dstep+etime(timenew,timeold); timeold = timenew;\n%%\n%%-----------------------------------------\n%%  stopping criteria for corrector step\n%%-----------------------------------------\n         if (iter >= 2) \n            idx = [max(2,iter-2) : iter];\n            corr_slow = all(runhist.gap(idx)./runhist.gap(idx-1) > 0.8); \n            idx = [max(2,iter-5) : iter];\n            corr_convg_rate = mean(runhist.gap(idx)./runhist.gap(idx-1));\n            corr_slow = corr_slow + (mucorr/mu > max(min(1,5*corr_convg_rate),0.8));\n         end \n\t if (max(relgap,infeas) < 1e-6) & (iter > 20) ...\n            & (corr_slow > 1) & (stoplevel)\n            msg = 'stop: lack of progress in corrector'; \n   \t    if (printlevel) \n               fprintf('\\n  %s',msg);\n               fprintf(': mucorr/mu = %3.2f, corr_convg_rate = %3.2f',...\n               mucorr/mu,corr_convg_rate); \n            end\n            runhist.cputime(iter+1) = etime(clock,tstart); \n            termcode = -2; \n            breakyes = 1;\n         else\n            update_iter = 1;\n         end\n      end \n%%---------------------------------------------------------------\n%% udpate iterate\n%%---------------------------------------------------------------\n      indef = [1,1]; \n      if (update_iter)\n         for t = 1:5\n            [Xchol,indef(1)] = blkcholfun(blk,ops(X,'+',dX,pstep)); \n            timenew = clock;\n            ttime.pchol = ttime.pchol + etime(timenew,timeold); timeold = timenew;\n            if (indef(1)); pstep = 0.8*pstep; else; break; end            \n         end\n\t if (t > 1); pstep = gamused*pstep; end\n\t for t = 1:5\n            [Zchol,indef(2)] = blkcholfun(blk,ops(Z,'+',dZ,dstep)); \n            timenew = clock;\n            ttime.dchol = ttime.dchol + etime(timenew,timeold); timeold = timenew; \n            if (indef(2)); dstep = 0.8*dstep; else; break; end             \n         end\n\t if (t > 1); dstep = gamused*dstep; end\n         %%-------------------------------------------\n         AXtmp = AX + pstep*AXfun(blk,At,par.permA,dX);\n         prim_infeasnew = norm(b-AXtmp)/normb2;\n         if (relgap < 5*infeas); alpha = 1e2; else; alpha = 1e3; end\n         if any(indef)\n            if indef(1); msg = 'stop: X not positive definite'; end\n            if indef(2); msg = 'stop: Z not positive definite'; end\n            if (printlevel); fprintf('\\n  %s',msg); end\n            termcode = -3;\n            breakyes = 1;         \n         elseif (prim_infeasnew > max([1e-8,relgap,20*prim_infeas]) & iter > 10) ...\n            | (prim_infeasnew > max([1e-7,1e3*prim_infeas,0.1*relgap]) & relgap < 1e-2) ...\n            | (prim_infeasnew > alpha*max([1e-9,param.prim_infeas_min]) ...\n               & (prim_infeasnew > max([3*prim_infeas,0.1*relgap])) ...\n               & (iter > 25) & (dual_infeas < 1e-6) & (relgap < 0.1)) ...\n            | ((prim_infeasnew > 1e3*prim_infeas & prim_infeasnew > 1e-12) ...\n               & (max(relgap,dual_infeas) < 1e-8))\n            if (stoplevel) \n               msg = 'stop: primal infeas has deteriorated too much'; \n               if (printlevel); fprintf('\\n  %s, %2.1e',msg,prim_infeasnew); end\n               termcode = -7; \n               breakyes = 1; \n            end\n         elseif (trXZnew > 1.05*runhist.gap(iter)) & (~exist_analytic_term) ...\n\t    & ((infeas < 1e-5) & (relgap < 1e-4) & (iter > 20) ...\n\t       | (max(infeas,relgap) < 1e-7) & (iter > 10)) \n            if (stoplevel) \n               msg = 'stop: progress in duality gap has deteriorated'; \n               if (printlevel); fprintf('\\n  %s, %2.1e',msg,trXZnew); end\n               termcode = -8; \n               breakyes = 1; \n            end\n         else\n            X = ops(X,'+',dX,pstep);  \n            y = y + dstep*dy;           \n            Z = ops(Z,'+',dZ,dstep);\n         end\n      end\n%%---------------------------------------------------------------\n%% adjust linear blk arising from unrestricted blk\n%%---------------------------------------------------------------\n      if (~breakyes)\n         for p = 1:size(blk,1)\n            if (u2lblk(p) == 1)\n               len = blk{p,2}/2;              \n               xtmp = min(X{p}([1:len]),X{p}(len+[1:len])); \n               alpha = 0.8; \n               X{p}([1:len])     = X{p}([1:len]) - alpha*xtmp;\n               X{p}(len+[1:len]) = X{p}(len+[1:len]) - alpha*xtmp;\n               if (mu < 1e-4) %% old: (mu < 1e-7)\n                  Z{p} = 0.5*mu./max(1,X{p}); %% good to keep this step\n               else\n                  ztmp = min(1,max(Z{p}([1:len]),Z{p}(len+[1:len])));\n                  if (dual_infeas > 1e-4 & dstep < 0.2)\n                     beta = 0.3; \n                  else  \n                     beta = 0.0; \n                  end\n                  %% important to set beta = 0 at later stage. \n                  Z{p}([1:len])     = Z{p}([1:len]) + beta*ztmp;\n                  Z{p}(len+[1:len]) = Z{p}(len+[1:len]) + beta*ztmp;\n               end\n            end\n         end\n      end\n%%--------------------------------------------------\n%% perturb Z: do this step before checking for break\n%%--------------------------------------------------\n      if (~breakyes) & (~exist_analytic_term)\n         trXZtmp = blktrace(blk,X,Z);\n         trXE  = blktrace(blk,X,EE);\n         Zpert = max(1e-12,0.2*min(relgap,prim_infeas)).*normC2./normE2;\n         Zpert = min(Zpert,0.1*trXZtmp./trXE);\n         Zpert = min([1,Zpert,1.5*Zpertold]); \n         if (infeas < 0.1) \n            Z = ops(Z,'+',EE,Zpert); \n            [Zchol,indef(2)] = blkcholfun(blk,Z);\n            if any(indef(2))\n               msg = 'stop: Z not positive definite';      \n               if (printlevel); fprintf('\\n  %s',msg); end\n               termcode = -3;\n               breakyes = 1; \n            end\n            %%if (printlevel > 2); fprintf(' %2.1e',Zpert); end\n         end\n         Zpertold = Zpert; \n      end\n%%---------------------------------------------------------------\n%% compute rp, Rd, infeasibities, etc\n%%---------------------------------------------------------------\n%%\n      AX  = AXfun(blk,At,par.permA,X); \n      rp  = b-AX;\n      ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n      ZpATynorm = ops(ZpATy,'norm');\n      Rd  = ops(C,'-',ZpATy);\n      objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0; \n      obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;  \n      gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n      relgap = gap/(1+sum(abs(obj))); \n      prim_infeas = norm(rp)/normb2;\n      dual_infeas = ops(Rd,'norm')/normC2;\n      infeas = max(prim_infeas,dual_infeas); \n      if (scale_data)\n         infeas_org(1) = prim_infeas*normb;\n         infeas_org(2) = dual_infeas*normC;\n      end\n      homRd = inf; homrp = inf; \n      if (ops(parbarrier,'norm') == 0)\n         if (obj(2) > 0); homRd = ZpATynorm/(obj(2)); end\n         if (obj(1) < 0); homrp = norm(AX)/(-obj(1))/(normC); end\n      end\n      trXZ = blktrace(blk,X,Z,parbarrier); \n      if (nn > 0); mu = trXZ/nn; else; mu = gap/ops(X,'getM'); end\n      normX = ops(X,'norm');\n%%\n      runhist.pobj(iter+1)  = obj(1); \n      runhist.dobj(iter+1)  = obj(2); \n      runhist.gap(iter+1)   = gap;\n      runhist.relgap(iter+1)  = relgap;\n      runhist.pinfeas(iter+1) = prim_infeas;\n      runhist.dinfeas(iter+1) = dual_infeas;\n      runhist.infeas(iter+1)  = infeas;\n      runhist.step(iter+1)    = min(pstep,dstep); \n      runhist.normX(iter+1)   = normX; \n      runhist.cputime(iter+1) = etime(clock,tstart); \n      timenew = clock;\n      ttime.misc = ttime.misc + etime(timenew,timeold); timeold = timenew;  \n      [hh,mm,ss] = mytime(sum(runhist.cputime)); \n      if (printlevel>=3)\n         fprintf('\\n%2.0f|%4.3f|%4.3f',iter,pstep,dstep);\n         fprintf('|%2.1e|%2.1e|%2.1e|',prim_infeas,dual_infeas,gap);\n         fprintf('%- 7.6e| %s:%s:%s|',mean(obj),hh,mm,ss);\n      end\n%%--------------------------------------------------\n%% check convergence\n%%--------------------------------------------------\n      param.use_LU      = use_LU; \n      param.stoplevel   = stoplevel; \n      param.termcode    = termcode; \n      param.iter        = iter; \n      param.obj         = obj;\n      param.gap         = gap; \n      param.relgap      = relgap; \n      param.prim_infeas = prim_infeas;\n      param.dual_infeas = dual_infeas;\n      param.mu        = mu; \n      param.homRd     = homRd; \n      param.homrp     = homrp; \n      param.AX        = AX; \n      param.ZpATynorm = ZpATynorm;\n      param.normX     = ops(X,'norm'); \n      param.normZ     = ops(Z,'norm'); \n      param.numpertdiagschur = numpertdiagschur; \n      if (~breakyes)\n         [param,breakyes,restart,msg2] = sqlpcheckconvg(param,runhist); \n      end\n      if (restart)\n         [X,y,Z] = infeaspt(blk,At,C,b,2,1e5); \n         rp  = b-AXfun(blk,At,par.permA,X); \n         ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n         Rd  = ops(C,'-',ZpATy); \n         trXZ = blktrace(blk,X,Z,parbarrier); \n         mu   = trXZ/nn;\n         gap  =  (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n         prim_infeas = norm(rp)/normb2;\n         dual_infeas = ops(Rd,'norm')/normC2;\n         infeas = max(prim_infeas,dual_infeas); \n         [Xchol,indef(1)] = blkcholfun(blk,X); \n         [Zchol,indef(2)] = blkcholfun(blk,Z); \n         stoplevel = 3;\n      end\n%%--------------------------------------------------\n%% check for break\n%%--------------------------------------------------\n      if ((prim_infeas < 1.5*prim_infeas_best) ...                \n         | (max(relgap,infeas) < 0.8*max(relgap_best,infeas_best))) ...\n         & (max(relgap,dual_infeas) < 0.8*max(relgap_best,dual_infeas_best)) \n         Xbest = X; ybest = y; Zbest = Z; \n         prim_infeas_best = prim_infeas; \n         dual_infeas_best = dual_infeas; \n         relgap_best = relgap; infeas_best = infeas; \n         update_best(iter+1) = 1; \n         %%fprintf('#')\n      else\n         update_best(iter+1) = 0; \n      end   \n      if (max(relgap_best,infeas_best) < 1e-4 ...\n          & norm(update_best(max(1,iter-1):iter+1)) == 0)\n         msg = 'lack of progress in infeas'; \n         if (printlevel); fprintf('\\n  %s',msg); end\n         termcode = -9; \n         breakyes = 1; \n      end\n      if (breakyes); break; end\n   end\n%%---------------------------------------------------------------\n%% end of main loop\n%%---------------------------------------------------------------\n%%\n   use_bestiter = 1; \n   if (use_bestiter) & (param.termcode <= 0)\n      X = Xbest; y = ybest; Z = Zbest; \n      Xchol = blkcholfun(blk,X); \n      Zchol = blkcholfun(blk,Z);      \n      AX = AXfun(blk,At,par.permA,X); \n      rp = b-AX;\n      ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n      Rd = ops(C,'-',ZpATy);\n      objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0; \n      obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;  \n      gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n      relgap = gap/(1+sum(abs(obj)));\n      prim_infeas = norm(rp)/normb2; \n      dual_infeas = ops(Rd,'norm')/normC2; \n      infeas = max(prim_infeas,dual_infeas); \n      runhist.pobj(iter+1)  = obj(1); \n      runhist.dobj(iter+1)  = obj(2); \n      runhist.gap(iter+1)   = gap;\n      runhist.relgap(iter+1)  = relgap;\n      runhist.pinfeas(iter+1) = prim_infeas;\n      runhist.dinfeas(iter+1) = dual_infeas;\n      runhist.infeas(iter+1)  = infeas; \n   end\n%%---------------------------------------------------------------\n%% unscale and produce infeasibility certificates if appropriate\n%%---------------------------------------------------------------\n   if (iter >= 1)\n      [X,y,Z,termcode,resid,reldist,msg3] = ...\n      sqlpmisc(blk,At,C,b,X,y,Z,par.permZ,param); \n   end\n%%---------------------------------------------------------------\n%% recover unrestricted blk from linear blk\n%%---------------------------------------------------------------\n%% \n   for p = 1:size(blk,1)\n      if (u2lblk(p) == 1)\n         n = blk{p,2}/2; \n         X{p} = X{p}(1:n)-X{p}(n+[1:n]); \n         Z{p} = Z{p}(1:n); \n      end\n   end\n   for p = 1:size(ublkidx,1) \n      if ~isempty(ublkidx{p,2})\n         n0 = ublkidx{p,1}; idxB = setdiff([1:n0]',ublkidx{p,2});\n         tmp = zeros(n0,1); tmp(idxB) = X{p}; X{p} = tmp; \n         tmp = zeros(n0,1); tmp(idxB) = Z{p}; Z{p} = tmp; \n      end\n   end\n   if (analytic_prob)\n      X = X(1:numblkold); Z = Z(1:numblkold); \n   end\n%%---------------------------------------------------------------\n%% print summary\n%%---------------------------------------------------------------\n%%\n   maxC = 1+ops(ops(C,'abs'),'max'); \n   maxb = 1+max(abs(b)); \n   if (scale_data)\n      dimacs = [infeas_org(1)*normb2/maxb; 0; infeas_org(2)*normC2/maxC; 0]; \n   else\n      dimacs = [prim_infeas*normb2/maxb; 0; dual_infeas*normC2/maxC; 0];\n   end\n   dimacs = [dimacs; [-diff(obj); gap]/(1+sum(abs(obj)))];\n   info.dimacs   = dimacs; \n   info.termcode = termcode;\n   info.iter     = iter; \n   info.obj      = obj; \n   info.gap      = gap; \n   info.relgap   = relgap;\n   info.pinfeas  = prim_infeas;\n   info.dinfeas  = dual_infeas;\n   info.cputime  = sum(runhist.cputime); \n   info.time     = ttime; \n   info.resid    = resid;\n   info.reldist  = reldist; \n   info.normX    = ops(X,'norm'); \n   info.normy    = norm(y); \n   info.normZ    = ops(Z,'norm'); \n   info.normb    = normb2; info.maxb = maxb; \n   info.normC    = normC2; info.maxC = maxC; \n   info.normA    = normA2;\n   info.msg1     = msg; \n   info.msg2     = msg2;\n   info.msg3     = msg3;\n   sqlpsummary(info,ttime,infeas_org,printlevel);\n   rand('state',randstate);\n   randn('state',randnstate);\n%%*****************************************************************************\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/sqlpmain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.24171778339276354}}
{"text": "function [uV] = eeg_volt2uv(Volts);\n\n% eeg_volt2uv - Convert volts to microvolts\n%\n%   [uV] = eeg_volts2uv(Volts)\n%\n%   Simply, uV = Volts .* 10^6\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:50 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  11/2001, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nuV = Volts .* 10^6;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/eeg_Volt2uV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2417177833927635}}
{"text": "function [cfg, artifact] = ft_artifact_zvalue(cfg, data)\n\n% FT_ARTIFACT_ZVALUE scans data segments of interest for artifacts, by means of\n% thresholding the z-scored values of signals that have been preprocessed,\n% using heuristics that increase the sensitivity to detect certain types of artifacts.\n% Depending on the preprocessing options, this method will be sensitive to EOG, muscle \n% or SQUID jump artifacts. The z-scoring is applied in order to make the threshold\n% independent of the phsyical units in the data.\n%\n% Use as\n%   [cfg, artifact] = ft_artifact_zvalue(cfg)\n% with the configuration options\n%   cfg.trl        = structure that defines the data segments of interest, see FT_DEFINETRIAL\n%   cfg.continuous = 'yes' or 'no' whether the file contains continuous data.\n%                    If the data has not been recorded continuously, then the cfg.trl should\n%                    stricly observe the boundaries of the discontinuous segments, and the \n%                    permitted values padding options (described below) are restricted to 0. \n%   cfg.dataset    = string with the filename\n% or\n%   cfg.headerfile = string with the filename\n%   cfg.datafile   = string with the filename\n% and optionally\n%   cfg.headerformat\n%   cfg.dataformat\n%\n% Alternatively you can use it as\n%   [cfg, artifact] = ft_artifact_zvalue(cfg, data)\n% where the input data is a structure as obtained from FT_PREPROCESSING. Any preprocessing options\n% defined in the cfg will be applied to the data before the z-scoring and thresholding.\n%\n% In both cases the configuration should also contain\n%   cfg.trl        = structure that defines the data segments of interest, see FT_DEFINETRIAL\n%   cfg.continuous = 'yes' or 'no' whether the file contains continuous data\n% and\n%   cfg.artfctdef.zvalue.channel    = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details\n%   cfg.artfctdef.zvalue.cutoff     = number, z-value threshold\n%   cfg.artfctdef.zvalue.trlpadding = number in seconds\n%   cfg.artfctdef.zvalue.fltpadding = number in seconds\n%   cfg.artfctdef.zvalue.artpadding = number in seconds\n%\n% If you encounter difficulties with memory usage, you can use\n%   cfg.memory = 'low' or 'high', whether to be memory or computationally efficient, respectively (default = 'high')\n%\n% The optional configuration settings (see below) are:\n%   cfg.artfctdef.zvalue.artfctpeak       = 'yes' or 'no'\n%   cfg.artfctdef.zvalue.artfctpeakrange  = [begin end]\n%   cfg.artfctdef.zvalue.interactive      = 'yes' or 'no'\n%   cfg.artfctdef.zvalue.zscore           = 'yes' (default) or 'no'   \n%\n% If you specify cfg.artfctdef.zvalue.artfctpeak='yes', a peak detection on the suprathreshold\n% z-scores will be performed, and the artifact will be defined relative to\n% the peak, where the begin and end points will be defined by\n% cfg.artfctdef.zvalue artfctpeakrange, rather than by the time points that\n% exceed the threshold.\n%\n% You can specify cfg.artfctdef.zvalue.artfctpeakrange if you want to use the\n% detected artifacts as input to the DSS method of FT_COMPONENTANALYSIS. The result\n% is saved into cfg.artfctdef.zvalue.artifact. The range will automatically\n% respect the trial boundaries, i.e. it will be shorter if peak is near the beginning\n% or end of a trial. Samples between trials will be removed, thus this will not match\n% the sampleinfo of the data structure.\n%\n% If you specify cfg.artfctdef.zvalue.zscore = 'no', the data will NOT be z-scored prior\n% to thresholding. This goes a bit against the name of the function, but it may be useful\n% if the threshold is to be defined in meaningful physical units, e.g. degrees of visual\n% angle for eye position data.\n%\n% If you specify cfg.artfctdef.zvalue.interactive = 'yes', a graphical user interface\n% will show in which you can manually accept/reject the detected artifacts, and/or\n% change the threshold. To control the graphical interface via keyboard, use the\n% following keys:\n%\n%     q                 : Stop\n%\n%     comma             : Step to the previous artifact trial\n%     a                 : Specify artifact trial to display\n%     period            : Step to the next artifact trial\n%\n%     x                 : Step 10 trials back\n%     leftarrow         : Step to the previous trial\n%     t                 : Specify trial to display\n%     rightarrow        : Step to the next trial\n%     c                 : Step 10 trials forward\n%\n%     k                 : Keep trial\n%     space             : Mark complete trial as artifact\n%     r                 : Mark part of trial as artifact\n%\n%     downarrow         : Shift the z-threshold down\n%     z                 : Specify the z-threshold\n%     uparrow           : Shift the z-threshold down\n%\n% Configuration settings related to the preprocessing of the data are\n%   cfg.artfctdef.zvalue.lpfilter      = 'no' or 'yes'  lowpass filter\n%   cfg.artfctdef.zvalue.hpfilter      = 'no' or 'yes'  highpass filter\n%   cfg.artfctdef.zvalue.bpfilter      = 'no' or 'yes'  bandpass filter\n%   cfg.artfctdef.zvalue.bsfilter      = 'no' or 'yes'  bandstop filter for line noise removal\n%   cfg.artfctdef.zvalue.dftfilter     = 'no' or 'yes'  line noise removal using discrete fourier transform\n%   cfg.artfctdef.zvalue.medianfilter  = 'no' or 'yes'  jump preserving median filter\n%   cfg.artfctdef.zvalue.lpfreq        = lowpass  frequency in Hz\n%   cfg.artfctdef.zvalue.hpfreq        = highpass frequency in Hz\n%   cfg.artfctdef.zvalue.bpfreq        = bandpass frequency range, specified as [low high] in Hz\n%   cfg.artfctdef.zvalue.bsfreq        = bandstop frequency range, specified as [low high] in Hz\n%   cfg.artfctdef.zvalue.lpfiltord     = lowpass  filter order\n%   cfg.artfctdef.zvalue.hpfiltord     = highpass filter order\n%   cfg.artfctdef.zvalue.bpfiltord     = bandpass filter order\n%   cfg.artfctdef.zvalue.bsfiltord     = bandstop filter order\n%   cfg.artfctdef.zvalue.medianfiltord = length of median filter\n%   cfg.artfctdef.zvalue.lpfilttype    = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n%   cfg.artfctdef.zvalue.hpfilttype    = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n%   cfg.artfctdef.zvalue.bpfilttype    = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n%   cfg.artfctdef.zvalue.bsfilttype    = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n%   cfg.artfctdef.zvalue.detrend       = 'no' or 'yes'\n%   cfg.artfctdef.zvalue.demean        = 'no' or 'yes'\n%   cfg.artfctdef.zvalue.baselinewindow = [begin end] in seconds, the default is the complete trial\n%   cfg.artfctdef.zvalue.hilbert       = 'no' or 'yes'\n%   cfg.artfctdef.zvalue.rectify       = 'no' or 'yes'\n%\n% The output argument \"artifact\" is a Nx2 matrix comparable to the \"trl\" matrix of\n% FT_DEFINETRIAL. The first column of which specifying the beginsamples of an\n% artifact period, the second column contains the endsamples of the artifactperiods.\n%\n% To facilitate data-handling and distributed computing, you can use\n%   cfg.inputfile   =  ...\n% to read the input data from a *.mat file on disk. This mat files should contain\n% only a single variable named 'data', corresponding to the input structure.\n%\n% See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG,\n% FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE\n\n% Copyright (C) 2003-2011, Jan-Mathijs Schoffelen & Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble provenance\nft_preamble loadvar data\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% for backward compatibility\ncfg = ft_checkconfig(cfg, 'renamed', {'artfctdef.blc',             'artfctdef.demean'});\ncfg = ft_checkconfig(cfg, 'renamed', {'artfctdef.blcwindow'        'artfctdef.baselinewindow'});\ncfg = ft_checkconfig(cfg, 'renamed', {'artfctdef.zvalue.sgn',      'artfctdef.zvalue.channel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'artfctdef.zvalue.feedback', 'artfctdef.zvalue.interactive'});\ncfg = ft_checkconfig(cfg, 'forbidden',  {'padding'});\n\n% set the default options\ncfg.continuous      = ft_getopt(cfg, 'continuous',     []);\ncfg.feedback        = ft_getopt(cfg, 'feedback',       'text');\ncfg.memory          = ft_getopt(cfg, 'memory',         'high');\ncfg.representation  = ft_getopt(cfg, 'representation', 'numeric'); % numeric or table\n\n% set default rejection parameters\ncfg.artfctdef                    = ft_getopt(cfg,                  'artfctdef',    []);\ncfg.artfctdef.zvalue             = ft_getopt(cfg.artfctdef,        'zvalue',       []);\ncfg.artfctdef.zvalue.method      = ft_getopt(cfg.artfctdef.zvalue, 'method',       'all');\ncfg.artfctdef.zvalue.ntrial      = ft_getopt(cfg.artfctdef.zvalue, 'ntrial',       10);\ncfg.artfctdef.zvalue.channel     = ft_getopt(cfg.artfctdef.zvalue, 'channel',      {});\ncfg.artfctdef.zvalue.trlpadding  = ft_getopt(cfg.artfctdef.zvalue, 'trlpadding',   0);\ncfg.artfctdef.zvalue.fltpadding  = ft_getopt(cfg.artfctdef.zvalue, 'fltpadding',   0);\ncfg.artfctdef.zvalue.artpadding  = ft_getopt(cfg.artfctdef.zvalue, 'artpadding',   0);\ncfg.artfctdef.zvalue.interactive = ft_getopt(cfg.artfctdef.zvalue, 'interactive',  'no');\ncfg.artfctdef.zvalue.cumulative  = ft_getopt(cfg.artfctdef.zvalue, 'cumulative',   'yes');\ncfg.artfctdef.zvalue.artfctpeak  = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeak',   'no');\ncfg.artfctdef.zvalue.artfctpeakrange  = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeakrange',[0 0]);\ncfg.artfctdef.zvalue.zscore      = ft_getopt(cfg.artfctdef.zvalue, 'zscore',       'yes');\n\nif isfield(cfg.artfctdef.zvalue, 'artifact')\n  ft_notice('zvalue artifact detection has already been done, retaining artifacts\\n');\n  artifact = cfg.artfctdef.zvalue.artifact;\n  return\nend\n\n% clear old warnings from this stack\nft_warning('-clear')\n\n% flag whether to compute z-value per trial or not, rationale being that if there are\n% fluctuations in the variance across trials (e.g. due to position differences in MEG\n% measurements) which don't have to do with the artifact per se, the detection is\n% compromised (although the data quality is questionable when there is a lot of\n% movement to begin with).\npertrial    = strcmp(cfg.artfctdef.zvalue.method, 'trial');\ndemeantrial = strcmp(cfg.artfctdef.zvalue.method, 'trialdemean');\nif pertrial\n  if isfield(cfg.artfctdef.zvalue, 'ntrial') && cfg.artfctdef.zvalue.ntrial>0\n    pertrial = cfg.artfctdef.zvalue.ntrial;\n  else\n    ft_error('you should specify cfg.artfctdef.zvalue.ntrial, and it should be > 0');\n  end\nend\n\n% the data can be passed as input arguments or can be read from disk\nhasdata = exist('data', 'var');\n\nif ~hasdata\n  cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');\n  cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'});\n  hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);\nelse\n  data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes');\n  cfg  = ft_checkconfig(cfg, 'forbidden', {'dataset', 'headerfile', 'datafile'});\n  hdr  = ft_fetch_header(data);\nend\n\n% set default cfg.continuous\nif isempty(cfg.continuous)\n  if hdr.nTrials==1\n    cfg.continuous = 'yes';\n  else\n    cfg.continuous = 'no';\n  end\nend\n\n% get the specification of the data segments that should be scanned for artifacts\nif ~isfield(cfg, 'trl') && hasdata\n  trl = data.sampleinfo;\n  for k = 1:numel(data.trial)\n    trl(k,3) = time2offset(data.time{k}, data.fsample);\n  end\nelseif isfield(cfg, 'trl') && ischar(cfg.trl)\n  trl = loadvar(cfg.trl, 'trl');\nelseif isfield(cfg, 'trl') && isnumeric(cfg.trl)\n  trl = cfg.trl;\nelse\n  ft_error('cannot determine which segments of data to scan for artifacts');\nend\n\n% check whether the value for trlpadding makes sense\nif hasdata && cfg.artfctdef.zvalue.trlpadding > 0\n  % negative trlpadding is allowed with in-memory data, since that would remove some data from each trial\n  ft_error('you cannot use positive trlpadding with in-memory data');\nend\n\ntrlpadding = round(cfg.artfctdef.zvalue.trlpadding*hdr.Fs);\nfltpadding = round(cfg.artfctdef.zvalue.fltpadding*hdr.Fs);\nartpadding = round(cfg.artfctdef.zvalue.artpadding*hdr.Fs);\n\ntrl(:,1)      = trl(:,1) - trlpadding;       % pad the trial with some samples, in order to detect\ntrl(:,2)      = trl(:,2) + trlpadding;       % artifacts at the edges of the relevant trials.\nif size(trl,2)>= 3\n  trl(:,3)    = trl(:,3) - trlpadding;       % the offset can of course be adjusted as well\nelseif hasdata\n  % reconstruct offset\n  for tr=1:size(trl,1)\n    % account for 0 might not be in data.time\n    t0        = interp1(data.time{tr}, 1:numel(data.time{tr}), 0, 'linear', 'extrap');\n    trl(tr,3) = -t0+1 - trlpadding;\n  end\nelse\n  % assuming that the trial starts at t=0s\n  trl(:,3) = trl(:,1);\nend\n\nnumtrl        = size(trl,1);\ncfg.artfctdef.zvalue.channel = ft_channelselection(cfg.artfctdef.zvalue.channel, hdr.label);\nchanindx      = match_str(hdr.label, cfg.artfctdef.zvalue.channel);\nnchan         = length(chanindx);\nthresholdsum  = strcmp(cfg.artfctdef.zvalue.cumulative, 'yes');\n\nif nchan<1\n  ft_error('no channels selected');\nend\n\n% read the data and apply preprocessing options\nif ~pertrial\n  sumval = zeros(nchan, 1);\n  sumsqr = zeros(nchan, 1);\n  numsmp = zeros(nchan, 1);\nelse\n  sumval = zeros(nchan, numtrl);\n  sumsqr = zeros(nchan, numtrl);\n  numsmp = zeros(nchan, numtrl);\nend\n\nif strcmp(cfg.memory, 'high') % store data in memory, saving computation time below\n  dat = cell(1, numtrl);\nend\n\nft_progress('init', cfg.feedback, ['searching for artifacts in ' num2str(nchan) ' channels']);\nfor trlop=1:numtrl\n\n  ft_progress(trlop/numtrl, 'processing trial %d from %d\\n', trlop, numtrl);\n  if hasdata\n    thisdat = ft_fetch_data(data,        'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'skipcheckdata', 1);\n  else\n    thisdat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat);\n  end\n  thisdat = preproc(thisdat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(thisdat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding);\n \n  if ~pertrial\n    % accumulate the sum and the sum-of-squares\n    sumval = sumval + nansum(thisdat,2);\n    sumsqr = sumsqr + nansum(thisdat.^2,2);\n    numsmp = numsmp + sum(isfinite(thisdat),2);\n  else\n    % store per trial the sum and the sum-of-squares\n    sumval(:,trlop) = nansum(thisdat,2);\n    sumsqr(:,trlop) = nansum(thisdat.^2,2);\n    numsmp(:,trlop) = sum(isfinite(thisdat),2);\n  end\n  \n  if strcmp(cfg.memory, 'high') % store data in memory, saving computation time below\n    dat{trlop} = thisdat;\n  end\n\nend % for trlop\nft_progress('close');\n\nif pertrial>1\n  sumval = ft_preproc_smooth(sumval, pertrial)*pertrial;\n  sumsqr = ft_preproc_smooth(sumsqr, pertrial)*pertrial;\n  numsmp = ft_preproc_smooth(numsmp, pertrial)*pertrial;\nend\n\n% compute the average and the standard deviation\nif strcmp(cfg.artfctdef.zvalue.zscore, 'yes')\n  datavg = sumval./numsmp;\n  datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2);\nelse\n  ft_warning('not performing z-scoring, note that the defined threshold has physical units');\n  datavg = zeros(size(sumval));\n  datstd = ones(size(sumval));\nend\n\nif strcmp(cfg.memory, 'low')\n  ft_info('\\n');\nend\n\nzmax  = cell(1, numtrl);\nzsum  = cell(1, numtrl);\nzindx = cell(1, numtrl);\n\n% create a vector that indexes the trials, or is all 1, in order to a per trial\n% z-scoring, or use a static std and mean\nif pertrial\n  indvec = 1:numtrl;\nelse\n  indvec = ones(1,numtrl);\nend\n\nft_progress('init', cfg.feedback, ['processing data in ' num2str(nchan) ' channels']);\nfor trlop = 1:numtrl\n  \n  if strcmp(cfg.memory, 'low') % store nothing in memory (note that we need to fetch/read and preproc AGAIN... *yawn*)\n    ft_progress(trlop/numtrl, 'processing trial %d from %d\\n', trlop, numtrl);\n    options_getdata = {'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no')};\n    if hasdata\n      thisdat = ft_fetch_data(data, options_getdata{:});\n    else\n      options_getdata = cat(2, options_getdata, {'dataformat', cfg.dataformat});\n      thisdat = ft_read_data(cfg.datafile, options_getdata{:});\n    end\n    thisdat = preproc(thisdat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(thisdat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding);\n  else\n    thisdat = dat{trlop};\n  end\n\n  nsmp    = size(thisdat,2);\n\n  zmax{trlop}  = -inf + zeros(1, nsmp);\n  zsum{trlop}  =        zeros(1, nsmp);\n  zindx{trlop} =        zeros(1, nsmp);\n        \n  ix           = indvec(trlop) * ones(1,nsmp);           % indexing vector dependent on the pertrial setting \n  zdata        = (thisdat - datavg(:,ix))./datstd(:,ix); % convert the filtered data to z-values\n  zsum{trlop}  = nansum(zdata,1);      % sum the z-values across channels\n  [zmax{trlop},ind] = max(zdata,[],1); % find the maximum z-value and remember it\n  zindx{trlop}      = chanindx(ind);   % also remember the channel number that has the largest z-value\n\nend % for trlop\nft_progress('close');\n\nif demeantrial\n  for trlop = 1:numtrl\n    zmax{trlop} = zmax{trlop}-nanmean(zmax{trlop},2);\n    zsum{trlop} = zsum{trlop}-nanmean(zsum{trlop},2);\n  end\nend\n\nfor trlop = 1:numtrl\n  zsum{trlop} = zsum{trlop} ./ sqrt(nchan);\nend\n\n% always create figure\n% keypress to enable keyboard uicontrol\nh = figure('KeyPressFcn', @keyboard_cb);\nset(h, 'visible', 'off');\n\nopt.artcfg       = cfg.artfctdef.zvalue;\nopt.artval       = {};\nopt.artpadding   = artpadding;\nopt.cfg          = cfg;\nopt.channel      = 'artifact';\nopt.hdr          = hdr;\nopt.numtrl       = size(trl,1);\nopt.quit         = 0;\nopt.threshold    = cfg.artfctdef.zvalue.cutoff;\nopt.thresholdsum = thresholdsum;\nopt.trialok      = true(1,opt.numtrl);  % OK by means of objective criterion\nopt.keep         = zeros(1,opt.numtrl); % OK overruled by user +1 to keep, -1 to reject, start all zeros for callback to work\nopt.trl          = trl;\nopt.trlop        = 1;\nopt.updatethreshold = true;\nopt.zmax         = zmax;\nopt.zsum         = zsum;\n\nif ~thresholdsum\n  opt.zval = zmax;\nelse\n  opt.zval = zsum;\nend\nopt.zindx = zindx;\nif ~hasdata\n  opt.data = {};\nelse\n  opt.data = data;\nend\n\nif strcmp(cfg.artfctdef.zvalue.interactive, 'yes')\n  set(h, 'visible', 'on');\n  set(h, 'CloseRequestFcn', @cleanup_cb);\n  % give graphical feedback and allow the user to modify the threshold\n  set(h, 'position', [100 200 900 400]);\n  h1 = axes('position', [0.05 0.15 0.4 0.8]);\n  h2 = axes('position', [0.5  0.57  0.45 0.38]);\n  h3 = axes('position', [0.5  0.15  0.45 0.32]);\n  opt.h1           = h1;\n  opt.h2           = h2;\n  opt.h3           = h3;\n  \n  setappdata(h, 'opt', opt);\n  artval_cb(h);\n  redraw_cb(h);\n  \n  % make the user interface elements for the data view, the order of the elements\n  % here is from left to right and should match the order in the documentation\n  uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'stop',    'userdata', 'q');\n  \n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<',        'userdata', 'comma');\n  uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'artifact', 'userdata', 'a');\n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>',        'userdata', 'period');\n  \n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<<',    'userdata', 'x');\n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<',     'userdata', 'leftarrow');\n  uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'trial', 'userdata', 't');\n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>',     'userdata', 'rightarrow');\n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>>',    'userdata', 'c');\n  \n  uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'keep trial',  'userdata', 'k');\n  uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject full', 'userdata', 'space');\n  uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject part', 'userdata', 'r');\n  \n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<',           'userdata', 'downarrow');\n  uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'threshold',   'userdata', 'z');\n  uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>',           'userdata', 'uparrow');\n  \n  %uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<',       'userdata', 'control+uparrow')\n  %uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel', 'userdata', 'c')\n  %uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>',       'userdata', 'control+downarrow')\n  \n  ft_uilayout(h, 'tag', 'width1', 'width', 0.10, 'height', 0.05);\n  ft_uilayout(h, 'tag', 'width2', 'width', 0.05, 'height', 0.05);\n  ft_uilayout(h, 'tag', 'width3', 'width', 0.12, 'height', 0.05);\n  \n  ft_uilayout(h, 'tag', 'width1', 'style', 'pushbutton', 'callback', @keyboard_cb);\n  ft_uilayout(h, 'tag', 'width2', 'style', 'pushbutton', 'callback', @keyboard_cb);\n  ft_uilayout(h, 'tag', 'width3', 'style', 'pushbutton', 'callback', @keyboard_cb);\n  \n  ft_uilayout(h, 'tag', 'width1', 'retag', 'viewui');\n  ft_uilayout(h, 'tag', 'width2', 'retag', 'viewui');\n  ft_uilayout(h, 'tag', 'width3', 'retag', 'viewui');\n  ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0.005);\n  \n  while opt.quit==0\n    uiwait(h);\n    opt = getappdata(h, 'opt');\n  end\n  \nelse\n  % compute the artifacts given the settings in the cfg\n  setappdata(h, 'opt', opt);\n  artval_cb(h);\nend\n\nh   = getparent(h);\nopt = getappdata(h, 'opt');\n\n% convert the artifact values per trial to one long boolean vector\nboolvec = zeros(1,max(opt.trl(:,2)));\nfor trlop=1:opt.numtrl\n  boolvec(opt.trl(trlop,1):opt.trl(trlop,2)) = opt.artval{trlop};\nend\n\n% find the padded artifacts and put them in a Nx2 trl-like matrix\nartifact = boolvec2artifact(boolvec);\n\nif strcmp(cfg.artfctdef.zvalue.artfctpeak, 'yes')\n  % this is a re-implementation of the peak-detection stuff, to make the\n  % overall code behavior more consistent. artifact will be adjusted\n  % according to the specifications of the user, i.e. the peak index for\n  % each identified artifact will be identified, and used for an offset\n  % column. the peak_indx, peaks, and dssartifact fields are be obsoleted\n  pre = round(cfg.artfctdef.zvalue.artfctpeakrange(1)*hdr.Fs);\n  pst = round(cfg.artfctdef.zvalue.artfctpeakrange(2)*hdr.Fs);\n  for k = 1:size(artifact,1)\n    % identify the corresponding trl for the current artifact, the artifact\n    % can either be fully within the trl, or overlapping at one (or\n    % both) edges\n    current = artifact(k,:);\n    seltrl  = find(current(2)>=opt.trl(:,1) & current(1)<=opt.trl(:,2));\n     \n    % in case the artifact is in more than one trial a for-loop is needed\n    mx     = [];\n    mx_idx = [];\n    for m = 1:numel(seltrl)\n      idx = current - opt.trl(seltrl(m),1) + 1;\n      idx(1) = max(idx(1),1);\n      idx(2) = min(idx(2),size(opt.zval{seltrl(m)},2));\n      [mx(m), mx_idx(m)] = max(opt.zval{seltrl(m)}(idx(1):idx(2)));\n    end\n    \n    [maxtrl, maxtrl_idx] = max(mx);\n    seltrl = seltrl(maxtrl_idx);\n    peak   = current(1) + mx_idx(maxtrl_idx) - 1;\n    \n    artifact(k,1) = max(peak+pre, opt.trl(seltrl,1));\n    artifact(k,2) = min(peak+pst, opt.trl(seltrl,2));\n    artifact(k,3) = artifact(k,1) - peak;\n  end\nend\n\nif strcmp(cfg.representation, 'numeric') && istable(artifact)\n  if isempty(artifact)\n    % an empty table does not have columns\n    artifact = zeros(0,2);\n  else\n    % convert the table to a numeric array with the columns begsample and endsample\n    artifact = table2array(artifact);\n  end\nelseif strcmp(cfg.representation, 'table') && isnumeric(artifact)\n  if isempty(artifact)\n    % an empty table does not have columns\n    artifact = table();\n  else\n    % convert the numeric array to a table with the columns begsample and endsample\n    begsample = artifact(:,1);\n    endsample = artifact(:,2);\n    if size(artifact,2)==3\n      offset   = artifact(:,3);\n      artifact = table(begsample, endsample, offset);\n    else\n      artifact = table(begsample, endsample);\n    end\n  end\nend\n\n% remember the details that were used here and store the detected artifacts\ncfg.artfctdef.zvalue.trl      = trl;              % remember where we have been looking for artifacts\ncfg.artfctdef.zvalue.cutoff   = opt.threshold;    % remember the threshold that was used\ncfg.artfctdef.zvalue.artifact = artifact;\n\nft_notice('detected %d artifacts\\n', size(artifact,1));\n\ndelete(h);\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble previous data\nft_postamble provenance\nft_postamble savevar\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction artval_cb(h, eventdata)\n\nopt = getappdata(h, 'opt');\n\nartval = cell(1,opt.numtrl);\nfor trlop=1:opt.numtrl\n  if opt.thresholdsum\n    % threshold the accumulated z-values\n    artval{trlop} = opt.zsum{trlop}>opt.threshold;\n  else\n    % threshold the max z-values\n    artval{trlop} = opt.zmax{trlop}>opt.threshold;\n  end\n  % pad the artifacts\n  artbeg = find(diff([0 artval{trlop}])== 1);\n  artend = find(diff([artval{trlop} 0])==-1);\n  artbeg = artbeg - opt.artpadding;\n  artend = artend + opt.artpadding;\n  artbeg(artbeg<1) = 1;\n  artend(artend>length(artval{trlop})) = length(artval{trlop});\n  for artlop=1:length(artbeg)\n    artval{trlop}(artbeg(artlop):artend(artlop)) = 1;\n  end\n  opt.trialok(trlop) = isempty(artbeg);\nend\n\nfor trlop = find(opt.keep==1 & opt.trialok==0)\n  % overrule the objective criterion, i.e. keep the trial when the user\n  % wants to keep it\n  artval{trlop}(:) = 0;\nend\n\nfor trlop = find(opt.keep<0 & opt.trialok==1)\n  % if the user specifies that the trial is not OK\n  % reject the whole trial if there is no extra-threshold data,\n  % otherwise use the artifact as found by the thresholding\n  if opt.thresholdsum && opt.keep(trlop)==-1\n    % threshold the accumulated z-values\n    artval{trlop} = opt.zsum{trlop}>opt.threshold;\n  elseif opt.keep(trlop)==-1\n    % threshold the max z-values\n    artval{trlop} = opt.zmax{trlop}>opt.threshold;\n  elseif opt.keep(trlop)==-2\n    artval{trlop}(:) = 1;\n  end\n  % pad the artifacts\n  artbeg = find(diff([0 artval{trlop}])== 1);\n  artend = find(diff([artval{trlop} 0])==-1);\n  artbeg = artbeg - opt.artpadding;\n  artend = artend + opt.artpadding;\n  artbeg(artbeg<1) = 1;\n  artend(artend>length(artval{trlop})) = length(artval{trlop});\n  if ~isempty(artbeg)\n    for artlop=1:length(artbeg)\n      artval{trlop}(artbeg(artlop):artend(artlop)) = 1;\n    end\n  else\n    artval{trlop}(:) = 1;\n  end\nend\n\nfor trlop = find(opt.keep==-2 & opt.trialok==0)\n  % if the user specifies the whole trial to be rejected define the whole\n  % segment to be bad\n  artval{trlop}(:) = 1;\n  % pad the artifacts\n  artbeg = find(diff([0 artval{trlop}])== 1);\n  artend = find(diff([artval{trlop} 0])==-1);\n  artbeg = artbeg - opt.artpadding;\n  artend = artend + opt.artpadding;\n  artbeg(artbeg<1) = 1;\n  artend(artend>length(artval{trlop})) = length(artval{trlop});\n  if ~isempty(artbeg)\n    for artlop=1:length(artbeg)\n      artval{trlop}(artbeg(artlop):artend(artlop)) = 1;\n    end\n  else\n    artval{trlop}(:) = 1;\n  end\nend\n\nopt.artval = artval;\nsetappdata(h, 'opt', opt);\nuiresume;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction keyboard_cb(h, eventdata)\n\n% If a mouseclick was made, use that value. If not, determine the key that\n% corresponds to the uicontrol element that was activated.\n\nif isa(eventdata, 'matlab.ui.eventdata.ActionData') % only the case when clicked with mouse\n  curKey = get(h, 'userdata');\nelseif isa(eventdata, 'matlab.ui.eventdata.KeyData') % only when key was pressed\n  if isempty(eventdata.Character) && any(strcmp(eventdata.Key, {'control', 'shift', 'alt', '0'}))\n    % only a modifier key was pressed\n    return\n  end\n  if isempty(eventdata.Modifier)\n    curKey = eventdata.Key;\n  else\n    curKey = [sprintf('%s+', eventdata.Modifier{:}) eventdata.Key];\n  end\nelseif isfield(eventdata, 'Key')  % only when key was pressed\n  curKey = eventdata.Key;\nelseif isempty(eventdata) % matlab2012b returns an empty double upon a mouse click\n  curKey = get(h, 'userdata');\nelse\n  ft_error('cannot process user input, please report this on http://bugzilla.fieldtriptoolbox.org including your MATLAB version');\nend\n\nh = getparent(h); % otherwise h is empty if isa [...].ActionData\nopt = getappdata(h, 'opt');\n\nswitch strtrim(curKey)\n  case 'leftarrow' % change trials\n    opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n  case 'x'\n    opt.trlop = max(opt.trlop - 10, 1); % should not be smaller than 1\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n  case 'rightarrow'\n    opt.trlop = min(opt.trlop + 1, opt.numtrl); % should not be larger than the number of trials\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n  case 'c'\n    opt.trlop = min(opt.trlop + 10, opt.numtrl); % should not be larger than the number of trials\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n  case 'uparrow' % change threshold\n    opt.threshold = opt.threshold+0.5;\n    opt.updatethreshold = true;\n    setappdata(h, 'opt', opt);\n    artval_cb(h, eventdata);\n    redraw_cb(h, eventdata);\n    opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks\n    opt.updatethreshold = false;\n    setappdata(h, 'opt', opt);\n  case 'downarrow'\n    opt.threshold = opt.threshold-0.5;\n    opt.updatethreshold = true;\n    setappdata(h, 'opt', opt);\n    artval_cb(h, eventdata);\n    redraw_cb(h, eventdata);\n    opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks\n    opt.updatethreshold = false;\n    setappdata(h, 'opt', opt);\n  case 'period' % change artifact\n    artfctindx = find(opt.trialok == 0);\n    sel        = find(artfctindx>opt.trlop);\n    if ~isempty(sel)\n      opt.trlop = artfctindx(sel(1));\n    end\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n  case 'comma'\n    artfctindx = find(opt.trialok == 0);\n    sel        = find(artfctindx<opt.trlop);\n    if ~isempty(sel)\n      opt.trlop = artfctindx(sel(end));\n    end\n    setappdata(h, 'opt', opt);\n    redraw_cb(h, eventdata);\n    %   case 'control+uparrow' % change channel\n    %     if strcmp(opt.channel, 'artifact')\n    %       [dum, indx] = max(opt.zval);\n    %       chanindx      = opt.zindx(indx);\n    %     else\n    %       if ~isempty(opt.data)\n    %         chanindx  = match_str(opt.channel, opt.data.label);\n    %         selchan = match_str(opt.artcfg.channel, opt.channel);\n    %       else\n    %         chanindx  = match_str(opt.channel,   opt.hdr.label);\n    %         selchan = match_str(opt.artcfg.channel, opt.channel);\n    %       end\n    %     end\n    %     numchan = numel(opt.artcfg.channel);\n    %     chansel = min(selchan+1, numchan);\n    %     % convert numeric array into cell-array with channel labels\n    %     opt.channel = tmpchan(chansel);\n    %     setappdata(h, 'opt', opt);\n    %     redraw_cb(h, eventdata);\n    %   case 'c' % select channel\n    %     select = match_str([opt.artcfg.channel;{'artifact'}], opt.channel);\n    %     opt.channel = select_channel_list([opt.artcfg.channel;{'artifact'}], select);\n    %     setappdata(h, 'opt', opt);\n    %     redraw_cb(h, eventdata);\n    %   case 'control+downarrow'\n    %     tmpchan = [opt.artcfg.channel;{'artifact'}]; % append the 'artifact' channel\n    %     chansel = match_str(tmpchan, opt.channel);\n    %     chansel = max(chansel-1, 1);\n    %     % convert numeric array into cell-array with channel labels\n    %     opt.channel = tmpchan(chansel);\n    %     setappdata(h, 'opt', opt);\n    %     redraw_cb(h, eventdata);\n  case 'a'\n    % select the artifact to display\n    response = inputdlg(sprintf('artifact trial to display'), 'specify', 1, {num2str(opt.trlop)});\n    if ~isempty(response)\n      artfctindx = find(opt.trialok == 0);\n      sel        = str2double(response);\n      sel        = min(numel(artfctindx), sel);\n      sel        = max(1,                 sel);\n      opt.trlop  = artfctindx(sel);\n      setappdata(h, 'opt', opt);\n      redraw_cb(h, eventdata);\n    end\n  case 'q'\n    setappdata(h, 'opt', opt);\n    cleanup_cb(h);\n  case 't'\n    % select the trial to display\n    response = inputdlg(sprintf('trial to display'), 'specify', 1, {num2str(opt.trlop)});\n    if ~isempty(response)\n      opt.trlop = str2double(response);\n      opt.trlop = min(opt.trlop, opt.numtrl); % should not be larger than the number of trials\n      opt.trlop = max(opt.trlop, 1); % should not be smaller than 1\n      setappdata(h, 'opt', opt);\n      redraw_cb(h, eventdata);\n    end\n  case 'z'\n    % select the threshold\n    response = inputdlg('z-threshold', 'specify', 1, {num2str(opt.threshold)});\n    if ~isempty(response)\n      opt.threshold = str2double(response);\n      opt.updatethreshold = true;\n      setappdata(h, 'opt', opt);\n      artval_cb(h, eventdata);\n      redraw_cb(h, eventdata);\n      opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks\n      opt.updatethreshold = false;\n      setappdata(h, 'opt', opt);\n    end\n  case 'k'\n    opt.keep(opt.trlop) = 1;\n    setappdata(h, 'opt', opt);\n    artval_cb(h);\n    redraw_cb(h);\n  case 'r'\n    % only of the trial contains a partial artifact\n    if opt.trialok(opt.trlop) == 0\n      opt.keep(opt.trlop) = -1;\n    end\n    setappdata(h, 'opt', opt);\n    artval_cb(h);\n    redraw_cb(h);\n  case 'space'\n    opt.keep(opt.trlop) = -2;\n    setappdata(h, 'opt', opt);\n    artval_cb(h);\n    redraw_cb(h);\n  case 'control+control'\n    % do nothing\n  case 'shift+shift'\n    % do nothing\n  case 'alt+alt'\n    % do nothing\n  otherwise\n    setappdata(h, 'opt', opt);\n    % this should be consistent with the help of the function\n    fprintf('----------------------------------------------------------------------\\n');\n    fprintf('     q                 : Stop\\n');\n    fprintf('\\n');\n    fprintf('     comma             : Step to the previous artifact trial\\n');\n    fprintf('     a                 : Specify artifact trial to display\\n');\n    fprintf('     period            : Step to the next artifact trial\\n');\n    fprintf('\\n');\n    fprintf('     x                 : Step 10 trials back\\n');\n    fprintf('     leftarrow         : Step to the previous trial\\n');\n    fprintf('     t                 : Specify trial to display\\n');\n    fprintf('     rightarrow        : Step to the next trial\\n');\n    fprintf('     c                 : Step 10 trials forward\\n');\n    fprintf('\\n');\n    fprintf('     k                 : Keep trial\\n');\n    fprintf('     space             : Mark complete trial as artifact\\n');\n    fprintf('     r                 : Mark part of trial as artifact\\n');\n    fprintf('\\n');\n    fprintf('     downarrow         : Shift the z-threshold down\\n');\n    fprintf('     z                 : Specify the z-threshold\\n');\n    fprintf('     uparrow           : Shift the z-threshold down\\n');\n    fprintf('----------------------------------------------------------------------\\n');\nend\nclear curKey;\nuiresume(h);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction redraw_cb(h, eventdata)\n\nh   = getparent(h);\nopt = getappdata(h, 'opt');\n\n% make a local copy of the relevant variables\ntrlop     = opt.trlop;\nartval    = opt.artval{trlop};\nzindx     = opt.zindx{trlop};\nzval      = opt.zval{trlop};\ncfg       = opt.cfg;\nartcfg    = opt.artcfg;\nhdr       = opt.hdr;\ntrl       = opt.trl;\ntrlpadsmp = round(artcfg.trlpadding*hdr.Fs);\nchannel   = opt.channel;\n\n% determine the channel with the highest z-value to be displayed\n% this is default behavior but can be overruled in the gui\nif strcmp(channel, 'artifact')\n  [dum, indx] = max(zval);\n  chanindx      = zindx(indx);\nelse\n  if ~isempty(opt.data)\n    chanindx = match_str(channel, opt.data.label);\n  else\n    chanindx = match_str(channel, hdr.label);\n  end\nend\n\nif ~isempty(opt.data)\n  data = ft_fetch_data(opt.data, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'));\nelse\n  data = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'));\nend\n\n% data = preproc(data, '', hdr.Fs, artcfg, [], artcfg.fltpadding, artcfg.fltpadding);\n\n% the string us used as title and printed in the command window\nstr = sprintf('trial %3d of %d, channel %s', trlop, size(trl,1), hdr.label{chanindx});\nfprintf('showing %s\\n', str);\n\n%-----------------------------\n% plot summary in left subplot\nsubplot(opt.h1); hold on;\n\n% plot as a blue line only once\nif isempty(get(opt.h1, 'children'))\n  for k = 1:opt.numtrl\n    xval = opt.trl(k,1):opt.trl(k,2);\n    if opt.thresholdsum\n      yval = opt.zsum{k};\n    else\n      yval = opt.zmax{k};\n    end\n    plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'b', 'displayname', 'data');\n    xlabel('samples');\n    ylabel('z-value');\n  end\nend\nh1children = get(opt.h1, 'children');\n\n% plot trial box\nboxhandle = findall(h1children, 'displayname', 'highlight');\nif isempty(boxhandle)\n  % draw it\n  xval = trl(opt.trlop,1):trl(opt.trlop,2);\n  if opt.thresholdsum\n    yval = opt.zsum{opt.trlop};\n  else\n    yval = opt.zmax{opt.trlop};\n  end\n  plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'm', 'linewidth', 2, 'displayname', 'highlight');\nelse\n  % update it\n  xval = trl(opt.trlop,1):trl(opt.trlop,2);\n  if opt.thresholdsum\n    yval = opt.zsum{opt.trlop};\n  else\n    yval = opt.zmax{opt.trlop};\n  end\n  set(boxhandle,  'XData', xval);\n  set(boxhandle,  'YData', yval);\nend\n\n% plot as red lines the suprathreshold data points\nthrhandle = findall(h1children, 'displayname', 'reddata');\nif isempty(thrhandle)\n  % they have to be drawn\n  for k = 1:opt.numtrl\n    xval = trl(k,1):trl(k,2);\n    if opt.thresholdsum\n      yval = opt.zsum{k};\n    else\n      yval = opt.zmax{k};\n    end\n    dum = yval<=opt.threshold;\n    yval(dum) = nan;\n    plot(opt.h1, xval, yval, 'linestyle', '-', 'color', [1 0 0], 'displayname', 'reddata');\n  end\n  hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline');\nelseif ~isempty(thrhandle) && opt.updatethreshold\n  % they can be updated\n  for k = 1:opt.numtrl\n    xval = trl(k,1):trl(k,2);\n    if opt.thresholdsum\n      yval = opt.zsum{k};\n    else\n      yval = opt.zmax{k};\n    end\n    dum = yval<=opt.threshold;\n    yval(dum) = nan;\n    set(thrhandle(k), 'XData', xval);\n    set(thrhandle(k), 'YData', yval);\n  end\n  set(findall(h1children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold);\nend\n\n%--------------------------------------------------\n% get trial specific x-axis values and padding info\nxval = ((trl(opt.trlop,1):trl(opt.trlop,2))-trl(opt.trlop,1)+trl(opt.trlop,3))./opt.hdr.Fs;\nif trlpadsmp>0\n  sel    = trlpadsmp:(size(data,2)-trlpadsmp);\n  selpad = 1:size(data,2);\nelse\n  sel    = 1:size(data,2);\n  selpad = sel;\nend\n\n% plot data of most aberrant channel in upper subplot\nsubplot(opt.h2); hold on\nif isempty(get(opt.h2, 'children'))\n  % do the plotting\n  plot(xval(selpad), data(selpad),          'color', [0.5 0.5 1], 'displayname', 'line1');\n  plot(xval(sel),    data(sel),             'color', [0 0 1],     'displayname', 'line2');\n  vline(xval(  1)+(trlpadsmp-1/opt.hdr.Fs), 'color', [0 0 0],     'displayname', 'vline1');\n  vline(xval(end)-(trlpadsmp/opt.hdr.Fs),   'color', [0 0 0],     'displayname', 'vline2');\n  data(~artval) = nan;\n  plot(xval, data, 'r-', 'displayname', 'line3');\n  xlabel('time(s)');\n  ylabel('uV or Tesla');\n  xlim([xval(1) xval(end)]);\n  title(str);\nelse\n  % update in the existing handles\n  h2children = get(opt.h2, 'children');\n  set(findall(h2children, 'displayname', 'vline1'), 'visible', 'off');\n  set(findall(h2children, 'displayname', 'vline2'), 'visible', 'off');\n  set(findall(h2children, 'displayname', 'line1'), 'XData', xval(selpad));\n  set(findall(h2children, 'displayname', 'line1'), 'YData', data(selpad));\n  set(findall(h2children, 'displayname', 'line2'), 'XData', xval(sel));\n  set(findall(h2children, 'displayname', 'line2'), 'YData', data(sel));\n  data(~artval) = nan;\n  set(findall(h2children, 'displayname', 'line3'),  'XData', xval);\n  set(findall(h2children, 'displayname', 'line3'),  'YData', data);\n  abc2 = axis(opt.h2);\n  set(findall(h2children, 'displayname', 'vline1'), 'XData', [1 1]*xval(  1)+(trlpadsmp-1/opt.hdr.Fs));\n  set(findall(h2children, 'displayname', 'vline1'), 'YData', abc2(3:4));\n  set(findall(h2children, 'displayname', 'vline2'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs));\n  set(findall(h2children, 'displayname', 'vline2'), 'YData', abc2(3:4));\n  set(findall(h2children, 'displayname', 'vline1'), 'visible', 'on');\n  set(findall(h2children, 'displayname', 'vline2'), 'visible', 'on');\n  str = sprintf('trial %3d, channel %s', opt.trlop, hdr.label{chanindx});\n  title(str);\n  xlim([xval(1) xval(end)]);\nend\n\n% plot z-values in lower subplot\nsubplot(opt.h3); hold on;\nif isempty(get(opt.h3, 'children'))\n  % do the plotting\n  plot(xval(selpad), zval(selpad), 'color', [0.5 0.5 1], 'displayname', 'line1b');\n  plot(xval(sel),    zval(sel),    'color', [0 0 1],     'displayname', 'line2b');\n  hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline');\n  vline(xval(  1)+(trlpadsmp-1/opt.hdr.Fs),     'color', [0 0 0],     'displayname', 'vline1b');\n  vline(xval(end)-(trlpadsmp/opt.hdr.Fs),       'color', [0 0 0],     'displayname', 'vline2b');\n  zval(~artval) = nan;\n  plot(xval, zval, 'r-', 'displayname', 'line3b');\n  xlabel('time(s)');\n  ylabel('z-value');\n  xlim([xval(1) xval(end)]);\nelse\n  % update in the existing handles\n  h3children = get(opt.h3, 'children');\n  set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'off');\n  set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'off');\n  set(findall(h3children, 'displayname', 'line1b'), 'XData', xval(selpad));\n  set(findall(h3children, 'displayname', 'line1b'), 'YData', zval(selpad));\n  set(findall(h3children, 'displayname', 'line2b'), 'XData', xval(sel));\n  set(findall(h3children, 'displayname', 'line2b'), 'YData', zval(sel));\n  zval(~artval) = nan;\n  set(findall(h3children, 'displayname', 'line3b'),     'XData', xval);\n  set(findall(h3children, 'displayname', 'line3b'),     'YData', zval);\n  set(findall(h3children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold);\n  set(findall(h3children, 'displayname', 'threshline'), 'XData', xval([1 end]));\n  abc = axis(opt.h3);\n  set(findall(h3children, 'displayname', 'vline1b'), 'XData', [1 1]*xval(  1)+(trlpadsmp-1/opt.hdr.Fs));\n  set(findall(h3children, 'displayname', 'vline1b'), 'YData', abc(3:4));\n  set(findall(h3children, 'displayname', 'vline2b'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs));\n  set(findall(h3children, 'displayname', 'vline2b'), 'YData', abc(3:4));\n  set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'on');\n  set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'on');\n  xlim([xval(1) xval(end)]);\nend\n\nsetappdata(h, 'opt', opt);\nuiresume\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cleanup_cb(h, eventdata)\nopt = getappdata(h, 'opt');\nopt.quit = true;\nsetappdata(h, 'opt', opt);\nuiresume\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction h = getparent(h)\np = h;\nwhile p~=0\n  h = p;\n  p = get(h, 'parent');\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_artifact_zvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.24163472009736578}}
{"text": "function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding)\n%CROP_BORDERS Crop the borders of an image or stack of images\n%\n%   [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])\n%\n%IN:\n%   A - HxWxCxN stack of images.\n%   bcol - Cx1 background colour vector.\n%   padding - scalar indicating how much padding to have in relation to\n%             the cropped-image-size (0<=padding<=1). Default: 0\n%\n%OUT:\n%   B - JxKxCxN cropped stack of images.\n%   vA     - coordinates in A that contain the cropped image\n%   vB     - coordinates in B where the cropped version of A is placed\n%   bb_rel - relative bounding box (used for eps-cropping)\n\n% 06/03/15: Improved image cropping thanks to Oscar Hartogensis\n% 08/06/15: Fixed issue #76: case of transparent figure bgcolor\n\n    if nargin < 3\n        padding = 0;\n    end\n    [h, w, c, n] = size(A);\n    if isempty(bcol)  % case of transparent bgcolor\n        bcol = A(ceil(end/2),1,:,1);\n    end\n    if isscalar(bcol)\n        bcol = bcol(ones(c, 1));\n    end\n\n    % Crop margin from left\n    bail = false;\n    for l = 1:w\n        for a = 1:c\n            if ~all(col(A(:,l,a,:)) == bcol(a))\n                bail = true;\n                break;\n            end\n        end\n        if bail\n            break;\n        end\n    end\n\n    % Crop margin from right\n    bcol = A(ceil(end/2),w,:,1);\n    bail = false;\n    for r = w:-1:l\n        for a = 1:c\n            if ~all(col(A(:,r,a,:)) == bcol(a))\n                bail = true;\n                break;\n            end\n        end\n        if bail\n            break;\n        end\n    end\n\n    % Crop margin from top\n    bcol = A(1,ceil(end/2),:,1);\n    bail = false;\n    for t = 1:h\n        for a = 1:c\n            if ~all(col(A(t,:,a,:)) == bcol(a))\n                bail = true;\n                break;\n            end\n        end\n        if bail\n            break;\n        end\n    end\n\n    % Crop margin from bottom\n    bcol = A(h,ceil(end/2),:,1);\n    bail = false;\n    for b = h:-1:t\n        for a = 1:c\n            if ~all(col(A(b,:,a,:)) == bcol(a))\n                bail = true;\n                break;\n            end\n        end\n        if bail\n            break;\n        end\n    end\n\n    % Crop the background, leaving one boundary pixel to avoid bleeding on resize\n    %v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];\n    %A = A(v(1):v(2),v(3):v(4),:,:);\n    if padding == 0  % no padding\n        padding = 1;\n    elseif abs(padding) < 1  % pad value is a relative fraction of image size\n        padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING\n    else  % pad value is in units of 1/72\" points\n        padding = round(padding);  % fix cases of non-integer pad value\n    end\n\n    if padding > 0  % extra padding\n        % Create an empty image, containing the background color, that has the\n        % cropped image size plus the padded border\n        B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2);\n        % vA - coordinates in A that contain the cropped image\n        vA = [t b l r];\n        % vB - coordinates in B where the cropped version of A will be placed\n        vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];\n        % Place the original image in the empty image\n        B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :);\n        A = B;\n    else  % extra cropping\n        vA = [t-padding b+padding l-padding r+padding];\n        A = A(vA(1):vA(2), vA(3):vA(4), :);\n        vB = [NaN NaN NaN NaN];\n    end\n\n    % For EPS cropping, determine the relative BoundingBox - bb_rel\n    bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];\nend\n\nfunction A = col(A)\n    A = A(:);\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/extern/export_fig/crop_borders.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24152627893750808}}
{"text": "function r = mldivide(p,q)\n%MLDIVIDE     Implements  p \\ q  for univariate polynomials (same as q/p)\n%\n\n% written  11/02/05     S.M. Rump\n%\n\n  r = q / p;\n  ", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/polynom/@polynom/mldivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24152627893750808}}
{"text": "function output = apply_net_filter(input_v, input_h)\n    global config mem;    \n    input_size = size(input_v);\n    %output = config.NEW_MEM(zeros(size(input_v, 1), size(input_v, 2), config.chs, config.batch_size));\n    output = zeros(size(input_v, 1), size(input_v, 2), config.chs, config.batch_size);\n    p_size = config.MEM.p_size;\n    size_differ = config.size_differ;\n    %count = config.NEW_MEM(zeros(size(input_v, 1), size(input_v, 2)));\n    count = zeros(size(input_v, 1), size(input_v, 2));\n    for v = 1 : length(config.MEM.start_rows)\n        for h = 1 : length(config.MEM.start_cols)\n            v_start = config.MEM.start_rows(v);\n            v_end = v_start + p_size - 1;\n            h_start = config.MEM.start_cols(h);\n            h_end = h_start + p_size - 1;\n            if(v_end > input_size(1))\n                v_end = input_size(1);\n                v_start = v_end - p_size + 1;\n            end\n            if(h_end > input_size(2))\n                h_end = input_size(2);\n                h_start = h_end - p_size + 1;\n            end\n            input_piece = cat(4, input_v(v_start:v_end, h_start:h_end,:), permute(input_h(v_start:v_end, h_start:h_end,:), [2 1 3]));\n\n            op_test_pipe(input_piece, mem.fake_output_for_test);\n            %output_piece = mem.output;\n            output_piece = gather(mem.output);\n            if(size_differ(1) ~= size_differ(2))\n                output_piece = output_piece(size_differ(2)/2+1:size(output_piece,1)-size_differ(2)/2, size_differ(1)/2+1:size(output_piece,2)-size_differ(1)/2,:,:);\n            end\n            output_piece(:,:,:,2) = permute(output_piece(:,:,:,2), [2 1 3]);\n\n            output(v_start+(max(size_differ)/2):v_end-(max(size_differ)/2), h_start+(max(size_differ)/2):h_end-(max(size_differ)/2),:,:) = ...\n                    output(v_start+(max(size_differ)/2):v_end-(max(size_differ)/2), h_start+(max(size_differ)/2):h_end-(max(size_differ)/2),:,:) + output_piece;\n            count(v_start+(max(size_differ)/2):v_end-(max(size_differ)/2), h_start+(max(size_differ)/2):h_end-(max(size_differ)/2)) = ...\n                    count(v_start+(max(size_differ)/2):v_end-(max(size_differ)/2), h_start+(max(size_differ)/2):h_end-(max(size_differ)/2)) + 1;\n        end\n    end\n    count = max(count, 1);\n    output = bsxfun(@rdivide, output, count);\n    %output = gather(output);\n    \n    %output = output_piece;\n    %output = padarray(output, [1 1]);\nend\n\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/applications/deep_edge_aware_filters/utility/apply_net_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24152627893750808}}
{"text": "function varargout = process_cohere2_time_2021( varargin )\n% PROCESS_COHERE2_TIME_2021: Compute the time-resolved coherence between all the pairs of signals, in one file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Elizabeth Bock, 2015\n%          Francois Tadel, 2015-2021\n%          Hossein Shahabi, 2019-2020\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'Time-resolved coherence AxB [2021]';\n    sProcess.Category    = 'Custom';\n    sProcess.SubGroup    = 'Connectivity';\n    sProcess.Index       = 660;\n    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Connectivity';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data',     'results',  'matrix'};\n    sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq'};\n    sProcess.nInputs     = 2;\n    sProcess.nMinFiles   = 1;\n    sProcess.isPaired    = 1;\n\n    % === CONNECT INPUT\n    sProcess = process_corr2('DefineConnectOptions', sProcess);\n    % === REMOVE EVOKED REPONSE\n    sProcess.options.removeevoked.Comment = 'Remove evoked response from each trial';\n    sProcess.options.removeevoked.Type    = 'checkbox';\n    sProcess.options.removeevoked.Value   = 0;\n    sProcess.options.removeevoked.Group   = 'input';\n    % === Time window\n    sProcess.options.slide_win.Comment = 'Sliding time window duration:';\n    sProcess.options.slide_win.Type    = 'value';\n    sProcess.options.slide_win.Value   = {.350, 'ms', []};\n    % === WinOverlap for Sliding window (Time)\n    sProcess.options.slide_overlap.Comment = 'Sliding window overlap:';\n    sProcess.options.slide_overlap.Type    = 'value';\n    sProcess.options.slide_overlap.Value   = {50, '%', []};\n    % === COHERENCE METHOD\n    sProcess.options.cohmeasure.Comment = {...\n        ['<B>Magnitude-squared Coherence</B><BR>' ...\n        '|C|^2 = |Gxy|^2/(Gxx*Gyy)'], ...\n        ['<B>Imaginary Coherence (2019)</B><BR>' ...\n        'IC    = |imag(C)|'], ...\n        ['<B>Lagged Coherence (2019)</B><BR>' ...\n        'LC    = |imag(C)|/sqrt(1-real(C)^2)'], ...\n        ['<FONT color=\"#777777\"> Imaginary Coherence (before 2019)</FONT><BR>' ...\n        '<FONT color=\"#777777\"> IC    = imag(C)^2 / (1-real(C)^2) </FONT>']; ...\n        'mscohere', 'icohere2019','lcohere2019', 'icohere'};\n    sProcess.options.cohmeasure.Type    = 'radio_label';\n    sProcess.options.cohmeasure.Value   = 'mscohere';\n    % === WINDOW LENGTH\n    sProcess.options.win_length.Comment = 'Window length for PSD estimation:';\n    sProcess.options.win_length.Type    = 'value';\n    sProcess.options.win_length.Value   = {1, 's', []};\n    % === OVERLAP\n    sProcess.options.overlap.Comment = 'WinOverlap for PSD estimation:' ;\n    sProcess.options.overlap.Type    = 'value';\n    sProcess.options.overlap.Value   = {50, '%', []};\n    % === HIGHEST FREQUENCY OF INTEREST\n    sProcess.options.maxfreq.Comment = 'Highest frequency of interest:';\n    sProcess.options.maxfreq.Type    = 'value';\n    sProcess.options.maxfreq.Value   = {60,'Hz',2};\n    % === OUTPUT FILE TAG\n    sProcess.options.commenttag.Comment = 'File tag: ';\n    sProcess.options.commenttag.Type    = 'text';\n    sProcess.options.commenttag.Value   = '';\n    sProcess.options.commenttag.Group   = 'output';\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n    Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputA, sInputB) %#ok<DEFNU>\n    % Initialize returned values\n    OutputFiles = {};\n    % Output mode 2021: Forcing the average cross-spectra of input files (one output file)\n    sProcess.options.outputmode.Value = 'avgcoh';\n    % Input options\n    OPTIONS = process_corr2('GetConnectOptions', sProcess, sInputA, sInputB);\n    if isempty(OPTIONS)\n        return\n    end\n    CommentTag = sProcess.options.commenttag.Value;\n    % Metric options\n    OPTIONS.Method = 'cohere';\n    OPTIONS.RemoveEvoked  = sProcess.options.removeevoked.Value;\n    OPTIONS.WinLen        = sProcess.options.win_length.Value{1};\n    OPTIONS.MaxFreq       = sProcess.options.maxfreq.Value{1};\n    OPTIONS.CohOverlap    = 0.50;\n    OPTIONS.pThresh       = 0.05;\n    OPTIONS.isSave        = 0;\n    OPTIONS.CohMeasure    = sProcess.options.cohmeasure.Value;\n    % Sliding time windows options\n    WinLength  = sProcess.options.slide_win.Value{1};\n    WinOverlap = sProcess.options.slide_overlap.Value{1};\n    \n    % Read time information\n    TimeVectorA  = in_bst(sInputA(1).FileName, 'Time');\n    sfreq        = round(1/(TimeVectorA(2) - TimeVectorA(1)));\n    % Get time window of first fileA if none specified in parameters\n    if isempty(OPTIONS.TimeWindow)\n        OPTIONS.TimeWindow = TimeVectorA([1, end]);\n    end\n    % Select input time window\n    TimeVectorA = TimeVectorA((TimeVectorA >= OPTIONS.TimeWindow(1)) & (TimeVectorA <= OPTIONS.TimeWindow(2)));\n    nTime       = length(TimeVectorA);\n\n    % Compute sliding windows length\n    Lwin  = round(WinLength * sfreq);\n    Loverlap = round(Lwin * WinOverlap / 100);\n    Nwin = floor((nTime - Loverlap) ./ (Lwin - Loverlap));\n    % If window is bigger than the data\n    if (Lwin > nTime)\n        bst_report('Error', sProcess, sInputA, 'Sliding window for the coherence estimation is too long compared with the epochs in input.');\n        return;\n    end\n\n    % Check that time is the same for FilesB\n    if ~isempty(sInputB)\n        TimeVectorB = in_bst(sInputB(1).FileName, 'Time');\n        if (length(TimeVectorA) ~= length(TimeVectorB))\n            bst_report('Error', sProcess, sInputA, 'Files A and B must share the same time vector.');\n            return;\n        end\n    end\n\n    % Get progress bar position\n    posProgress = bst_progress('get');\n    % Loop over all the time windows\n    for iWin = 1:Nwin\n        % Set the progress bar at the same level at every iteration\n        bst_progress('set', posProgress);\n        % Select time window\n        iTimes = (1:Lwin) + (iWin-1)*(Lwin - Loverlap);\n        OPTIONS.TimeWindow = TimeVectorA(iTimes([1,end]));\n        % Compute metric\n        if ~isempty(sInputB)\n            ConnectMat = bst_connectivity({sInputA.FileName}, {sInputB.FileName}, OPTIONS);\n        else\n            ConnectMat = bst_connectivity({sInputA.FileName}, [], OPTIONS);\n        end\n        % Processing errors\n        if isempty(ConnectMat) || ~iscell(ConnectMat) || ~isstruct(ConnectMat{1}) || isempty(ConnectMat{1}.TF)\n            bst_report('Error', sProcess, sInputA, 'Coherence for the selected time segment could not be calculated.');\n            return;\n        end\n        % Start a new brainstorm structure\n        if (iWin == 1)\n            NewMat = ConnectMat{1};\n            NewMat.Time = OPTIONS.TimeWindow(1);             \n            NewMat.TimeBands = [];\n        % Add next time point\n        else\n            NewMat.TF(:,iWin,:) = ConnectMat{1}.TF;\n            NewMat.Time(end+1) = OPTIONS.TimeWindow(1);\n        end\n    end\n    \n    % Fix time vector\n    if (length(NewMat.Time) == 1)\n        bst_report('Warning', sProcess, sInputA, 'Only one sliding time window could be estimated.');\n        NewMat.Time = [TimeVectorA(1), TimeVectorA(end)];\n    end\n    % Add comment tag\n    if ~isempty(CommentTag)\n        NewMat.Comment = [NewMat.Comment ' | ' CommentTag];\n    end\n    % File tag\n    if (length(NewMat.RefRowNames) == 1)\n        fileTag = 'connect1';\n    else\n        fileTag = 'connectn';\n    end\n    % Output filename\n    sOutputStudy = bst_get('Study', OPTIONS.iOutputStudy);\n    OutputFiles{1} = bst_process('GetNewFilename', bst_fileparts(sOutputStudy.FileName), ['timefreq_' fileTag '_cohere_time']);\n    % Save file\n    bst_save(OutputFiles{1}, NewMat, 'v6');\n    % Add file to database structure\n    db_add_data(OPTIONS.iOutputStudy, OutputFiles{1}, NewMat);\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_cohere2_time_2021.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24152627893750808}}
{"text": "function rgb = skull\n\n% This returns a predefined color as [red green blue] values\n%   red               = [255   0   0]/255;\n%   green             = [  0 192   0]/255;\n%   blue              = [  0   0 255]/255;\n%   magenta           = [255 255   0]/255;\n%   cyan              = [  0 255 255]/255;\n%   yellow            = [255 255   0]/255;\n%   white             = [255 255 255]/255;\n%   black             = [  0   0   0]/255;\n%\n%   skull             = [140  85  85]/255\n%   cortex            = [255 213 119]/255;\n%   cortex_light      = [199 194 169]/255;\n%   cortex_dark       = [100  97  85]/255;\n%   skin              = [249 223 192]/255;\n%   skin_light        = [249 223 192]/255;\n%   skin_medium_light = [225 194 158]/255;\n%   skin_medium       = [188 142 106]/255;\n%   skin_medium_dark  = [155 102\t65]/255;\n%   skin_dark         = [ 91  71  61]/255;\n\nrgb = [140 85 85]/255;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/skull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2414589830372118}}
{"text": "function results = eco_vot_deep(seq, res_path, bSaveImage, parameters)\n\t \t \t \nparams.use_gpu = false;\nparams.gpu_id = 1;\n\n% Feature specific parameters\n% hog_params.cell_size = 4;\n% hog_params.compressed_dim = 10;\n\n% grayscale_params.colorspace='gray';\n% grayscale_params.cell_size = 1;\n\n% cn_params.tablename = 'CNnorm';\n% cn_params.useForGray = false;\n% cn_params.cell_size = 4;\n% cn_params.compressed_dim = 3;\n% \n% ic_params.tablename = 'intensityChannelNorm6';\n% ic_params.useForColor = false;\n% ic_params.cell_size = 4;\n% ic_params.compressed_dim = 3;\n\n% cnn_params.nn_name = 'imagenet-vgg-m-2048_new.mat'; % Name of the network\ncnn_params.nn_name = 'UDT_Unsupervised.mat';\n\ncnn_params.output_layer = [4];               % Which layers to use\ncnn_params.downsample_factor = [4];           % How much to downsample each output layer\ncnn_params.compressed_dim = [32];            % Compressed dimensionality of each output layer\ncnn_params.input_size_mode = 'adaptive';        % How to choose the sample size\ncnn_params.input_size_scale = 1;    \n\n% Which features to include\nparams.t_features = {\n    struct('getFeature',@get_cnn_layers, 'fparams',cnn_params),...\n    ...struct('getFeature',@get_colorspace, 'fparams',grayscale_params),...\n    ...struct('getFeature',@get_fhog,'fparams',hog_params),...\n    ...struct('getFeature',@get_table_feature, 'fparams',cn_params),...\n    ...struct('getFeature',@get_table_feature, 'fparams',ic_params),...\n};\n\n% Global feature parameters1s\nparams.t_global.normalize_power = 2;    % Lp normalization with this p\nparams.t_global.normalize_size = true;  % Also normalize with respect to the spatial size of the feature\nparams.t_global.normalize_dim = true;   % Also normalize with respect to the dimensionality of the feature\n\n% Image sample parameters\nparams.search_area_shape = 'square';    % The shape of the samples\nparams.search_area_scale = 4.0;         % The scaling of the target size to get the search area\nparams.min_image_sample_size = 200^2;   % Minimum area of image samples\nparams.max_image_sample_size = 250^2;   % Maximum area of image samples\n\n% Detection parameters\nparams.refinement_iterations = 1;       % Number of iterations used to refine the resulting position in a frame\nparams.newton_iterations = 5;           % The number of Newton iterations used for optimizing the detection score\nparams.clamp_position = false;          % Clamp the target position to be inside the image\n\n% Learning parameters\nparams.output_sigma_factor = 1/12;\t\t% Label function sigma\nparams.learning_rate = 0.011;\t \t    % Learning rate\nparams.nSamples = 50;                   % Maximum number of stored training samples\nparams.sample_replace_strategy = 'lowest_prior';    % Which sample to replace when the memory is full\nparams.lt_size = 0;                     % The size of the long-term memory (where all samples have equal weight)\nparams.train_gap = 5;                   % The number of intermediate frames with no training (0 corresponds to training every frame)\nparams.skip_after_frame = 10;           % After which frame number the sparse update scheme should start (1 is directly)\nparams.use_detection_sample = true;     % Use the sample that was extracted at the detection stage also for learning\n\n% Factorized convolution parameters\nparams.use_projection_matrix = true;    % Use projection matrix, i.e. use the factorized convolution formulation\nparams.update_projection_matrix = true; % Whether the projection matrix should be optimized or not\nparams.proj_init_method = 'pca';        % Method for initializing the projection matrix\nparams.projection_reg = 2e-7;           % Regularization paremeter of the projection matrix\n\n% Generative sample space model parameters\nparams.use_sample_merge = true;                 % Use the generative sample space model to merge samples\nparams.sample_merge_type = 'Merge';        % Strategy for updating the samples\nparams.distance_matrix_update_type = 'exact';  % Strategy for updating the distance matrix\nparams.neglect_higher_frequency = false;        % Neglect hiigher frequency components in the distance comparison for speed\n\n% Conjugate Gradient parameters\nparams.CG_iter = 5;                     % The number of Conjugate Gradient iterations in each update after the first frame\nparams.init_CG_iter = 10*20;            % The total number of Conjugate Gradient iterations used in the first frame\nparams.init_GN_iter = 10;               % The number of Gauss-Newton iterations used in the first frame (only if the projection matrix is updated)\nparams.CG_use_FR = false;               % Use the Fletcher-Reeves (true) or Polak-Ribiere (false) formula in the Conjugate Gradient\nparams.CG_standard_alpha = true;        % Use the standard formula for computing the step length in Conjugate Gradient\nparams.CG_forgetting_rate = 60;\t \t \t% Forgetting rate of the last conjugate direction\nparams.precond_data_param = 0.75;\t \t% Weight of the data term in the preconditioner\t \nparams.precond_reg_param = 0.2;\t \t    % Weight of the regularization term in the preconditioner  \t \nparams.precond_proj_param = 40;         % Weight of the projection matrix part in the preconditioner\n\n% Regularization window parameters\nparams.use_reg_window = true;           % Use spatial regularization or not\nparams.reg_window_min = 1e-4;\t\t\t% The minimum value of the regularization window\nparams.reg_window_edge = 10e-3;         % The impact of the spatial regularization\nparams.reg_window_power = 2;            % The degree of the polynomial to use (e.g. 2 is a quadratic window)\nparams.reg_sparsity_threshold = 0.15;   % A relative threshold of which DFT coefficients that should be set to zero\n\n% Interpolation parameters\nparams.interpolation_method = 'bicubic';    % The kind of interpolation kernel\nparams.interpolation_bicubic_a = -0.75;     % The parameter for the bicubic interpolation kernel\nparams.interpolation_centering = true;      % Center the kernel at the feature sample\nparams.interpolation_windowing = false;     % Do additional windowing on the Fourier coefficients of the kernel\n\n% Scale parameters for the translation model\n% Only used if: params.use_scale_filter = false\n\n% params.number_of_scales = 3;            % Number of scales to run the detector\n% params.scale_step = 1.02;               % The scale factor\n\n% Scale filter parameters\n% Only used if: params.use_scale_filter = true\nparams.use_scale_filter = true;        % Use the fDSST scale filter or not (for speed)\nparams.scale_sigma_factor = 1/16;       % Scale label function sigma\nparams.scale_learning_rate = 0.025;\t\t% Scale filter learning rate\nparams.number_of_scales_filter = 17;    % Number of scales\nparams.number_of_interp_scales = 33;    % Number of interpolated scales\nparams.scale_model_factor = 1.0;        % Scaling of the scale model\nparams.scale_step_filter = 1.02;        % The scale factor for the scale filter\nparams.scale_model_max_area = 32*16;    % Maximume area for the scale sample patch\nparams.scale_feature = 'HOG4';          % Features for the scale filter (only HOG4 supported)\nparams.s_num_compressed_dim = 'MAX';    % Number of compressed feature dimensions in the scale filter\nparams.lambda = 1e-2;\t\t\t\t\t% Scale filter regularization\nparams.do_poly_interp = true;           % Do 2nd order polynomial interpolation to obtain more accurate scale\n               \n% Other parameters\nparams.visualization = 0;               % Visualiza tracking and detection scores\nparams.debug = 0;                       % Do full debug visualization\n\n% Initialize\nparams.seq = seq;\n\n% Run tracker\nresults = tracker(params);\n", "meta": {"author": "594422814", "repo": "UDT", "sha": "0f2fe0b302cbe3b691b0e3aab21465c03377d935", "save_path": "github-repos/MATLAB/594422814-UDT", "path": "github-repos/MATLAB/594422814-UDT/UDT-0f2fe0b302cbe3b691b0e3aab21465c03377d935/tracker/UDT+/eco_vot_deep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2414589773369685}}
{"text": "% greBasedSegment.m\n%\n% APA, 3/20/2017\n\n% directory containing all files\ndirName = 'H:\\Public\\Aditya\\mimExtensions\\CERR_files_Sandra_contours_PC';\ndirName = 'H:\\Public\\Aditya\\mimExtensions\\CERR_files_Sandra_contours_CT';\ndirName = 'H:\\Public\\Aditya\\mimExtensions\\Atlas_Sanne\\PC_cerr';\n% dirName = 'H:\\Public\\Aditya\\mimExtensions\\Atlas_Sanne\\CT_cropped_cerr';\n\n% directory for writing the registered files (must have \\ or / as last character)\nregisteredDir = 'H:\\Public\\Aditya\\mimExtensions\\registered_to_ROBINSON^HEATH_35487047\\';\nregisteredDir = 'H:\\Public\\Aditya\\mimExtensions\\registered_to_ROBINSON^HEATH_35487047_CT\\';\nregisteredDir = 'H:\\Public\\Aditya\\mimExtensions\\registered_to_MT160_PC\\';\n% registeredDir = 'H:\\Public\\Aditya\\mimExtensions\\registered_to_MT160_CT\\';\n\ndirS = dir(dirName);\ndirS(1:2) = [];\n\n% base scan file name\nindBase = 3; %9 for Sandra's atlas, 3 for Sanne's \nbaseScan = fullfile(dirName,dirS(indBase).name);\n\n% moving scan file names\nindV = 1:length(dirS);\nindV(indBase) = [];\nmovScanC = fullfile(dirName,{dirS(indV).name});\n\n% registration callback\nstrNameToWarp = 'Parotid_L_SvD';\nregisterToAtlas(baseScan,movScanC,registeredDir,strNameToWarp)\n\n\n% combine using the STAPLE and the GRE metric\nregDirS = dir(registeredDir);\nregDirS(1:2) = [];\nregFilesC = strcat(registeredDir,{regDirS.name});\nindBase = [3];\nregFilesC(indBase) = [];\nstructNum = 2;\ndoseNum = 1;\nscanNum = 1;\ndoseAllM = [];\nstrAllM = logical([]);\nfor i = 1:length(regFilesC)\n    planC = loadPlanC(regFilesC{i},tempdir);\n    indexS = planC{end};    \n    % Calculate the GRE metric\n    baseScanNum = 1;\n    movScanNum = 2;\n    planC = calculateGRE(baseScanNum,movScanNum,planC);\n    dose3M = getDoseOnCT(doseNum, scanNum, 'uniform', planC);\n    str3M = getUniformStr(structNum,planC);\n    strAllM(:,i) = str3M(:);\n    doseAllM(:,i) = dose3M(:) .* str3M(:);\nend\n\nsiz = size(str3M);\n\n% STAPLE\nnumIter = 50;\nconfidence = 0.8;\nnumObservers = size(strAllM,2);\np = ones(1,numObservers)*0.999;\nq = p;\n[W,p,q] = staple(strAllM,confidence,p,q);\nstapleStr3M = reshape(W > confidence,siz);\nisUniform = 1;\nscanNum = 1;\nmaskToCERRStructure(stapleStr3M,isUniform,scanNum,'STAPLE_80_pct_conf')\n\n\n% Smooth contour\nstructNum = 2;\nfor slc = 1:length(planC{indexS.structures}(structNum).contour)\n    for seg = 1:length(planC{indexS.structures}(structNum).contour(slc).segments)\n        ptsM = planC{indexS.structures}(structNum).contour(slc).segments(seg).points;\n        if isempty(ptsM)\n            continue;\n        end\n        numPts = size(ptsM,1);\n        intrvl = ceil(numPts*0.2/10);\n        pts1M = spcrv(ptsM(1:intrvl:end,1:2)',3,100)';\n        pts1M(:,3) = ptsM(1,3)*pts1M(:,1).^0;\n        pts1M(end+1,:) = pts1M(1,:);\n        planC{indexS.structures}(structNum).contour(slc).segments(seg).points = pts1M;\n    end\nend\nreRasterAndUniformize\n\n% GRE map\natlasGreV = sum(doseAllM,1) ./ sum(strAllM,1);\nindToUse = atlasGreV < prctile(atlasGreV,30);\nindToUse = 1:12;\nweightedSegM = bsxfun(@times, strAllM(:,indToUse), (1./atlasGreV(indToUse)).^5);\nweightedSegM(weightedSegM == 0) = NaN;\nWv = nansum(weightedSegM,2); % voxels weighted by GRE per registration\n\n% Wv = nanmean(weightedSegM,2) < prctile(atlasGreV,50);\n% % Wv = strAllM(:,2);\n% segM = reshape(Wv,siz);\n% maskToCERRStructure(segM,1,1,'GRE Weighted Majority')\n\n\n% Combine GRE for each voxel\n% gama = 1;\n% invDoseAllM = 1./(doseAllM(:,indToUse)+eps);\n% indZeroV = doseAllM(:,indToUse) > 0;\n% invThrV = nanmean(doseAllM(:,indToUse),2);\n% thrM = 1 ./ invThrV;\n% thrM(invThrV < eps) = 0;\n% thrV = mean(thrM,2)+1e10;\n% % thr = mean(invDoseAllM(indZeroV)); % global thr\n% % indZeroV = indZeroV & invDoseAllM > thrV;\n% indZeroV = indZeroV & bsxfun(@le,invDoseAllM', thrV')';\n% invDoseAllM(~indZeroV) = NaN;\n% Wv = nansum(invDoseAllM.^gama , 2);\n% % numMembersV = sum(strAllM,2);\n% % Wv = Wv ./ numMembersV;\n\nweightM = reshape(Wv,siz);\nweightM(isnan(weightM)) = 0;\nshowIMDose(weightM,'ConsensusGRE',1);\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/BABS/greBasedSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24145897733696844}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MRiLab auto generated file: DO NOT EDIT!     %\n% Generated by MRiLab \"DoWriteXML2m\" Generator %\n% MRiLab Version 1.3                           %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [rfAmp,rfPhase,rfFreq,rfCoil,GzAmp,GyAmp,GxAmp,ADC,Ext,uts,ts,flags]=PSD_SPGR3DME\nglobal VCtl\nglobal VVar\nCV1=2e-3;\nCV10=0;\nCV11=0;\nCV12=0;\nCV13=0;\nCV14=0;\nCV2=3e-3;\nCV3=abs(rem(VVar.TRCount,2)*2-1);\nCV4=0e-3;\nCV5=0;\nCV6=0;\nCV7=0;\nCV8=0;\nCV9=0;\nrfAmpAll=[];\nrfPhaseAll=[];\nrfFreqAll=[];\nrfCoilAll=[];\nGzAmpAll=[];\nGyAmpAll=[];\nGxAmpAll=[];\nADCAll=[];\nExtAll=[];\nrfTimeAll=[];\nGzTimeAll=[];\nGyTimeAll=[];\nGxTimeAll=[];\nADCTimeAll=[];\nExtTimeAll=[];\nSEtAll=[];\nuts=[];\nts=[];\nflags=[];\nif VCtl.PlotSeq == 1\nrfAmp=[];\nrfPhase=[];\nrfFreq=[];\nrfCoil=[];\nGzAmp=[];\nGyAmp=[];\nGxAmp=[];\nADC=[];\nExt=[];\nFreq=1;\nNotes='regular TR section';\nAttributeOpt={'on','off'};\nSwitch=AttributeOpt{1};\nTREnd=Inf;\nTRStart=1;\ntE=VCtl.TR;\ntS=0;\nif VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')\n% do nothing\nelse\nts = [ts tS tE];\nend\nts = [0 max(ts)-min(ts)];\nreturn;\nend\n%==============Pulses 1==============\nrfAmp=[];\nrfPhase=[];\nrfFreq=[];\nrfCoil=[];\nGzAmp=[];\nGyAmp=[];\nGxAmp=[];\nADC=[];\nExt=[];\nrfTime=[];\nGzTime=[];\nGyTime=[];\nGxTime=[];\nADCTime=[];\nExtTime=[];\nFreq=1;\nNotes='regular TR section';\nAttributeOpt={'on','off'};\nSwitch=AttributeOpt{1};\nTREnd=Inf;\nTRStart=1;\ntE=VCtl.TR;\ntS=0;\nif isempty(tS) | isempty(tE) | (tS>=tE)\nerror('SE setting is incorrect for Pulses 1!');\nend\nif VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')\n% do nothing\nelse\n%--------------------\nAttributeOpt={'on','off'};\np.AnchorTE=AttributeOpt{1};\nAttributeOpt={'Non','Hamming','Hanning'};\np.Apod=AttributeOpt{2};\np.CoilID=1;\np.DupSpacing=0;\np.Duplicates=1;\np.FA=VCtl.FlipAng;\np.Notes='sinc rf pulse';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.TBP=4;\np.dt=20e-6;\np.rfFreq=0;\np.rfPhase=0;\np.tEnd=CV4+0.5e-3;\np.tStart=CV4;\nif strcmp(p.Switch,'on')\nif strcmp(p.AnchorTE,'on')\nswitch VCtl.TEAnchor\ncase 'Start'\nVCtl.TEAnchorTime=p.tStart; \ncase 'Middle'\nVCtl.TEAnchorTime=(p.tStart+p.tEnd)/2; \ncase 'End'\nVCtl.TEAnchorTime=p.tEnd;\nend\nend\n[rfAmp1,rfPhase1,rfFreq1,rfCoil1,rfTime1]=rfSinc(p);\nif strcmp(VCtl.MultiTransmit,'off')\nif VCtl.MasterTxCoil==rfCoil1(1)\nrfAmp=[rfAmp rfAmp1];\nrfPhase=[rfPhase rfPhase1];\nrfFreq=[rfFreq rfFreq1];\nrfCoil=[rfCoil rfCoil1];\nrfTime=[rfTime rfTime1];\nend\nelse\nrfAmp=[rfAmp rfAmp1];\nrfPhase=[rfPhase rfPhase1];\nrfFreq=[rfFreq rfFreq1];\nrfCoil=[rfCoil rfCoil1];\nrfTime=[rfTime rfTime1];\nend\nend\np=[];\n%--------------------\nAttributeOpt={'on','off'};\np.AnchorTE=AttributeOpt{2};\nAttributeOpt={'Non','Hamming','Hanning'};\np.Apod=AttributeOpt{2};\np.CoilID=1;\np.DupSpacing=0;\np.Duplicates=1;\np.FA=0;\np.Notes='sinc rf pulse';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.TBP=4;\np.dt=0.05e-3;\np.rfFreq=0;\np.rfPhase=0;\np.tEnd=VCtl.TR;\np.tStart=CV4+0.6e-3;\nif strcmp(p.Switch,'on')\nif strcmp(p.AnchorTE,'on')\nswitch VCtl.TEAnchor\ncase 'Start'\nVCtl.TEAnchorTime=p.tStart; \ncase 'Middle'\nVCtl.TEAnchorTime=(p.tStart+p.tEnd)/2; \ncase 'End'\nVCtl.TEAnchorTime=p.tEnd;\nend\nend\n[rfAmp2,rfPhase2,rfFreq2,rfCoil2,rfTime2]=rfSinc(p);\nif strcmp(VCtl.MultiTransmit,'off')\nif VCtl.MasterTxCoil==rfCoil2(1)\nrfAmp=[rfAmp rfAmp2];\nrfPhase=[rfPhase rfPhase2];\nrfFreq=[rfFreq rfFreq2];\nrfCoil=[rfCoil rfCoil2];\nrfTime=[rfTime rfTime2];\nend\nelse\nrfAmp=[rfAmp rfAmp2];\nrfPhase=[rfPhase rfPhase2];\nrfFreq=[rfFreq rfFreq2];\nrfCoil=[rfCoil rfCoil2];\nrfTime=[rfTime rfTime2];\nend\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Gz1Sign=1;\np.Gz2Sign=0;\np.Notes='cartesian phase';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.t1End=CV4+CV2;\np.t1Start=CV4+CV1;\np.t2End=VCtl.TE+CV2;\np.t2Start=VCtl.TE+CV1;\np.tRamp=100e-6;\nif strcmp(p.Switch,'on')\n[GzAmp1,GzTime1]=GzCartesian(p);\nGzAmp=[GzAmp GzAmp1];\nGzTime=[GzTime GzTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Gy1Sign=1;\np.Gy2Sign=0;\np.Notes='cartesian phase';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.t1End=CV4+CV2;\np.t1Start=CV4+CV1;\np.t2End=VCtl.TE+CV2;\np.t2Start=VCtl.TE+CV1;\np.tRamp=100e-6;\nif strcmp(p.Switch,'on')\n[GyAmp1,GyTime1]=GyCartesian(p);\nGyAmp=[GyAmp GyAmp1];\nGyTime=[GyTime GyTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Gx1Sign=-1;\np.Gx2Sign=1;\np.Gx3Sign=0;\np.Notes='cartesian frequency';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.t1Start=CV4+CV1;\np.t2Middle=VCtl.TE;\np.t3Start=VCtl.TE+CV1;\np.tRamp=100e-6;\nif strcmp(p.Switch,'on')\n[GxAmp1,GxTime1]=GxCartesian(p);\nGxAmp=[GxAmp GxAmp1];\nGxTime=[GxTime GxTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Notes='cartesian readout';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tMiddle=VCtl.TE;\nif strcmp(p.Switch,'on')\n[ADC1,ADCTime1]=ADCCartesian(p);\nADC=[ADC ADC1];\nADCTime=[ADCTime ADCTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=5;\np.Notes='calculate remaining scan time';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=0;\nif strcmp(p.Switch,'on')\n[Ext1,ExtTime1]=ExtBit(p);\nExt=[Ext Ext1];\nExtTime=[ExtTime ExtTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=1;\np.Notes='reset K space location';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=CV4+0.5e-3;\nif strcmp(p.Switch,'on')\n[Ext2,ExtTime2]=ExtBit(p);\nExt=[Ext Ext2];\nExtTime=[ExtTime ExtTime2];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=6;\np.Notes='dephase Mxy';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=VCtl.TR*(99/100);\nif strcmp(p.Switch,'on')\n[Ext3,ExtTime3]=ExtBit(p);\nExt=[Ext Ext3];\nExtTime=[ExtTime ExtTime3];\nend\np=[];\n%--------------------\nSEt=[tS tE];\nrfAmp(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfPhase(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfFreq(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfCoil(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nGzAmp(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];\nGyAmp(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];\nGxAmp(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];\nADC(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];\nExt(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];\nrfTime(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nGzTime(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];\nGyTime(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];\nGxTime(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];\nADCTime(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];\nExtTime(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];\nrfAmp(abs(rfAmp)<eps) = 0;\nrfTime = rfTime + SEt(1);\nGzTime = GzTime + SEt(1);\nGyTime = GyTime + SEt(1);\nGxTime = GxTime + SEt(1);\nADCTime = ADCTime + SEt(1);\nExtTime = ExtTime + SEt(1);\nrfAmpAll=[rfAmpAll rfAmp];\nrfPhaseAll=[rfPhaseAll rfPhase];\nrfFreqAll=[rfFreqAll rfFreq];\nrfCoilAll=[rfCoilAll rfCoil];\nGzAmpAll=[GzAmpAll GzAmp];\nGyAmpAll=[GyAmpAll GyAmp];\nGxAmpAll=[GxAmpAll GxAmp];\nADCAll=[ADCAll ADC];\nExtAll=[ExtAll Ext];\nrfTimeAll=[rfTimeAll rfTime];\nGzTimeAll=[GzTimeAll GzTime];\nGyTimeAll=[GyTimeAll GyTime];\nGxTimeAll=[GxTimeAll GxTime];\nADCTimeAll=[ADCTimeAll ADCTime];\nExtTimeAll=[ExtTimeAll ExtTime];\nSEtAll=[SEtAll SEt];\nend\n%====================================\nif isempty(rfTimeAll)\nerror('rf sequence line can not be empty! Master Tx coil element must be used.');\nend\nif isempty(GzTimeAll)\nerror('GzSS sequence line can not be empty!');\nend\nif isempty(GyTimeAll)\nerror('GyPE sequence line can not be empty!');\nend\nif isempty(GxTimeAll)\nerror('GxR sequence line can not be empty!');\nend\nif isempty(ADCTimeAll)\nerror('ADC sequence line can not be empty!');\nend\nif isempty(ExtTimeAll)\nerror('Ext sequence line can not be empty!');\nend\nSEflag=repmat([0 0 0 0 0 0]',[1 2]);\nrfflag=repmat([1 0 0 0 0 0]',[1 max(size(rfTimeAll))]);\nGzflag=repmat([0 1 0 0 0 0]',[1 max(size(GzTimeAll))]);\nGyflag=repmat([0 0 1 0 0 0]',[1 max(size(GyTimeAll))]);\nGxflag=repmat([0 0 0 1 0 0]',[1 max(size(GxTimeAll))]);\nADCflag=repmat([0 0 0 0 1 0]',[1 max(size(ADCTimeAll))]);\nExtflag=repmat([0 0 0 0 0 1]',[1 max(size(ExtTimeAll))]);\nts=[[min(SEtAll) max(SEtAll)] rfTimeAll GzTimeAll GyTimeAll GxTimeAll ADCTimeAll ExtTimeAll]-min(SEtAll);\nflags=[SEflag rfflag Gzflag Gyflag Gxflag ADCflag Extflag];\n[ts,ind]=sort(ts);\nuts=unique(ts);\nflags=flags(:,ind);\n[rfTime,ind]=sort(rfTimeAll-min(SEtAll));\nrfAmp=rfAmpAll(:,ind);\nrfPhase=rfPhaseAll(:,ind);\nrfFreq=rfFreqAll(:,ind);\nrfCoil=rfCoilAll(:,ind);\n[GzTime,ind]=sort(GzTimeAll-min(SEtAll));\nGzAmp=GzAmpAll(:,ind);\n[GyTime,ind]=sort(GyTimeAll-min(SEtAll));\nGyAmp=GyAmpAll(:,ind);\n[GxTime,ind]=sort(GxTimeAll-min(SEtAll));\nGxAmp=GxAmpAll(:,ind);\n[ADCTime,ind]=sort(ADCTimeAll-min(SEtAll));\nADC=ADCAll(:,ind);\n[ExtTime,ind]=sort(ExtTimeAll-min(SEtAll));\nExt=ExtAll(:,ind);\nrfAmp(1) = 0;\nrfPhase(1) = 0;\nrfFreq(1) = 0;\nGzAmp(1) = 0;\nGyAmp(1) = 0;\nGxAmp(1) = 0;\nADC(1) = 0;\nExt(1) = 0;\nrfAmp(end) = 0;\nrfPhase(end) = 0;\nrfFreq(end) = 0;\nGzAmp(end) = 0;\nGyAmp(end) = 0;\nGxAmp(end) = 0;\nADC(end) = 0;\nExt(end) = 0;\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/PSD/3D/User/PSD_SPGR3DME/PSD_SPGR3DME.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24141290125295242}}
{"text": "%% Reads ECG recording in HES format\n% Reads ECG recordings in HES (Biosigna) format. Implements the documentation\n% available in the help of the application provided with the database (not\n% available with the ECHkit). \n% \n% Arguments:\n%   + filename: recording to be read.\n%   + start_sample: (opt) start sample to read. Default 1.\n%   + end_sample: (opt) end sample to read. Default min(All recording, ECG block of 200 Mbytes)\n% \n% Output:\n%   + ECG: the ECG block\n%   + heasig: header with the ECG properties. \n%   + ann: annotations for the ECG recordings.\n% \n% Limits:\n% This routine is limited to read blocks smaller than 200 Mbytes for\n% performance reasons. You can disable this limit by doing:\n% MaxIOread = Inf; %megabytes\n% \n% See also read_HES_ann, read_HES_header, read_ECG, ECGwrapper\n% \n% Author: Mariano Llamedo Soria\n% <matlab:web('mailto:llamedom@electron.frba.utn.edu.ar','-browser') (email)> \n% Version: 0.1 beta\n% Birthdate: 17/12/2010\n% Last update: 19/11/2014\n% Copyright 2008-2015\n% \nfunction [ECG heasig ann last_sample] = read_HES_format( filename, start_sample, end_sample )\n\nann = [];\nheasig = [];\nECG = [];\nlast_sample = [];\n\ntablas_y_constantes;\n\n%No leer bloques mas grandes de 200 megabytes\nMaxIOread = 200; %megabytes\n\nif( nargin < 2 || isempty( start_sample ) )\n    start_sample = 1;\nelse\n    start_sample = max(1,start_sample);\nend\n\nfidECG = fopen( filename, 'r');\n\nif( fidECG > 0 )\n    \n    fseek(fidECG, 900, 'bof');\n    \n    num_of_leads = fread(fidECG, 1, 'uint8');\n    num_of_leads_simult = fread(fidECG, 1, 'uint8');\n    \n    if( num_of_leads ~= num_of_leads_simult)\n        error('Sampleo no simult\ufffdneo, revisar.')\n    end\n    \n    heasig.nsig = num_of_leads_simult;\n    \n    lead_description_idx = fread(fidECG, heasig.nsig, 'uint8');\n    [dummy lead_description_table_idx] = intersect(Lead_description_idx, lead_description_idx);\n    heasig.desc = char(cLead_description_table(lead_description_table_idx,1));\n\n    fseek(fidECG, 992, 'bof');\n    \n    aux = fread(fidECG, 5, 'uint16');\n    \n    sample_interval_usec = aux(1);\n    heasig.freq = 1/sample_interval_usec*1e6;\n    heasig.gain = repmat(1/aux(3),1,heasig.nsig);\n    heasig.units = repmat('nV',heasig.nsig,1);\n    heasig.adcres = repmat(aux(4),1,heasig.nsig);\n    heasig.adczero = repmat(2^(aux(4)-1),1,heasig.nsig);\n    heasig.nsamp = fread(fidECG, 1, 'uint32');\n    \n    if( nargin < 3 || isempty( end_sample ) )\n        %Intento la lectura total por defecto\n        samples2read = heasig.nsamp - (start_sample-1);\n    else\n        samples2read = min(heasig.nsamp, end_sample) - (start_sample-1);\n    end\n    \n    if( (samples2read*heasig.nsig*2) > (MaxIOread * 1024^2) )\n        samples2read = (MaxIOread * 1024^2) / heasig.nsig / 2;\n        warning(['No es recomendable leer mas de ' num2str(MaxIOread) ' Mb. Realice varias lecturas.'])\n    end\n    \n    ECG = nan(samples2read,heasig.nsig);\n    \n    try \n        \n        fseek(fidECG, 1024+((start_sample-1)*heasig.nsig)*2, 'bof');\n\n        ECG = fread(fidECG, [heasig.nsig samples2read], '*int16')';\n\n        fclose(fidECG);\n\n    catch ME\n        fclose(fidECG);\n        rethrow(ME)\n    end\n\n    last_sample = size(ECG,1) + start_sample - 1;\n    \n    [~, heasig.recname] = fileparts(filename);\n    heasig.btime = '00:00:00';\n    heasig.bdate = '01/01/2000';\n    \n    if( nargout > 2 )\n        ann = read_HES_ann([ filename(1:end-4) '.lst' ]);\n        ann.time = round(ann.time * heasig.freq);\n    end\n\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/read_HES_format.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2414129012529524}}
{"text": "function Rob = motion(Rob, Tim)\n%MOTION Robot motion.\n%   ROB = MOTION(ROB, TIM) performs one EKF-prediction motion step to robot\n%   Rob in the global map Map, following the motion model in Rob.motion.\n%   Both Rob and Map are updated. The time information Tim is used only if\n%   the motion model requires it, but it has to be provided because MOTION\n%   is a generic method.\n%\n%   The following motion models are supported:\n%       'odometry'   uses function odo3()\n%       'constVel'   uses function constVel()\n%   Edit this file to add new motion models.\n%\n%   See also SIMMOTION, CONSTVEL, ODO3, UPDATEFRAME.\n\n%   Copyright 2009 David Marquez @ LAAS-CNRS.\n\nglobal Map\n\n% Update rob and sen info from map\nRob = map2rob(Rob);\n\n% robot state range\nr = Rob.state.r;\n\nswitch Rob.motion\n    \n    case  {'constVel'} % constant velocity\n        \n        % motion model of the robot: mean and Jacobians\n        [Map.x(r), F_x, F_u] = constVel(Map.x(r),Rob.con.u,Tim.dt);\n        \n        % update Rob and Map structures - mean only\n        Rob = map2rob(Rob);\n        \n        % Covariances matrix update\n        predictBlockEkf(r, F_x, Rob.con.U, F_u);\n        \n       \n    case  {'odometry'}  % 3D odometry\n        \n        % motion model of the robot: mean and Jacobians\n        [Rob.frame, F_x, F_u]   = odo3(Rob.frame,Rob.con.u);\n        \n        % update Rob and Map structures - mean only\n        Map.x(Rob.frame.r) = Rob.frame.x;\n        \n        % Covariances matrix update\n        predictBlockEkf(r, F_x, Rob.con.U, F_u);\n                \n    otherwise\n        \n        error('??? Unknown motion model ''%s''.',Rob.motion);\nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n%   # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n%   This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n%   SLAMTB is free software: you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation, either version 3 of the License, or\n%   (at your option) any later version.\n%\n%   SLAMTB is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You should have received a copy of the GNU General Public License\n%   along with SLAMTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n%---------------------------------------------------------------------\n\n%   SLAMTB is Copyright:\n%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n%   Copyright (c) 2010-2013, Joan Sola,\n%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n%   SLAMTB is Copyright 2009 \n%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n%   @ LAAS-CNRS.\n%   See on top of this file for its particular copyright.\n\n%   # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/motion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.24136908880810728}}
{"text": "function [BSL,BKG] = BSLcalcShedsVis(Wsheds,nSheds,IMAGE)\n%\"BSLcalcShedsVis\"\n%   Strips away low values watersheds and calculates BSL \n%   -- Returns BSL and Background estimates after each water shed is\n%   removed and returns vectors of these values\n%\n% CRS 07/17/13\n%\n%Usage: \n%   [BSL,BKG] = BSLcalcShedsVis(Wsheds,nSheds,IMAGE)\n%       Wsheds  = Struture that holds:\n%          Wsheds.PET    = PET VOI\n%          Wsheds.Shed   = Watersheds ordered from low mean uptake to high\n%          Wsheds.voxVol = voxel volume\n%       nSheds = total number of sheds\n%       Image  = Flag for display of smoothed BSL vector\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.%\n%\n%\n%\n%% BSL calc for all sheds\nif (IMAGE == 1)\n    figure,\nend\nbsl = zeros([nSheds 1]);\nbkg = zeros([nSheds 1]);\n\nPT = Wsheds.PET;\nShed = Wsheds.Shed;\nvoxVol = Wsheds.voxVol;\n[pX pY pZ] = size(PT);\n\n% build shed masks\nShedTmp = zeros(size(PT));\nindNZ = find(Shed);\nShed(isnan(Shed)) = 0;\nShed(isinf(Shed)) = 0;\nShedTmp(indNZ) = Shed(indNZ);\n\nSUVcut = 0.2;\nShedTmp(ShedTmp < SUVcut) = 0;\nPT(ShedTmp <= 0) = 0;\n\n% Shed Trimming\nk = 0;\nwhile ( sum(ShedTmp(:)) > 0 )\n    voxVec = [];\n    \n    minShed = min(nonzeros(ShedTmp(:)));\n    indS = find(ShedTmp == minShed);\n    ShedTmp(indS) = 0;\n    PT(indS) = 0;\n    if (isempty(indS) == 1)\n        continue\n    end\n    k = k + 1;\n    voxVec = nonzeros(PT);\n    \n    if (sum(voxVec) <=0)\n        bsl(k) = -1;\n        bkg(k) = -1;\n        BKG = bkg(1:k);\n        BSL = bsl(1:k);\n        if (IMAGE ~= 0)\n            hold off\n        end\n        return\n    end\n    \n    nVox = numel(voxVec);\n    SUViqr = iqr(voxVec);\n    IVHBinWidth = 2 * SUViqr * nVox^(-1/3);\n    %%%\n    if (numel(voxVec) < 5)\n        BKG = bkg(1:k);\n        BSL = bsl(1:k);\n        if (IMAGE ~= 0)\n            hold off\n        end\n        return\n    end\n    %%%\n    [binHistV, volHistV]  = doseHist(voxVec, voxVol*ones(size(voxVec)), IVHBinWidth);\n    nBins = numel(binHistV);\n    \n    [Hmax iBkg] = max(volHistV);\n    Hbkg = binHistV(iBkg);\n    if (iBkg > 1 && iBkg < numel(binHistV))\n        Hbkg = ( volHistV(iBkg-1)*binHistV(iBkg-1) ...\n            + volHistV(iBkg)*binHistV(iBkg) ...\n            + volHistV(iBkg+1)*binHistV(iBkg+1) ) ...\n            / ( volHistV(iBkg-1) + volHistV(iBkg) + volHistV(iBkg+1) );\n    else\n        if (iBkg < numel(binHistV))\n            Hbkg = ( volHistV(iBkg)*binHistV(iBkg) ...\n                + volHistV(iBkg+1)*binHistV(iBkg+1) ) ...\n                / ( volHistV(iBkg) + volHistV(iBkg+1) );\n        else\n            Hbkg = ( volHistV(iBkg-1)*binHistV(iBkg-1) ...\n                + volHistV(iBkg)*binHistV(iBkg) ) ...\n                / ( volHistV(iBkg-1) + volHistV(iBkg) );\n        end\n    end\n    SUVcut = Hbkg/3;\n\n    voxVec(voxVec < SUVcut) = 0;\n    voxVec = nonzeros(voxVec);\n    ShedTmp(ShedTmp < SUVcut) = 0;\n    PT(ShedTmp < SUVcut) = 0;\n    \n    nVox = numel(voxVec);\n    SUViqr = iqr(voxVec);\n    IVHBinWidth = 2 * SUViqr * nVox^(-1/3);\n    \n    [binHistV, volHistV]  = doseHist(voxVec, voxVol*ones(size(voxVec)), IVHBinWidth);\n    nBins = numel(binHistV);\n    if (IMAGE == 1)\n        colorWidth = 2;\n        colorPlot = mod(k,7);\n        switch colorPlot\n            case (1)\n                plot(binHistV,volHistV,'-c','LineWidth',colorWidth)\n            case (2)\n                plot(binHistV,volHistV,'-g','LineWidth',colorWidth)\n            case (3)\n                plot(binHistV,volHistV,'-y','LineWidth',colorWidth)\n            case (4)\n                plot(binHistV,volHistV,'-r','LineWidth',colorWidth)\n            case (5)\n                plot(binHistV,volHistV,'-k','LineWidth',colorWidth)\n            case (6)\n                plot(binHistV,volHistV,'-m','LineWidth',colorWidth)\n            otherwise\n                plot(binHistV,volHistV,'-b','LineWidth',colorWidth)\n        end\n        drawnow, hold on\n    end\n    if (IMAGE == 2)\n        plot3(binHistV,-k*ones(numel(binHistV)),volHistV), drawnow\n        hold on\n    end\n    if (IMAGE == 3)\n        colorWidth = 4;\n        colorPlot = mod(k,7);\n        switch colorPlot\n            case (1)\n                plot(binHistV,volHistV,'-c','LineWidth',colorWidth)\n            case (2)\n                plot(binHistV,volHistV,'-g','LineWidth',colorWidth)\n            case (3)\n                plot(binHistV,volHistV,'-y','LineWidth',colorWidth)\n            case (4)\n                plot(binHistV,volHistV,'-r','LineWidth',colorWidth)\n            case (5)\n                plot(binHistV,volHistV,'-k','LineWidth',colorWidth)\n            case (6)\n                plot(binHistV,volHistV,'-m','LineWidth',colorWidth)\n            otherwise\n                plot(binHistV,volHistV,'-b','LineWidth',colorWidth)\n        end\n        drawnow, hold on\n    end\n    %% Gaussian FITS\n    fitOptions = optimset('Display','off');\n    lBins = ceil(SUViqr/IVHBinWidth);\n    \n    plusBins  = iBkg + lBins;\n    if (plusBins > numel(binHistV))\n        plusBins = numel(binHistV);\n    end\n    minusBins = iBkg  - lBins;\n    if (minusBins < 1)\n        minusBins = 1;\n    end\n    if (numel(minusBins:plusBins) < 3)\n        if (minusBins+2 <= numel(binHistV))\n            plusBins = minusBins + 2;\n        else\n            minusBins = plusBins - 2;\n        end\n    end\n    if (minusBins < 1)\n        BKG = bkg(1:k);\n        BSL = bsl(1:k);\n        if (IMAGE ~= 0)\n            hold off\n        end\n        return\n    end\n    \n    sL2 = [];\n    initVar = [ Hmax*sqrt(2*pi())*Hbkg Hbkg SUViqr ];\n    lBound =  [ 0.01  0.01  0.01  ];\n    uBound =  [ inf   inf   inf  ];\n    \n    sL2  = lsqnonlin(@(X) (...\n        ( volHistV(minusBins:plusBins) - X(1)*normpdf(binHistV(minusBins:plusBins),X(2),X(3)) ) ...\n        / sum(volHistV(minusBins:plusBins)) ).*sqrt(volHistV(minusBins:plusBins)), ...\n        initVar,lBound,uBound,fitOptions);\n    \n    estGauss2 = sL2(1)*normpdf(binHistV(:),sL2(2),sL2(3));\n    \n    bkg(k) = sL2(2);\n    \n    %% Volume and TLG Estimation\n    iEst2 = round( 2*sL2(3)/IVHBinWidth + sL2(2)/IVHBinWidth );\n    if  (sL2(2) <= 0)\n        iEst2 = round( 2*sL2(3)/IVHBinWidth + iBkg );\n    end\n    volGauss2 = estGauss2(iEst2:end);\n    \n    % Gauss volumes\n    vecG2 = zeros(size(volGauss2));\n    vecG2 = volHistV(iEst2:end)' - volGauss2;\n    vecG2(vecG2 < 0) = 0;\n    volG2 = sum(vecG2);\n    \n    bsl(k) = vecG2'*binHistV(iEst2:end)';\n    if (bsl(k) <= 0 && k > nSheds/10)\n        BKG = bkg(1:k);\n        BSL = bsl(1:k);\n        if (IMAGE ~= 0)\n            hold off\n        end\n        return;\n    end\n    \nend\nBKG = bkg(1:k);\nBSL = bsl(1:k);\nif (IMAGE ~= 0)\n    hold off\nend\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageMetrics/BSLcalcShedsVis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2413216195074579}}
{"text": "function spm_dcm_search(P)\n% Post hoc optimisation of DCMs (under Laplace approximation)\n% FORMAT spm_dcm_search(P)\n%\n% P         -  character/cell array of DCM filenames\n%\n%--------------------------------------------------------------------------\n% spm_dcm_search operates on different DCMs of the same data to identify\n% the best model. It will invert the full model whose free-parameters are\n% the union (superset) of all free parameters in each model specified. The\n% routine then uses a post hoc selection procedure to evaluate the log-\n% evidence and conditional density over free-parameters of each model\n% specified.\n%\n% The DCM specified does not need to be estimated. spm_dcm_search will \n% invert the requisite (full DCM) automatically.\n%\n% The outputs of this routine are graphics reporting the model space search\n% (optimisation) and a DCM_optimum (in the first DCMs directory) for the\n% best DCM. The structural and function (spectral embedding) graphs are\n% based on this DCM.\n%\n% DCM_optimum  contains the fields:\n%        DCM.P   - character/cell array of DCM filenames\n%        DCM.PF  - their associated free energies\n%        DCM.PP  - and posterior (model) probabilities\n%\n% In addition, the free energies and posterior estimates of each DCM in P \n% are saved for subsequent searches over different partitions of model \n% space.\n%\n% See alos: spm_dcm_post_hoc.m\n%\n%__________________________________________________________________________\n% Copyright (C) 2008-2011 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_dcm_search.m 6615 2015-11-30 12:56:02Z peter $\n \n% get filenames\n%--------------------------------------------------------------------------\ntry\n    P;\ncatch\n    [P, sts] = spm_select([2 Inf],'^DCM.*\\.mat$','Select DCM*.mat files');\n    if ~sts, return; end\nend\n \nif ischar(P), P = cellstr(P); end\nN = numel(P);\n \n%-Check models are compatible in terms of their data\n%==========================================================================\nfor j = 1:N\n    \n    % get prior covariances\n    %----------------------------------------------------------------------\n    load(P{j});\n    \n    % and compare it with the first model\n    %----------------------------------------------------------------------\n    if j == 1\n        Y = DCM.Y.y;\n    else\n        try\n            if any(any(Y - DCM.Y.y))\n                fprintf('Please check model %i for compatibility',j)\n                return\n            end\n        catch\n            fprintf('Please check model %i for compatibility',j)\n            return\n        end\n    end\n    \n    % accumate model in terms of which parameters are free\n    %----------------------------------------------------------------------\n    A = DCM.a;\n    B = DCM.b;\n    C = DCM.c;\n    D = DCM.d;\n    \n    % Get full models free parameters\n    %----------------------------------------------------------------------\n    if j == 1\n        a    = A;\n        b    = B;\n        c    = C;\n        d    = D;\n    else\n        a    = a | A;\n        b    = b | B;\n        c    = c | C;\n        d    = d | D;\n    end\nend\n \n%-Estimate full model\n%==========================================================================\nDCM.a = a;\nDCM.b = b;\nDCM.c = c;\nDCM.d = d;\n \nDCM.name = 'optimum';\n \n% Get full priors and posteriors\n% -------------------------------------------------------------------------\nFUL   = spm_dcm_estimate(DCM);\n \nqE    = FUL.Ep;\nqC    = FUL.Cp;\npE    = FUL.M.pE;\npC    = FUL.M.pC;\n \n%-Loop through models and get log-evidences\n%==========================================================================\nfor j = 1:N\n    \n    load(P{j});\n    \n    % Fix for endogenous DCM (to match spm_dcm_estimate)\n    % ---------------------------------------------------------------------\n    if isempty(DCM.c) || isempty(U.u)\n        DCM.c  = zeros(DCM.n,1);\n        DCM.b  = zeros(DCM.n,DCM.n,1);\n    end\n    \n    % Get model (priors) and evaluate (reduced) free-energy and posteriors\n    % ---------------------------------------------------------------------\n    [rE,rC]   = spm_dcm_fmri_priors(DCM.a,DCM.b,DCM.c,DCM.d,DCM.options);\n    [F,Ep,Cp] = spm_log_evidence(qE,qC,pE,pC,rE,rC);\n    \n    % Put reduced conditional estimates in DCM\n    % =====================================================================\n    \n    % Bayesian inference and variance\n    %----------------------------------------------------------------------\n    sw       = warning('off','SPM:negativeVariance');\n    Pp       = spm_unvec(1 - spm_Ncdf(0,abs(spm_vec(Ep)),diag(Cp)),Ep);\n    Vp       = spm_unvec(diag(Cp),Ep);\n    warning(sw);\n    \n    \n    % Store parameter estimates\n    %----------------------------------------------------------------------\n    DCM.M.pC = rC;\n    DCM.Ep   = Ep;\n    DCM.Cp   = Cp;\n    DCM.Pp   = Pp;\n    DCM.Vp   = Vp;\n    DCM.T    = 0;\n    \n    % Store predictions of states from full model for simplicity\n    %----------------------------------------------------------------------\n    DCM.Ce   = FUL.Ce;\n    DCM.H1   = FUL.H1;\n    DCM.K1   = FUL.K1;\n    DCM.R    = FUL.R;\n    DCM.y    = FUL.y;\n    \n    % Save approximations to model evidence: negative free energy, AIC, BIC\n    %----------------------------------------------------------------------\n    evidence = spm_dcm_evidence(DCM);\n    DCM.F    = F;\n    DCM.AIC  = evidence.aic_overall;\n    DCM.BIC  = evidence.bic_overall;\n    \n    % Save DCM\n    %======================================================================\n    save(P{j},'DCM','F','Ep','Cp', spm_get_defaults('mat.format'));\n    \n    % Record free-energy\n    %----------------------------------------------------------------------\n    G(j) = F;\n    \nend\n \n% Model evidences and best model\n% =========================================================================\nG     = G - min(G);\np     = exp(G - max(G));\np     = p/sum(p);\n \n% Get selected model\n%--------------------------------------------------------------------------\n[q,j] = max(p);\nload(P{j});\n \ni   = spm_fieldindices(DCM.Ep,'A','B','C','D');\nqE  = spm_vec(FUL.Ep);\nEp  = spm_vec(DCM.Ep);\nqC  = DCM.Cp;\nCp  = DCM.Cp;\nF   = DCM.F;\n \n% Show results\n% -------------------------------------------------------------------------\nspm_figure('Getwin','Graphics'); clf\n \nsubplot(2,2,1)\nif length(P) > 32, plot(G,'k'), else bar(G,'c'), end\ntitle('log-posterior','FontSize',16)\nxlabel('model','FontSize',12)\nylabel('log-probability','FontSize',12)\naxis square\n \nsubplot(2,2,2)\nif length(P) > 32, plot(p,'k'), else, bar(p,'r'), end\ntitle('model posterior','FontSize',16)\nxlabel('model','FontSize',12)\nylabel('probability','FontSize',12)\naxis square\n \n% Show full and reduced conditional estimates (for optimum DCM)\n%--------------------------------------------------------------------------\nsubplot(2,2,3)\nspm_plot_ci(qE(i),qC(i,i))\ntitle('MAP connections (full)','FontSize',16)\naxis square\na   = axis;\n \nsubplot(2,2,4)\nspm_plot_ci(Ep(i),Cp(i,i))\ntitle('MAP connections (optimum)','FontSize',16)\naxis square\naxis(a)\n \n% Show structural and functional graphs\n%--------------------------------------------------------------------------\nspm_figure('Getwin','Graph'); clf\n \nspm_dcm_graph(DCM.xY,DCM.Ep.A)\n \n \n%-Save optimum and full DCM\n%==========================================================================\nDCM.P  = P;\nDCM.PF = G;\nDCM.PP = p;\n \n% Reduced model (optimum)\n%--------------------------------------------------------------------------\npth      = fileparts(P{1});\nfilename = fullfile(pth,'DCM_optimum.mat');\nsave(filename,'DCM','F','Ep','Cp', spm_get_defaults('mat.format'));\n \n% Full model\n%--------------------------------------------------------------------------\nDCM      = FUL;\nEp       = FUL.Ep;\nCp       = FUL.Cp;\nF        = FUL.F;\nfilename = fullfile(pth,'DCM_full');\nsave(filename,'DCM','F','Ep','Cp', spm_get_defaults('mat.format'));\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dcm_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2413216195074579}}
{"text": "function computeFluxConsistentReactionPresence(modelFolder,propertiesFolder,reconVersion)\n% This function extracts the presence of flux consistent reactions for a \n% resource of reconstructions that were refined through the semi-automatic \n% refinement pipeline (1 = present in the flux consistent submodel, 0 = not\n% present in the flux consistent submodel).\n%\n% USAGE\n%   computeFluxConsistentReactionPresence(modelFolder,propertiesFolder,reconVersion)\n%\n% INPUTS\n% modelFolder                                                                                                                                                                                           Folder with COBRA models to be analyzed\n% propertiesFolder      Folder where the retrieved reaction presences will\n%                       be stored (default: current folder)\n% reconVersion          Name assigned to the reconstruction resource\n%\n%   - AUTHOR\n%   Almut Heinken, 12/2020\n\nmkdir([propertiesFolder filesep 'ReactionMetabolitePresence'])\ncurrentDir=pwd;\ncd([propertiesFolder filesep 'ReactionMetabolitePresence'])\n\ndInfo = dir(modelFolder);\nmodelList={dInfo.name};\nmodelList=modelList';\nmodelList(~(contains(modelList(:,1),{'.mat','.sbml','.xml'})),:)=[];\n\n% check if output file already exists\nif isfile(['ReactionPresence_' reconVersion '.txt'])\n    reactionPresence = readInputTableForPipeline(['ReactionPresence_' reconVersion '.txt']);\n    allRxns=ReactionPresence(1,2:end)';\nelse\n    % restart from existing data if possible\n    if isfile([propertiesFolder filesep 'Reactions_' reconVersion '.txt'])\n        reactions = readInputTableForPipeline([propertiesFolder filesep 'Reactions_' reconVersion '.txt']);\n        allRxns=reactions(:,1);\n    else\n        allRxns={};\n        for i=1:length(modelList)\n            i\n            model=readCbModel([modelFolder filesep modelList{i} '.mat']);\n            allRxns=unique(vertcat(allRxns,model.rxns));\n        end\n    end\nend\n\n% remove models that were already retrieved\nmodelsRenamed=strrep(modelList(:,1),'.mat','');\nmodelsRenamed=strrep(modelsRenamed,'.sbml','');\nmodelsRenamed=strrep(modelsRenamed,'.xml','');\n[C,IA]=intersect(modelsRenamed,ReactionPresence(2:end,1));\nmodelList(IA,:)=[];\n\n% define the intervals in which the computations will be performed\nif length(modelList)>5000\n    steps=2000;\nelseif length(modelList)>200\n    steps=200;\nelse\n    steps=25;\nend\n\n% in case of reruns, skip if all models are already analyzed\nif ~isempty(modelList)\n    for i=1:steps:length(modelList)\n        if length(modelList)-i>=steps-1\n            endPnt=steps-1;\n        else\n            endPnt=length(modelList)-i;\n        end\n        \n        modelsToLoad={};\n        for j=i:i+endPnt\n            if j <= length(modelList)\n                modelsToLoad{j}=[modelFolder filesep modelList{j} '.mat'];\n            end\n        end\n        \n        rxnsTmp={};\n        parfor j=i:i+endPnt\n            model=readCbModel(modelsToLoad{j});\n            [~, ~, ~, ~, model] = findFluxConsistentSubset(model);\n            rxnsTmp{j}=model.rxns;\n        end\n        \n        for j=i:i+endPnt\n            plusonerow=size(ReactionPresence,1)+1;\n            \n            ReactionPresence{plusonerow,1}=strrep(modelList{j},'.mat','');\n            for k=1:length(allRxns)\n                if ~isempty(find(ismember(rxnsTmp{j},allRxns{k})))\n                    ReactionPresence{plusonerow,k+1}=1;\n                else\n                    ReactionPresence{plusonerow,k+1}=0;\n                end\n            end\n        end\n        % export the results as a table\n        writetable(cell2table(ReactionPresence),['FluxConsistent_ReactionPresence_' reconVersion],'FileType','text','WriteVariableNames',false,'Delimiter','tab');\n    end\nend\n\ncd(currentDir)\n\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/demeter/src/properties/computeFluxConsistentReactionPresence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24130592333619968}}
{"text": "n = 500;\n\n% You need to return the following variables correctly.\nx = zeros(n, 1);\n\nword_indices=[100,212,312,423,345,46,37];\n\nfor i=1:length(word_indices)\n\tif (word_indices(i))\n\t\tx(i)=1\n\telse\n\t\tx(i)=0;\n\tend\nend", "meta": {"author": "yhyap", "repo": "machine-learning-coursera", "sha": "fb33f0ad54ff2104660c86b0d26456b15029a798", "save_path": "github-repos/MATLAB/yhyap-machine-learning-coursera", "path": "github-repos/MATLAB/yhyap-machine-learning-coursera/machine-learning-coursera-fb33f0ad54ff2104660c86b0d26456b15029a798/mlclass-ex6/new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363242, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24130556349315277}}
{"text": "plot(p,h,'LineWidth',2,'Color','b'),grid,ylabel('Altitude: h [m]'),xlabel('Pressure: p [Pa]')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19470-isa-chart/plotp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2413055634931527}}
{"text": "function [model] = tapas_sem_multiv_model(data, ptheta, pars)\n%% Set up the model.\n%\n% Input\n%       hgf         -- Hgf model.\n%       pars        -- pars structure.\n% Output\n%       model       -- Model structre.\n%       \n\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n%% Define the model.\n%\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nmodel = struct('graph', []);\nmodel.graph = cell(4, 1);\n\nfor i = 1:4\n    model.graph{i} = struct('llh', [], 'htheta', []);\nend\n\nmodel.graph{1}.llh = @tapas_sem_multiv_llh;\nmodel.graph{2}.llh = @tapas_mdlinear_hier_llh;\nmodel.graph{3}.llh = @tapas_mdlinear_llh;\nmodel.graph{4}.llh = [];\n\n% Computes the likelihood for a single node.\nmodel.graph{2}.llh_sn = @tapas_mdlinear_hier_llh_sn;\n\nmodel.graph{1}.htheta = struct('pe', 0.5, 'T', pars.T, 'model', ptheta);\n\nmodel.graph{2}.htheta = struct('T', ones(size(pars.T, 2)));\nmodel.graph{3}.htheta = struct('T', ones(size(pars.T, 2)));\n\n% The last level is a dummy used to store the hyperpriors.\n\nmodel.graph{4}.htheta = struct('y', [], 'u', []);\n\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/sem/multivar/tapas_sem_multiv_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2413055634931527}}
{"text": "%% This function is used for moving the endeffector on a circle, for the KUKA iiwa 7 R 800.\nfunction [ state ] = movePTPCirc1OrintationInterCheck( t , f1,f2, relVel)\n% This function is used to move the end-effector on a circle,\n\n%% Arreguments\n% t: is the TCP/IP connection\n% f1: intermediate frame, to specify a point from the circle, it is 1x6 cell array.\n% f2: final frame, to specify the end point of the circle, it is 1x6 cell array.\n% the first three elements of cell array represent the X,Y and Z position of\n% the frame\n% the second three elements of cell array represent the alpha,beta\n% and gamma rotaion angles (rads) that represent the frame orientation\n% relVel: is a double, the over-ride relative velocity.\n\n%% Return value:\n% state: returns (true) if the circular motion is valid, returns false\n% otherwise\n\n% Copyright, Mohammad SAFEEA, 9th of May 2017\n\n    theCommand=['jRelVel_',num2str(relVel),'_']; % set over ride.\n    fprintf(t, theCommand);\n    message=fgets(t);\n    % The new position of end-effector, described in robot \n    newPos={0,0,0,0,0,0};\n    \n    newPos{1}=f1{1};\n    newPos{2}=f1{2};\n    newPos{3}=f1{3};\n    newPos{4}=f1{4};\n    newPos{5}=f1{5};\n    newPos{6}=f1{6};\n    \n    sendCirc1FramePos( t ,newPos); % send first frame of circle to server on controller.\n    \n    newPos{1}=f2{1};\n    newPos{2}=f2{2};\n    newPos{3}=f2{3};\n    newPos{4}=f2{4};\n    newPos{5}=f2{5};\n    newPos{6}=f2{6};\n    \n    sendCirc2FramePos( t ,newPos); % send second frame of circle to server on controller.\n    \n    theCommand='doPTPinCSCircle1_';\n    fprintf(t, theCommand); % start the point to point motion.\n    message=fgets(t);\n    \n    readingFlag=false;\n    \n    message='';\n    \n    while readingFlag==false\n        message=fgets(t);\n        \n        if checkAcknowledgment(message)\n            state=true;\n            break;\n        end\n        \n        if checkErrorMessage(message)\n            state=false;\n            break;\n         end\n        pause(0.1);  %% This is to enable breaking the program from the outside, using Ctrl+C for example\n    end\n    \n    \n    \nend\n\nfunction [ output_args ] = sendCirc1FramePos( t ,jPos)\n%% sendCircFramePos \n% This function is used to send the first frame of the circle\n% to the robot\n\n% Pos: is 6 cells array of doubles\n% t: is the TCP/IP connection object\n% Copy right, Mohammad SAFEEA, 3rd of May 2017\n\ntheCommand='cArtixanPositionCirc1_';\n\nfor i=1:6\n    x=sprintf('%0.2f',jPos{i});\n    theCommand=[theCommand,x,'_'];\nend\n\nfprintf(t, theCommand);\nmessage=fgets(t);\nend\n\nfunction [ output_args ] = sendCirc2FramePos( t ,jPos)\n%% sendCircFramePos \n% This function is used to send the first frame of the circle\n% to the robot\n\n% Pos: is 6 cells array of doubles\n% t: is the TCP/IP connection object\n% Copy right, Mohammad SAFEEA, 3rd of May 2017\n\ntheCommand='cArtixanPositionCirc2_';\n\nfor i=1:6\n    x=sprintf('%0.2f',jPos{i});\n    theCommand=[theCommand,x,'_'];\nend\n\nfprintf(t, theCommand);\nmessage=fgets(t);\nend\n\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/movePTPCirc1OrintationInterCheck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "function [baseMVA, bus, gen, branch, areas, gencost] = case57\n%CASE57    Power flow data for IEEE 57 bus test case.\n%   Please see 'help caseformat' for details on the case file format.\n%   This data was converted from IEEE Common Data Format\n%   (ieee57cdf.txt) on 20-Sep-2004 by cdf2matp, rev. 1.11\n%   See end of file for warnings generated during conversion.\n%\n%   Converted from IEEE CDF file from:\n%       http://www.ee.washington.edu/research/pstca/\n%\n%   Manually modified Qmax, Qmin on generator 1 to 200, -140, respectively.\n% \n%  08/25/93 UW ARCHIVE           100.0  1961 W IEEE 57 Bus Test Case\n\n%   MATPOWER\n%   $Id: case57.m,v 1.5 2004/09/21 01:47:48 ray Exp $\n\n%%-----  Power Flow Data  -----%%\n%% system MVA base\nbaseMVA = 100;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nbus = [\n\t1\t3\t55\t17\t0\t0\t1\t1.04\t0\t0\t1\t1.06\t0.94;\n\t2\t2\t3\t88\t0\t0\t1\t1.01\t-1.18\t0\t1\t1.06\t0.94;\n\t3\t2\t41\t21\t0\t0\t1\t0.985\t-5.97\t0\t1\t1.06\t0.94;\n\t4\t1\t0\t0\t0\t0\t1\t0.981\t-7.32\t0\t1\t1.06\t0.94;\n\t5\t1\t13\t4\t0\t0\t1\t0.976\t-8.52\t0\t1\t1.06\t0.94;\n\t6\t2\t75\t2\t0\t0\t1\t0.98\t-8.65\t0\t1\t1.06\t0.94;\n\t7\t1\t0\t0\t0\t0\t1\t0.984\t-7.58\t0\t1\t1.06\t0.94;\n\t8\t2\t150\t22\t0\t0\t1\t1.005\t-4.45\t0\t1\t1.06\t0.94;\n\t9\t2\t121\t26\t0\t0\t1\t0.98\t-9.56\t0\t1\t1.06\t0.94;\n\t10\t1\t5\t2\t0\t0\t1\t0.986\t-11.43\t0\t1\t1.06\t0.94;\n\t11\t1\t0\t0\t0\t0\t1\t0.974\t-10.17\t0\t1\t1.06\t0.94;\n\t12\t2\t377\t24\t0\t0\t1\t1.015\t-10.46\t0\t1\t1.06\t0.94;\n\t13\t1\t18\t2.3\t0\t0\t1\t0.979\t-9.79\t0\t1\t1.06\t0.94;\n\t14\t1\t10.5\t5.3\t0\t0\t1\t0.97\t-9.33\t0\t1\t1.06\t0.94;\n\t15\t1\t22\t5\t0\t0\t1\t0.988\t-7.18\t0\t1\t1.06\t0.94;\n\t16\t1\t43\t3\t0\t0\t1\t1.013\t-8.85\t0\t1\t1.06\t0.94;\n\t17\t1\t42\t8\t0\t0\t1\t1.017\t-5.39\t0\t1\t1.06\t0.94;\n\t18\t1\t27.2\t9.8\t0\t10\t1\t1.001\t-11.71\t0\t1\t1.06\t0.94;\n\t19\t1\t3.3\t0.6\t0\t0\t1\t0.97\t-13.2\t0\t1\t1.06\t0.94;\n\t20\t1\t2.3\t1\t0\t0\t1\t0.964\t-13.41\t0\t1\t1.06\t0.94;\n\t21\t1\t0\t0\t0\t0\t1\t1.008\t-12.89\t0\t1\t1.06\t0.94;\n\t22\t1\t0\t0\t0\t0\t1\t1.01\t-12.84\t0\t1\t1.06\t0.94;\n\t23\t1\t6.3\t2.1\t0\t0\t1\t1.008\t-12.91\t0\t1\t1.06\t0.94;\n\t24\t1\t0\t0\t0\t0\t1\t0.999\t-13.25\t0\t1\t1.06\t0.94;\n\t25\t1\t6.3\t3.2\t0\t5.9\t1\t0.982\t-18.13\t0\t1\t1.06\t0.94;\n\t26\t1\t0\t0\t0\t0\t1\t0.959\t-12.95\t0\t1\t1.06\t0.94;\n\t27\t1\t9.3\t0.5\t0\t0\t1\t0.982\t-11.48\t0\t1\t1.06\t0.94;\n\t28\t1\t4.6\t2.3\t0\t0\t1\t0.997\t-10.45\t0\t1\t1.06\t0.94;\n\t29\t1\t17\t2.6\t0\t0\t1\t1.01\t-9.75\t0\t1\t1.06\t0.94;\n\t30\t1\t3.6\t1.8\t0\t0\t1\t0.962\t-18.68\t0\t1\t1.06\t0.94;\n\t31\t1\t5.8\t2.9\t0\t0\t1\t0.936\t-19.34\t0\t1\t1.06\t0.94;\n\t32\t1\t1.6\t0.8\t0\t0\t1\t0.949\t-18.46\t0\t1\t1.06\t0.94;\n\t33\t1\t3.8\t1.9\t0\t0\t1\t0.947\t-18.5\t0\t1\t1.06\t0.94;\n\t34\t1\t0\t0\t0\t0\t1\t0.959\t-14.1\t0\t1\t1.06\t0.94;\n\t35\t1\t6\t3\t0\t0\t1\t0.966\t-13.86\t0\t1\t1.06\t0.94;\n\t36\t1\t0\t0\t0\t0\t1\t0.976\t-13.59\t0\t1\t1.06\t0.94;\n\t37\t1\t0\t0\t0\t0\t1\t0.985\t-13.41\t0\t1\t1.06\t0.94;\n\t38\t1\t14\t7\t0\t0\t1\t1.013\t-12.71\t0\t1\t1.06\t0.94;\n\t39\t1\t0\t0\t0\t0\t1\t0.983\t-13.46\t0\t1\t1.06\t0.94;\n\t40\t1\t0\t0\t0\t0\t1\t0.973\t-13.62\t0\t1\t1.06\t0.94;\n\t41\t1\t6.3\t3\t0\t0\t1\t0.996\t-14.05\t0\t1\t1.06\t0.94;\n\t42\t1\t7.1\t4.4\t0\t0\t1\t0.966\t-15.5\t0\t1\t1.06\t0.94;\n\t43\t1\t2\t1\t0\t0\t1\t1.01\t-11.33\t0\t1\t1.06\t0.94;\n\t44\t1\t12\t1.8\t0\t0\t1\t1.017\t-11.86\t0\t1\t1.06\t0.94;\n\t45\t1\t0\t0\t0\t0\t1\t1.036\t-9.25\t0\t1\t1.06\t0.94;\n\t46\t1\t0\t0\t0\t0\t1\t1.05\t-11.89\t0\t1\t1.06\t0.94;\n\t47\t1\t29.7\t11.6\t0\t0\t1\t1.033\t-12.49\t0\t1\t1.06\t0.94;\n\t48\t1\t0\t0\t0\t0\t1\t1.027\t-12.59\t0\t1\t1.06\t0.94;\n\t49\t1\t18\t8.5\t0\t0\t1\t1.036\t-12.92\t0\t1\t1.06\t0.94;\n\t50\t1\t21\t10.5\t0\t0\t1\t1.023\t-13.39\t0\t1\t1.06\t0.94;\n\t51\t1\t18\t5.3\t0\t0\t1\t1.052\t-12.52\t0\t1\t1.06\t0.94;\n\t52\t1\t4.9\t2.2\t0\t0\t1\t0.98\t-11.47\t0\t1\t1.06\t0.94;\n\t53\t1\t20\t10\t0\t6.3\t1\t0.971\t-12.23\t0\t1\t1.06\t0.94;\n\t54\t1\t4.1\t1.4\t0\t0\t1\t0.996\t-11.69\t0\t1\t1.06\t0.94;\n\t55\t1\t6.8\t3.4\t0\t0\t1\t1.031\t-10.78\t0\t1\t1.06\t0.94;\n\t56\t1\t7.6\t2.2\t0\t0\t1\t0.968\t-16.04\t0\t1\t1.06\t0.94;\n\t57\t1\t6.7\t2\t0\t0\t1\t0.965\t-16.56\t0\t1\t1.06\t0.94;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\ngen = [\n\t1\t128.9\t-16.1\t200\t-140\t1.04\t100\t1\t575.88\t0;\n\t2\t0\t-0.8\t50\t-17\t1.01\t100\t1\t100\t0;\n\t3\t40\t-1\t60\t-10\t0.985\t100\t1\t140\t0;\n\t6\t0\t0.8\t25\t-8\t0.98\t100\t1\t100\t0;\n\t8\t450\t62.1\t200\t-140\t1.005\t100\t1\t550\t0;\n\t9\t0\t2.2\t9\t-3\t0.98\t100\t1\t100\t0;\n\t12\t310\t128.5\t155\t-150\t1.015\t100\t1\t410\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\nbranch = [\n\t1\t2\t0.0083\t0.028\t0.129\t9900\t0\t0\t0\t0\t1;\n\t2\t3\t0.0298\t0.085\t0.0818\t9900\t0\t0\t0\t0\t1;\n\t3\t4\t0.0112\t0.0366\t0.038\t9900\t0\t0\t0\t0\t1;\n\t4\t5\t0.0625\t0.132\t0.0258\t9900\t0\t0\t0\t0\t1;\n\t4\t6\t0.043\t0.148\t0.0348\t9900\t0\t0\t0\t0\t1;\n\t6\t7\t0.02\t0.102\t0.0276\t9900\t0\t0\t0\t0\t1;\n\t6\t8\t0.0339\t0.173\t0.047\t9900\t0\t0\t0\t0\t1;\n\t8\t9\t0.0099\t0.0505\t0.0548\t9900\t0\t0\t0\t0\t1;\n\t9\t10\t0.0369\t0.1679\t0.044\t9900\t0\t0\t0\t0\t1;\n\t9\t11\t0.0258\t0.0848\t0.0218\t9900\t0\t0\t0\t0\t1;\n\t9\t12\t0.0648\t0.295\t0.0772\t9900\t0\t0\t0\t0\t1;\n\t9\t13\t0.0481\t0.158\t0.0406\t9900\t0\t0\t0\t0\t1;\n\t13\t14\t0.0132\t0.0434\t0.011\t9900\t0\t0\t0\t0\t1;\n\t13\t15\t0.0269\t0.0869\t0.023\t9900\t0\t0\t0\t0\t1;\n\t1\t15\t0.0178\t0.091\t0.0988\t9900\t0\t0\t0\t0\t1;\n\t1\t16\t0.0454\t0.206\t0.0546\t9900\t0\t0\t0\t0\t1;\n\t1\t17\t0.0238\t0.108\t0.0286\t9900\t0\t0\t0\t0\t1;\n\t3\t15\t0.0162\t0.053\t0.0544\t9900\t0\t0\t0\t0\t1;\n\t4\t18\t0\t0.555\t0\t9900\t0\t0\t0.97\t0\t1;\n\t4\t18\t0\t0.43\t0\t9900\t0\t0\t0.978\t0\t1;\n\t5\t6\t0.0302\t0.0641\t0.0124\t9900\t0\t0\t0\t0\t1;\n\t7\t8\t0.0139\t0.0712\t0.0194\t9900\t0\t0\t0\t0\t1;\n\t10\t12\t0.0277\t0.1262\t0.0328\t9900\t0\t0\t0\t0\t1;\n\t11\t13\t0.0223\t0.0732\t0.0188\t9900\t0\t0\t0\t0\t1;\n\t12\t13\t0.0178\t0.058\t0.0604\t9900\t0\t0\t0\t0\t1;\n\t12\t16\t0.018\t0.0813\t0.0216\t9900\t0\t0\t0\t0\t1;\n\t12\t17\t0.0397\t0.179\t0.0476\t9900\t0\t0\t0\t0\t1;\n\t14\t15\t0.0171\t0.0547\t0.0148\t9900\t0\t0\t0\t0\t1;\n\t18\t19\t0.461\t0.685\t0\t9900\t0\t0\t0\t0\t1;\n\t19\t20\t0.283\t0.434\t0\t9900\t0\t0\t0\t0\t1;\n\t21\t20\t0\t0.7767\t0\t9900\t0\t0\t1.043\t0\t1;\n\t21\t22\t0.0736\t0.117\t0\t9900\t0\t0\t0\t0\t1;\n\t22\t23\t0.0099\t0.0152\t0\t9900\t0\t0\t0\t0\t1;\n\t23\t24\t0.166\t0.256\t0.0084\t9900\t0\t0\t0\t0\t1;\n\t24\t25\t0\t1.182\t0\t9900\t0\t0\t1\t0\t1;\n\t24\t25\t0\t1.23\t0\t9900\t0\t0\t1\t0\t1;\n\t24\t26\t0\t0.0473\t0\t9900\t0\t0\t1.043\t0\t1;\n\t26\t27\t0.165\t0.254\t0\t9900\t0\t0\t0\t0\t1;\n\t27\t28\t0.0618\t0.0954\t0\t9900\t0\t0\t0\t0\t1;\n\t28\t29\t0.0418\t0.0587\t0\t9900\t0\t0\t0\t0\t1;\n\t7\t29\t0\t0.0648\t0\t9900\t0\t0\t0.967\t0\t1;\n\t25\t30\t0.135\t0.202\t0\t9900\t0\t0\t0\t0\t1;\n\t30\t31\t0.326\t0.497\t0\t9900\t0\t0\t0\t0\t1;\n\t31\t32\t0.507\t0.755\t0\t9900\t0\t0\t0\t0\t1;\n\t32\t33\t0.0392\t0.036\t0\t9900\t0\t0\t0\t0\t1;\n\t34\t32\t0\t0.953\t0\t9900\t0\t0\t0.975\t0\t1;\n\t34\t35\t0.052\t0.078\t0.0032\t9900\t0\t0\t0\t0\t1;\n\t35\t36\t0.043\t0.0537\t0.0016\t9900\t0\t0\t0\t0\t1;\n\t36\t37\t0.029\t0.0366\t0\t9900\t0\t0\t0\t0\t1;\n\t37\t38\t0.0651\t0.1009\t0.002\t9900\t0\t0\t0\t0\t1;\n\t37\t39\t0.0239\t0.0379\t0\t9900\t0\t0\t0\t0\t1;\n\t36\t40\t0.03\t0.0466\t0\t9900\t0\t0\t0\t0\t1;\n\t22\t38\t0.0192\t0.0295\t0\t9900\t0\t0\t0\t0\t1;\n\t11\t41\t0\t0.749\t0\t9900\t0\t0\t0.955\t0\t1;\n\t41\t42\t0.207\t0.352\t0\t9900\t0\t0\t0\t0\t1;\n\t41\t43\t0\t0.412\t0\t9900\t0\t0\t0\t0\t1;\n\t38\t44\t0.0289\t0.0585\t0.002\t9900\t0\t0\t0\t0\t1;\n\t15\t45\t0\t0.1042\t0\t9900\t0\t0\t0.955\t0\t1;\n\t14\t46\t0\t0.0735\t0\t9900\t0\t0\t0.9\t0\t1;\n\t46\t47\t0.023\t0.068\t0.0032\t9900\t0\t0\t0\t0\t1;\n\t47\t48\t0.0182\t0.0233\t0\t9900\t0\t0\t0\t0\t1;\n\t48\t49\t0.0834\t0.129\t0.0048\t9900\t0\t0\t0\t0\t1;\n\t49\t50\t0.0801\t0.128\t0\t9900\t0\t0\t0\t0\t1;\n\t50\t51\t0.1386\t0.22\t0\t9900\t0\t0\t0\t0\t1;\n\t10\t51\t0\t0.0712\t0\t9900\t0\t0\t0.93\t0\t1;\n\t13\t49\t0\t0.191\t0\t9900\t0\t0\t0.895\t0\t1;\n\t29\t52\t0.1442\t0.187\t0\t9900\t0\t0\t0\t0\t1;\n\t52\t53\t0.0762\t0.0984\t0\t9900\t0\t0\t0\t0\t1;\n\t53\t54\t0.1878\t0.232\t0\t9900\t0\t0\t0\t0\t1;\n\t54\t55\t0.1732\t0.2265\t0\t9900\t0\t0\t0\t0\t1;\n\t11\t43\t0\t0.153\t0\t9900\t0\t0\t0.958\t0\t1;\n\t44\t45\t0.0624\t0.1242\t0.004\t9900\t0\t0\t0\t0\t1;\n\t40\t56\t0\t1.195\t0\t9900\t0\t0\t0.958\t0\t1;\n\t56\t41\t0.553\t0.549\t0\t9900\t0\t0\t0\t0\t1;\n\t56\t42\t0.2125\t0.354\t0\t9900\t0\t0\t0\t0\t1;\n\t39\t57\t0\t1.355\t0\t9900\t0\t0\t0.98\t0\t1;\n\t57\t56\t0.174\t0.26\t0\t9900\t0\t0\t0\t0\t1;\n\t38\t49\t0.115\t0.177\t0.003\t9900\t0\t0\t0\t0\t1;\n\t38\t48\t0.0312\t0.0482\t0\t9900\t0\t0\t0\t0\t1;\n\t9\t55\t0\t0.1205\t0\t9900\t0\t0\t0.94\t0\t1;\n];\n\n%%-----  OPF Data  -----%%\n%% area data\nareas = [\n\t1\t1;\n];\n\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx0\ty0\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\ngencost = [\n\t2\t0\t0\t3\t0.0775795\t20\t0;\n\t2\t0\t0\t3\t0.01\t40\t0;\n\t2\t0\t0\t3\t0.25\t20\t0;\n\t2\t0\t0\t3\t0.01\t40\t0;\n\t2\t0\t0\t3\t0.0222222\t20\t0;\n\t2\t0\t0\t3\t0.01\t40\t0;\n\t2\t0\t0\t3\t0.0322581\t20\t0;\n];\n\nreturn;\n\n% Warnings from cdf2matp conversion:\n%\n% ***** Qmax = Qmin at generator at bus    1 (Qmax set to Qmin + 10)\n% ***** area data conversion not yet implemented (creating dummy area data)\n% ***** Insufficient generation, setting Pmax at slack bus (bus 1) to 575.88\n% ***** MVA limit of branch 1 - 2 not given, set to 9900\n% ***** MVA limit of branch 2 - 3 not given, set to 9900\n% ***** MVA limit of branch 3 - 4 not given, set to 9900\n% ***** MVA limit of branch 4 - 5 not given, set to 9900\n% ***** MVA limit of branch 4 - 6 not given, set to 9900\n% ***** MVA limit of branch 6 - 7 not given, set to 9900\n% ***** MVA limit of branch 6 - 8 not given, set to 9900\n% ***** MVA limit of branch 8 - 9 not given, set to 9900\n% ***** MVA limit of branch 9 - 10 not given, set to 9900\n% ***** MVA limit of branch 9 - 11 not given, set to 9900\n% ***** MVA limit of branch 9 - 12 not given, set to 9900\n% ***** MVA limit of branch 9 - 13 not given, set to 9900\n% ***** MVA limit of branch 13 - 14 not given, set to 9900\n% ***** MVA limit of branch 13 - 15 not given, set to 9900\n% ***** MVA limit of branch 1 - 15 not given, set to 9900\n% ***** MVA limit of branch 1 - 16 not given, set to 9900\n% ***** MVA limit of branch 1 - 17 not given, set to 9900\n% ***** MVA limit of branch 3 - 15 not given, set to 9900\n% ***** MVA limit of branch 4 - 18 not given, set to 9900\n% ***** MVA limit of branch 4 - 18 not given, set to 9900\n% ***** MVA limit of branch 5 - 6 not given, set to 9900\n% ***** MVA limit of branch 7 - 8 not given, set to 9900\n% ***** MVA limit of branch 10 - 12 not given, set to 9900\n% ***** MVA limit of branch 11 - 13 not given, set to 9900\n% ***** MVA limit of branch 12 - 13 not given, set to 9900\n% ***** MVA limit of branch 12 - 16 not given, set to 9900\n% ***** MVA limit of branch 12 - 17 not given, set to 9900\n% ***** MVA limit of branch 14 - 15 not given, set to 9900\n% ***** MVA limit of branch 18 - 19 not given, set to 9900\n% ***** MVA limit of branch 19 - 20 not given, set to 9900\n% ***** MVA limit of branch 21 - 20 not given, set to 9900\n% ***** MVA limit of branch 21 - 22 not given, set to 9900\n% ***** MVA limit of branch 22 - 23 not given, set to 9900\n% ***** MVA limit of branch 23 - 24 not given, set to 9900\n% ***** MVA limit of branch 24 - 25 not given, set to 9900\n% ***** MVA limit of branch 24 - 25 not given, set to 9900\n% ***** MVA limit of branch 24 - 26 not given, set to 9900\n% ***** MVA limit of branch 26 - 27 not given, set to 9900\n% ***** MVA limit of branch 27 - 28 not given, set to 9900\n% ***** MVA limit of branch 28 - 29 not given, set to 9900\n% ***** MVA limit of branch 7 - 29 not given, set to 9900\n% ***** MVA limit of branch 25 - 30 not given, set to 9900\n% ***** MVA limit of branch 30 - 31 not given, set to 9900\n% ***** MVA limit of branch 31 - 32 not given, set to 9900\n% ***** MVA limit of branch 32 - 33 not given, set to 9900\n% ***** MVA limit of branch 34 - 32 not given, set to 9900\n% ***** MVA limit of branch 34 - 35 not given, set to 9900\n% ***** MVA limit of branch 35 - 36 not given, set to 9900\n% ***** MVA limit of branch 36 - 37 not given, set to 9900\n% ***** MVA limit of branch 37 - 38 not given, set to 9900\n% ***** MVA limit of branch 37 - 39 not given, set to 9900\n% ***** MVA limit of branch 36 - 40 not given, set to 9900\n% ***** MVA limit of branch 22 - 38 not given, set to 9900\n% ***** MVA limit of branch 11 - 41 not given, set to 9900\n% ***** MVA limit of branch 41 - 42 not given, set to 9900\n% ***** MVA limit of branch 41 - 43 not given, set to 9900\n% ***** MVA limit of branch 38 - 44 not given, set to 9900\n% ***** MVA limit of branch 15 - 45 not given, set to 9900\n% ***** MVA limit of branch 14 - 46 not given, set to 9900\n% ***** MVA limit of branch 46 - 47 not given, set to 9900\n% ***** MVA limit of branch 47 - 48 not given, set to 9900\n% ***** MVA limit of branch 48 - 49 not given, set to 9900\n% ***** MVA limit of branch 49 - 50 not given, set to 9900\n% ***** MVA limit of branch 50 - 51 not given, set to 9900\n% ***** MVA limit of branch 10 - 51 not given, set to 9900\n% ***** MVA limit of branch 13 - 49 not given, set to 9900\n% ***** MVA limit of branch 29 - 52 not given, set to 9900\n% ***** MVA limit of branch 52 - 53 not given, set to 9900\n% ***** MVA limit of branch 53 - 54 not given, set to 9900\n% ***** MVA limit of branch 54 - 55 not given, set to 9900\n% ***** MVA limit of branch 11 - 43 not given, set to 9900\n% ***** MVA limit of branch 44 - 45 not given, set to 9900\n% ***** MVA limit of branch 40 - 56 not given, set to 9900\n% ***** MVA limit of branch 56 - 41 not given, set to 9900\n% ***** MVA limit of branch 56 - 42 not given, set to 9900\n% ***** MVA limit of branch 39 - 57 not given, set to 9900\n% ***** MVA limit of branch 57 - 56 not given, set to 9900\n% ***** MVA limit of branch 38 - 49 not given, set to 9900\n% ***** MVA limit of branch 38 - 48 not given, set to 9900\n% ***** MVA limit of branch 9 - 55 not given, set to 9900\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19961-power-flow-software-in-rectangular-coordinates/finallf/c57.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "function this = alt_ba_optical_flow(varargin)\n%\n%ALT_BA_OPTICAL_FLOW   \n%       \n%   ALT_BA_OPTICAL_FLOW([IMGS]) constructs a ALT_BA optical flow object\n%   with the optional image sequence IMGS ([n x m x 2] array). \n%   ALT_BA_OPTICAL_FLOW(O) constructs BA optical flow object by copying O.\n%  \n%   This is a member function of the class 'alt_ba_optical_flow'. \n%\n% Authors: Deqing Sun, Department of Computer Science, Brown University\n% Contact: dqsun@cs.brown.edu\n% $Date: 2009 $\n% $Revision: $\n%\n% Copyright 2009-2010, Brown University, Providence, RI. USA\n% \n%                          All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes.     \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission.        \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE.        \n\nerror(nargchk(0, 1, length(varargin)));\n  \n  switch (length(varargin))\n    case 0\n        \n      this.images          = [];              \n      this.lambda          = 5;\n      this.lambda_q        = 5;    % Quadratic formulation of the objective function\n      \n      \n      this.sor_max_iters   = 1e4;       % 100 seems sufficient\n\n      this.limit_update    = true;      % limit the flow incrment to be less than 1 per linearization step\n      this.display         = false;      \n      \n      \n      this.solver          = 'backslash';   % 'sor' 'pcg' for machines with limited moemory \n      this.warping_mode    = 'backward';\n      \n      this.texture              = false;     % use texture component as input\n      this.deriv_filter         = [1 -8 0 8 -1]/12; % 5-point 7 point [-1 9 -45 0 45 -9 1]/60; \n      this.median_filter_size   = []; %[5 5];\n      this.interpolation_method = 'cubic';  % 'bi-cubic', 'cubic', 'bi-linear'\n            \n      % For Graduated Non-Convexity (GNC) optimization\n      this.gnc_iters       = 3;\n      this.alpha           = 1;             % change linearly from 1 to 0 through the GNC stages\n\n      this.max_iters       = 10;            % number of warping per pyramid level\n      this.max_linear      = 1;             % maximum number of linearization performed per warping, 1 OK for HS\n      \n      % For GNC stage 1\n      this.pyramid_levels  = 4;           \n      this.pyramid_spacing = 2;\n\n      % For GNC stage 2 to end\n      this.gnc_pyramid_levels     = 2;\n      this.gnc_pyramid_spacing    = 1.25;           \n\n      method = 'lorentzian'; %'geman_mcclure'; %\n      this.spatial_filters = {[1 -1], [1; -1]};  \n      for i = 1:length(this.spatial_filters);\n          this.rho_spatial_u{i}   = robust_function(method, 0.03); % 0.1\n          this.rho_spatial_v{i}   = robust_function(method, 0.03);      \n      end;\n      this.rho_data        = robust_function(method, 1.5); % 6.3             \n      \n      this.seg             = [];    % sore segementatio result\n      this.mfT             = 15;    % threshold for intensity-median-filter\n      this.imfsz           = [7 7]; % for intensity-median-filter\n      this.qterm            = true;   % true: use the qterm\n      this.lambda2         = 1e-1;      % weight for coupling term\n      this.lambda3         = 1;         % weight for non local term term\n      this.weightRatio     = 1;     % lambdaA/weight on the forth term\n      this.itersLO         = 1;     % # Li & Osher iterations \n      this.color_images     = [];      \n      this.replacment       = true; \n      \n%       this.rho_couple       = robust_function('quadratic', 1);      % penalty function for coupling term\n      this.rho_couple       = robust_function('charbonnier', 1e-3);      % penalty function for coupling term\n      \n      this = class(this, 'alt_ba_optical_flow');         \n      \n    case 1\n      if isa(varargin{1}, 'alt_ba_optical_flow')\n        this = varargin{1};        \n      else    \n          this = alt_ba_optical_flow;\n          this.images = varargin{1};  \n      end\n      \n    otherwise\n      error('Incompatible arguments!');\n      \n  end", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/@alt_ba_optical_flow/alt_ba_optical_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "function [reac, exMets, micRea, binOrg, patOrg, reacPat, reacNumb, reacSet, reacTab, reacAbun, reacNumber] = getMappingInfo(modPath, organisms, abunFilePath)\n% This function automatically extracts information from strain abundances in\n% different individuals and combines this information into different tables.\n%\n% USAGE:\n%\n%    [reac, exMets, micRea, binOrg, patOrg, reacPat, reacNumb, reacSet, reacTab, reacAbun, reacNumber] = getMappingInfo(modPath, organisms, abunFilePath, patNumb)\n%\n% INPUTS:\n%   organisms:         nx1 cell array cell array with names of organisms in the study\n%   modPath:           char with path of directory where models are stored\n%   abunFilePath:      char with path and name of file from which to retrieve abundance information\n%   patNumb:           number of individuals in the study\n%\n% OUTPUTS:\n%   reac:              cell array with all the unique set of reactions\n%                      contained in the models\n%   exMets:            cell array with all unique extracellular metabolites\n%                      contained in the models\n%   micRea:            binary matrix assessing presence of set of unique\n%                      reactions for each of the microbes\n%   binOrg:            binary matrix assessing presence of specific strains in\n%                      different individuals\n%   reacPat:           matrix with number of reactions per individual\n%                      (organism resolved)\n%   reacSet:           matrix with names of reactions of each individual\n%   reacTab:           char with names of individuals in the study\n%   reacAbun:          binary matrix with presence/absence of reaction per\n%                      individual: to compare different individuals\n%   reacNumber:        number of unique reactions of each individual\n%\n% .. Author: Federico Baldini 2017-2018\n\nreac = {}; % array with unique set of all the reactions present in the models\nexMets = {}; % array with unique set of all the extracellular metabolites present in the models\n\nmodels = {};\nparfor i = 1:length(organisms) % find the unique set of all the reactions contained in the models\n    model =readCbModel([modPath filesep organisms{i,1} '.mat']);\n    models{i, 1} = model;\nend\n\nfor i = 1:length(organisms) % find the unique set of all the reactions contained in the models\n    smd = models{i, 1};\n    reac = union(reac,smd.rxns);\n    findmets = smd.mets(find(contains(smd.mets,'[e]')));\n    exMets = union(exMets,findmets);\nend\n\n% Code to detect reaction presence in each model and create inary matrix\n% assessing presence of set of unique reactions for each of the microbes\n\nmicRea = zeros(length(models), length(reac));\n\nmdlt = length(models);\nparfor i = 1:mdlt\n    model = models{i, 1};\n    micRea(i,:) = ismember(reac,model.rxns)\nend\n\n% creating binary table for abundances\n[abundance] = readtable(abunFilePath);\n\n[binary] = abundance;\ns = size(binary);\ns = s(1, 2);\nbinary = binary(:, 2:s);  % removing model info and others\nbinary{:,:} = double(binary{:,:}~=0);\nbinOrg = binary;\n\n% Compute number of reactions per individual (species resolved)\n\nreacPat = zeros(length(table2cell(binOrg(:, 1))), length(table2cell(binOrg(1, :))));\ncleantabc = table2cell(binOrg);\nfor j = 1:length(table2cell(binOrg(1, :)))\n    for i = 1:length(table2cell(binOrg(:, 1)))\n        temp = cell2mat(cleantabc(i, j));\n        if temp == 1\n            reacPat(i, j) = sum(micRea(i, :));\n        end\n    end\nend\n\n% Computing overall (non unique) number of reactions per individual\n\ntotReac = [];\nfor i = 1:length(reacPat(1, :))\n    totReac(i, 1) = sum(reacPat(:, i));\nend\n\n% Computing number of reactions per organism\n\nreacNumb = [];\nfor i = 1:length(micRea(:, 1))\n    reacNumb(i, 1) = sum(micRea(i, :));\nend\n\n% Computing number of organism per individual\n\npatOrg = [];\nfor i = 1:length(cleantabc(1, :))\n    patOrg(i, 1) = sum(table2array(binOrg(:, i)));\nend\npatOrg = patOrg';\n\n% number and names of UNIQUE reactions per patient\n% Briefly, the nonunique reaction content of each individual (reacvec) is \n% retrieved from the binary matrix of microbial presence (binOrg) and each of \n% the related models. The same is also done using the abundance table for \n% establishing reactions coefficients (abunvec) on the base of microbial presence. \n% We end up with two nonunique matrices: (completeset) containing reaction content \n% for each individual and (completeabunnorm).  Finally, for each individual using \n% a list of unique reactions in all the study (reac) all the matches are found and \n% the correspondent abundances summed up (numbtab). \n\nreacSet = {};\nreacNumber = [];\n\nfor j = 1: length(table2cell(binOrg(1, :)))\n    abunvec = [];\n    reacvec = [];\n    for i = 1: length(table2cell(binOrg(:, 1)))\n        if (cell2mat(table2cell(binOrg(i, j)))) == 1\n            model = models{i, 1};\n            reacvec = vertcat(reacvec, model.rxns);\n            abunvec((length(abunvec) + 1): ((length(abunvec)) + length(model.rxns))) = table2array(abundance(i, j + 1));\n        end\n    end\n\n    completeset(1:length(reacvec), j) = reacvec;  % to get lists of reactions per each individual\n    completeabunorm(1:length(reacvec), j) = abunvec';  % matrix with abundance coefficients for normalization\n    reacSet(1:length(unique(reacvec)), j) = unique(reacvec);  % to get lists of reactions per each individual\n    reacNumber(j) = length(unique(reacvec));\nend\n\nreacLng = length(reac);\n\nparfor j = 2:size(abundance,2)\n    for i = 1:reacLng\n        indrxn = find(strcmp(reac(i, 1), completeset(:, j-1)));\n        numbtab(i, j-1) = sum(completeabunorm(indrxn,j-1));\n    end\nend\n\nreacAbun = [reac, num2cell(numbtab)];\n\n\n% presence/absence of reaction per patient: to compare different patients\n% with pCoA\nreacTab = zeros(length(reac), length(reacPat(1, :)));\n\n\nparfor k = 1: length(reacPat(1, :))\n    match = zeros(1,length(reac));\n        for i = 1: length(reac)\n            for j = 1: length(reacSet(:, 1))\n                if strcmp(reac(i), reacSet(j, k)) == 1  % the 2 reactions are equal\n                    match(i) = 1;\n                end\n            end\n        end\n    reacTab(:, k) = match\nend\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/multiSpecies/microbiomeModelingToolbox/mgPipe/getMappingInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "clear;close all;clc;j=1i;\nGlobal_Parameters;\n%% Hardware Parameters\nMode='transmitRepeat'; % Select Mode\ntx_object = sdrtx('ZedBoard and FMCOMMS2/3/4', ...\n           'IPAddress',            '192.168.3.2', ...\n           'CenterFrequency',      Parameters_struct.CenterFrequency, ...\n           'BasebandSampleRate',   Parameters_struct.Bandwidth, ...  % Bandwidth\n           'Gain',                 -10, ...\n           'ChannelMapping',       1);\n%          'EnableBurstMode',1,...\n\n%% Button Setting\nfigure('Name','TX','NumberTitle','off');\nTransmittingDisplay = uicontrol('Style', 'text', 'Position',[55,150,155,35],'String', 'Transmitting','FontSize',20,'HorizontalAlignment','left','BackgroundColor',[0.937 0.867 0.867]);\nbutton = uicontrol; % Generate GUI button\nset(button,'String','Stop !','Position',[80 50 100 60]); % Add \"Stop !\" text\nset(gcf,'Units','centimeters','position',[3 3 7 6]); % Set the postion of GUI\n%% TX Load\nload('TX_signal'); % [1x972]\n% transmitRepeat Mode\nTX_Hardware = repmat(TX_signal.',5,1); % Transmit Data must be >= 4096 % [4860x1]\nstate = 1;\n%% Main\nswitch Mode\n    case 'step'\n        while(state == 1)\n           step(tx_object,TX_Hardware);\n           % ----- Button Behavior -----%\n           set(button,'Callback','setstate0_TX'); % Set the reaction of pushing button\n           drawnow;\n        end\n        release(tx_object);\n\n    case 'transmitRepeat'\n        transmitRepeat(tx_object,TX_Hardware);\n        % ----- Button Behavior -----%\n        set(button,'Callback','setstate0_TX'); % Set the reaction of pushing button\nend", "meta": {"author": "MeowLucian", "repo": "SDR_Matlab_OFDM_802.11a", "sha": "ee4a1ff01799242bad455054bfb318242250f973", "save_path": "github-repos/MATLAB/MeowLucian-SDR_Matlab_OFDM_802.11a", "path": "github-repos/MATLAB/MeowLucian-SDR_Matlab_OFDM_802.11a/SDR_Matlab_OFDM_802.11a-ee4a1ff01799242bad455054bfb318242250f973/Hardware_TX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2411819813664201}}
{"text": "function test_bug2770\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY eeglab2fieldtrip\n\n% the *.set file is actually a MATLAB file with the EEG structure in it\n% but it require EEGLAB to read it together with the ftd (which has the binary data)\n\n% I imported the data in EEGLAB with the GUI, and then saved it to a *.mat file\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug2770/164_MIST_prac.mat'));\n\n% the eeglab2fieldtrip function is maintained\nft_hastoolbox('eeglab', 1);\n\ndata = eeglab2fieldtrip(EEG, 'preprocessing', 'none');\n\ncfg = [];\ncfg.method = 'mtmfft';\ncfg.taper = 'hanning';\ncfg.foilim = [4 7];\ncfg.output = 'pow';\nfreq = ft_freqanalysis(cfg,data); % this failed\n\ncfg = [];\ncfg.trials = 'all';\ncfg.channel = 'all';\ndata1 = ft_selectdata(cfg, data);\nassert(isfield(data1, 'trial')); % this failed\n\n% this is actually at the core of the problem\nassert(numel(data.label)==size(data.trial{1},1));\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2770.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24118197534741484}}
{"text": "function [source] = ft_dipolefitting(cfg, data)\n\n% FT_DIPOLEFITTING perform grid search and non-linear fit with one or multiple\n% dipoles and try to find the location where the dipole model is best able\n% to explain the measured EEG or MEG topography.\n%\n% This function will initially scan the whole brain with a single dipole on\n% a regular coarse grid, and subsequently start at the most optimal location\n% with a non-linear search. Alternatively you can specify the initial\n% location of the dipole(s) and the non-linear search will start from there.\n%\n% Use as\n%   [source] = ft_dipolefitting(cfg, data)\n%\n% The configuration has the following general fields\n%   cfg.numdipoles  = number, default is 1\n%   cfg.symmetry    = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = [])\n%   cfg.channel     = Nx1 cell-array with selection of channels (default = 'all'),\n%                     see FT_CHANNELSELECTION for details\n%   cfg.gridsearch  = 'yes' or 'no', perform global search for initial\n%                     guess for the dipole parameters (default = 'yes')\n%   cfg.nonlinear   = 'yes' or 'no', perform nonlinear search for optimal\n%                     dipole parameters (default = 'yes')\n%\n% If you start with a grid search, the complete grid with dipole positions is\n% constructed using FT_PREPARE_SOURCEMODEL. It can be specified as as a regular 3-D\n% grid that is aligned with the axes of the head coordinate system using\n%   cfg.xgrid               = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.ygrid               = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.zgrid               = vector (e.g.   0:1:20) or 'auto' (default = 'auto')\n%   cfg.resolution          = number (e.g. 1 cm) for automatic grid generation\n% If the source model destribes a triangulated cortical sheet, it is described as\n%   cfg.sourcemodel.pos     = N*3 matrix with the vertex positions of the cortical sheet\n%   cfg.sourcemodel.tri     = M*3 matrix that describes the triangles connecting the vertices\n% Alternatively the position of a few dipoles at locations of interest can be\n% user-specified, for example obtained from an anatomical or functional MRI\n%   cfg.sourcemodel.pos     = N*3 matrix with position of each source\n%   cfg.sourcemodel.inside  = N*1 vector with boolean value whether grid point is inside brain (optional)\n%   cfg.sourcemodel.dim     = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional)\n%\n% If you do not start with a grid search, you have to give a starting location\n% for the nonlinear search\n%   cfg.dip.pos     = initial dipole position, matrix of Ndipoles x 3\n%\n% The conventional approach is to fit dipoles to event-related averages, which\n% within FieldTrip can be obtained from the FT_TIMELOCKANALYSIS or from\n% the FT_TIMELOCKGRANDAVERAGE function. This has the additional options\n%   cfg.latency     = [begin end] in seconds or 'all' (default = 'all')\n%   cfg.model       = 'moving' or 'regional'\n% A moving dipole model has a different position (and orientation) for each\n% timepoint, or for each component. A regional dipole model has the same\n% position for each timepoint or component, and a different orientation.\n%\n% You can also fit dipoles to the spatial topographies of an independent\n% component analysis, obtained from the FT_COMPONENTANALYSIS function.\n% This has the additional options\n%   cfg.component   = array with numbers (can be empty -> all)\n%\n% You can also fit dipoles to the spatial topographies that are present\n% in the data in the frequency domain, which can be obtained using the\n% FT_FREQANALYSIS function. This has the additional options\n%   cfg.frequency   = single number (in Hz)\n%\n% Low level details of the fitting can be specified in the cfg.dipfit structure\n%   cfg.dipfit.display      = level of display, can be 'off', 'iter', 'notify' or 'final' (default = 'iter')\n%   cfg.dipfit.optimfun     = function to use, can be 'fminsearch' or 'fminunc' (default is determined automatic)\n%   cfg.dipfit.maxiter      = maximum number of function evaluations allowed (default depends on the optimfun)\n%   cfg.dipfit.checkinside  = boolean, check that the dipole remains in the source compartment (default = false)\n%\n% Optionally, you can modify the leadfields by reducing the rank, i.e. remove the weakest orientation\n%   cfg.reducerank    = 'no', or number (default = 3 for EEG, 2 for MEG)\n%   cfg.backproject   = 'yes' or 'no',  determines when reducerank is applied whether the\n%                       lower rank leadfield is projected back onto the original linear\n%                       subspace, or not (default = 'yes')\n%\n% The volume conduction model of the head should be specified as\n%   cfg.headmodel     = structure with volume conduction model, see FT_PREPARE_HEADMODEL\n%\n% The EEG or MEG sensor positions can be present in the data or can be specified as\n%   cfg.elec          = structure with electrode positions or filename, see FT_READ_SENS\n%   cfg.grad          = structure with gradiometer definition or filename, see FT_READ_SENS\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_SOURCEANALYSIS, FT_PREPARE_LEADFIELD, FT_PREPARE_HEADMODEL\n\n% TODO change the output format, more suitable would be something like:\n% dip.label\n% dip.time\n% dip.avg (instead of Vdata)\n% dip.dip.pos\n% dip.dip.mom\n% dip.dip.model, or dip.dip.avg\n% dip.dimord\n\n% Undocumented local options:\n%   cfg.dipfit.constr   = Source model constraints, depends on cfg.symmetry\n% Optionally, you can include a noise covariance structure to sphere the data (is useful when using both\n% magnetometers and gradiometers to fit your dipole)\n%   cfg.dipfit.noisecov       = noise covariance matrix, see e.g. FT_TIMELOCK_ANALYSIS\n\n% Copyright (C) 2004-2013, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar data\nft_preamble provenance data\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% check if the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', {'comp', 'timelock', 'freq'}, 'feedback', 'yes');\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden',  {'channels'}); % prevent accidental typos, see issue 1729\ncfg = ft_checkconfig(cfg, 'renamed',    {'elecfile', 'elec'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'gradfile', 'grad'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'optofile', 'opto'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'hdmfile', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'vol',     'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'grid',    'sourcemodel'});\n\n% get the defaults\ncfg.channel         = ft_getopt(cfg, 'channel', 'all');\ncfg.component       = ft_getopt(cfg, 'component', 'all');   % for comp input\ncfg.frequency       = ft_getopt(cfg, 'frequency');          % for freq input\ncfg.latency         = ft_getopt(cfg, 'latency', 'all');     % for timelock input\ncfg.feedback        = ft_getopt(cfg, 'feedback', 'text');\ncfg.gridsearch      = ft_getopt(cfg, 'gridsearch', 'yes');\ncfg.nonlinear       = ft_getopt(cfg, 'nonlinear', 'yes');\ncfg.symmetry        = ft_getopt(cfg, 'symmetry');\ncfg.dipfit          = ft_getopt(cfg, 'dipfit', []);     % the default for this is handled below\n\ncfg = ft_checkconfig(cfg, 'renamed',    {'tightgrid', 'tight'});  % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed',    {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit  by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\n% determine data type\niscomp = ft_datatype(data, 'comp');           % it can also be raw+comp, timelock+comp or freq+comp\nisfreq = ft_datatype(data, 'freq');           % it might also be freq+comp, in that case it should be treated as component data\nistimelock = ft_datatype(data, 'timelock');   % it might also be timelock+comp, in that case it should be treated as component data\n\n% the default for this depends on the data type\nif ~isfield(cfg, 'model')\n  if iscomp\n    % each component is fitted independently\n    cfg.model = 'moving';\n  elseif isfreq\n    % fit the data with a dipole at one location\n    cfg.model = 'regional';\n  elseif istimelock\n    % fit the data with a dipole at one location\n    cfg.model = 'regional';\n  end\nend\n\nif ~isfield(cfg, 'numdipoles')\n  if isfield(cfg, 'dip')\n    cfg.numdipoles = size(cfg.dip(1).pos,1);\n  else\n    cfg.numdipoles = 1;\n  end\nend\n\n% set up the symmetry constraints\nif ~isempty(cfg.symmetry)\n  if cfg.numdipoles~=2\n    ft_error('symmetry constraints are only supported for two-dipole models');\n  elseif strcmp(cfg.symmetry, 'x')\n    % this structure is passed onto the low-level FT_INVERSE_DIPOLEFIT function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 -1 1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 -x1 y1 z1]\n  elseif strcmp(cfg.symmetry, 'y')\n    % this structure is passed onto the low-level FT_INVERSE_DIPOLEFIT function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 1 -1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 -y1 z1]\n  elseif strcmp(cfg.symmetry, 'z')\n    % this structure is passed onto the low-level FT_INVERSE_DIPOLEFIT function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 1 1 -1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 y1 -z1]\n  else\n    ft_error('unrecognized symmetry constraint');\n  end\nelseif ~isfield(cfg, 'dipfit') || ~isfield(cfg.dipfit, 'constr')\n  % no symmetry constraints have been specified\n  cfg.dipfit.constr = [];\nend\n\nif ft_getopt(cfg.dipfit.constr, 'sequential', false) && strcmp(cfg.model, 'moving')\n  ft_error('the moving dipole model does not combine with the sequential constraint')\n  % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3119\nend\n\nif iscomp\n  % transform the data into a representation on which the timelocked dipole fit can perform its trick\n  data = comp2timelock(cfg, data);\n  \n  % default component selection is all components\n  if ischar(cfg.component) && strcmp(cfg.component, 'all')\n    cfg.component = (1:size(data.avg, 2));\n  end\nelseif isfreq\n  % transform the data into a representation on which the timelocked dipole fit can perform its trick\n  data = freq2timelock(cfg, data);\nelseif istimelock\n  % no transformation is needed\nend\n  \n% collect and preprocess the electrodes/gradiometer and head model\n% this will also update cfg.channel to match the electrodes/gradiometers\n[headmodel, sens, cfg] = prepare_headmodel(cfg, data);\n\n% construct the low-level options for the leadfield computation as key-value pairs, these are passed to FT_COMPUTE_LEADFIELD and FT_INVERSE_DIPOLEFIT\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     ft_getopt(cfg, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    ft_getopt(cfg, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      ft_getopt(cfg, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(cfg, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         ft_getopt(cfg, 'weight'));\n\n% construct the low-level options for the dipole fitting as key-value pairs, these are passed to FT_INVERSE_DIPOLEFIT\ndipfitopt = ft_cfg2keyval(cfg.dipfit);\n\n% select the desired channels, ordered according to the sensor structure or configuration\n[selcfg, seldata] = match_str(cfg.channel, data.label);\n% take the selected channels from the data structure\nVdata = data.avg(seldata, :);\n\n% sphere the date using the noise covariance matrix supplied, if any\n% this affects both the gridsearch and the nonlinear optimization\nnoisecov = ft_getopt(cfg.dipfit, 'noisecov');\nif ~isempty(noisecov)\n  [u, s] = svd(noisecov);\n  tol = max(size(noisecov)) * eps(norm(s, inf));\n  s = diag(s);\n  r1 = sum(s > tol) + 1;\n  s(1:(r1 - 1)) = 1 ./ sqrt(s(1:(r1 - 1)));\n  s(r1:end)     = 0;\n  sphere = diag(s) * u';\n  % apply the sphering to the data\n  Vdata = sphere * Vdata;\n  % apply the sphering as a pre-multiplication to the sensor definition\n  montage = [];\n  montage.labelold = cfg.channel;\n  montage.labelnew = cfg.channel;\n  montage.tra = sphere;\n  sens = ft_apply_montage(sens, montage, 'balancename', 'sphering');\nend\n\nif iscomp\n  % select the desired component topographies\n  Vdata = Vdata(:, cfg.component);\nelseif isfreq\n  % the desired frequencies have already been selected\n  Vdata = Vdata(:, :);\nelseif istimelock\n  % select the desired latencies\n  if ischar(cfg.latency) && strcmp(cfg.latency, 'all')\n    cfg.latency = data.time([1 end]);\n  end\n  tbeg = nearest(data.time, cfg.latency(1));\n  tend = nearest(data.time, cfg.latency(end));\n  cfg.latency = [data.time(tbeg) data.time(tend)];\n  Vdata = Vdata(:, tbeg:tend);\nend\n\nnchans = size(Vdata,1);\nntime  = size(Vdata,2);\nVmodel = zeros(nchans, ntime);\nft_info('selected %d channels\\n', nchans);\nft_info('selected %d topographies\\n', ntime);\n\nif nchans<cfg.numdipoles*3\n  ft_warning('not enough channels to perform a dipole fit');\nend\n\nif ntime<1\n  ft_error('no spatial topography selected');\nend\n\n% check whether EEG is average referenced\nif ft_senstype(sens, 'eeg')\n  if any(rv(Vdata, avgref(Vdata))>0.001)\n    ft_warning('the EEG data is not average referenced, correcting this');\n  end\n  Vdata = avgref(Vdata);\nend\n\n% set to zeros if no initial dipole was specified\nif ~isfield(cfg, 'dip')\n  cfg.dip.pos = zeros(cfg.numdipoles, 3);\n  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);\nend\n\n% set to zeros if no initial dipole position was specified\nif ~isfield(cfg.dip, 'pos')\n  cfg.dip.pos = zeros(cfg.numdipoles, 3);\nend\n\n% set to zeros if no initial dipole moment was specified\nif ~isfield(cfg.dip, 'mom')\n  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);\nend\n\n% check the specified dipole model\nif numel(cfg.dip.pos)~=cfg.numdipoles*3 || numel(cfg.dip.mom)~=cfg.numdipoles*3\n  ft_error('inconsistent number of dipoles in configuration')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% perform the dipole scan, this is usefull for generating an initial guess\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif strcmp(cfg.gridsearch, 'yes')\n  % test whether we have a valid configuration for dipole scanning\n  if cfg.numdipoles==1\n    % this is ok\n  elseif cfg.numdipoles==2 && ~isempty(cfg.dipfit.constr)\n    % this is also ok\n  elseif isfield(cfg.sourcemodel, 'pos') && size(cfg.sourcemodel.pos,2)==cfg.numdipoles*3\n    % this is also ok\n  else\n    ft_error('dipole scanning is only possible for a single dipole or a symmetric dipole pair');\n  end\n  \n  if isfield(cfg.sourcemodel, 'leadfield')\n    ft_notice('using precomputed leadfields for the gridsearch');\n\n    sourcemodel = keepfields(cfg.sourcemodel, {'pos', 'tri', 'dim', 'inside', 'leadfield', 'leadfielddimord', 'label'});\n    \n    % select the channels corresponding to the data and the user configuration\n    tmpcfg = keepfields(cfg, 'channel');\n    sourcemodel = ft_selectdata(tmpcfg, sourcemodel);\n    \n    % sort the channels to be consistent with the data\n    [dum, chansel] = match_str(data.label, sourcemodel.label);\n    sourcemodel.label = sourcemodel.label(chansel);\n    for i=1:numel(sourcemodel.leadfield)\n      if ~isempty(sourcemodel.leadfield{i})\n        sourcemodel.leadfield{i} = sourcemodel.leadfield{i}(chansel, :);\n      end\n    end\n    \n    % ensure that the channels are consistent with the data\n    assert(isequal(sourcemodel.label, cfg.channel), 'cannot match the channels in the sourcemodel to those in the data')\n    \n  else\n    ft_notice('computing the leadfields for the gridsearch on the fly');\n    \n    % construct the dipole positions on which the source reconstruction will be done\n    tmpcfg           = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\n    tmpcfg.headmodel = headmodel;\n    if ft_senstype(sens, 'eeg')\n      tmpcfg.elec = sens;\n    elseif ft_senstype(sens, 'meg')\n      tmpcfg.grad = sens;\n    end\n    sourcemodel = ft_prepare_sourcemodel(tmpcfg);\n    \n  end % if precomputed leadfield or not\n\n  ngrid = size(sourcemodel.pos,1);\n  \n  switch cfg.model\n    case 'regional'\n      sourcemodel.error = nan(ngrid, 1);\n    case 'moving'\n      sourcemodel.error = nan(ngrid, ntime);\n    otherwise\n      ft_error('unsupported cfg.model');\n  end\n  \n  insideindx = find(sourcemodel.inside);\n  ft_progress('init', cfg.feedback, 'scanning grid');\n  for i=1:length(insideindx)\n    ft_progress(i/length(insideindx), 'scanning grid location %d/%d\\n', i, length(insideindx));\n    thisindx = insideindx(i);\n    if isfield(sourcemodel, 'leadfield')\n      % reuse the previously computed leadfield\n      lf = sourcemodel.leadfield{thisindx};\n    else\n      lf = ft_compute_leadfield(sourcemodel.pos(thisindx,:), sens, headmodel, leadfieldopt{:});\n    end\n    % the model is V=lf*mom+noise, therefore mom=pinv(lf)*V estimates the\n    % dipole moment this makes the model potential U=lf*pinv(lf)*V and the\n    % model error is norm(V-U) = norm(V-lf*pinv(lf)*V) = norm((eye-lf*pinv(lf))*V)\n    if any(isnan(lf(:)))\n      % this might happen if one of the dipole locations of the grid is\n      % outside the brain compartment\n      lf(:) = 0;\n    end\n    switch cfg.model\n      case 'regional'\n        % sum the error over all latencies\n        sourcemodel.error(thisindx,1) = sum(sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2));\n      case 'moving'\n        % remember the error for each latency independently\n        sourcemodel.error(thisindx,:) = sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2);\n      otherwise\n        ft_error('unsupported cfg.model');\n    end % switch model\n  end % looping over the grid\n  ft_progress('close');\n  \n  switch cfg.model\n    case 'regional'\n      % find the source position with the minimum error\n      [err, indx] = min(sourcemodel.error);\n      dip.pos = sourcemodel.pos(indx,:);                % note that for a symmetric dipole pair this results in a vector\n      dip.pos = reshape(dip.pos,3,cfg.numdipoles)';     % convert to a Nx3 array\n      dip.mom = zeros(cfg.numdipoles*3,1);              % set the dipole moment to zero\n      if cfg.numdipoles==1\n        ft_info('found minimum after scanning on grid point [%g %g %g]\\n', dip.pos(1), dip.pos(2), dip.pos(3));\n      elseif cfg.numdipoles==2\n        ft_info('found minimum after scanning on grid point [%g %g %g; %g %g %g]\\n', dip.pos(1,1), dip.pos(1,2), dip.pos(1,3), dip.pos(2,1), dip.pos(2,2), dip.pos(2,3));\n      end\n      \n    case 'moving'\n      for t=1:ntime\n        % find the source position with the minimum error\n        [err, indx] = min(sourcemodel.error(:,t));\n        dip(t).pos = sourcemodel.pos(indx,:);                 % note that for a symmetric dipole pair this results in a vector\n        dip(t).pos = reshape(dip(t).pos,3,cfg.numdipoles)';   % convert to a Nx3 array\n        dip(t).mom = zeros(cfg.numdipoles*3,1);               % set the dipole moment to zero\n        if cfg.numdipoles==1\n          ft_info('found minimum after scanning for topography %d on grid point [%g %g %g]\\n', t, dip(t).pos(1), dip(t).pos(2), dip(t).pos(3));\n        elseif cfg.numdipoles==2\n          ft_info('found minimum after scanning for topography %d on grid point [%g %g %g; %g %g %g]\\n', t, dip(t).pos(1,1), dip(t).pos(1,2), dip(t).pos(1,3), dip(t).pos(2,1), dip(t).pos(2,2), dip(t).pos(2,3));\n        end\n      end\n      \n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\n  \nelseif strcmp(cfg.gridsearch, 'no')\n  % there is no grid needed for dipole scanning\n  sourcemodel = [];\n  % use the initial guess supplied in the configuration for the remainder\n  switch cfg.model\n    case 'regional'\n      dip = cfg.dip;\n    case 'moving'\n      for t=1:ntime\n        dip(t) = cfg.dip;\n      end\n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\n  \nend % if gridsearch yes/no\n\n% multiple dipoles can be represented either as a 1x(N*3) vector or as a Nx3 matrix,\n% i.e. [x1 y1 z1 x2 y2 z2] or [x1 y1 z1; x2 y2 z2]\nswitch cfg.model\n  case 'regional'\n    dip = fixdipole(dip);\n  case 'moving'\n    for t=1:ntime\n      dip(t) = fixdipole(dip(t));\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% perform the non-linear fit\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif strcmp(cfg.nonlinear, 'yes')\n  switch cfg.model\n    case 'regional'\n      % perform the non-linear dipole fit for all latencies together\n      % catch errors due to non-convergence\n      try\n        dip = ft_inverse_dipolefit(dip, sens, headmodel, Vdata, dipfitopt{:}, leadfieldopt{:});\n        success = 1;\n        if cfg.numdipoles==1\n          ft_info('found minimum after non-linear optimization on [%g %g %g]\\n', dip.pos(1), dip.pos(2), dip.pos(3));\n        elseif cfg.numdipoles==2\n          ft_info('found minimum after non-linear optimization on [%g %g %g; %g %g %g]\\n', dip.pos(1,1), dip.pos(1,2), dip.pos(1,3), dip.pos(2,1), dip.pos(2,2), dip.pos(2,3));\n        end\n      catch\n        success = 0;\n        disp(lasterr);\n      end\n      \n    case 'moving'\n      % perform the non-linear dipole fit for each latency independently\n      % instead of using dip(t) = ft_inverse_dipolefit(dip(t),...), I am using temporary variables dipin and dipout\n      % to prevent errors like \"Subscripted assignment between dissimilar structures\"\n      dipin = dip;\n      for t=1:ntime\n        % catch errors due to non-convergence\n        try\n          dipout(t) = ft_inverse_dipolefit(dipin(t), sens, headmodel, Vdata(:,t), dipfitopt{:}, leadfieldopt{:});\n          success(t) = 1;\n          if cfg.numdipoles==1\n            ft_info('found minimum after non-linear optimization for topography %d on [%g %g %g]\\n', t, dipout(t).pos(1), dipout(t).pos(2), dipout(t).pos(3));\n          elseif cfg.numdipoles==2\n            ft_info('found minimum after non-linear optimization for topography %d on [%g %g %g; %g %g %g]\\n', t, dipout(t).pos(1,1), dipout(t).pos(1,2), dipout(t).pos(1,3), dipout(t).pos(2,1), dipout(t).pos(2,2), dipout(t).pos(2,3));\n          end\n        catch\n          % keep the position and moment according to the initial guess\n          dipout(t).pos = dipin(t).pos;\n          dipout(t).mom = dipin(t).mom;\n          success(t) = 0;\n          disp(lasterr);\n        end\n      end\n      dip = dipout;\n      clear dipin dipout\n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\nend % if nonlinear\n\nif strcmp(cfg.nonlinear, 'no')\n  % the optimal dipole positions are either obtained from scanning\n  % or from the initial configured specified by the user\n  switch cfg.model\n    case 'regional'\n      success = 1;\n    case 'moving'\n      success = ones(1,ntime);\n    otherwise\n      ft_error('unsupported cfg.model');\n      \n  end % switch model\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute the model potential distribution and the residual variance\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch cfg.model\n  case 'regional'\n    if success\n      % re-compute the leadfield in order to compute the model potential and dipole moment\n      lf = ft_compute_leadfield(dip.pos, sens, headmodel, leadfieldopt{:});\n      if isfield(dip, 'mom') && isfield(dip, 'ampl')\n        % the orientation and amplitude have already been estimated, this applies to the case of a fixed dipole orientation\n        dip.pot = (lf * dip.mom) * dip.ampl;\n      else\n        % compute all details of the final dipole model using linear estimation\n        dip.mom = pinv(lf)*Vdata;\n        dip.pot = lf*dip.mom;\n      end\n      dip.rv  = rv(Vdata, dip.pot);\n      Vmodel  = dip.pot;\n    end\n  case 'moving'\n    for t=1:ntime\n      if success(t)\n        % re-compute the leadfield in order to compute the model potential and dipole moment\n        lf = ft_compute_leadfield(dip(t).pos, sens, headmodel, leadfieldopt{:});\n        % compute all details of the final dipole model\n        dip(t).mom = pinv(lf)*Vdata(:,t);\n        dip(t).pot = lf*dip(t).mom;\n        dip(t).rv  = rv(Vdata(:,t), dip(t).pot);\n        Vmodel(:,t) = dip(t).pot;\n      end\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\nswitch cfg.model\n  case 'regional'\n    if isfreq\n      % the matrix with the dipole moment is encrypted and cannot be interpreted straight away\n      % reconstruct the frequency representation of the data at the source level\n      if isfield(dip, 'mom') && isfield(dip, 'ampl')\n        % this applies to the case of a fixed dipole orientation\n        [dip.pow, dip.csd, dip.fourier] = timelock2freq(dip.mom * dip.ampl);\n      else\n        [dip.pow, dip.csd, dip.fourier] = timelock2freq(dip.mom);\n      end\n    end\n  case 'moving'\n    if isfreq\n      % although this is technically possible so far, it does not make any sense\n      ft_warning('a moving dipole model in the frequency domain is not supported');\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% collect the results\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsource.label  = cfg.channel; % these channels were used in fitting\nsource.dip    = dip;\nsource.Vdata  = Vdata;  % FIXME this should be renamed (if possible w.r.t. EEGLAB)\nsource.Vmodel = Vmodel; % FIXME this should be renamed (if possible w.r.t. EEGLAB)\n\n% the units of the fitted source are the same as the units of the headmodel and the sensor array\nfor i=1:length(source.dip)\n  if isfield(headmodel, 'unit')\n    source.dip(i).unit = headmodel.unit;\n  elseif isfield(sourcemodel, 'unit')\n    source.dip(i).unit = sourcemodel.unit;\n  end\nend\n\n% assign a latency, frequeny or component axis to the output\nif iscomp\n  source.component = cfg.component;\n  % FIXME assign Vdata to an output variable, idem for the model potential\nelseif isfreq\n  source.freq   = cfg.frequency;\n  source.dimord = 'chan_freq';\n  % FIXME assign Vdata to an output variable, idem for the model potential\nelseif istimelock\n  tbeg = nearest(data.time, cfg.latency(1));\n  tend = nearest(data.time, cfg.latency(end));\n  source.time   = data.time(tbeg:tend);\n  source.dimord = 'chan_time';\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous   data\nft_postamble provenance source\nft_postamble history    source\nft_postamble savevar    source\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_dipolefitting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.24114810644920712}}
{"text": "function by = cvx_getlog( bx )\n\n% WARNING: This assumes that there is exactly one non-zero element per\n% column, that all non-zeros are positive, and that any element appearing\n% in rows greater than 1 has a non-zero entry in cvx___.logarithm.\n\nglobal cvx___\nnb = size( bx, 2 );\n[ rx, cx, vx ] = find( bx );\ntt = rx > 1;\nry = rx(tt);\ncy = cx(tt);\nlogs = cvx___.logarithm( ry, 1 );\nnl = max([1,max(logs)]);\nby = sparse( logs, cy, 1, nl, nb ) + sparse( 1, cx, log(vx), nl, nb );\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.tx for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/lib/cvx_getlog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884987393448}}
{"text": "\nfunction TooltipString=DoTellMeInfo(var)\n\nUnits = [];\nTips = '';\nswitch var\n    \n    %% Imaging Tab\n    case 'BandWidth'\n        Units ='Hz';\n        Tips ='Full receiver bandwidth';\n    case 'FOVFreq'\n        Units ='m';\n        Tips ='Field of view in the frequency encoding direction';\n    case 'FOVPhase'\n        Units ='m';\n        Tips ='Field of view in the first phase encoding direction';\n    case 'FlipAng'\n        Units ='Degree';\n        Tips ='Nominal flip angle of excitation pulse';\n    case 'FreqDir'\n        Tips ='Frequency encoding direction';\n    case 'ResFreq'\n        Tips ='Number of voxels in frequency encoding direction';\n    case 'ResPhase'\n        Tips ='Number of voxels in the first phase encoding direction';\n    case 'ScanPlane'\n        Tips ='The scanning plane';\n    case 'SliceNum'\n        Tips ='The number of encoding slice';\n    case 'SliceThick'\n        Units ='m';\n        Tips ='The thickness of one slice';\n    case 'TE'\n        Units ='s';\n        Tips ='The time of echo';\n    case 'TEPerTR'\n        Tips ='The number of echoes in multiple echo mode, using a number greater than one requires ''MultiEcho'' tab to be loaded';\n    case 'TR'\n        Units ='s';\n        Tips ='The time of repetition';\n        %% Advanced Tab\n    case 'MasterTxCoil'\n        Tips ='The master transmitting coil ID in multi RF transmitting mode';\n    case 'MultiTransmit'\n        Tips ='The flag for turning on and off multi RF transmitting mode, default mode is ''off'' for single RF transmitting';\n    case 'NEX'\n        Tips ='The number of excitation';\n    case 'NoFreqAlias'\n        Tips ='The flag for avoiding aliasing in frequency encoding direction, default ''on'' truncates object outside field of view in frequency encoding direction';\n    case 'NoPhaseAlias'\n        Tips ='The flag for avoiding aliasing in the first phase encoding direction, default ''on'' truncates object outside field of view in the first phase encoding direction';\n    case 'NoSliceAlias'\n        Tips ='The flag for avoiding aliasing in the second phase encoding (i.e. slice encoding) direction, default ''on'' truncates object outside field of view in slice encoding direction';\n    case 'Shim'\n        Tips ='Main static field shimming';\n    case 'TEAnchor'\n        Tips ='The flag for choosing TE time offset regarding the excitation RF pulse';\n        %% Hardware Tab\n    case 'B0'\n        Units ='T';\n        Tips ='Main static magnetic field strength';\n    case 'B1Level'\n        Units ='T';\n        Tips ='A linear scale factor for B1. The input B1+ field with magnitude of this number produces nominal flip angle';\n    case 'E1Level'\n        Units ='T';\n        Tips ='A linear scale factor for E1. When calculating spatial SAR, the input E1+ field is scaled by a factor of nominal RF amplitude divided by this number';\n    case 'MaxGrad'\n        Units ='T/m';\n        Tips ='Maximum allowable gradient strength';\n    case 'MaxSlewRate'\n        Units ='T/m/s';\n        Tips ='Maximum allowable gradient slew rate';\n    case 'MinUpdRate'\n        Units ='s';\n        Tips ='Minimum update time on generating sequence waveform';\n    case 'Model'\n        Tips ='Model type';\n    case 'NoiseLevel'\n        Tips ='The level of adjustable noise, the higher the number, the more noise';\n    case 'PulseType'\n        Tips ='The type of generated sequence pulse';\n    case 'SpinPerVoxel'\n        Tips ='The number of spins in each voxel. Default one spin per voxel treats T2* equal to T2, use a number greater than one to simulate T2* effect based on T2Star input (linear simulation time cost)';\n        %% Recon Tab\n    case 'AutoRecon'\n        Tips ='The flag for turning on and off automatic image reconstruction after MR signal acquisition';\n    case 'ExternalEng'\n        Tips ='User defined script for image reconstruction';\n    case 'OutputType'\n        Tips ='The type of output data including both simulated image and signal';\n    case 'ReconEng'\n        Tips ='The image reconstruction engine, choosing ''External'' uses external engine which requires ''ExternalEng'' to be provided';\n    case 'ReconType'\n        Tips ='The type of image reconstruction';\n        %% CV Tab\n    case 'CV1'\n        Tips ='Controllable variable 1';\n    case 'CV2'\n        Tips ='Controllable variable 2';\n    case 'CV3'\n        Tips ='Controllable variable 3';\n    case 'CV4'\n        Tips ='Controllable variable 4';\n    case 'CV5'\n        Tips ='Controllable variable 5';\n    case 'CV6'\n        Tips ='Controllable variable 6';\n    case 'CV7'\n        Tips ='Controllable variable 7';\n    case 'CV8'\n        Tips ='Controllable variable 8';\n    case 'CV9'\n        Tips ='Controllable variable 9';\n    case 'CV10'\n        Tips ='Controllable variable 10';\n    case 'CV11'\n        Tips ='Controllable variable 11';\n    case 'CV12'\n        Tips ='Controllable variable 12';\n    case 'CV13'\n        Tips ='Controllable variable 13';\n    case 'CV14'\n        Tips ='Controllable variable 14';\n        %% SpecialTech Tab\n    case 'GRAPPA'\n        Tips ='GRAPPA';\n    case 'GM'\n        Tips ='Generalized Multi-pool exchanging simulation';\n    case 'FSE'\n        Tips ='Fast Spin Echo';\n    case 'EPI'\n        Tips ='Echo Planar Imaging';\n    case 'DummyPulse'\n        Tips ='Dummy pulse';\n    case 'CEST'\n        Tips ='Chemical Exchange Saturation Transfer simulation';\n    case 'PartialEcho'\n        Tips ='Partial echo';\n    case 'MultiEcho'\n        Tips ='Multi echo';\n    case 'MT'\n        Tips ='Magnetization Transfer simulation';\n    case 'ME'\n        Tips ='Multiple pool spin Exchange simulation';\n    case 'IRPrep'\n        Tips ='Inversion recovery preparation';\n    case 'T2Prep'\n        Tips ='T2 decay preparation';\n    case 'Gridding'\n        Tips ='Non-Cartesian gridding';\n    case 'Spiral'\n        Tips ='Spiral imaging';\n    case 'SENSE'\n        Tips ='SENSE';\n    case 'Radial'\n        Tips ='Radial imaging';\n    case 'RTRecon'\n        Tips ='Real Time reconstruction';\n    case 'ZeroFilling'\n        Tips ='Zero filling k-space';\n    case 'VIPR'\n        Tips ='VIPR';\n    case 'DP_Flag'\n        Tips ='The flag for turning on and off dummy pulse';\n    case 'DP_FlipAng'\n        Units ='Degree';\n        Tips ='The flip angle of excitation pulse for dummy pulse';\n    case 'DP_Num'\n        Tips ='The number of TRs for dummy pulse';\n    case 'DP_TR'\n        Units ='s';\n        Tips ='The time of repetition for dummy pulse';\n    case 'EPI_ESP'\n        Units ='s';\n        Tips ='The echo spacing for EPI';\n    case 'EPI_ETL'\n        Tips ='The echo train length for EPI';\n    case 'EPI_EchoShifting'\n        Tips ='The flag for turning on and off echo shifting';\n    case 'EPI_ShotNum'\n        Tips ='The number of EPI shots, multi shot EPI uses interleave mode';\n    case 'FSE_ESP'\n        Units ='s';\n        Tips ='The echo spacing for FSE';\n    case 'FSE_ETL'\n        Tips ='The echo train length for FSE';\n    case 'FSE_ShotNum'\n        Tips ='The number of FSE shots, multi shot FSE uses interleave mode';\n    case 'G_Deapodization'\n        Tips ='The flag for turning on and off kernel deapodization (i.e. dividing reconstructed image with the iFFT of the gridding kernel)';\n    case 'G_KernelSample'\n        Tips ='The number of kernel sample point, the more sample points, the better kernel approximation';\n    case 'G_KernelWidth'\n        Tips ='The full width of kernel in the unit of gridding grid';\n    case 'G_OverGrid'\n        Tips ='The over gridding factor';\n    case 'G_Truncation'\n        Tips ='The flag for turning on and off image truncation for reconstructed image';\n    case 'TI'\n        Units ='s';\n        Tips ='The time of inversion recovery';\n    case 'MT_Flag'\n        Tips ='The flag for turning on and off Magnetization Transfer simulation';\n    case 'ME_Flag'\n        Tips ='The flag for turning on and off Multiple pool spin Exchange simulation';\n    case 'CEST_Flag'\n        Tips ='The flag for turning on and off Chemical Exchange Saturation Transfer simulation';\n    case 'GM_Flag'\n        Tips ='The flag for turning on and off Generalized Multi-pool exchanging simulation';\n    case 'RTR_Flag'\n        Tips ='The flag for turning on and off real time reconstruction';\n    case 'PlotK_Flag'\n        Tips ='The flag for turning on and off real time k-space plotting';\n    case 'DelayTime'\n        Tips ='The delay time for refreshing graphics';\n    case 'ME_TEs'\n        Units ='s';\n        Tips ='An array of multiple echo values';\n    case 'R_AngPattern'\n        Tips ='The pattern for sampling the angle in k-space';\n    case 'R_AngRange'\n        Tips ='The range of sampling angle';\n    case 'R_SampPerSpoke'\n        Tips ='The number of sampling points in each spoke';\n    case 'R_SpokeNum'\n        Tips ='The number of sampling spokes';\n    case 'Sh_X'\n        Tips ='The constant for X term';\n    case 'Sh_Y'\n        Tips ='The constant for Y term';\n    case 'Sh_Z'\n        Tips ='The constant for Z term';\n    case 'Sh_ZX'\n        Tips ='The constant for ZX term';\n    case 'Sh_ZY'\n        Tips ='The constant for ZY term';\n    case 'Sh_Z2'\n        Tips ='The constant for Z^2 term';\n    case 'Sh_XYZ'\n        Tips ='The constant for XYZ term';\n    case 'Sh_X2_Y2'\n        Tips ='The constant for (X^2)(Y^2) term';\n    case 'S_ShotNum'\n        Tips ='The number of spiral interleaves';\n    case 'S_GradientEff'\n        Tips ='A linear scale factor for adjusting maximum allowable gradient in spiral design';\n    case 'S_F1'\n        Tips ='A scale factor for varying FOV with k-space radius r, as FOV(r) = F0 + F1*r + F2*r*r (in variable density spiral design)';\n    case 'S_F2'\n        Tips ='A scale factor for varying FOV with k-space radius r, as FOV(r) = F0 + F1*r + F2*r*r (in variable density spiral design)';\n    case 'tT2Prep'\n        Units ='s';\n        Tips ='The time of T2 decay preparation';\n    case 'ZF_Kz'\n        Tips ='The zero filling factor in Kz';\n    case 'ZF_Ky'\n        Tips ='The number of point in Ky after zero filling';\n    case 'ZF_Kx'\n        Tips ='The number of point in Kx after zero filling';\n    case 'ChemShift'\n        Units ='Hz/T';\n        Tips ='The chemical shift of the spin';\n    case 'Gyro'\n        Units ='rad/s/T';\n        Tips ='The gyromagnetic ratio of the spin';\n    case 'Rho'\n        Tips ='The spin density of the spin';\n    case 'T1'\n        Units ='s';\n        Tips ='The longitudinal relaxation time';\n    case 'T2'\n        Units ='s';\n        Tips ='The transverse relaxation time';\n    case 'TypeNum'\n        Tips ='The number of spin species';\n    case 'ZCenter'\n        Tips ='The index of the centeral spin in Z direction';\n    case 'ZSpin'\n        Tips ='The number of the spins in Z direction';\n    case 'ZSpinGap'\n        Units ='m';\n        Tips ='The distance between adjacent spins in Z direction';\n    case 'XCenter'\n        Tips ='The index of the centeral spin in X direction';\n    case 'XSpin'\n        Tips ='The number of the spins in X direction';\n    case 'XSpinGap'\n        Units ='m';\n        Tips ='The distance between adjacent spins in X direction';\n    case 'Spat_Flag'\n        Tips ='The flag to turn on and off 2D spatial RF analysis';\n    case 'YCenter'\n        Tips ='The index of the centeral spin in Y direction';\n    case 'YSpin'\n        Tips ='The number of the spins in Y direction';\n    case 'YSpinGap'\n        Units ='m';\n        Tips ='The distance between adjacent spins in Y direction';\n    case 'FreqRes'\n        Tips ='The number of linear frequency sample points';\n    case 'FreqUpLimit'\n        Units ='Hz';\n        Tips ='The upper limit of frequency range';\n    case 'FreqDownLimit'\n        Units ='Hz';\n        Tips ='The lower limit of frequency range';\n    case 'Freq_Flag'\n        Tips ='The flag to turn on and off Spatial-Spectral RF analysis';\n    case 'ConstantGrad'\n        Units ='T/m';\n        Tips ='The constant gradient applied when gradient tab is empty';\n    case 'dB0'\n        Units ='T';\n        Tips ='The main static magnetic field offset';\n        %% Pulse Waveform\n    case 'tS'\n        Units ='s';\n        Tips ='The starting time point in TR section, any waveform timing in this pulse group is relative to this time point';\n    case 'tE'\n        Units ='s';\n        Tips ='The ending time point in TR section, any waveform timing in this pulse group will be truncated after this time point';\n    case 'TRStart'\n        Tips ='The starting TR number';\n    case 'TREnd'\n        Tips ='The ending TR number';\n    case 'Freq'\n        Tips ='The occurrence frequency (e.g. 1 means occurring every TR section, 5 means occurring every 5 TR sections)';\n    case 'Moments'\n        Tips ='The flag for turning on and off the zeroth moment display for the gradient';\n    case 'LineMarker'\n        Tips ='The flag for turning on and off waveform line marker';\n    case 'RenderMode'\n        Tips ='The k-space rendering mode';\n    case 'RenderPoint'\n        Tips ='The flag for turning on and off k-space point rendering';\n    case 'Tar'\n        Tips ='The flag for turning on and off sequence deployment for Toppe';\n    case 'PlayToppeMovie'\n        Tips ='The flag for turning on and off Toppe movie playback';\n    case 'NumTRSkip'\n        Tips ='The number of TR sections to skip during Toppe movie playback';\n    case 'PlayPulseqMovie'\n        Tips ='The flag for turning on and off Pulseq movie playback';\n    case 'ShowUnit'\n        Tips ='The Pulseq display time unit';\n    case 'ShowNum'\n        Tips ='The number of time sections to show during Pulseq movie playback';\n    case 'Apod'\n        Tips ='Apodization methods for RF pulse';\n    case 'FA'\n        Units ='Degree';\n        Tips ='Prescribed flip angle';\n    case 'TBP'\n        Tips ='The time bandwidth product of RF pulse';\n    case 'dt'\n        Units ='s';\n        Tips ='The time interval of sample points';\n    case 'rfPhase'\n        Units ='rad';\n        Tips ='RF pulse phase';\n    case 'rfFreq'\n        Units ='Hz';\n        Tips ='RF pulse frequency offset';\n    case 'tStart'\n        Units ='s';\n        Tips ='The starting time';\n    case 'tEnd'\n        Units ='s';\n        Tips ='The ending time';\n    case 'Switch'\n        Tips ='The flag for turning on and off this pulse';\n    case 'AnchorTE'\n        Tips ='The flag for turning on and off TE reference, TE is calculated from this RF pulse if this flag is turned on';\n    case 'Duplicates'\n        Tips ='The number of the pulse duplicates, used for creating multiple pulses with the same shape';\n    case 'DupSpacing'\n        Units ='s';\n        Tips ='The time spacing between pulse duplicates';\n    case 'CoilID'\n        Tips ='The ID of the coil element';\n    case 'Notes'\n        Tips ='The notes of this object';\n    case 'PW'\n        Tips ='The measure of the pulse width in Fermi RF pulse';\n    case 'SLRPulseType'\n        Tips ='The type of this SLR pulse, including ''st''(small tip angle pulse), ''ex''(excitation pulse), ''se''(spin-echo pulse), ''sat''(saturation pulse) and ''inv''(inversion pulse)';\n    case 'FilterType'\n        Tips ='The type of the applied filter design method, including ''ls''(least squares), ''min''(minimum phase), ''max''(maximum phase), ''pm''(Parks-McClellan equal ripple), and ''ms''(Hamming windowed sinc)';\n    case 'PRipple'\n        Tips ='The ripple factor at passband';\n    case 'SRipple'\n        Tips ='The ripple factor at stopband';\n    case 'Adiab'\n        Tips ='The adiabatic factor';\n    case 'MaxB1'\n        Units ='T';\n        Tips ='The maximum B1 field';\n    case 'MaxFreq'\n        Units ='Hz';\n        Tips ='The maximum RF frequency';\n    case 'Lambda'\n        Tips ='The lambda adiabatic factor';\n    case 'Beta'\n        Tips ='The beta adiabatic factor';\n    case 'BIRFlag'\n        Tips ='The type of BIR pulse, including ''BIR-1'', ''BIR-2'' and ''BIR-4''';\n    case 'BIREFFlag'\n        Tips ='The type of BIREF pulse, including ''BIREF-1'', ''BIREF-2a'' and ''BIREF-2b''';\n    case 'rfGain'\n        Tips ='The standard deviation of the normal distribution';\n    case 'rfFile'\n        Tips ='The path to the file that stores the RF pulse data, quoted using single quotes';\n    case 't2Start'\n        Units ='s';\n        Tips ='The second gradient pulse starting time';\n    case 't2End'\n        Units ='s';\n        Tips ='The second gradient pulse ending time';\n    case 'tRamp'\n        Units ='s';\n        Tips ='The pulse ramp time from zero to plateau, assume symmetric ramp on both side';\n    case 'GzAmp'\n        Units ='T';\n        Tips ='The amplitude of the Gz pulse';\n    case 'Gz1Sign'\n        Tips ='The polarity of the first gradient pulse, set 0 for nulling';\n    case 'Gz2Sign'\n        Tips ='The polarity of the second gradient pulse, set 0 for nulling';\n    case 'Gz3Sign'\n        Tips ='The polarity of the last gradient pulse, set 0 for nulling';\n    case 'sRamp'\n        Tips ='The sample points on the ramp, use the value of 2 for ignoring the area under the ramp, use values greater than 2 for counting the ramp area';\n    case 'Area'\n        Units ='1/m';\n        Tips ='The area under this gradient pulse';\n    case 'nCycles'\n        Tips ='The number of cycles of phase across the pixel size';\n    case 't1Start'\n        Units ='s';\n        Tips ='The first gradient pulse starting time';\n    case 't1End'\n        Units ='s';\n        Tips ='The first gradient pulse ending time';\n    case 'GzFile'\n        Tips ='The path to the file that stores the Gz pulse data, quoted using single quotes';\n    case 'GyFile'\n        Tips ='The path to the file that stores the Gy pulse data, quoted using single quotes';\n    case 'GxFile'\n        Tips ='The path to the file that stores the Gx pulse data, quoted using single quotes';\n    case 'ADCFile'\n        Tips ='The path to the file that stores the ADC pulse data, quoted using single quotes';\n    case 'GyAmp'\n        Units ='T';\n        Tips ='The amplitude of the Gy pulse';\n    case 'Gy1Sign'\n        Tips ='The polarity of the first gradient pulse, set 0 for nulling';\n    case 'Gy2Sign'\n        Tips ='The polarity of the second gradient pulse, set 0 for nulling';\n    case 'Gy3Sign'\n        Tips ='The polarity of the last gradient pulse, set 0 for nulling';\n    case 't2Middle'\n        Units ='s';\n        Tips ='The second encoding gradient pulse middle time';\n    case 't3Start'\n        Units ='s';\n        Tips ='The last gradient pulse starting time';\n    case 'tMiddle'\n        Units ='s';\n        Tips ='The middle time of the pulse';\n    case 'tOffset'\n        Units ='s';\n        Tips ='The time offset of the gradient pulse';\n    case 'tGy1'\n        Units ='s';\n        Tips ='The duration of the first gradient pulse';\n    case 'tGy2'\n        Units ='s';\n        Tips ='The duration of the second gradient pulse';\n    case 'GxAmp'\n        Units ='T';\n        Tips ='The amplitude of the Gx pulse';\n    case 'Gx1Sign'\n        Tips ='The polarity of the first gradient pulse, set 0 for nulling';\n    case 'Gx2Sign'\n        Tips ='The polarity of the second gradient pulse, set 0 for nulling';\n    case 'Gx3Sign'\n        Tips ='The polarity of the last gradient pulse, set 0 for nulling';\n    case 'sSample'\n        Tips ='The number of linear sample points when ADC flag is 1';\n    case 'Ext'\n        Tips ='The Ext flag';\n    case 'isVardens'\n        Tips ='The flag for turning on and off variable density spiral design';\n    case 'InOut'\n        Tips ='Spiral in or out';\n        %% Others\n    case 'Name'\n        Tips ='The name of the structure';\n    case 'Type'\n        Tips ='A description about the phantom type';\n    case 'XDim'\n        Tips ='The number of voxels in X direction';\n    case 'YDim'\n        Tips ='The number of voxels in Y direction';\n    case 'ZDim'\n        Tips ='The number of voxels in Z direction';\n    case 'XDimRes'\n        Units ='m';\n        Tips ='The spatial resolution in X direction';\n    case 'YDimRes'\n        Units ='m';\n        Tips ='The spatial resolution in Y direction';\n    case 'ZDimRes'\n        Units ='m';\n        Tips ='The spatial resolution in Z direction';\n    case 'Grid'\n        Tips ='Turn on and off grid';\n    case 'Box'\n        Tips ='Turn on and off boundary box';\n    case 'CameraTool'\n        Tips ='Hide or show Matlab camera tool';\n    case 'Color'\n        Tips ='The display color';\n    case 'Alpha'\n        Tips ='The display transparency';\n    case 'Radius'\n        Units ='m';\n        Tips ='The radius of the object';\n    case 'CenterX'\n        Units ='m';\n        Tips ='The X coordinate of the object center';\n    case 'CenterY'\n        Units ='m';\n        Tips ='The Y coordinate of the object center';\n    case 'CenterZ'\n        Units ='m';\n        Tips ='The Z coordinate of the object center';\n    case 'FaceNum'\n        Tips ='The number of the faces for the object';\n    case 'TypeIdx'\n        Tips ='An index number of the spin species, used when the phantom has multiple spin species. The index must not exceed the ''TypeNum''';\n    case 'TypeFlag'\n        Tips ='A flag number for describing the type of the spin, 0 for free pool and 1 for bound pool';\n    case 'LineShapeFlag'\n        Tips ='A flag number for describing RF saturation line shape for bound proton pool, 0 for super-Lorentzian and 1 for Gaussian (:ToDo), the flag is ignored for free pool';\n    case 'ECon'\n        Units ='S/m';\n        Tips ='A array with size of [1 3] for tissue electrical conductivity (optional)';\n    case 'MassDen'\n        Units ='kg/m^3';\n        Tips ='The tissue mass density (optional)';\n    case 'T2Star'\n        Units ='s';\n        Tips ='The T2* relaxation time';\n    case 'K'\n        Units ='1/s';\n        Tips ='A array with the size of [1 TypeNum] for describing the exchange rate of the spin, ignored for regular phantom';\n    case 'RadiusX'\n        Units ='m';\n        Tips ='The X semi-axis length of the ellipsoid';\n    case 'RadiusY'\n        Units ='m';\n        Tips ='The Y semi-axis length of the ellipsoid';\n    case 'RadiusZ'\n        Units ='m';\n        Tips ='The Z semi-axis length of the ellipsoid';\n    case 'Length'\n        Units ='m';\n        Tips ='The length of the object';\n    case 'Height'\n        Units ='m';\n        Tips ='The height of the pyramid';\n    case 'Colormap'\n        Tips ='The colormap for the field';\n    case 'CLimDown'\n        Tips ='The lower bound of color limits';\n    case 'CLimUp'\n        Tips ='The upper bound of color limits';\n    case 'CoilDisplay'\n        Tips ='The flag for turning on and off coil display';\n    case 'CoilShow'\n        Tips ='The flag for choosing active coil for field display';\n    case 'Mode'\n        Tips ='The B1 field display mode';\n    case 'FieldType'\n        Tips ='The flag to choose B1 field or E1 field, note E1 field only support ''Magnitude'' display mode';\n    case 'Plane'\n        Tips ='The flag for activating field slicing plane';\n    case 'Azimuth'\n        Units ='rad';\n        Tips ='The azimuth angle of the plane';\n    case 'Elevation'\n        Units ='rad';\n        Tips ='The elevation angle of the plane';\n    case 'PosZ'\n        Units ='m';\n        Tips ='The Z position of object center';\n    case 'PosY'\n        Units ='m';\n        Tips ='The Y position of object center';\n    case 'PosX'\n        Units ='m';\n        Tips ='The X position of object center';\n    case 'CurrentDir'\n        Tips ='The current direction in the coil circle, 1 for clockwise, -1 for counterclockwise';\n    case 'Scale'\n        Tips ='The scale factor for the field amplitude';\n    case 'Segment'\n        Tips ='The number of line segments for approximating circle, MRiLab requires the same ''Segment'' for each coil circle';\n    case 'Width'\n        Units ='m';\n        Tips ='The width of the object';\n    case 'B1File'\n        Tips ='The path to the file that stores the B1 field data, quoted using single quotes';\n    case 'E1File'\n        Tips ='The path to the file that stores the E1 field data, quoted using single quotes';\n    case 'Interp'\n        Tips ='The interpolation method';\n    case 'GradZ'\n        Tips ='The linear gradient in Z direction';\n    case 'GradY'\n        Tips ='The linear gradient in Y direction';\n    case 'GradX'\n        Tips ='The linear gradient in X direction';\n    case 'DeltaZ'\n        Units ='m';\n        Tips ='The width of Gaussian function in Z direction';\n    case 'DeltaY'\n        Units ='m';\n        Tips ='The width of Gaussian function in Y direction';\n    case 'DeltaX'\n        Units ='m';\n        Tips ='The width of Gaussian function in X direction';\n    case 'Equation'\n        Tips ='A field described with a symbolic equation';\n    case 'MagFile'\n        Tips ='The path to the file that stores the dB0 field data, quoted using single quotes';\n    case 'GradLine'\n        Tips ='The gradient sequence line';\n    case 'DispMode'\n        Tips ='The display mode';\n    case 'GradZEqu'\n        Tips ='A symbolic equation for gradient field vector in Z direction';\n    case 'GradYEqu'\n        Tips ='A symbolic equation for gradient field vector in Y direction';\n    case 'GradXEqu'\n        Tips ='A symbolic equation for gradient field vector in X direction';\n    case 'GradFile'\n        Tips ='The path to the file that stores the gradient field data, quoted using single quotes';\n    case 'Object'\n        Tips ='The object model, currently only supports ''Sphere''';\n    case 'ViewPoint'\n        Tips ='A default view point';\n    case 'ZoomOut'\n        Tips ='A factor of view zoom out';\n    case 'Sample'\n        Tips ='The sample steps between two adjacent positions during movement';\n    case 'Repeat'\n        Tips ='The repeat time of playback';\n    case 'Direction'\n        Tips ='A vector describing translation direction in 3D space';\n    case 'Displacement'\n        Units ='m';\n        Tips ='An equation of translation displacement pattern with respect to time';\n    case 'Axis'\n        Tips ='A vector describing rotation axis in 3D space';\n    case 'Angle'\n        Units ='rad';\n        Tips ='An equation of rotation angle with respect to time';\n    case 'LocZ'\n        Tips ='The Z location of the selected voxel';\n    case 'LocY'\n        Tips ='The Y location of the selected voxel';\n    case 'LocX'\n        Tips ='The X location of the selected voxel';\n    case 'WindowSize'\n        Tips ='The window width of the spin evolution plot';\n    case 'ISOHighlight'\n        Tips ='The flag for turning on and off isocenter mark';\n    case 'Axes'\n        Tips ='The flag for turning on and off axes label';\n    case 'N_Gram'\n        Units ='g';\n        Tips ='The number to specify averaged N-gram SAR, set to 0 indicating unaveraged spatial SAR';\n    case 'N_Second'\n        Units ='s';\n        Tips ='The nominal time window for SAR calculation';\nend\n\nif ~isempty(Units)\n    TooltipString = [var '(' Units '): ' Tips];\nelse\n    TooltipString = [var ': ' Tips];\nend\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Src/Main/DoTellMeInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884341669138}}
{"text": "function Y = vl_nnreshape(X,dest_size,dzdy)\n% VL_NNRESHAPE CNN reshapes input to des_size\n%\n%    DEST_SIZE: desired size\n%\n%    DZDX = VL_NNRESHAPE(X, DEST_SIZE, DZDY) computes the derivative DZDX\n%    of the CNN with respect to the input X given the derivative DZDY\n%    with respect to the block output Y. DZDX has the same dimension\n%    as X.\n\n% Copyright (C) 2015 Tuan-Hung VU.\n% All rights reserved.\n%\n% This file is made available under the terms of the BSD license (see the COPYING file).\n\nif nargin <= 2\n    sz = [size(X,1) size(X,2) size(X,3) size(X,4)] ;\n    Y = reshape(X, [size(X,1) size(X,2) dest_size(2) size(X,3)*size(X,4)/dest_size(2)]);\nelse\n    Y = reshape(dzdy, size(X));\nend\n", "meta": {"author": "aosokin", "repo": "cnn_head_detection", "sha": "80624e7a25c62f7b504fa6f4d830136beb66eec8", "save_path": "github-repos/MATLAB/aosokin-cnn_head_detection", "path": "github-repos/MATLAB/aosokin-cnn_head_detection/cnn_head_detection-80624e7a25c62f7b504fa6f4d830136beb66eec8/globalModel/vl_nnreshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.24105574422662424}}
{"text": "classdef StressVoigt2TensorConverterPS < SecondOrderVoigt2TensorConverterPS\n    \n    properties\n    end\n    \n    methods (Access = public)\n        \n        function obj = StressVoigt2TensorConverterPS(tensor)\n           obj.computeConversion(tensor) \n        end\n        \n    end\n    \n    methods (Access = protected)\n        \n        function factor = computeVoigtFactor(obj)\n            factor = 1;               \n        end            \n        \n        function selectTensorClass(obj)\n            obj.tensor = StressPlaneStressTensor();\n        end\n    end\n    \nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Homogenization/Sources/Tensors/TensorVoigtConverters/Voigt2TensorConverter/StressVoigt2TensorConverterPS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2410557442266242}}
{"text": "% writelocs() - write a file containing channel location, type and gain information\n%             \n% Usage:\n%   >> writelocs( chanstruct, filename );\n%   >> writelocs( chanstruct, filename, 'key', 'val' );\n%\n% Inputs:\n%   chanstruct - EEG.chanlocs data structure returned by readlocs() containing\n%                channel location, type and gain information.\n%   filename   - File name for saving channel location, type and gain information\n%\n% Optional inputs:\n%   'filetype'  - ['loc'|'sph'|'sfp'|'xyz'|'polhemus'|'besa'|'chanedit'|'custom'] \n%                 Type of the file to write. By default the file type is indicated \n%                 by the file extension. \n%                  'loc' - An EEGLAB 2-D polar coordinates channel locations file \n%                          Coordinates are theta and radius (see definitions below).\n%                  'sph' - A Matlab spherical coordinates file (Note: spherical\n%                          coordinates used by Matlab functions are different \n%                          from spherical coordinates used in BESA - see below).\n%                  'sfp' - EGI cartesian coordinates (not Matlab cartesian - see below).\n%                  'xyz' - MATLAB/EEGLAB cartesian coordinates (Not EGI cartesian; \n%                          z is toward nose; y is toward left ear; z is toward vertex).\n%                  'polhemus' or 'polhemusx' - Polhemus electrode location file recorded with \n%                          'X' on sensor pointing to subject (see below and readelp()).\n%                  'polhemusy' - Polhemus electrode location file recorded with \n%                          'Y' on sensor pointing to subject (see below and readelp()).\n%                  'besa' - BESA'(.elp') spherical coordinate file. (Not MATLAB spherical\n%                           - see below).\n%                  'chanedit' - EEGLAB channel location files created by pop_chanedit().\n%                  'custom' - Ascii files with columns in user-defined 'format' (see below).\n%   'format'    - [cell array] Format of a 'custom' channel location file (see above).\n%                          Default if no file type is defined. The cell array contains\n%                          labels defining the meaning of each column of the input file.\n%                           'channum'   [positive integer] channel number \n%                           'labels'    [string] channel name (no spaces)\n%                           'theta'     [real degrees] 2-D angle in polar coordinates. \n%                                       positive => rotating from nose (0) toward left ear \n%                           'radius'    [real] radius in 2-D polar coords (0.5 is disk limits)\n%                           'X'         [real] Matlab-cartesian X coordinate (to nose)\n%                           'Y'         [real] Matlab-cartesian Y coordinate (to left ear)\n%                           'Z'         [real] Matlab-cartesian Z coordinate (to vertex)\n%                           '-X','-Y','-Z' Matlab-cartesian coordinates pointing away from above\n%                           'sph_theta' [real degrees] Matlab spherical horizontal angle. \n%                                       positive => rotating from nose (0) toward left ear.\n%                           'sph_phi'   [real degrees] Matlab spherical elevation angle;\n%                                       positive => rotating from horizontal (0) upwards.\n%                           'sph_radius' [real] distance from head center (unused) \n%                           'sph_phi_besa' [real degrees] BESA phi angle from vertical. \n%                                       positive => rotating from vertex (0) towards right ear.\n%                           'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle. \n%                                       positive => rotating from right ear (0) toward nose.\n%     The input file may also contain other channel information fields\n%                           'type'      channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...\n%                           'calib'     [real near 1.0] channel calibration value.\n%                           'gain'      [real > 1] channel gain. \n%                           'custom1'   custom field #1.\n%                           'custom2', 'custom3', 'custom4' more custom fields.\n%   'unicoord'     - ['on'|'off'] Uniformize all coordinates. Default 'on'.\n%   'header'       - ['on'|'off'] Add a header comment line with the name of each column.\n%                             Comment lines begin with '%'. Default is 'off'.\n%   'customheader' - [string] Add a custom header at the beginning of the file and\n%                             preceded by '%'.  If used with 'header' set to 'on', \n%                             the column names will be insterted after the custom header.\n%   'elecind' - [integer array] Indices of channels to export. \n%                             Default is all channels.\n%\n% Note: for file formats, see readlocs() help  (>> help readlocs)\n%\n% Author: Arnaud Delorme, Salk Institute, 16 Dec 2002\n%\n% See also: readlocs(), readelp()\n\n% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction writelocs( chans, filename, varargin ); \n\nif nargin < 2\n\thelp writelocs;\n\treturn;\nend;\n\n% get infos from readlocs\n% -----------------------\n%[listtype formatinfo listcolformat formatskip] = readlocs('getinfos');\n[chanformat listcolformat] = readlocs('getinfos');\nindformat  = [];\nfor index = 1:length(chanformat), \n    if ~isstr(chanformat(index).importformat)\n        indformat = [ indformat index ];\n    end;\n    if isempty(chanformat(index).skipline), chanformat(index).skipline = 0; end;\nend;\nlisttype   = { chanformat(indformat).type };\nformatinfo = { chanformat(indformat).importformat };\nformatskip = [ chanformat(indformat).skipline ];\n\ng = finputcheck( varargin, ...\n                 { 'filetype'\t  'string'\t listtype \t\t\t'loc';\n                   'header'       'string'   { 'on' 'off' } \t'off';\n                   'customheader' 'string'   [] \t\t\t\t\t'';\n                   'elecind'      'integer'  [1 Inf]\t\t\t\t[];\n                   'unicoord'     'string'   { 'on' 'off' } \t'on'; \n                   'format'\t\t  'cell'\t []\t\t\t\t\t{} }, 'writelocs');\nif isstr(g), error(g); end;  \n\nif strcmpi(g.unicoord, 'on')\n    disp('Uniformizing coordinates');\n    chans = convertlocs(chans, 'auto', 'verbose', 'off');\nend;\n\n% select channels\n% ---------------\nif ~isempty(g.elecind)\n\tchans = chans(g.elecind);\nend;\n\n% finding types of input\n% ----------------------\nif isempty(g.format)\n   indexformat = strmatch(lower(g.filetype), listtype, 'exact');\n   g.format = formatinfo{indexformat};\n   g.skipline = formatskip(indexformat);\nelse \n   g.skipline = 0;   \nend;\n\n% creating file\n% -------------\nfid = fopen(filename, 'w');\n\n% exporting header\n% ----------------\nif ~isempty(g.customheader)\n    allstrs = cellstr(g.customheader);\n    for index=1:length(allstrs)\n        fprintf(fid, '%s\\n', allstrs{index});\n    end;\nend;\nif  strcmpi(g.header, 'on') | g.skipline == 2\n   for index=1:length(g.format)\n      fprintf(fid, '%8s\\t', g.format{index});\n   end;\n   fprintf(fid, '\\n');\n   for index=1:length(g.format)\n      fprintf(fid, '%8s\\t', char(ones(1,8)*45));\n   end;\n   fprintf(fid, '\\n');\nend;\nif g.skipline == 1\n   fprintf(fid, '%d\\n', length(chans));\nend;         \n\n% writing infos\n% -------------\nfor indexchan = 1:length(chans)\n   for index=1:length(g.format)\n      [str, mult] = checkformat(g.format{index});\n      if strcmpi(str, 'channum')\n         fprintf(fid, '%d', indexchan);\n      else\n         if ~isfield(chans, str)\n            error([ 'Non-existant field: ''' str '''' ]);\n         end;\n         eval( [ 'chanval = chans(indexchan).' str ';' ] );\n         if   isstr(chanval), fprintf(fid, '%8s', chanval);\n         else   \t\n             if abs(mult*chanval) > 1E-10\n                 fprintf(fid, '%8s', num2str(mult*chanval,5));\n             else\n                 fprintf(fid, '%8s', '0');\n             end;\n         end;\n      end;\n      if index ~= length(g.format)\n         fprintf(fid, '\\t');\n      end;         \n   end;\n   fprintf(fid, '\\n');\nend;\nfclose(fid);\n\nreturn;\n\n% check field format\n% ------------------\nfunction [str, mult] = checkformat(str)\n\tmult = 1;\n\tif strcmpi(str, 'labels'), str = lower(str); return; end;\n\tif strcmpi(str, 'channum'), str = lower(str); return; end;\n\tif strcmpi(str, 'theta'), str = lower(str); return; end;\n\tif strcmpi(str, 'radius'), str = lower(str); return; end;\n\tif strcmpi(str, 'sph_theta'), str = lower(str); return; end;\n\tif strcmpi(str, 'sph_phi'), str = lower(str); return; end;\n\tif strcmpi(str, 'sph_radius'), str = lower(str); return; end;\n\tif strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;\n\tif strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;\n\tif strcmpi(str, 'gain'), str = lower(str); return; end;\n\tif strcmpi(str, 'calib'), str = lower(str); return; end;\n\tif strcmpi(str, 'type') , str = lower(str); return; end;\n\tif strcmpi(str, 'X'), str = upper(str); return; end;\n\tif strcmpi(str, 'Y'), str = upper(str); return; end;\n\tif strcmpi(str, 'Z'), str = upper(str); return; end;\n\tif strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;\n\tif strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;\n\tif strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;\n\tif strcmpi(str, 'custum1'), return; end;\n\tif strcmpi(str, 'custum2'), return; end;\n\tif strcmpi(str, 'custum3'), return; end;\n\tif strcmpi(str, 'custum4'), return; end;\n   error(['writelocs: undefined field ''' str '''']);\n   \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/writelocs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2410027997701847}}
{"text": "function z = rsum(fit)\n%\n% function to extract log-likelihood and degrees-of-freedom\n% from locfit fit.\n%\n% order of returned vector:   df0 df1 llk.\n%\n\nfp = fit.fit_points;\ngf = fp.kappa;\n\nz = gf([2 3 1]);\n\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/m/rsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.240776942258484}}
{"text": "function [roiImg, imgXform, bb] = dtiRoiToImg(coords, imgXform, bb)\n% \n% [roiImg, imgXform, bb] = dtiRoiToImg(roi, [imgXform=eye(4)], [bb])\n%\n% If not the identity matrix, imgXform is typically set to xformToAcpc. This\n% has the effect of forcing the roiImg to have the same voxel size as the \n% image that xformToAcpc is based on.\n%\n% bb is the bounding box, defined in the xformed spaced. Defaults to \n% [min(coords)-10; max(coords)+10].\n%\n% [roiImg, imgXform, bb] = dtiRoiToImg(roi);\n% % Do some processing on the ROI\n% % perimImg = bwperim(roiImg);\n% perimRoi = dtiRoiFromImg(roiImg, imgXform, bb);\n%\n% HISTORY:\n% 2009.08.19 RFD wrote it.\n\nif(isstruct(coords))\n    coords = coords.coords;\nend\n\nif(~exist('bb','var')||isempty(bb))\n    bb = [min(coords)-10; max(coords)+10];\n    if(~exist('imgXform','var')||isempty(imgXform))\n        imgXform = eye(4);\n        imgXform(1:3,4) = bb(1,:)'-1;\n    end\nend\nif(~exist('imgXform','var')||isempty(imgXform))\n    imgXform = eye(4);\nend\n\nsz = abs(diff(ceil(mrAnatXformCoords(inv(imgXform), bb))))+1;\nroiImg = false((sz));\n\n% Remove coords outside the bounding box\nbadCoords = coords(:,1)<bb(1,1) | coords(:,1)>bb(2,1) ...\n          | coords(:,2)<bb(1,2) | coords(:,2)>bb(2,2) ...\n          | coords(:,3)<bb(1,3) | coords(:,3)>bb(2,3);\ncoords = coords(~badCoords,:);\n\n%coords(:,1) = coords(:,1) - bb(1,1) + 1;\n%coords(:,2) = coords(:,2) - bb(1,2) + 1;\n%coords(:,3) = coords(:,3) - bb(1,3) + 1;\ncoords = round(mrAnatXformCoords(inv(imgXform), coords));\nroiImg(sub2ind(size(roiImg), coords(:,1), coords(:,2), coords(:,3))) = true;\n\nreturn;\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/roi/dtiRoiToImg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.240776942258484}}
{"text": "function [p] = registerjacobian(p)\n%REGISTERJACOBIAN Register jacobians to an expression\n\nif ~isfield(p.extra, 'jacobian')\n    x = recover(depends(p));\n    p.extra.jacobian = jacobian(p,x);\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/registerjacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24077694225848398}}
{"text": "%% Copyright (C) 2017, 2019 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @deftypefun {@var{y} =} double_to_sym_exact (@var{x})\n%% Convert a double value to the equivalent rational sym\n%%\n%% Private helper function.\n%%\n%% @end deftypefun\n\nfunction y = double_to_sym_exact (x)\n  if (isnan (x))\n    y = pycall_sympy__ ('return S.NaN');\n  elseif (isinf (x) && x < 0)\n    y = pycall_sympy__ ('return -S.Infinity');\n  elseif (isinf (x))\n    y = pycall_sympy__ ('return S.Infinity');\n  else\n    %% Rational will exactly convert from a float\n    y = pycall_sympy__ ('return Rational(_ins[0])', x);\n  end\nend\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/private/double_to_sym_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24077694225848398}}
{"text": "function model = ivmAddPoint(model, i)\n\n% IVMADDPOINT Add a point into the IVM representation.\n% FORMAT\n% DESC incorporates the ith point from the data set into the IVM\n% model.\n% ARG model : the model to which the point is to be added.\n% ARG index : the index of the point in the training data which is\n% to be added.\n% RETURN model : the returned model with the point added in.\n%\n% SEEALSO : ivmUpdateSites, ivmUpdateM, ivmUpdateNuG, ivmSelectPoint,\n% ivmRemovePoint, ivmCreate\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n% IVM\n\nindex = find(model.J == i);\nif isempty(index)\n  error(['Point ' num2str(i) ' is not in inactive set'])\nend\n\n%/~model = ivmUpdateNuG(model, i);\n%~/\nmodel = ivmUpdateSites(model, i);\nmodel = ivmUpdateM(model, i);\n\n% Remove point from the non-active set and place in the active.\nmodel.J(index) = [];\nmodel.I = [model.I; i];\n\nmodel = ivmUpdateNuG(model, model.J);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ivm/ivmAddPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24076539255656612}}
{"text": "function [volume, sagSize, numSlices, calc, dataRange] = mrLoadUnfVol()\n%\n%  [volume, sagSize, numSlices, calc, dataRange] = mrLoadUnfVol()\n%\n% AUTHOR:  Engel, Boynton, Wandell\n%\n% Loads in anatomy in mrUnfold format.\n%\n% TODO:\n%   Returns vSize, not sagSize,numSlices\n%   Separate out the loading of anatomy and gray matter\n%   This routine should be called through the preferences at\n%    start up, and it should run only once for each scan\n%   The information obtained here goes with a subject's brain.\n%    So, this routine should probably just take a subject's identifier\n%    as input and go to the right directory and get the relevant\n%    information all at once instead of bothering me.  That directory\n%    should contain all the relevant information about the anatomies.\n\n\n% Ask user for the volume anatomy data file\n%\nvolumeDataFile = input('Enter volume anatomy data file: ','s');\n\n% Convert the volume anatomy into the vector format\n%\n[volume vSize] = readVolume(volumeDataFile);\n\nvolume = createVolumeVector(volume');\nsagSize = [ vSize(1) vSize(2)]; \nnumSlices = vSize(3);\n\n% This loads the locations of the gray matter within\n% the anatomical volume.  We are not currently using gray-matter,\n% though we will.  This should be around in a separate module.\n%\n%grayDataFile = input('Enter gray matter data file: ','s');\n%[calc vSize] = readVolume(grayDataFile);\n%calc = replaceValue(calc,2,1);\n%calc = createVolumeVector(calc');\ncalc = [];\n\n% This is probably unnecessary ... we would like to make this\n% variable go away.\n%\ndataRange = [1,numSlices];\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/volume/mrLoadUnfVol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24076539255656607}}
{"text": "function planC = createStapleStruct(structNumV,probCutoff,structureName,planC)\n% function planC = createStapleStruct(structNumV,probCutoff,structureName,planC)\n%\n% Function to create STAPLE agreement structure at the passed probability\n% probCutoff.\n%\n% APA, 11/13/2017\n\nif ~exist('planC','var')\n    global planC\nend\nindexS = planC{end};\n\nscanNum = getStructureAssociatedScan(structNumV(1),planC);\nnumObs = length(structNumV);\nsiz = getUniformScanSize(planC{indexS.scan}(scanNum));\nrateMatM = false(prod(siz),numObs);\nfor i=1:numObs\n    mask3M = getUniformStr(structNumV(i),planC);\n    rateMatM(:,i) = mask3M(:);\nend\nindV = sum(rateMatM,2) > 0;\nrateMatM = rateMatM(indV,:);\n\niterlim=100;\nsenstart=0.9999*ones(1,numObs);\nspecstart=0.9999*ones(1,numObs);\n%[stapleV, sen, spec, Sall] = staple(rateMatM,iterlim, single(senstart), single(specstart));\n[stapleV, sen, spec, Sall] = gpuStaple(rateMatM,iterlim, single(senstart), single(specstart));\n\nstaple3M = zeros(siz);\nstaple3M(indV) = stapleV;\nnewStrMask3M = staple3M >= probCutoff;\n\nplanC = maskToCERRStructure(newStrMask3M, 1, scanNum, structureName, planC);\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/BABS/createStapleStruct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2407653863836354}}
{"text": "% Astar \n% A* navigation class\n% \n% A concrete subclass of the Navigation class that implements the A*\n% navigation algorithm. Methods included are for the standard case,\n% multiobjective optimization (MOO) -- i.e. optimizes over several \n% objectives/criteria -- and the A*-PO algorithms for MOO that utilizes\n% Pareto optimality.\n% \n% Methods:\n% \tplan            Compute the cost map given a goal and map\n% \tpath            Compute a path to the goal\n% \tvisualize       Display the obstacle map (deprecated)\n% \tplot            Display the obstacle map\n% \tcostmap_modify \tModify the costmap\n% \tcostmap_get     Return the current costmap\n% \tcostmap_set     Set the current costmap\n% \tdisplay         Print the parameters in human readable form\n% \tchar            Convert to string\n% \n% Properties:\n% TBD\n% \n% Example 1::\n%        load map1              % load map\n%        goal = [50;30];\n%        start=[20;10];\n%        as = Astar(map);       % create Navigation object\n%        as.plan(goal,2,3,0);   % setup costmap for specified goal; \n%                               % standard D* algorithm w/ 2 objectives\n%                               % and 3 costmap layers\n%        as.path(start);        % plan solution path start-to-goal, animate\n%        P = as.path(start);    % plan solution path start-to-goal, return \n%                               % path\n% Example 2::\n%        goal = [100;100];\n%        start = [1;1];\n%        as = Astar(0);          % create Navigation object with pseudo-\n%                                % random occupancy grid\n%        ds.addCost(terrain);    % terrain is a 100x100 matrix of \n%                                % elevations [0,1]\n% \t     ds.plan(goal,3,4,0);    % setup costmap for specified goal\n%                                % (3 and 4 include the added terrain cost)\n%        as.path(start);         % plan solution path start-goal, animate\n%        P = as.path(start);     % plan solution path start-goal, return \n%                                % path\n%     \n% Notes\n% - Obstacles are represented by Inf in the costmap.\n% \n% References\n% - A Pareto Optimal D* Search Algorithm for Multiobjective Path Planning,\n%   A. Lavin.\n% - A Pareto Front-Based Multiobjective Path Planning Algorithm, A. Lavin.\n% - Robotics, Vision & Control, Sec 5.2.2, Peter Corke, Springer, 2011.\n% \n% See Also Navigation, Dstar\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n\n% Implementation notes:\n%\n% X is an index into the array of states.\n% State pointers are kept as matlab array index rather than row,col format.\n\nclassdef Astar < Navigation\n\n    properties (SetAccess=private, GetAccess=private)\n\n        % essential world info\n        costmap   % cost layers (1st is map)\n        G         % index of goal point\n        N         % number of objectives\n        L         % number of cost layers\n        \n        % info kept per cell (state):\n        b         % backpointer (0 means not set)\n        t         % tag: NEW/OPEN/CLOSED\n        \n        algorithm % A*, A*-MOO, or A*-PO\n        tie\n        openlist  % priority queue with states and their costs\n        niter\n        changed\n        openlist_maxlen\n        quiet     % specifies verbosity\n\n        % tag state values\n        NEW = 0;\n        OPEN = 1;\n        CLOSED = 2;\n    end\n    \n    \n    methods  % start of public methods\n\n        function as = Astar(world, varargin)\n            %Astar.Astar A* constructor\n            %\n            % AS = Astar(MAP, OPTIONS) is a A* navigation object, and MAP \n            % is an occupancy grid, a representation of a planar world as \n            % a matrix whose elements are 0 (free space) or 1 (occupied).\n            % The occupancy grid is coverted to a costmap with a unit cost\n            % for traversing a cell.\n            %\n            % Options::\n            % 'world' = 0   will call for a pseudo-random occupancy grid\n            % 'goal',G      Specify the goal point (2x1)\n            % 'metric',M    Specify the distance metric as 'Euclidean'\n            %               (default) or 'cityblock'\n            % 'inflate',K   Inflate all obstacles by K cells\n            % 'quiet'       Don't display the progress spinner\n            %\n            % Other options are supported by the Navigation superclass.\n            %\n            % See also Navigation.Navigation.\n            \n            % Invoke the superclass constructor\n            as = as@Navigation(world, varargin{:});  % includes the occgrid\n\n            % Options\n            opt.quiet = false;\n            opt = tb_optparse(opt, varargin);\n            as.quiet = opt.quiet;\n            \n            as.occgrid2costmap(as.occgrid);\n\n            % Initialize A* state variables\n            as.reset();\n            if ~isempty(as.goal)\n                as.goal_change();\n            end\n            as.changed = false;\n        end\n        \n        \n        function reset(as)\n            %Astar.reset Reset the planner\n            %\n            % AS.reset() resets the A* planner.  The next instantiation\n            % of AS.plan() will perform a global replan.\n\n            % Build the matrices required to hold the state of each cell\n            as.b = zeros(size(as.occgrid), 'uint32');     % backpointers\n            as.t = zeros(size(as.occgrid), 'uint8');      % tags, all NEW=0\n            as.costmap(:,:,2) = zeros(size(as.occgrid));  % path cost g\n            as.costmap(:,:,3) = zeros(size(as.occgrid));  % path cost h\n            \n            % Priority queue has col for each open state, one row for the\n            % state location, and rows for each cost layer\n            as.openlist = zeros(as.L+1,0);    \n            as.openlist_maxlen = -Inf;\n        end\n        \n        \n        function goal_change(as)\n            %Astar.goal_change Changes the costlayers due to new goal\n            %position\n            if isempty(as.b)\n                return;\n            end\n            goal = as.goal;\n\n            % Keep goal in index rather than row,col format\n            as.G = sub2ind(size(as.occgrid), goal(2), goal(1));\n            as.INSERT(as.G, as.projectCost(as.G), 'goalset');\n            as.costmap(goal(2),goal(1),2) = 0;\n            \n            % If new goal modifies costs for a layer, recalculate here\n            as.calcHeuristic(as.occgrid, as.goal);\n        end\n        \n        \n        function s = char(as)\n            %Astar.char Convert Navigation object to string\n            %\n            % AS.char() is a string representing the state of the Astar\n            % object in human-readable form.\n            %\n            % See also Astar.display, Navigation.char.\n \n            % Work is done by the superclass\n            s = char@Navigation(as);\n        end\n\n        \n        function plot(as, varargin)\n            %Astar.plot Visualize navigation environment\n            %\n            % AS.plot() displays the occupancy grid and the goal distance\n            % in a new figure.  The goal distance is shown by intensity \n            % which increases with distance from the goal.  Obstacles are \n            % overlaid and shown in red.\n            %\n            % AS.plot(P) as above but also overlays a path given by the set\n            % of points P (Mx2).\n            %\n            % See also Navigation.plot.\n            \n            plot@Navigation(as, 'distance', as.costmap(:,:,3), varargin{:});\n        end\n\n        \n        function n = next(as, current)\n            % Invoked by Navigation.step\n            % Backpropagate from goal to start\n            % Return [col;row] of previous step\n            if as.changed\n                error('Cost map has changed, replan');\n            end\n            X = sub2ind(size(as.occgrid), current(2), current(1));\n            % Set X as the backpointer of X\n            X = as.b(X);\n            if X == 0\n                % Goal (no further backpointer)\n                n = [];\n            else\n                [r,c] = ind2sub(size(as.occgrid), X);\n                n = [c;r];\n            end\n        end        \n        \n        \n        function plan(as, goal, N, layers, algorithm)\n            %Astar.plan Prep the grid for planning.\n            %\n            % AS.plan() updates AS with a costmap of distance to the\n            % goal from every non-obstacle point in the map.  The goal is\n            % as specified to the constructor.\n            %\n            % Inputs:\n            %   goal: goal state coordinates\n            %   N: number of optimization objectives; standard A* is 2\n            %   (i.e. distance and heuristic)\n            %   layers: number of cost layers in costmap\n            %   algorithm: specify standard A*(0), A*-MOO (1), A*-PO (2)\n                        \n            % Setup parameters\n            if nargin < 3\n                N = 2;\n            end\n            if nargin < 4\n                layers = 3;\n            end\n            if nargin < 5\n                algorithm = 0;\n            end\n            as.N = N;\n            as.L = layers;\n            as.algorithm = algorithm;\n            as.openlist = zeros(as.L+1,0);\n            \n            % Initialize cost layers\n            for a = 2:as.L\n                as.costmap(:,:,a) = zeros(size(as.occgrid));\n            end\n            \n            % Cost priority/tiebreaker: layer 2 (distance to node)\n            as.tie = 2;\n            \n            % Set goal\n            if nargin > 1\n                as.goal = goal;  % invokes superclass method set.goal()\n            end\n            if isempty(as.goal)\n                error('must specify a goal point');\n            end\n            \n            % Populate heuristic cost layer\n            as.calcHeuristic(as.occgrid, as.goal);\n        end\n        \n        \n        function P = path(as, start)\n        %Astar.path Find a path between two points\n        %\n        % AS.path(START) finds and displays a path from START to GOAL\n        % which is overlaid on the occupancy grid.\n        %\n        % P = AS.path(START) returns the path (2xM) from START to GOAL.\n            if nargin < 1\n                error('must specify start state');\n            end\n\n            % Invoke the superclass path function, which iterates on our\n            % next method\n%             start = [start; 1];  % specifies backpropogation for NAV.path()\n%             temp = start;\n%             start = as.goal;\n%             as.goal = temp;\n            \n            if nargout == 0\n                path@Navigation(as, start);\n            else\n                P = path@Navigation(as, start);\n            end\n        end\n        \n        \n        % Handler invoked by Navigation.path() to start the navigation\n        % process -- calculate the solution path.\n        % Line comments Ln reference A* pseudocode in Lavin's \"A Pareto\n        % Front-Based Multiobjective Path Planning Algorithm\" where n is\n        % the line number.\n        function navigate_init(as, start)\n            as.openlist = zeros(as.L+1,0);  % openlist must be empty\n            % Begin search with the start node\n            start = sub2ind(size(as.occgrid), start(2), start(1));\n            as.openlist(1,1) = start;\n            as.t(start) = as.OPEN;\n\n            % Plan the A* path\n            as.niter = 0; flag = 0;\n            while ~isempty(as.openlist)                              % L4\n                % Normalize costs on the open list, choose expansion state\n                queue = normc(as.openlist(2:size(as.openlist,1),:)');\n                if as.algorithm == 2\n                    % Get Pareto optimal point off the open list\n                    front = as.openlist(:,paretofront(queue));\n                    [~,col] = min(front(as.tie+1,:));\n                    X = front(1,col);                                % L5\n                else\n                    [~,ind]=min(sum(queue,2));                       \n                    X = as.openlist(1,ind);                          % L5\n                end\n                    as.DELETE(X);                                    % L6\n                \n                as.niter = as.niter + 1;\n                if ~as.quiet && mod(as.niter, 20) == 0\n                    as.spinner();\n                end\n                \n                % Populate the openlist\n                for Y=as.neighbors(X)                                % L7,8\n                    if(Y==as.G)                                      % L9\n                        as.b(Y) = X; \n                        as.updateCosts(Y,X,as.N)\n                        flag = 1;  % flag for goal\n                        break;\n                    end\n                    if as.t(Y)==as.NEW && as.costmap(Y)~=Inf\n                        as.b(Y) = X;\n                        as.updateCosts(Y,X,as.N);\n                        % Project node's costs into objective space:\n                        objspace = as.projectCost(Y,X);\n                        as.INSERT(Y, objspace, '');\n                    end\n                end                \n                if as.verbose\n                    disp(' ')\n                end\n                if flag==1 % goal found\n                    break;\n                end\n            end\n            if ~as.quiet\n                fprintf('\\r');\n            end\n            as.changed = false;\n        end\n        \n        \n        function layer = cost_get(as, layer)\n        %Astar.cost_get Get the specified cost layer\n            layer = as.costmap(:,:,layer);\n        end\n        \n        \n        function c = heurstic_get(as)\n        %Astar.heuristice_get Get the current heuristic map\n        %\n        % C = AS.heuristice_get() is the current heuristic layer. It is\n        % computed in Astar.plan.\n        %\n        % See also Astar.plan.\n            c = as.costmap(:,:,3);\n        end\n\n        \n        function c = costmap_get(as)\n        %Astar.costmap_get Get the current costmap\n        %\n        % C = AS.costmap_get() is the current costmap.\n        % The value of each element represents the cost of traversing the \n        % cell.  It is autogenerated by the class constructor from the\n        % occupancy grid such that:\n        % - free cell (occupancy 0) has a cost of 1\n        % - occupied cell (occupancy >0) has a cost of Inf\n        %\n        % See also Astar.costmap_set, Astar.costmap_modify.\n            c = as.costmap;\n        end\n        \n        \n        function costmap_set(as, costmap)\n        %Astar.costmap_set Set the current costmap\n        %\n        % AS.costmap_set(C) sets the current costmap.\n        % This method accepts the full costmap -- i.e. all layers.\n        %\n        % Notes:\n        % - After the cost map is changed the path should be replanned by \n        %   calling AS.plan(). \n        %\n        % See also Astar.costmap_get, Astar.costmap_modify.\n            [i,j,k] = size(costmap);\n            if ~all([i,j] == size(as.occgrid))\n                error('costmap must be same size as occupancy grid');\n            end\n            as.L = k;  % set the number of cost layers\n            as.costmap = costmap;\n            as.changed = true;\n        end\n\n            \n        function costmap_modify(as, point, newcost)\n        %Astar.costmap_modify Modify cost map\n        %\n        % AS.costmap_modify(P, NEW) modifies the cost map at P=[X,Y] to\n        % have the value NEW.  If P (2xM) and NEW (1xM) then the cost of\n        % the points defined by the columns of P are set to the corresponding\n        % elements of NEW.\n        %\n        % Notes::\n        % - After one or more point costs have been updated the path\n        %   should be replanned by calling AS.plan().\n        %\n        % See also Astar.costmap_set, Astar.costmap_get.\n            if (newcost < 0) || (1 < newcost)\n                error('new cost value must be normlaized [0,1]')\n            end\n            \n            [i,j,k] = size(as.costmap);\n            if (point(1) < 0) || (point(1) > i)\n                error('1st dimension of point is out of bounds')\n            end\n            if (point(2) < 0) || (point(2) > j)\n                error('2nd dimension of point is out of bounds')\n            end\n            if (point(2) < 0) || (point(3) > k)\n                error('3rd dimension of point is out of bounds')\n            end\n\n            as.costmap(point) = newcost;\n        end \n        \n        \n        function addCost(as, values)\n        %Astar.addCost Add an additional cost layer\n        %\n        % AS.addCost(values) adds the matrix specified by values as a\n        % cost layer.\n        % Inputs\n        %   values: normalized matrix the size of the environment\n            [i,j,k] = size(as.costmap);\n            \n            if [i,j]~=size(as.occgrid)\n                error('layer size does not match the environment')\n            end\n            if max(max(values))~=1 || min(min(values))~=0\n                error('layer values are not normalized [0,1]')\n            end\n            \n            as.costmap(:,:,k+1) = values;\n        end\n        \n        \n        function flag = backProp(as)\n            flag = 1;\n        end\n        \n    end  % end of public methods\n    \n    \n    methods (Access=protected)  % start of private methods\n        \n        function occgrid2costmap(as, og, cost)\n            if nargin < 3\n                cost = 1;\n            end\n            og(og==1) = Inf;  % occupied cells -> infinite path cost\n            og(og==0) = cost;  % unoccupied cells -> path cost\n            as.costmap(:,:,1) = og;\n        end\n        \n        \n        function calcHeuristic(as, grid, goal)\n            as.costmap(:,:,3) = zeros(size(grid));\n            for ii=1:size(grid,1)\n                for jj=1:size(grid,2)\n                    as.costmap(ii,jj,3) = sqrt((ii-goal(1))^2+(jj-goal(2))^2);\n                end\n            end\n        end\n        \n        function k_new = updateCosts(as, a, b, obj)\n            % NOTE: Only for costs that accumulate (i.e. sum) over the\n            % path, and for dynamic costs.\n            % E.g. the heuristic parameter only needs updating when the\n            % goal state changes; its values are stored for each cell.\n            %\n            % Location moving from state b to a.\n            %\n            % The costs are coded to be (1) distance, (2) heuristic, (3)\n            % elevation, (4) solar deviation, and (5) risk. If deviating\n            % from these costs (in this order) you MUST EDIT THIS METHOD.\n            [i,j,~] = size(as.costmap);\n            \n            if nargout > 0\n                k_new = as.costmap(i*j+b) + as.dc(b,a);\n                return\n            end\n            if obj == 0\n                % Return what the new priority cost would be (k_new)\n                return\n            end\n            if obj > 1\n                % Standard A* search\n                as.costmap(i*j+a) = as.costmap(i*j+b) + as.dc(b,a);\n                % (no heuristic update needed)\n            end\n            if obj > 2\n                % W/ elevation costs\n                % (no elevation update needed)\n            end\n            if obj > 3\n                % W/ solar costs\n                % Rotate the solar vector 1rad per 100 steps\n                sV = [cos(as.niter/100);sin(as.niter/100)];\n                as.costmap(4*i*j+a) = dot(sV,as.vc(b,a));\n            end\n            if obj > 4\n                % W/ risk costs\n                % (no risk update needed)\n            end\n        end\n        \n        \n        function pt = projectCost(as, a, b)\n            % Returns the projection of state a into objective space. If\n            % specified, location is moving from b to a (case 3).\n            [i,j,k] = size(as.costmap);\n            pt(1) = as.costmap(a);\n            switch nargin\n                case 2\n                    pt(2) = as.costmap(i*j+a);\n                case 3\n                    pt(2) = as.costmap(i*j+b) + as.dc(a,b);\n                otherwise\n                    return\n            end\n            for n=3:k\n                pt(n) = as.costmap((n-1)*i*j+a);\n            end\n        end\n        \n        \n        function INSERT(as, X, pt, where)\n            % Add state X to the openlist with objective space values\n            % specified by pt.\n\n            if nargin>2\n                as.message('insert (%s) %d = %f\\n', where, X, pt);\n            end\n            \n            i = find(as.openlist(1,:) == X);\n            if length(i) > 1\n                error('A*:INSERT: state in open list %d times', X);\n            end\n\n            [i,j,~] = size(as.costmap);\n            if (as.t(X) == as.OPEN || as.CLOSED) && ...\n               (pt(as.tie) > as.costmap((as.tie-1)*i*j+X))\n                % L13/14: If a node with same position as successor is in \n                % the OPEN/CLOSED list & has a lower f than successor, \n                % then skip this successor.\n            else\n                % Add a new column to the open list for this node\n                as.openlist = [as.openlist [X; pt(:)]];\n            end\n            \n            % Keep track of the max length of the openlist\n            if numcols(as.openlist) > as.openlist_maxlen\n                as.openlist_maxlen = numcols(as.openlist);\n            end\n\n            % Tag state X as open\n            as.t(X) = as.OPEN;\n        end\n\n        \n        function DELETE(as, X)\n            as.message('delete %d\\n', X);\n            i = find(as.openlist(1,:) == X);\n            if length(i) ~= 1\n                error('A*:DELETE: state %d does not exist', X);\n            end\n            \n            % Remove the column, close the state\n            as.openlist(:,i) = [];\n            as.t(X) = as.CLOSED;\n        end\n        \n\n        function cost = dc(as, X, Y)\n            % Return the distance cost of moving from state X to state Y\n            [r,c] = ind2sub(size(as.occgrid), [X; Y]);\n            dist = sqrt(sum(diff([r c]).^2));\n            dcost = (as.costmap(X) + as.costmap(Y))/2;\n\n            cost = dist * dcost;\n        end\n        \n\n        function vector = vc(as, X, Y)\n            % Return the robot unit vector -- direction of moving from \n            % state X to state Y\n            [Xi,Xj] = ind2sub(size(as.occgrid),X);\n            [Yi,Yj] = ind2sub(size(as.occgrid),Y);\n            vector = [Yi-Xi;Yj-Xj];\n            vector = vector/norm(vector);           \n        end\n        \n        \n        function Y = neighbors(as, X)\n            % Return indices of neighbor states (max 8) as a row vector\n            dims = size(as.occgrid);\n            [r,c] = ind2sub(dims, X);\n\n            % Of 8-way neighbors, only use those w/in grid bounds\n            Y = [r-1 r-1 r-1 r r  r+1 r+1 r+1; c-1 c c+1 c-1 c+1 c-1 c c+1];\n            k = (min(Y)>0) & (Y(1,:)<=dims(1)) & (Y(2,:)<=dims(2));\n            Y = Y(:,k);\n            Y = sub2ind(dims, Y(1,:)', Y(2,:)')';\n        end\n \n    end  % end of private methods\n    \nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/Astar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2407653863836354}}
{"text": "% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos\n% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n\nfunction CstTDMMeshSettings(mws, CellsPerWavelenth, MinimumCell)\n\n%'@ set mesh properties (Hexahedral)\nMesh = invoke(mws,'Mesh');\ninvoke(Mesh,'MeshType','PBA');\ninvoke(Mesh,'SetCreator','High Frequency');\n\nMeshSettings = invoke(mws,'MeshSettings');\ninvoke(MeshSettings,'SetMeshType','Hex');\ninvoke(MeshSettings,'Set','Version','1%');\n\n\n%'MAX CELL - WAVELENGTH REFINEMENT \ninvoke(MeshSettings,'Set','StepsPerWaveNear',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','StepsPerWaveFar',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','WavelengthRefinementSameAsNear','1');\n%'MAX CELL - GEOMETRY REFINEMENT \ninvoke(MeshSettings,'Set','StepsPerBoxNear',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','StepsPerBoxFar',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','MaxStepNear',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','MaxStepFar',num2str(CellsPerWavelenth));\ninvoke(MeshSettings,'Set','ModelBoxDescrNear','maxedge');\ninvoke(MeshSettings,'Set','ModelBoxDescrFar','maxedge');\ninvoke(MeshSettings,'Set','UseMaxStepAbsolute','0');\ninvoke(MeshSettings,'Set','GeometryRefinementSameAsNear','1');\n%'MIN CELL \ninvoke(MeshSettings,'Set','UseRatioLimitGeometry','1');\ninvoke(MeshSettings,'Set','RatioLimitGeometry',num2str(MinimumCell));\ninvoke(MeshSettings,'Set','MinStepGeometryX','0');\ninvoke(MeshSettings,'Set','MinStepGeometryY','0');\ninvoke(MeshSettings,'Set','MinStepGeometryZ','0');\ninvoke(MeshSettings,'Set','UseSameMinStepGeometryXYZ','1');\n\nMeshSettings = invoke(mws,'MeshSettings');\ninvoke(MeshSettings,'SetMeshType','Hex');\ninvoke(MeshSettings,'Set','FaceRefinementOn','0');\ninvoke(MeshSettings,'Set','FaceRefinementPolicy','2');\ninvoke(MeshSettings,'Set','FaceRefinementRatio','2');\ninvoke(MeshSettings,'Set','FaceRefinementStep','0');\ninvoke(MeshSettings,'Set','FaceRefinementNSteps','2');\ninvoke(MeshSettings,'Set','EllipseRefinementOn','0');\ninvoke(MeshSettings,'Set','EllipseRefinementPolicy','2');\ninvoke(MeshSettings,'Set','EllipseRefinementRatio','2');\ninvoke(MeshSettings,'Set','EllipseRefinementStep','0');\ninvoke(MeshSettings,'Set','EllipseRefinementNSteps','2');\ninvoke(MeshSettings,'Set','FaceRefinementBufferLines','3');\ninvoke(MeshSettings,'Set','EdgeRefinementOn','1');\ninvoke(MeshSettings,'Set','EdgeRefinementPolicy','1');\ninvoke(MeshSettings,'Set','EdgeRefinementRatio','2');\ninvoke(MeshSettings,'Set','EdgeRefinementStep','0');\ninvoke(MeshSettings,'Set','EdgeRefinementBufferLines','3');\ninvoke(MeshSettings,'Set','RefineEdgeMaterialGlobal','0');\ninvoke(MeshSettings,'Set','RefineAxialEdgeGlobal','0');\ninvoke(MeshSettings,'Set','BufferLinesNear','3');\ninvoke(MeshSettings,'Set','UseDielectrics','1');\ninvoke(MeshSettings,'Set','EquilibrateOn','0');\ninvoke(MeshSettings,'Set','Equilibrate','1.5');\ninvoke(MeshSettings,'Set','IgnoreThinPanelMaterial','0');\n\nMeshSettings = invoke(mws,'MeshSettings');\ninvoke(MeshSettings,'SetMeshType','Hex');\ninvoke(MeshSettings,'Set','SnapToAxialEdges','1');\ninvoke(MeshSettings,'Set','SnapToPlanes','1');\ninvoke(MeshSettings,'Set','SnapToSpheres','1');\ninvoke(MeshSettings,'Set','SnapToEllipses','1');\ninvoke(MeshSettings,'Set','SnapToCylinders','1');\ninvoke(MeshSettings,'Set','SnapToCylinderCenters','1');\ninvoke(MeshSettings,'Set','SnapToEllipseCenters','1');\n\n\nDiscretizer = invoke(mws,'Discretizer');\ninvoke(Discretizer,'MeshType','PBA');\ninvoke(Discretizer,'PBAType','Fast PBA');\ninvoke(Discretizer,'AutomaticPBAType','True');\ninvoke(Discretizer,'FPBAAccuracyEnhancement','enable');\ninvoke(Discretizer,'ConnectivityCheck','False');\ninvoke(Discretizer,'ConvertGeometryDataAfterMeshing','True');\ninvoke(Discretizer,'UsePecEdgeModel','True');\ninvoke(Discretizer,'GapDetection','False');\ninvoke(Discretizer,'FPBAGapTolerance','1e-3');\ninvoke(Discretizer,'SetMaxParallelMesherThreads','Hex','12');\ninvoke(Discretizer,'SetParallelMesherMode','Hex','Maximum');\ninvoke(Discretizer,'PointAccEnhancement','0');\ninvoke(Discretizer,'UseSplitComponents','True');\ninvoke(Discretizer,'EnableSubgridding','False');\ninvoke(Discretizer,'PBAFillLimit','99');\ninvoke(Discretizer,'AlwaysExcludePec','False');\nend\n\n\n    \n", "meta": {"author": "simos421", "repo": "CST-MATLAB-API", "sha": "a6019ad6f33fa14ebfd459579b6e7151dd3d4ece", "save_path": "github-repos/MATLAB/simos421-CST-MATLAB-API", "path": "github-repos/MATLAB/simos421-CST-MATLAB-API/CST-MATLAB-API-a6019ad6f33fa14ebfd459579b6e7151dd3d4ece/Home/CstTDMMeshSettings.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24076538638363537}}
{"text": "% pop_snapread() - load an EEG SnapMaster file (pop out window if no arguments).\n%\n% Usage:\n%   >> [dat] = pop_snapread( filename, gain);\n%\n% Graphic interface:\n%   \"Relative gain\" - [edit box] to compute the relative gain, fisrt look at\n%                   the text header of the snapmater file with a text editor. \n%                   Find the recording unit, usually in volts (UNITS field).  \n%                   Then, find the voltage range in the \"CHANNEL.RANGE\" [cmin cmax]\n%                   field. Finally, determine the gain of the amplifiers (directly\n%                   on the machine, not in the header file).\n%                   Knowing that the recording precision is 12 bits. The folowing\n%                   formula \n%                                    1/2^12*[cmax-cmin]*1e6/gain \n%                   returns the relative gain. You have to compute it and enter\n%                   it in the edit box. Enter 1, for preserving the data file units. \n%                   (note that if the voltage range is not the same for all channels\n%                   or if the CONVERSION.POLY field in the file header\n%                   is not \"0 + 1x\" for all channels,  you will have to load the data \n%                   using snapread() and scale manually all channels, then import\n%                   the Matlab array into EEGLAB).\n%\n% Inputs:\n%   filename       - SnapMaster file name\n%   gain           - relative gain. See graphic interface help.\n% \n% Outputs:\n%   dat            - EEGLAB data structure\n%\n% Author: Arnaud Delorme, CNL/Salk Institute, 13 March 2002\n%\n% See also: eeglab(), snapread()\n\n% Copyright (C) 13 March 2002 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [EEG, command] = pop_snapread(filename, gain); \ncommand = '';\nEEG = [];\n\nif nargin < 1 \n\t% ask user\n\t[filename, filepath] = uigetfile('*.SMA', 'Choose a SnapMaster file -- pop_snapread()'); \n\tif filename == 0 return; end;\n\tfilename = [filepath filename];\n     \n    promptstr    = { 'Relative gain (see help)' };\n    inistr       = { '400' };\n    result       = inputdlg2( promptstr, 'Import SnapMaster file -- pop_snapread()', 1,  inistr, 'pop_snapread');\n    if length(result) == 0 return; end;\n    gain   = eval( result{1} );\n\nend;\n\nif exist('gain') ~= 1\n    gain = 1;\nend;\n\n% load datas\n% ----------\nEEG = eeg_emptyset;\n[EEG.data,params,events, head] = snapread(filename);  \n\nEEG.data            = EEG.data*gain;\nEEG.comments        = [ 'Original file: ' filename ];\nEEG.filepath        = '';\nEEG.setname \t\t= 'SnapMaster file';\nEEG.nbchan          = params(1);\nEEG.pnts            = params(2);\nEEG.trials          = 1;\nEEG.srate           = params(3);\nEEG.xmin            = 0; \n\nA = find(events ~= 0);\nif ~isempty(A)\n    EEG.event = struct( 'type', mattocell(events(A), [1], ones(1,length(events(A)))), ...\n                        'latency', mattocell(A(:)', [1], ones(1,length(A))) );\nend;\n\nEEG = eeg_checkset(EEG, 'eventconsistency');\nEEG = eeg_checkset(EEG, 'makeur');\ncommand = sprintf('EEG = pop_snapread(''%s'', %f);', filename, gain); \n\nreturn;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/pop_snapread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24076538638363537}}
{"text": "classdef imtool3DROI_ellipse < imtool3DROI_rect\n    \n    properties (SetAccess = protected, GetAccess = protected)\n        nPoints = 20;   %number of points to use to define the polygon that makes the elliptical mask \n    end\n    \n   \n    \n    methods\n        %constructor\n        function ROI = imtool3DROI_ellipse(varargin)\n            \n            switch nargin\n                case 0  %use the current figure\n                    \n                    %let the user draw the ROI\n                    h = imellipse;\n                    \n                    %get the parent axes\n                    ha = get(h,'Parent');\n                    \n                    %get the handle of the image\n                    hi = imhandles(ha);\n                    if length(hi)>1\n                        for i=1:length(hi)\n                            if ndims(get(hi(i),'CData'))<3\n                                imageHandle = hi(i);\n                            end\n                        end\n                    else\n                        imageHandle = hi;\n                    end\n                    \n                    %get the position\n                    pos = getPosition(h);\n                    position = [pos(1)+pos(3)/2 pos(2)+pos(4)/2 pos(3) pos(4)];\n                    \n                    %delete the imroi object\n                    delete(h);\n                case 1 %user inputs only the handle to the image\n                    imageHandle = varargin{1};\n                    parent = get(imageHandle,'Parent');\n                    h = imellipse(parent);\n                    pos = getPosition(h);\n                    position = [pos(1)+pos(3)/2 pos(2)+pos(4)/2 pos(3) pos(4)];\n                    delete(h);\n                case 2 %user inputs both the parent handle and a position\n                    imageHandle = varargin{1};\n                    position = varargin{2};\n                case 3\n                    imageHandle = varargin{1};\n                    position = varargin{2};\n                    if isempty(position)\n                        parent = get(imageHandle,'Parent');\n                        h = imellipse(parent);\n                        pos = getPosition(h);\n                        position = [pos(1)+pos(3)/2 pos(2)+pos(4)/2 pos(3) pos(4)];\n                        delete(h);\n                    end\n                    tool = varargin{3};\n\n            end\n            \n            %contruct the rect ROI\n            if ~exist('tool','var'), tool=[]; end\n            ROI@imtool3DROI_rect(imageHandle,position, tool)\n            \n            %make the rectangle an ellipse\n            set(ROI.graphicsHandles(1),'Curvature',[1 1]);\n            \n            %update the position\n            newPosition(ROI,position)\n            \n            %Set the button down functions of the graphics\n            for i=1:length(ROI.graphicsHandles)\n                fun = @(hObject,evnt) ButtonDownFunction(hObject,evnt,ROI,i); set(ROI.graphicsHandles(i),'ButtonDownFcn',fun);\n            end\n            \n        end\n        \n        function newPosition(ROI,position)\n            \n            %set the position property of the ROI\n            ROI.position = position;\n            \n            %find the top left corner of the box\n            pos = [position(1)-position(3)/2 position(2)-position(4)/2 position(3) position(4)];\n            \n            %get the graphics handles\n            graphicsHandles = ROI.graphicsHandles;\n            \n            %get the corner positions\n            t = pi/4:pi/2:2*pi-pi/4;\n            [x,y] = getEllipsePoints(position,t,'');\n            \n            %set the new position of the rectangle and other graphics\n            %objects\n            set(graphicsHandles(1),'Position',pos);\n            set(graphicsHandles(2),'Xdata',position(1),'Ydata',position(2));\n            set(graphicsHandles(3),'Xdata',x(3),'Ydata',y(3));\n            set(graphicsHandles(4),'Xdata',x(4),'Ydata',y(4));\n            set(graphicsHandles(5),'Xdata',x(2),'Ydata',y(2));\n            set(graphicsHandles(6),'Xdata',x(1),'Ydata',y(1));\n            set(graphicsHandles(7),'Xdata',pos(1),'Ydata',position(2));\n            set(graphicsHandles(8),'Xdata',pos(1)+pos(3),'Ydata',position(2));\n            set(graphicsHandles(9),'Xdata',position(1),'Ydata',pos(2));\n            set(graphicsHandles(10),'Xdata',position(1),'Ydata',pos(2)+pos(4));\n            \n            %get the ROI measurements\n            stats = getMeasurements(ROI);\n            \n            %set the textbox\n            V = get(gca,'View');\n            if V(1)==-90\n                x = pos(1) + pos(3) + ROI.tbuff;\n            else\n                x = pos(1);\n            end\n            y = pos(2)-ROI.tbuff;\n            \n            str = {['Mean: ' num2str(stats.mean,'%+.2f')], ['STD:     ' num2str(stats.STD,'%.2f')]};\n            set(ROI.textHandle,'String',str,'Position',[x y]);\n            \n            %notify a new position\n            notify(ROI,'newROIPosition');\n        end\n        \n        function [x, y] = getPoly(ROI)\n            %get the position\n            position = ROI.position;\n            \n            %find the top left corner of the box\n            pos = [position(1)-position(3)/2 position(2)-position(3)/2 position(3) position(4)];\n            \n            %make the polygon\n            [x,y] = getEllipsePoints(position,ROI.nPoints,'nPoints');\n        end\n\n        function stats = getMeasurements(ROI)\n            [x, y] = getPoly(ROI);\n            im = double(get(ROI.imageHandle,'CData'));\n            \n            m = size(im,1);\n            n = size(im,2);\n            %Scale the polygon to match the size of the displayed image (in\n            %the case that the displayed image is being upsampled to match\n            %the screen resolution).\n            x = x*n/ROI.imageHandle.XData(2);\n            y = y*m/ROI.imageHandle.YData(2);\n            mask = poly2mask(x,y,m,n);\n            \n            im = im(mask);\n            \n            stats.mean = mean(im);\n            stats.STD = std(im);\n            stats.min = min(im);\n            stats.max = max(im);\n            stats.mask = mask;\n            stats.position = ROI.position;\n            \n        end\n        \n        function varargout = autoCenterROI(ROI,varargin)\n            Tforeground = .2;\n            Tbackground = .8;\n            pos=ROI.position(1:2);\n            switch nargin\n                case 1\n                    weighting = 'pixels';\n                    mode = 'normal';\n                case 2\n                    weighting = varargin{1}; %Weighting can be 'pixels' or 'mask'\n                    mode ='normal'; %can be 'normal' or 'force positive contrast';\n                case 3\n                    weighting = varargin{1};\n                    mode = varargin{2};\n            end\n                \n            \n            %Get the image\n            im = double(get(ROI.imageHandle,'CData'));\n            %Get coordinate system\n            [X, Y]=meshgrid((1:size(im,2))-pos(1),(1:size(im,1))-pos(2));\n            R=sqrt((X).^2 +(Y.^2));\n            %get the mask\n            stats = getMeasurements(ROI);\n            mask=stats.mask;\n            \n            amin=min(im(mask));\n            amax=max(im(mask));\n            sim=mat2gray(im,[amin amax]);\n            t=graythresh(sim(mask)); %Otsu threshold\n            bw=im2bw(sim,t);\n            bw=bw & mask;\n            %bw=bwareaopen(bw,100);\n            \n            switch mode\n                case 'force positive contrast'\n                    obj=mean(im(bw));\n                    bkg=mean(im(~bw & mask));\n                case 'normal'\n                    bkg=mean(im(mask & R>quantile(R(mask),Tbackground)));\n                    obj=mean(im(mask & R<quantile(R(mask),Tforeground)));\n                otherwise\n                    bkg=mean(im(mask & R>quantile(R(mask),Tbackground)));\n                    obj=mean(im(mask & R<quantile(R(mask),Tforeground)));\n            end\n            contrast=obj-bkg;\n            if contrast<0\n                bw=~bw & mask;\n            end\n            \n            if any(bw(:))\n                success = true;\n                %compute the centroid of the rod\n                center=zeros(1,2);\n                switch weighting\n                    case 'pixels'\n                        center(1) = sum(X(bw).*im(bw))/sum(im(bw));\n                        center(2) = sum(Y(bw).*im(bw))/sum(im(bw));\n                    case 'mask'\n                        center(1) = sum(X(bw).*bw(bw))/sum(bw(bw));\n                        center(2) = sum(Y(bw).*bw(bw))/sum(bw(bw));\n                    otherwise\n                        center(1) = sum(X(bw).*im(bw))/sum(im(bw));\n                        center(2) = sum(Y(bw).*im(bw))/sum(im(bw));\n                end\n                \n                position = [center 0 0];\n                position=position+ROI.position;\n                newPosition(ROI,position);\n            else\n                success = false;\n            end\n            \n            switch nargout\n                case 1\n                    varargout{1} = success;\n            end\n            \n        end\n        \n        function success = autoCenterROIFindCircleMethod(ROI,circleRange)\n            rescale=4;\n            %Get the image\n            im = double(get(ROI.imageHandle,'CData'));\n            stats = getMeasurements(ROI);\n            mask=stats.mask;\n            \n            %Crop the image\n            [Yind Xind]=ind2sub(size(im),find(mask(:)));\n            im=im(min(Yind):max(Yind),min(Xind):max(Xind));\n            \n            %Upsample the image\n            im=imresize(im,rescale);\n            \n            %Find the circles\n            warning('off','images:imfindcircles:warnForLargeRadiusRange')\n            center = imfindcircles(im, round(rescale*circleRange),'Sensitivity',.95);\n            warning('on','images:imfindcircles:warnForLargeRadiusRange')\n            \n            %move the ROI\n            if ~isempty(center)\n                center=center(1,:);\n                success=true;\n                center=center/rescale;\n                center=center + [min(Xind) min(Yind)];\n                position = [center ROI.position(3:4)];\n                newPosition(ROI,position);\n            else\n                success=false;\n            end\n                \n            \n        end\n       \n        \n    end\n    \n    \nend\n\nfunction [x,y] = getEllipsePoints(position,t,mode)\n%This function returns a list of vertices of an elliptical polygon with\n%nPoints number of vertices;\nif strcmp(mode,'nPoints')\n    t=linspace(0,2*pi,t); %elliptical equation is parameterized by t\nend\na = position(3)/2;\nb = position(4)/2;\nx = a*cos(t); x = x+position(1);\ny = b*sin(t); y = y+position(2);\nend\n\nfunction ButtonDownFunction(hObject,evnt,ROI,n)\n\n%get the parent figure handle\nfig = ROI.figureHandle;\n\n%get the type of click\nclick = get(fig,'SelectionType');\n\nif strcmp(click,'normal')\n    %get the current button motion and button up functions of the figure\n    WBMF_old = get(fig,'WindowButtonMotionFcn');\n    WBUF_old = get(fig,'WindowButtonUpFcn');\n    \n    %set the new window button motion function and button up function of the figure\n    fun = @(src,evnt) ButtonMotionFunction(src,evnt,ROI,n);\n    fun2=@(src,evnt)  ButtonUpFunction(src,evnt,ROI,WBMF_old,WBUF_old);\n    set(fig,'WindowButtonMotionFcn',fun,'WindowButtonUpFcn',fun2);\nend\nend\n\nfunction ButtonMotionFunction(src,evnt,ROI,n)\ncp = get(ROI.axesHandle,'CurrentPoint'); cp=[cp(1,1) cp(1,2)];\n\nposition = getPosition(ROI);\n\n\nswitch n\n    case 2                                          %middle cross\n        position(1) = cp(1); position(2) = cp(2);\n        \n    case 3                                          %top left corner\n        %find the x and y for the current position\n        [x,y] = getEllipsePoints(position,5*pi/4,'');\n        dx = x-cp(1); dy = y-cp(2);\n        cp(1) = position(1)-(position(3)/2+dx); cp(2) = position(2)-(position(4)/2+dy);\n        \n         %find the bottom edge\n        bottom = position(2)+position(4)/2;\n        %get the new height\n        height = bottom - cp(2);\n        if height>1\n            cy = cp(2)+height/2;\n            position(2) = cy;\n            position(4) = height;\n            %Adjust cp(1) if you want to fix the aspect ratio\n            if ROI.fixedAspectRatio\n                cp(1) = position(1)+position(3)/2-height*ROI.aspectRatio;\n            end\n        end\n        %find the right edge\n        right = position(1)+position(3)/2;\n        %find the new width\n        width = right-cp(1);\n        if width>1\n            %find the new center\n            cx = cp(1)+width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n       \n        \n    case 4                                          %top right corner\n        %find the x and y for the current position\n        [x,y] = getEllipsePoints(position,7*pi/4,'');\n        dx = cp(1)-x; dy = y-cp(2);\n        cp(1) = position(1)+(position(3)/2+dx); cp(2) = position(2)-(position(4)/2+dy);\n         %find the bottom edge\n        bottom = position(2)+position(4)/2;\n        %get the new height\n        height = bottom - cp(2);\n        if height>1\n            cy = cp(2)+height/2;\n            position(2) = cy;\n            position(4) = height;\n            %Adjust cp(1) if you want to fix the aspect ratio\n            if ROI.fixedAspectRatio\n                cp(1) = position(1)-position(3)/2+height*ROI.aspectRatio;\n            end\n        end\n        \n        %find the left edge\n        left = position(1)-position(3)/2;\n        %find the new width\n        width = cp(1) - left;\n        if width>1\n            cx = cp(1)-width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n        \n    case 5                                          %bottom left corner\n        %find the x and y for the current position\n        [x,y] = getEllipsePoints(position,3*pi/4,'');\n        dx = x-cp(1); dy = cp(2)-y;\n        cp(1) = position(1)-(position(3)/2+dx); cp(2) = position(2)+(position(4)/2+dy);\n        %find the top edge\n        top = position(2)-position(4)/2;\n        %get the new height\n        height = cp(2) - top;\n        if height>1\n            cy = cp(2)-height/2;\n            position(2) = cy;\n            position(4) = height;\n            %Adjust cp(1) if you want to fix the aspect ratio\n            if ROI.fixedAspectRatio\n                cp(1) = position(1)+position(3)/2+-height*ROI.aspectRatio;\n            end\n        end\n        \n        %find the right edge\n        right = position(1)+position(3)/2;\n        %find the new width\n        width = right-cp(1);\n        if width>1\n            %find the new center\n            cx = cp(1)+width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n        \n    case 6                                          %bottom right corner\n        %find the x and y for the current position\n        [x,y] = getEllipsePoints(position,pi/4,'');\n        dx = cp(1)-x; dy = cp(2)-y;\n        cp(1) = position(1)+(position(3)/2+dx); cp(2) = position(2)+(position(4)/2+dy);\n        %find the top edge\n        top = position(2)-position(4)/2;\n        %get the new height\n        height = cp(2) - top;\n        if height>1\n            cy = cp(2)-height/2;\n            position(2) = cy;\n            position(4) = height;\n            %Adjust cp(1) if you want to fix the aspect ratio\n            if ROI.fixedAspectRatio\n                cp(1) = position(1)-position(3)/2+height*ROI.aspectRatio;\n            end\n        end\n        \n        %find the left edge\n        left = position(1)-position(3)/2;\n        %find the new width\n        width = cp(1) - left;\n        if width>1\n            cx = cp(1)-width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n        \n    case 7                                          %left\n        %find the right edge\n        right = position(1)+position(3)/2;\n        %find the new width\n        width = right-cp(1);\n        if width>1\n            %find the new center\n            cx = cp(1)+width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n        if ROI.fixedAspectRatio\n            position(4) = width/ROI.aspectRatio;\n        end\n        \n    case 8                                          %right\n        %find the left edge\n        left = position(1)-position(3)/2;\n        %find the new width\n        width = cp(1) - left;\n        if width>1\n            cx = cp(1)-width/2;\n            position(1) = cx;\n            position(3) = width;\n        end\n        \n        if ROI.fixedAspectRatio\n            position(4) = width/ROI.aspectRatio;\n        end\n        \n    case 9                                          %top\n        %find the bottom edge\n        bottom = position(2)+position(4)/2;\n        %get the new height\n        height = bottom - cp(2);\n        if height>1\n            cy = cp(2)+height/2;\n            position(2) = cy;\n            position(4) = height;\n        end\n        \n        if ROI.fixedAspectRatio\n            position(3) = height*ROI.aspectRatio;\n        end\n        \n    case 10                                         %bottom\n        %find the top edge\n        top = position(2)-position(4)/2;\n        %get the new height\n        height = cp(2) - top;\n        if height>1\n            cy = cp(2)-height/2;\n            position(2) = cy;\n            position(4) = height;\n        end\n        \n        if ROI.fixedAspectRatio\n            position(3) = height*ROI.aspectRatio;\n        end\n        \nend\n\nnewPosition(ROI,position);\n\nend\n\nfunction ButtonUpFunction(src,evnt,ROI,WBMF_old,WBUF_old)\nfig = ROI.figureHandle;\n\nset(fig,'WindowButtonMotionFcn',WBMF_old,'WindowButtonUpFcn',WBUF_old);\n\nend", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/imtool3D_td/imtool3DROI_ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24070064830150542}}
{"text": "classdef PatternSearchOptimizer < AbstractOptimizer\n    %PatternSearchOptimizer Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        options(1,1) PatternSearchOptions = PatternSearchOptions();\n    end\n    \n    methods\n        function obj = PatternSearchOptimizer()\n            obj.options = PatternSearchOptions();\n        end\n        \n        function [exitflag, message] = optimize(obj, lvdOpt, writeOutput, callOutputFcn, hLvdMainGUI)\n            [x0All, actVars, varNameStrs] = lvdOpt.vars.getTotalScaledXVector();\n            [lbAll, ubAll, lbUsAll, ubUsAll] = lvdOpt.vars.getTotalScaledBndsVector();\n%             typicalX = lvdOpt.vars.getTypicalScaledXVector();\n            \n            if(isempty(x0All) && isempty(actVars))\n                exitflag = 0;\n                message = 'No variables enabled on script.  Aborting optimization.';\n\n                return;\n            end\n            \n            evtNumToStartScriptExecAt = obj.getEvtNumToStartScriptExecAt(lvdOpt, actVars);\n            evtToStartScriptExecAt = lvdOpt.lvdData.script.getEventForInd(evtNumToStartScriptExecAt);\n            \n            objFuncWrapper = @(x) lvdOpt.objFcn.evalObjFcn(x, evtToStartScriptExecAt);\n            nonlcon = @(x) lvdOpt.constraints.evalConstraints(x, true, evtToStartScriptExecAt, true, []);\n                        \n%             initMeshSize = norm(typicalX)/(10*length(typicalX));\n            opts = obj.options.getOptionsForOptimizer(x0All);\n%             opts = optimoptions(opts, 'ScaleMesh',scaleMesh, 'UseParallel',usePara, 'InitialMeshSize',initMeshSize);\n            \n            problem.objective = objFuncWrapper;\n            problem.x0 = x0All;\n            problem.Aineq = [];\n            problem.bineq = [];\n            problem.Aeq = [];\n            problem.beq = [];\n            problem.lb = lbAll;\n            problem.ub = ubAll;\n            problem.nonlcon = nonlcon;\n            problem.options = opts;\n            problem.solver = 'patternsearch';\n            \n            problem.lvdData = lvdOpt.lvdData; %need to get lvdData in somehow\n                    \n            %%% Run optimizer\n            celBodyData = lvdOpt.lvdData.celBodyData;\n            recorder = ma_OptimRecorder();\n            \n            if(callOutputFcn)\n                propNames = lvdOpt.lvdData.launchVehicle.tankTypes.getFirstThreeTypesCellArr();\n%                 handlesObsOptimGui = ma_ObserveOptimGUI(celBodyData, problem, true, writeOutput, [], varNameStrs, lbUsAll, ubUsAll);\n                \n                out = AppDesignerGUIOutput();\n                ma_ObserveOptimGUI_App(out);\n                handlesObsOptimGui = out.output{1};\n\n                hOptimStatusLabel = handlesObsOptimGui.optimStatusLabel;\n                hFinalStateOptimLabel = handlesObsOptimGui.finalStateOptimLabel;\n                hDispAxes = handlesObsOptimGui.dispAxesPanel;\n                hCancelButton = handlesObsOptimGui.cancelButton;\n                optimStartTic = tic();\n                \n                outputFnc = @(optimvalues,options,flag) PatternSearchOptimizer.getOutputFunction(optimvalues,options,flag, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...\n                                                                                              problem.objective, problem.lb, problem.ub, celBodyData, recorder, propNames, writeOutput, varNameStrs, lbUsAll, ubUsAll, optimStartTic);\n                problem.options.OutputFcn = outputFnc;\n            end\n            \n            [exitflag, message] = lvd_executeOptimProblem(celBodyData, writeOutput, problem, recorder, callOutputFcn);\n            \n            if(callOutputFcn)\n                close(handlesObsOptimGui.ma_ObserveOptimGUI);\n            end\n        end\n        \n        function options = getOptions(obj)\n            options = obj.options;\n        end\n        \n        function tf = usesParallel(obj)\n            tf = obj.options.useParallel.optionVal;\n        end\n        \n        function numWorkers = getNumParaWorkers(obj)\n            numWorkers = obj.options.getNumParaWorkers();\n        end\n        \n        function openOptionsDialog(obj)\n%             lvd_editPatternSearchOptionsGUI(obj);\n            \n            output = AppDesignerGUIOutput({false});\n            lvd_editPatternSearchOptionsGUI_App(obj, output);\n        end\n    end\n    \n    methods(Static, Access=private)\n        function [stop,options,optchanged] = getOutputFunction(optimValues,options,flag, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...\n                                                               objFcn, lb, ub, celBodyData, recorder, propNames, writeOutput, varLabels, lbUsAll, ubUsAll, optimStartTic)\n            \n            optchanged = false;\n            x = optimValues.x;\n            maxConstr = PatternSearchOptimizer.getConstrViolation(optimValues);              \n\n            switch flag\n                case 'iter'\n                    stop = get(hCancelButton,'Value');\n\n                    recorder.iterNums(end+1) = optimValues.iteration;\n                    recorder.xVals(end+1) = {x};\n                    recorder.fVals(end+1) = optimValues.fval;            \n                    recorder.maxCVal(end+1) = maxConstr;\n                case {'init','interrupt','done'}\n                    stop = get(hCancelButton,'Value');\n            end\n            \n            if(stop == true)\n                return;\n            end\n            \n            [~, stateLog] = objFcn(x);\n            \n%             finalStateLogEntry = stateLog.getFinalStateLogEntry();\n%             finalStateLogEntryMA = finalStateLogEntry.getMAFormattedStateLogMatrix(true);\n\n            stateLogMA = stateLog.getMAFormattedStateLogMatrix(true);\n                       \n            if(strcmpi(flag,'init') || strcmpi(flag,'iter'))\n                PatternSearchOptimizer.writeOptimStatus(hOptimStatusLabel, optimValues, flag, writeOutput, optimStartTic);\n                ma_UpdateStateReadout(hFinalStateOptimLabel, 'final', propNames, stateLogMA, celBodyData);\n                PatternSearchOptimizer.generatePlots(x, optimValues, flag, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll);\n                drawnow;\n            end\n        end\n        \n        function writeOptimStatus(hOptimStatusLabel, optimValues, flag, writeOutput, timer)\n            elapTime = toc(timer);\n\n            maxConstr = PatternSearchOptimizer.getConstrViolation(optimValues);\n            \n            if(length(optimValues.method) > 13)\n                method = optimValues.method(1:13);\n            else\n                method = optimValues.method;\n            end\n            \n            outStr = {};\n            outStr{end+1} = ['State                = ', flag];\n            outStr{end+1} = '                        ';\n            outStr{end+1} = ['Iterations           = ', num2str(optimValues.iteration)];\n            outStr{end+1} = ['Function Evals       = ', num2str(optimValues.funccount)];\n            outStr{end+1} = ['Objective Value      = ', num2str(optimValues.fval)];\n            outStr{end+1} = ['Constraint Violation = ', num2str(maxConstr)];\n            outStr{end+1} = ['Method               = ', method];\n            outStr{end+1} = ['Mesh Size            = ', num2str(optimValues.meshsize)];\n            outStr{end+1} = '                       ';\n            outStr{end+1} = ['Elapsed Time         = ', num2str(elapTime), ' sec'];\n            \n            set(hOptimStatusLabel, 'String', outStr);\n            \n            switch flag\n                case 'iter'\n                    formatstr = ' %- 12.1i %- 12.0i %- 12.6g %- 12.3g %- 13s %- 12.3g';\n\n                    iter = optimValues.iteration;\n                    fcnt = optimValues.funccount;\n                    val  = optimValues.fval;\n                    feas = maxConstr;\n                    mesh = optimValues.meshsize;\n\n                    hRow = sprintf(formatstr,iter,fcnt,val,feas,method,mesh);\n                    writeOutput(hRow,'append');\n                case 'init'\n                    hdrStr = sprintf('%- 13s%- 13s%- 13s%- 13s%- 13s%- 13s', 'Iteration','Fcn-Count','f(x)-Value', 'Feasibility', 'Method', 'Mesh Size');\n                    writeOutput(hdrStr,'append');\n            end\n        end\n        \n        function generatePlots(x, optimValues, flag, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll)\n            persistent fValPlotIsLog tLayout hPlot1 hPlot2 hPlot3\n\n            if(isempty(fValPlotIsLog))\n                fValPlotIsLog = true;\n            end\n\n            switch flag\n                case 'init'\n                    if(isvalid(hDispAxes))\n%                         set(hDispAxes,'Visible','on');\n%                         subplot(hDispAxes);\n%                         axes(hDispAxes);\n                        tLayout = tiledlayout(hDispAxes, 3,1);\n                    end\n                    fValPlotIsLog = true;\n            end\n\n            hPlot1 = nexttile(tLayout, 1);\n            if(strcmpi(flag,'init'))\n                \n                hPlot1.XTickLabel= [];\n                hPlot1.YTickLabel= [];\n                hPlot1.ZTickLabel= [];\n%                 axes(hPlot1);\n            else\n%                 axes(hPlot1);\n            end\n            optimplotxKsptot(x, optimValues, flag, lb, ub, varLabels, lbUsAll, ubUsAll);\n\n            hPlot2 = nexttile(tLayout, 2);\n            if(strcmpi(flag,'init'))\n                hPlot2.XTickLabel= [];\n                hPlot2.YTickLabel= [];\n                hPlot2.ZTickLabel= [];\n                h = hPlot2;\n            else\n                h = hPlot2;\n%                 axes(hPlot2);\n            end\n            if(optimValues.fval<=0)\n                fValPlotIsLog = false;\n                set(h,'yscale','linear');\n            end\n            psplotbestf(optimValues, flag);\n            if(fValPlotIsLog)\n                set(h,'yscale','log');\n            else\n                set(h,'yscale','linear');\n            end\n            grid on;\n            grid minor;\n\n            hPlot3 = nexttile(tLayout, 3);\n            if(strcmpi(flag,'init'))\n                hPlot3.XTickLabel= [];\n                hPlot3.YTickLabel= [];\n                hPlot3.ZTickLabel= [];\n                h = hPlot3;\n            else\n                h = hPlot3;\n%                 axes(hPlot3);\n            end\n            psplotmaxconstr(optimValues, flag);\n\n            if(not(isempty(h.Children)))\n                hLine = h.Children(1);\n                if(isa(hLine,'matlab.graphics.chart.primitive.Line'))\n                    yDataLine = hLine.YData;\n                    if(abs(max(yDataLine) / min(yDataLine)) >= 10 && all(yDataLine > 0))\n                        set(h,'yscale','log');\n                    else\n                        set(h,'yscale','linear');\n                    end\n                else\n                    set(h,'yscale','linear');\n                end\n            end\n\n            grid on;\n            grid minor;\n        end\n        \n        function maxConstr = getConstrViolation(optimValues)\n            if(not(isfield(optimValues,'nonlinineq')))\n                optimValues.nonlinineq = [];\n            end\n            \n            if(not(isfield(optimValues,'nonlineq')))\n                optimValues.nonlineq = [];\n            end\n            \n            maxConstr = max([max(abs(optimValues.nonlinineq)), max(abs(optimValues.nonlineq))]);\n\n            if(isempty(maxConstr))\n                maxConstr = 0;\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/optimizers/@PatternSearchOptimizer/PatternSearchOptimizer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24070064251158144}}
{"text": "function [newF,cData] = surface_outlines(plotdat,patchobj,colmap)\n\n% helper function to compute the borders of ROIs on surface data\n%\n% input:\n%\n% plotdat   - cell array (1x2) with the data to plot for a single \n%             hemisphere in each cell. \n%             plotdat{1} = left hemisphere, plotdat{2} = right hemisphere\n% \n% patchobj  - cell array (1x2) containing the patch objects for left {1}\n%             and right {2} hemispheres. Only need the Face and Vertex info\n%             here, so could be structs in the cells. \n%             e.g. patchobj{hem}.Faces = yourFaces;  \n%             patchobj{hem}.Vertices = yourVertices;\n% \n% colmap    - colormap to color the ROI outlines with. Can also be a single\n%             color for all borders (e.g. [0.2 0.2 0.2]).\n% \n% output:\n% \n% newF      - the new Faces containing only the outline faces around each ROI\n% \n% cData     - the color information for the new outline faces. use with \n%             patch as patch(...,'FaceVertexCdata',cData) \n%                 \n%         \n%  Examples:\n%  % make surface figure\n%  h = make_surface_figure('surfacefiles',surffiles);\n%  [outlineF, outlineCData] = surface_outlines({ldat,rdat},{h.obj(1),h.obj(2)}, [0 0 0]);\n%  % left lateral hem\n%  patch(h.ax(1),'Faces',outlineF{1},'Vertices',h.obj(1).Vertices,'FaceVertexCData',outlineCData{1},...,\n%         'FaceColor',fcolormode,'EdgeColor','none','SpecularStrength',.2,'FaceAlpha',facealpha,'SpecularExponent',200);\n%  % right lateral hem \n%  patch(h.ax(3),'Faces',outlineF{2},'Vertices',h.obj(3).Vertices,'FaceVertexCData',outlineCData{2},...,\n%         'FaceColor',fcolormode,'EdgeColor','none','SpecularStrength',.2,'FaceAlpha',facealpha,'SpecularExponent',200);\n% \n%\n% \n% ..\n%     Author and copyright information:\n%     -------------------------------------------------------------------------\n%     Copyright (C) 2018 Stephan Geuter\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n% \n\n%\n% ..\n%    Programmers' notes:\n%    List dates and changes here, and author of changes\n%\n%   3/30/2018 - created\n%   Stephan Geuter, sgeuter@jhmi.edu\n%\n\n\n\n% regionIDs = [199 214 280 360  20 100 170];\n% col = lines(numel(regionIDs));\n% \n\n\n\n% loop hemispheres\nfor hem=1:2\n    \n    % get data for this hemisphere\n    atlasDat = plotdat{hem};\n    atlasDat(isnan(atlasDat)) = 0;\n    \n    % get Faces, Vertices of the brain surface\n    F = patchobj{hem}.Faces;\n    V = patchobj{hem}.Vertices;\n    \n    % unique ROI/blob ID's\n    hemRegions = unique(atlasDat(isfinite(atlasDat)));\n    \n    newF{hem}  = double.empty(0,3);\n    cData{hem} = double.empty(0,3);\n    \n    % loop ROIs\n    for r=1:numel(hemRegions)\n        \n        % find the vertices that belong to the current ROI\n        idx = atlasDat .* single(ismember(atlasDat,hemRegions(r)));\n        \n        if numel(unique(idx))>1 && any(unique(idx)~=0)\n            % compute the new Faces\n            Fclasses = idx(F);\n            roiFace  = F(any(diff(Fclasses,1,2),2) , :);\n            \n            % get color for current ROI outline\n            if size(colmap,1) == 1\n                roiCol   = repmat(colmap,size(roiFace,1),1);\n            else\n                roiCol   = repmat(colmap(hemRegions(r),:),size(roiFace,1),1);\n            end\n            \n            % cat data across ROIs\n            newF{hem} = vertcat(newF{hem},roiFace);\n            cData{hem}= vertcat(cData{hem},roiCol);\n        end\n    end\n    \n    \n%     for j=find(cellregexp(h.label,hemstr))\n%         hp(j) = patch(h.ax(j),'Faces',newF{hem},'Vertices',V,'FaceColor','flat',...\n%             'Edgecolor','none','FaceVertexCdata',cData{hem},...\n%             'SpecularStrength',.2,'SpecularExponent',200);\n%         material(hp(j),'dull');\n%         lighting(h.ax(j),'gouraud');\n%     end\nend\n\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Cifti_plotting/surface_outlines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24062990457402494}}
{"text": "function proposals= calcEdgeBoxesForIm( input, ebconfig )\nrmpath(genpath([pwd '/rigor']));\nrmpath(genpath([pwd '/mcg/']));\nif(isstr(input))\n\tim = im2double(imread(input));\nelse\n        im = im2double(input); % Just to make input consistent\nend\nif(size(im, 3) == 1)\n        im=repmat(im,[1,1,3]);\nend\n% load pre-trained edge detection model and set opts\nif(~exist(ebconfig.modelPath))\n    fprintf('Path to model does not exist. Please make sure you give a proper full path\\n');\n    return; \nend\n\nmodel = load(ebconfig.modelPath);\nmodel = model.model;\nmodel.opts.multiscale = 0;\nmodel.opts.sharpen = 2;\nmodel.opts.nThread = 4;\n\n%Write code to set options \n% call edgeBoxes() to get back options\n\nopts = edgeBoxes();\nbbs=edgeBoxes(im,model,opts);\nif(isfield((ebconfig.opts),'numProposals'))\n\tnumProposals=ebconfig.opts.numProposals;\n        if(size(bbs,1)>=numProposals)\n       \t        bbs=bbs(1:numProposals);\n       \telse\n               \tfprintf('Only %d proposals were generated for input image.\\n',size(bbs,1));\n        end\nend\n%edges boxes produces baoxes as \"[x y w, h]\"\n%we convert to [x y x+w y+h]==[xmin ymin xmax ymax]\nboxes=bbs(:,1:4);\nboxes=[boxes(:,1) boxes(:,2) boxes(:,1)+ boxes(:,3) boxes(:,2)+boxes(:,4)];\nproposals.boxes= boxes;\nproposals.scores = bbs(:,5);\n\naddpath(genpath([pwd '/mcg/']));\naddpath(genpath([pwd '/rigor']));\nend\n\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/edgeBoxes/API/calcedgeBoxesForIm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24062990457402492}}
{"text": "function [features, gparams, feature_info] = init_features(features, gparams, is_color_image, img_sample_sz, size_mode)\n\nif nargin < 3\n    size_mode = 'same';\nend\n\n\n% Set missing global parameters to default values\nif ~isfield(gparams, 'normalize_power')\n    gparams.normalize_power = [];\nend\nif ~isfield(gparams, 'normalize_size')\n    gparams.normalize_size = true;\nend\nif ~isfield(gparams, 'normalize_dim')\n    gparams.normalize_dim = false;\nend\nif ~isfield(gparams, 'square_root_normalization')\n    gparams.square_root_normalization = false;\nend\nif ~isfield(gparams, 'use_gpu')\n    gparams.use_gpu = false;\nend\n\n% find which features to keep\nfeat_ind = false(length(features),1);\nfor n = 1:length(features)\n    \n    if ~isfield(features{n}.fparams,'useForColor')\n        features{n}.fparams.useForColor = true;\n    end\n    \n    if ~isfield(features{n}.fparams,'useForGray')\n        features{n}.fparams.useForGray = true;\n    end\n    \n    if (features{n}.fparams.useForColor && is_color_image) || (features{n}.fparams.useForGray && ~is_color_image)\n        % keep feature\n        feat_ind(n) = true;\n    end\nend\n\n% remove features that are not used\nfeatures = features(feat_ind);\n\nnum_features = length(features);\n\nfeature_info.min_cell_size = zeros(num_features,1);\n\n\n% Initialize features by\n% - setting the dimension (nDim)\n% - specifying if a cell array is returned (is_cell)\n% - setting default values of missing feature-specific parameters\n% - loading and initializing necessary data (e.g. the lookup table or the network)\nfor k = 1:length(features)\n    if isequal(features{k}.getFeature, @get_fhog)\n        if ~isfield(features{k}.fparams, 'nOrients')\n            features{k}.fparams.nOrients = 9;\n        end\n        features{k}.fparams.nDim = 3*features{k}.fparams.nOrients+5-1;\n        features{k}.is_cell = false;\n        features{k}.is_cnn = false;\n        \n    elseif isequal(features{k}.getFeature, @get_table_feature)\n        table = load(['lookup_tables/' features{k}.fparams.tablename]);\n        features{k}.fparams.nDim = size(table.(features{k}.fparams.tablename),2);\n        features{k}.is_cell = false;\n        features{k}.is_cnn = false;\n        \n    elseif isequal(features{k}.getFeature, @get_colorspace)\n        features{k}.fparams.nDim = 1;\n        features{k}.is_cell = false;\n        features{k}.is_cnn = false;\n        \n    elseif isequal(features{k}.getFeature, @get_cnn_layers) || isequal(features{k}.getFeature, @get_OFcnn_layers)\n        % make sure the layers are correcly sorted\n        features{k}.fparams.output_layer = sort(features{k}.fparams.output_layer);\n        \n        % Set default parameters\n        if ~isfield(features{k}.fparams, 'input_size_mode')\n            features{k}.fparams.input_size_mode = 'adaptive';\n        end\n        if ~isfield(features{k}.fparams, 'input_size_scale')\n            features{k}.fparams.input_size_scale = 1;\n        end\n        if ~isfield(features{k}.fparams, 'downsample_factor')\n            features{k}.fparams.downsample_factor = ones(1, length(features{k}.fparams.output_layer));\n        end\n        \n        % load the network\n        net = load_cnn(features{k}.fparams, img_sample_sz);\n        \n        % find the dimensionality of each layer\n        features{k}.fparams.nDim = net.info.dataSize(3, features{k}.fparams.output_layer+1)';\n        \n        % find the stride of the layers\n        if isfield(net.info, 'receptiveFieldStride')\n            net_info_stride = cat(2, [1; 1], net.info.receptiveFieldStride);\n        else\n            net_info_stride = [1; 1];\n        end\n        \n        % compute the cell size of the layers (takes down-sampling factor\n        % into account)\n        features{k}.fparams.cell_size = net_info_stride(1, features{k}.fparams.output_layer+1)' .* features{k}.fparams.downsample_factor';\n        \n        % this feature will always return a cell array\n        features{k}.is_cell = true;\n        features{k}.is_cnn = true;\n    elseif isequal(features{k}.getFeature,@get_eitel_cnn)\n        features{k}.fparams = make_eitel_feature(features{k}.fparams);\n    else\n        error('Unknown feature type');\n    end\n    \n    % Set default cell size\n    if ~isfield(features{k}.fparams, 'cell_size')\n        features{k}.fparams.cell_size = 1;\n    end\n    \n    % Set default penalty\n    if ~isfield(features{k}.fparams, 'penalty')\n        features{k}.fparams.penalty = zeros(length(features{k}.fparams.nDim),1);\n    end\n    \n    % Find the minimum cell size of each layer\n    feature_info.min_cell_size(k) = min(features{k}.fparams.cell_size);\nend\n\n% Order the features in increasing minimal cell size\n[~, feat_ind] = sort(feature_info.min_cell_size);\nfeatures = features(feat_ind);\nfeature_info.min_cell_size = feature_info.min_cell_size(feat_ind);\n\n% Set feature info\nfeature_info.dim_block = cell(num_features,1);\nfeature_info.penalty_block = cell(num_features,1);\n\nfor k = 1:length(features)\n    % update feature info\n    feature_info.dim_block{k} = features{k}.fparams.nDim;\n    feature_info.penalty_block{k} = features{k}.fparams.penalty(:);\nend\n% Feature info for each cell block\nfeature_info.dim = cell2mat(feature_info.dim_block);\nfeature_info.penalty = cell2mat(feature_info.penalty_block);\n\n% Find if there is any CNN feature\ncnn_feature_ind = -1;\nfor k = 1:length(features)\n    if features{k}.is_cnn\n        cnn_feature_ind = k;\n    end\nend\n\n% This ugly code sets the image sample size to be used for extracting the\n% features. It then computes the data size (size of the features) and the\n% image support size (the corresponding size in the image).\nif cnn_feature_ind > 0\n    scale = features{cnn_feature_ind}.fparams.input_size_scale;\n    \n    new_img_sample_sz = img_sample_sz;\n    \n    % First try decrease one\n    net_info = net.info;\n    \n    if ~strcmpi(size_mode, 'same') && strcmpi(features{cnn_feature_ind}.fparams.input_size_mode, 'adaptive')\n        orig_sz = net.info.dataSize(1:2,end)' / features{cnn_feature_ind}.fparams.downsample_factor(end);\n        \n        if strcmpi(size_mode, 'exact')\n            desired_sz = orig_sz + 1;\n        elseif strcmpi(size_mode, 'odd_cells')\n            desired_sz = orig_sz + 1 + mod(orig_sz,2);\n        end\n        \n        while desired_sz(1) > net_info.dataSize(1,end)\n            new_img_sample_sz = new_img_sample_sz + [1, 0];\n            net_info = vl_simplenn_display(net, 'inputSize', [round(scale * new_img_sample_sz), 3 1]);\n        end\n        while desired_sz(2) > net_info.dataSize(2,end)\n            new_img_sample_sz = new_img_sample_sz + [0, 1];\n            net_info = vl_simplenn_display(net, 'inputSize', [round(scale * new_img_sample_sz), 3 1]);\n        end\n    end\n    \n    feature_info.img_sample_sz = round(new_img_sample_sz);\n    \n    if strcmpi(features{cnn_feature_ind}.fparams.input_size_mode, 'adaptive')\n        features{cnn_feature_ind}.img_input_sz = feature_info.img_sample_sz;\n    else\n        features{cnn_feature_ind}.img_input_sz = net.meta.normalization.imageSize(1:2);\n    end\n    \n    % Sample size to be input to the net\n    scaled_sample_sz = round(scale * features{cnn_feature_ind}.img_input_sz);\n    \n    if isfield(net_info, 'receptiveFieldStride')\n        net_info_stride = cat(2, [1; 1], net_info.receptiveFieldStride);\n    else\n        net_info_stride = [1; 1];\n    end\n    \n    net_stride = net_info_stride(:, features{cnn_feature_ind}.fparams.output_layer+1)';\n    total_feat_sz = net_info.dataSize(1:2, features{cnn_feature_ind}.fparams.output_layer+1)';\n    \n    shrink_number = max(2 * ceil((net_stride(end,:) .* total_feat_sz(end,:) - scaled_sample_sz) ./ (2 * net_stride(end,:))), 0);\n    \n    deepest_layer_sz = total_feat_sz(end,:) - shrink_number;\n    scaled_support_sz = net_stride(end,:) .* deepest_layer_sz;\n    \n    % Calculate output size for each layer\n    cnn_output_sz = round(bsxfun(@rdivide, scaled_support_sz, net_stride));\n    features{cnn_feature_ind}.fparams.start_ind = floor((total_feat_sz - cnn_output_sz)/2) + 1;\n    features{cnn_feature_ind}.fparams.end_ind = features{cnn_feature_ind}.fparams.start_ind + cnn_output_sz - 1;\n    \n    feature_info.img_support_sz = round(scaled_support_sz .* feature_info.img_sample_sz ./ scaled_sample_sz);\n    \n    % Set the input size\n    features{cnn_feature_ind}.fparams.net = set_cnn_input_size(net, feature_info.img_sample_sz);\n    \n    if gparams.use_gpu\n        if isempty(gparams.gpu_id)\n            gpuDevice();\n        elseif gparams.gpu_id > 0\n            gpuDevice(gparams.gpu_id);\n        end\n        features{cnn_feature_ind}.fparams.net = vl_simplenn_move(features{cnn_feature_ind}.fparams.net, 'gpu');\n    end\nelse\n    max_cell_size = max(feature_info.min_cell_size);\n    \n    if strcmpi(size_mode, 'same')\n        feature_info.img_sample_sz = round(img_sample_sz);\n    elseif strcmpi(size_mode, 'exact')\n        feature_info.img_sample_sz = round(img_sample_sz / max_cell_size) * max_cell_size;\n    elseif strcmpi(size_mode, 'odd_cells')\n        new_img_sample_sz = (1 + 2*round(img_sample_sz / (2*max_cell_size))) * max_cell_size;\n        \n        % Check the size with the largest number of odd dimensions (choices in the\n        % third dimension)\n        feature_sz_choices = floor(bsxfun(@rdivide, bsxfun(@plus, new_img_sample_sz, reshape(0:max_cell_size-1, 1, 1, [])), feature_info.min_cell_size));\n        num_odd_dimensions = sum(sum(mod(feature_sz_choices, 2) == 1, 1), 2);\n        [~, best_choice] = max(num_odd_dimensions(:));\n        pixels_added = best_choice - 1;\n        feature_info.img_sample_sz = round(new_img_sample_sz + pixels_added);\n    else\n        error('Unknown size_mode');\n    end\n    \n    % Setting the feature size and support size\n    %     feature_info.data_sz = floor(bsxfun(@rdivide, feature_info.img_sample_sz, feature_info.min_cell_size));\n    feature_info.img_support_sz = feature_info.img_sample_sz;\nend\n\n% Set the sample size and data size for each feature\nfeature_info.data_sz_block = cell(num_features,1);\nfor k = 1:length(features)\n    if features{k}.is_cnn\n        % CNN features have a different sample size, since the receptive\n        % field is often larger than the support size\n        features{k}.img_sample_sz = feature_info.img_sample_sz(:)';\n        \n        % Set the data size based on the computed output size\n        feature_info.data_sz_block{k} = floor(bsxfun(@rdivide, cnn_output_sz, features{k}.fparams.downsample_factor'));\n    else\n        % implemented classic features always have the same sample and\n        % support size\n        features{k}.img_sample_sz = feature_info.img_support_sz(:)';\n        features{k}.img_input_sz = features{k}.img_sample_sz;\n        \n        % Set data size based on cell size\n        feature_info.data_sz_block{k} = floor(bsxfun(@rdivide, features{k}.img_sample_sz, features{k}.fparams.cell_size));\n    end\nend\n\nfeature_info.data_sz = cell2mat(feature_info.data_sz_block);", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/feature_extraction/init_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24046929253846613}}
{"text": "function retPhases = atlasEstimatePhases(vw, areaCorners, scanNum, fieldName)\n% Define retinotopy phases for an angle and wedge map\n%\n%   retPhases = atlasEstimatePhases(vw, areaCorners, scanNum, fieldName)\n%\n% Lets the user interactively define the data phases corresponding to the\n% fovea, periphery, upper and lower vertical meridians for the atlas and\n% data fits.\n%\n% scanNum is the scan number of the wedge and ring in this view (and for\n% the view's selected data type). fieldName is a 1 x 2 cell array\n% specifying the field containing the polar angle and eccentricity data,\n% respectively. (For PRF analyses, these are not necessarily loaded into\n% the phase slot.)\n%\nif notDefined('fieldName'),\t\tfieldName = {'ph' 'ph'};\t\t\tend\n\nnAreas = length(areaCorners);\nfor ii=1:nAreas\n    corners = areaCorners{ii};\n    retPhases(ii,1) = atlasEstimateBoundaryPhases(vw, corners(1,:), ...\n\t\t\t\t\t\t\tcorners(2,:), scanNum(1), fieldName{1});\n    retPhases(ii,2) = atlasEstimateBoundaryPhases(vw, corners(3,:), ...\n\t\t\t\t\t\t\tcorners(4,:), scanNum(1), fieldName{1});\n    retPhases(ii,3) = atlasEstimateBoundaryPhases(vw, corners(1,:), ...\n\t\t\t\t\t\t\tcorners(4,:), scanNum(2), fieldName{2});\n    retPhases(ii,4) = atlasEstimateBoundaryPhases(vw, corners(2,:), ...\n\t\t\t\t\t\t\tcorners(3,:), scanNum(2), fieldName{2});\nend\n\nif nAreas > 1, retPhases = meanPhase(retPhases); end\n\n\n%% this part of the code seems to attempt to adjust the phase difference\n%% between the stored data in the flat view, and real world units. A couple\n%% comments / points of confusion here:\n%% (1) It seems that things would be much simplified if the downstream code\n%% to this function dealt exclusively with data already in real-world\n%% units.\n%% (2) for traveling-wave data, the functions polarAngle and eccentricity\n%% map between phase and real-world units. Perhaps this should be used?\n%% (3) for pRF data, the loaded data are already in real world units.\n%% (4) what exactly do the retPhases do?\n%% ras, 04/09.\nprompt = {'Foveal', 'Peripheral', 'Lower Phase (angle map)'};\ndef = {num2str(retPhases(1)), num2str(retPhases(2)), num2str(retPhases(3))};\ndlgTitle = 'Adjust retinal phase estimates';\nlineNo = 1;\nanswer = inputdlg(prompt, dlgTitle, lineNo, def);\n\n% adjust the retPhases based on the user response\nangleShift = retPhases(3) - str2double(answer{3});\nfor ii=1:3, retPhases(ii) = str2double(answer{ii}); end \n\n% We shift the fourth (UVM) by the same amount as the LVM\nretPhases(4) = retPhases(4) - angleShift;\n\nreturn;\n\n%----------------------------------------------------\nfunction meanPh = atlasEstimateBoundaryPhases(vw, p1, p2, scanNum, fieldName)\n%\n%   meanPh = atlasEstimateBoundaryPhases(vw, p1, p2, scanNum, fieldName)\n%\n% Author:  Wandell\n% Purpose:\n%     Estimate the average phase along a line between two points.  This\n%     code is used to provide first estimates of the foveal, peripheral,\n%     UVM and LVM phase in building atlases.\n%\n% Example:\n%\n%   scanNum = 1\n%   retPhase(1)= atlasEstimateBoundaryPhases(vw,corners(1,:),corners(2,:),scanNum);\n%\n%\n% ras 04/2009:  allows the field to be passed as a parameter -- not only\n% confined to phase field, and doesn't require multiple different scans for\n% polar angle / eccentricity. This is critical for use with pRF models.\n\ncurSlice = viewGet(vw, 'Current Slice');\n[x, y] = findLinePoints([p1(1) p1(2)], [p2(1) p2(2)]);\n\nnewCoords = zeros(3,length(x));\nnewCoords(1,:) = y;\nnewCoords(2,:) = x;\nnewCoords(3,:) = curSlice*ones(1,length(x));\n\n% Convert coords to canonical frame of reference\nnewCoords = curOri2CanOri(vw, newCoords);\nph = getCurDataROI(vw, fieldName, scanNum, newCoords);\nif ~isequal( lower(fieldName), 'ph' )\n\t% put the data into the range [0 2*pi]. \n\t% there may be a chance that it is not correct that the ph data span\n\t% this range -- for instance, if someone provides polar angle data in a\n\t% different field. I should deal with this contingency, but it might be\n\t% even better to have the downstream code deal with real-world-unit\n\t% data, and leave the conversion to these units up to the user before\n\t% entering this function (ras 04/09)...\n\tph = normalize(ph, 0, 2*pi);\nend\ncxph = exp(sqrt(-1)*ph);\n\n% We add pi to the output so that the variables run from [0,2pi] instead of\n% from [-pi,pi].  This is consistent with mrLoadRet encoding of phase.\nmeanPh = angle(mean(cxph));\n\nif meanPh < 0, meanPh = meanPh + 2*pi; end\nif meanPh > 2*pi, meanPh = meanPh - 2*pi; end\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/Atlas/atlasEstimatePhases.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2401973761644581}}
{"text": "function bmu_colors=som_bmucolor(bmus, m, colors)\n\n% SOM_BMUCOLOR Returns the colors of the bmus according to a map colorcode\n%\n% bmu_colors=som_bmucolor(bmus, msize, colors);\n%\n% INPUT ARGUMENTS ([]'s are optional)\n%\n% bmus   (matrix) Nx1 vector of BMU indexes\n% msize  (map struct, topol struct or 1x2 vector) \n%          gives the map grid size \n% colors (matrix) colormap(s): munits x 3 x d matrix of RGB vectors\n%\n% OUTPUT ARGUMENTS \n%\n% bmu_colors (Nx3xd matrix) color of the data point according to its BMU's \n%              color(s).\n%\n% Idea is to get a color for each data point that links it to its BMU. \n%\n% EXAMPLE\n%\n% We want to show how an time series is projected  to a map. Instead of \n% a trajectory, we use 'color linking'\n%\n% map=som_make(multi_dim_signal); \n% bmus=som_bmu(map,multi_dim_signal);\n% Colors=som_bmucolor(bmus, map, som_colorcode(map,'rgb1'));\n% colorsignal(Colors, multi_dim_signal);\n%\n% See also SOM_COLORCODE.\n\n% Copyright (c) 1999-2000 by the SOM toolbox programming team.\n% http://www.cis.hut.fi/projects/somtoolbox/             \n\n% Version 2.0alpha Johan 170699\n\n%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nerror(nargchk(3, 3, nargin))   % check no. of input args is correct\n\n% Check map grid size\n\nif vis_valuetype(m,{'1x2'}),\n  msize=m;  \nelse\n  [tmp,ok,tmp]=som_set(m);\n  if isstruct(m) && all(ok)        % check m type\n    switch m.type\n    case 'som_topol'\n      msize=m.msize;\n      lattice=m.lattice;\n    case 'som_map'\n      msize=m.topol.msize;\n      lattice=m.topol.lattice;\n    otherwise\n      error('Invalid map or topol struct.');\n    end\n  end\nend  \n\nif length(msize)>2\n  error('Only 2D maps allowed!');\nend\n\nn=prod(msize)\n\n% Check colorcode size\n\nif ~vis_valuetype(colors,{'nx3xdimrgb','nx3rgb'})\n  error('Colorcode matrix not valid!');\nend\n\n% Check bmu vector\n\nif ~vis_valuetype(bmus,{'nx1'}),\n  error('Need a column vector of BMU indexes!');\nelse\n  bmus=round(bmus);\n  if max(bmus) > n || min(bmus) < 1\n    error('BMU indexes exeed the map size!')\n  end\nend\n\n%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nbmu_c=colors(bmus,:,:);\n\n%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nbmu_colors=squeeze(bmu_c);\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/som/som_bmucolor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24016287625726426}}
{"text": "function [scores, maxlabel] = classification_demo(im, use_gpu)\n% [scores, maxlabel] = classification_demo(im, use_gpu)\n%\n% Image classification demo using BVLC CaffeNet.\n%\n% IMPORTANT: before you run this demo, you should download BVLC CaffeNet\n% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)\n%\n% ****************************************************************************\n% For detailed documentation and usage on Caffe's Matlab interface, please\n% refer to Caffe Interface Tutorial at\n% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab\n% ****************************************************************************\n%\n% input\n%   im       color image as uint8 HxWx3\n%   use_gpu  1 to use the GPU, 0 to use the CPU\n%\n% output\n%   scores   1000-dimensional ILSVRC score vector\n%   maxlabel the label of the highest score\n%\n% You may need to do the following before you start matlab:\n%  $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64\n%  $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n%\n% Usage:\n%  im = imread('../../examples/images/cat.jpg');\n%  scores = classification_demo(im, 1);\n%  [score, class] = max(scores);\n% Five things to be aware of:\n%   caffe uses row-major order\n%   matlab uses column-major order\n%   caffe uses BGR color channel order\n%   matlab uses RGB color channel order\n%   images need to have the data mean subtracted\n\n% Data coming in from matlab needs to be in the order\n%   [width, height, channels, images]\n% where width is the fastest dimension.\n% Here is the rough matlab for putting image data into the correct\n% format in W x H x C with BGR channels:\n%   % permute channels from RGB to BGR\n%   im_data = im(:, :, [3, 2, 1]);\n%   % flip width and height to make width the fastest dimension\n%   im_data = permute(im_data, [2, 1, 3]);\n%   % convert from uint8 to single\n%   im_data = single(im_data);\n%   % reshape to a fixed size (e.g., 227x227).\n%   im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n%   % subtract mean_data (already in W x H x C with BGR channels)\n%   im_data = im_data - mean_data;\n\n% If you have multiple images, cat them with cat(4, ...)\n\n% Add caffe/matlab to you Matlab search PATH to use matcaffe\nif exist('../+caffe', 'dir')\n  addpath('..');\nelse\n  error('Please run this demo from caffe/matlab/demo');\nend\n\n% Set caffe mode\nif exist('use_gpu', 'var') && use_gpu\n  caffe.set_mode_gpu();\n  gpu_id = 0;  % we will use the first gpu in this demo\n  caffe.set_device(gpu_id);\nelse\n  caffe.set_mode_cpu();\nend\n\n% Initialize the network using BVLC CaffeNet for image classification\n% Weights (parameter) file needs to be downloaded from Model Zoo.\nmodel_dir = '../../models/bvlc_reference_caffenet/';\nnet_model = [model_dir 'deploy.prototxt'];\nnet_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];\nphase = 'test'; % run with phase test (so that dropout isn't applied)\nif ~exist(net_weights, 'file')\n  error('Please download CaffeNet from Model Zoo before you run this demo');\nend\n\n% Initialize a network\nnet = caffe.Net(net_model, net_weights, phase);\n\nif nargin < 1\n  % For demo purposes we will use the cat image\n  fprintf('using caffe/examples/images/cat.jpg as input image\\n');\n  im = imread('../../examples/images/cat.jpg');\nend\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Channels x Num, where Channels == 1000\ntic;\n% The net forward function. It takes in a cell array of N-D arrays\n% (where N == 4 here) containing data of input blob(s) and outputs a cell\n% array containing data from output blob(s)\nscores = net.forward(input_data);\ntoc;\n\nscores = scores{1};\nscores = mean(scores, 2);  % take average scores over 10 crops\n\n[~, maxlabel] = max(scores);\n\n% call caffe.reset_all() to reset caffe\ncaffe.reset_all();\n\n% ------------------------------------------------------------------------\nfunction crops_data = prepare_image(im)\n% ------------------------------------------------------------------------\n% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that\n% is already in W x H x C with BGR channels\nd = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');\nmean_data = d.mean_data;\nIMAGE_DIM = 256;\nCROPPED_DIM = 227;\n\n% Convert an image returned by Matlab's imread to im_data in caffe's data\n% format: W x H x C with BGR channels\nim_data = im(:, :, [3, 2, 1]);  % permute channels from RGB to BGR\nim_data = permute(im_data, [2, 1, 3]);  % flip width and height\nim_data = single(im_data);  % convert from uint8 to single\nim_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');  % resize im_data\nim_data = im_data - mean_data;  % subtract mean_data (already in W x H x C, BGR)\n\n% oversample (4 corners, center, and their x-axis flips)\ncrops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\nn = 1;\nfor i = indices\n  for j = indices\n    crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);\n    crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);\n    n = n + 1;\n  end\nend\ncenter = floor(indices(2) / 2) + 1;\ncrops_data(:,:,:,5) = ...\n  im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);\ncrops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);\n", "meta": {"author": "aimerykong", "repo": "deepImageAestheticsAnalysis", "sha": "3c51f0b65660fe65970256c3c04913ccf7b1e056", "save_path": "github-repos/MATLAB/aimerykong-deepImageAestheticsAnalysis", "path": "github-repos/MATLAB/aimerykong-deepImageAestheticsAnalysis/deepImageAestheticsAnalysis-3c51f0b65660fe65970256c3c04913ccf7b1e056/demoRatingImages/matlab/demo/classification_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2401628762572642}}
{"text": "function out = isMisorientation(o)\n% check whether o is a misorientation\n\nout = isa(o.SS,'crystalSymmetry') && isa(o.CS,'crystalSymmetry');\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@orientation/isMisorientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24015142691958238}}
{"text": "function pesq_mos= pesq_psychoacoustic_model (ref_data, ref_Nsamples, deg_data, ...\n    deg_Nsamples )\n\nglobal CALIBRATE Nfmax Nb Sl Sp\nglobal nr_of_hz_bands_per_bark_band centre_of_band_bark\nglobal width_of_band_hz centre_of_band_hz width_of_band_bark\nglobal pow_dens_correction_factor abs_thresh_power\nglobal Downsample SEARCHBUFFER DATAPADDING_MSECS Fs Nutterances\nglobal Utt_Start Utt_End Utt_Delay NUMBER_OF_PSQM_FRAMES_PER_SYLLABE \nglobal Fs Plot_Frame\n\n% Plot_Frame= 75; % this is the frame whose spectrum will be plotted\n\nFALSE= 0;\nTRUE= 1;\nNUMBER_OF_PSQM_FRAMES_PER_SYLLABE= 20;\n\nmaxNsamples = max (ref_Nsamples, deg_Nsamples);\nNf = Downsample * 8;\nMAX_NUMBER_OF_BAD_INTERVALS = 1000;\n\nstart_frame_of_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\nstop_frame_of_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\nstart_sample_of_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\nstop_sample_of_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\nnumber_of_samples_in_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\ndelay_in_samples_in_bad_interval= zeros( 1, MAX_NUMBER_OF_BAD_INTERVALS);\nnumber_of_bad_intervals= 0;\nthere_is_a_bad_frame= FALSE;\n\nWhanning= hann( Nf, 'periodic');\nWhanning= Whanning';\n\nD_POW_F = 2;\nD_POW_S = 6;\nD_POW_T = 2;\nA_POW_F = 1;\nA_POW_S = 6;\nA_POW_T = 2;\nD_WEIGHT= 0.1;\nA_WEIGHT= 0.0309;\n\nCRITERIUM_FOR_SILENCE_OF_5_SAMPLES = 500;\nsamples_to_skip_at_start = 0;\nsum_of_5_samples= 0;\nwhile ((sum_of_5_samples< CRITERIUM_FOR_SILENCE_OF_5_SAMPLES) ...\n        && (samples_to_skip_at_start < maxNsamples / 2))\n    sum_of_5_samples= sum( abs( ref_data( samples_to_skip_at_start...\n        + SEARCHBUFFER * Downsample + 1: samples_to_skip_at_start...\n        + SEARCHBUFFER * Downsample + 5)));\n\n    if (sum_of_5_samples< CRITERIUM_FOR_SILENCE_OF_5_SAMPLES)\n        samples_to_skip_at_start = samples_to_skip_at_start+ 1;\n    end\nend\n% fprintf( 'samples_to_skip_at_start is %d\\n', samples_to_skip_at_start);\n\nsamples_to_skip_at_end = 0;\nsum_of_5_samples= 0;\nwhile ((sum_of_5_samples< CRITERIUM_FOR_SILENCE_OF_5_SAMPLES) ...\n        && (samples_to_skip_at_end < maxNsamples / 2))\n    sum_of_5_samples= sum( abs( ref_data( maxNsamples - ...\n        SEARCHBUFFER* Downsample + DATAPADDING_MSECS* (Fs/ 1000) ...\n        - samples_to_skip_at_end - 4: maxNsamples - ...\n        SEARCHBUFFER* Downsample + DATAPADDING_MSECS* (Fs/ 1000) ...\n        - samples_to_skip_at_end)));\n    if (sum_of_5_samples< CRITERIUM_FOR_SILENCE_OF_5_SAMPLES)\n        samples_to_skip_at_end = samples_to_skip_at_end+ 1;\n    end\nend\n% fprintf( 'samples_to_skip_at_end is %d\\n', samples_to_skip_at_end);\n\nstart_frame = floor( samples_to_skip_at_start/ (Nf/ 2));\nstop_frame = floor( (maxNsamples- 2* SEARCHBUFFER* Downsample ...\n    + DATAPADDING_MSECS* (Fs/ 1000)- samples_to_skip_at_end) ...\n    / (Nf/ 2))- 1;\n% number of frames in speech data plus DATAPADDING_MSECS\n% fprintf( 'start/end frame is %d/%d\\n', start_frame, stop_frame);\n\nD_disturbance= zeros( stop_frame+ 1, Nb);\nDA_disturbance= zeros( stop_frame+ 1, Nb);\n\npower_ref = pow_of (ref_data, SEARCHBUFFER* Downsample, ...\n    maxNsamples- SEARCHBUFFER* Downsample+ DATAPADDING_MSECS* (Fs/ 1000),...\n    maxNsamples- 2* SEARCHBUFFER* Downsample+ DATAPADDING_MSECS* (Fs/ 1000));\npower_deg = pow_of (deg_data, SEARCHBUFFER * Downsample, ...\n    maxNsamples- SEARCHBUFFER* Downsample+ DATAPADDING_MSECS* (Fs/ 1000),...\n    maxNsamples- 2* SEARCHBUFFER* Downsample+ DATAPADDING_MSECS* (Fs/ 1000));\n% fprintf( 'ref/deg power is %f/%f\\n', power_ref, power_deg);\n\nhz_spectrum_ref             = zeros( 1, Nf/ 2);\nhz_spectrum_deg             = zeros( 1, Nf/ 2);\nframe_is_bad                = zeros( 1, stop_frame + 1);\nsmeared_frame_is_bad        = zeros( 1, stop_frame + 1);\nsilent                      = zeros( 1, stop_frame + 1);\n\npitch_pow_dens_ref          = zeros( stop_frame + 1, Nb);\npitch_pow_dens_deg          = zeros( stop_frame + 1, Nb);\n\nframe_was_skipped           = zeros( 1, stop_frame + 1);\nframe_disturbance           = zeros( 1, stop_frame + 1);\nframe_disturbance_asym_add  = zeros( 1, stop_frame + 1);\n\navg_pitch_pow_dens_ref      = zeros( 1, Nb);\navg_pitch_pow_dens_deg      = zeros( 1, Nb);\nloudness_dens_ref           = zeros( 1, Nb);\nloudness_dens_deg           = zeros( 1, Nb);\ndeadzone                    = zeros( 1, Nb);\ndisturbance_dens            = zeros( 1, Nb);\ndisturbance_dens_asym_add   = zeros( 1, Nb);\n\ntime_weight                 = zeros( 1, stop_frame + 1);\ntotal_power_ref             = zeros( 1, stop_frame + 1);\n\n% fid= fopen( 'tmp_mat.txt', 'wt');\n\nfor frame = 0: stop_frame\n    start_sample_ref = 1+ SEARCHBUFFER * Downsample + frame* (Nf/ 2);\n    hz_spectrum_ref= short_term_fft (Nf, ref_data, Whanning, ...\n        start_sample_ref);\n\n    utt = Nutterances;\n    while ((utt >= 1) && ((Utt_Start(utt)- 1)* Downsample+ 1 ...\n            > start_sample_ref))\n        utt= utt - 1;\n    end\n\n    if (utt >= 1)\n        delay = Utt_Delay(utt);\n    else\n        delay = Utt_Delay(1);\n    end\n\n    start_sample_deg = start_sample_ref + delay;\n\n    if ((start_sample_deg > 0) && (start_sample_deg + Nf- 1 < ...\n            maxNsamples+ DATAPADDING_MSECS* (Fs/ 1000)))\n        hz_spectrum_deg= short_term_fft (Nf, deg_data, Whanning, ...\n            start_sample_deg);\n    else\n        hz_spectrum_deg( 1: Nf/ 2)= 0;\n    end\n\n    pitch_pow_dens_ref( frame+ 1, :)= freq_warping (...\n        hz_spectrum_ref, Nb, frame);\n    %peak = maximum_of (pitch_pow_dens_ref, 0, Nb);\n    pitch_pow_dens_deg( frame+ 1, :)= freq_warping (...\n        hz_spectrum_deg, Nb, frame);\n\n    total_audible_pow_ref = total_audible (frame, pitch_pow_dens_ref, 1E2);\n    total_audible_pow_deg = total_audible (frame, pitch_pow_dens_deg, 1E2);\n    silent(frame+ 1) = (total_audible_pow_ref < 1E7);\n    \n\nend\n% fclose( fid);\n\navg_pitch_pow_dens_ref= time_avg_audible_of (stop_frame + 1, ...\n    silent, pitch_pow_dens_ref, floor((maxNsamples- 2* SEARCHBUFFER* ...\n    Downsample+ DATAPADDING_MSECS* (Fs/ 1000))/ (Nf / 2))- 1);\navg_pitch_pow_dens_deg= time_avg_audible_of (stop_frame + 1, ...\n    silent, pitch_pow_dens_deg, floor((maxNsamples- 2* SEARCHBUFFER* ...\n    Downsample+ DATAPADDING_MSECS* (Fs/ 1000))/ (Nf/ 2))- 1);\n\n% fid= fopen( 'tmp_mat.txt', 'wt');\n% fprintf( fid, '%f\\n', avg_pitch_pow_dens_deg);\n% fclose( fid);\n\nif (CALIBRATE== 0)\n    pitch_pow_dens_ref= freq_resp_compensation (stop_frame + 1, ...\n        pitch_pow_dens_ref, avg_pitch_pow_dens_ref, ...\n        avg_pitch_pow_dens_deg, 1000);\n    if (Plot_Frame>= 0) % plot pitch_pow_dens_ref\n        figure;\n        subplot( 1, 2, 1);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            pitch_pow_dens_ref( Plot_Frame+ 1, :)));\n        axis( [0 Fs/2 0 95]); %xlabel( 'Hz'); ylabel( 'Db');   \n        title( 'reference signal bark spectrum with frequency compensation');\n        subplot( 1, 2, 2);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            pitch_pow_dens_deg( Plot_Frame+ 1, :)));\n        axis( [0 Fs/2 0 95]); %xlabel( 'Hz'); ylabel( 'Db');\n        title( 'degraded signal bark spectrum');\n    end\n        \nend\n% tmp1= pitch_pow_dens_ref';\n\n\nMAX_SCALE = 5.0;\nMIN_SCALE = 3e-4;\noldScale = 1;\nTHRESHOLD_BAD_FRAMES = 30;\nfor frame = 0: stop_frame\n    \n    total_audible_pow_ref = total_audible (frame, pitch_pow_dens_ref, 1);\n    total_audible_pow_deg = total_audible (frame, pitch_pow_dens_deg, 1);        \n    total_power_ref (1+ frame) = total_audible_pow_ref;\n    \n    scale = (total_audible_pow_ref + 5e3)/ (total_audible_pow_deg + 5e3);    \n    if (frame > 0) \n        scale = 0.2 * oldScale + 0.8 * scale;\n    end\n    oldScale = scale;\n    \n    if (scale > MAX_SCALE) \n        scale = MAX_SCALE;\n    elseif (scale < MIN_SCALE) \n        scale = MIN_SCALE;            \n    end\n\n    pitch_pow_dens_deg( 1+ frame, :) = ...\n        pitch_pow_dens_deg( 1+ frame, :) * scale;\n    \n    if (frame== Plot_Frame)\n        figure;\n        subplot( 1, 2, 1);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            pitch_pow_dens_ref( Plot_Frame+ 1, :)));\n        axis( [0 Fs/2 0 95]); %xlabel( 'Hz'); ylabel( 'Db');        \n        subplot( 1, 2, 2);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            pitch_pow_dens_deg( Plot_Frame+ 1, :)));\n        axis( [0 Fs/2 0 95]); %xlabel( 'Hz'); ylabel( 'Db');\n    end\n\n    loudness_dens_ref = intensity_warping_of (frame, pitch_pow_dens_ref);\n    loudness_dens_deg = intensity_warping_of (frame, pitch_pow_dens_deg);         \n    disturbance_dens = loudness_dens_deg - loudness_dens_ref;\n    \n    if (frame== Plot_Frame)\n        figure;\n        subplot( 1, 2, 1);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            loudness_dens_ref));\n        axis( [0 Fs/2 0 15]); %xlabel( 'Hz'); ylabel( 'Db'); \n        title( 'reference signal loudness density');\n        subplot( 1, 2, 2);\n        plot( centre_of_band_hz, 10* log10( eps+ ...\n            loudness_dens_deg));\n        axis( [0 Fs/2 0 15]); %xlabel( 'Hz'); ylabel( 'Db');\n        title( 'degraded signal loudness density');        \n    end\n    \n    for band =1: Nb\n        deadzone (band) = 0.25* min (loudness_dens_deg (band), ...\n            loudness_dens_ref (band));    \n    end\n\n    for band = 1: Nb\n        d = disturbance_dens (band);\n        m = deadzone (band);\n        \n        if (d > m) \n            disturbance_dens (band) = disturbance_dens (band)- m;\n%             disturbance_dens (band) = d- m;\n        else\n            if (d < -m) \n                disturbance_dens (band) = disturbance_dens (band)+ m;\n%                 disturbance_dens (band) = d+ m;\n            else\n                disturbance_dens (band) = 0;\n            end\n        end\n    end\n    \n    if (frame== Plot_Frame)\n        figure;\n        subplot( 1, 2, 1);\n        plot( centre_of_band_hz, disturbance_dens);\n        axis( [0 Fs/2 -1 50]); %xlabel( 'Hz'); ylabel( 'Db');                \n        title( 'disturbance');        \n    end\n    D_disturbance( frame+ 1, :)= disturbance_dens;\n\n    frame_disturbance (1+ frame) = pseudo_Lp (disturbance_dens, D_POW_F);    \n    if (frame_disturbance (1+ frame) > THRESHOLD_BAD_FRAMES) \n        there_is_a_bad_frame = TRUE;\n    end\n    \n    disturbance_dens= multiply_with_asymmetry_factor (...\n        disturbance_dens, frame, pitch_pow_dens_ref, pitch_pow_dens_deg);\n    \n    if (frame== Plot_Frame)        \n        subplot( 1, 2, 2);\n        plot( centre_of_band_hz, disturbance_dens);\n        axis( [0 Fs/2 -1 50]); %xlabel( 'Hz'); ylabel( 'Db');\n        title( 'disturbance after asymmetry processing');\n    end\n    DA_disturbance( frame+ 1, :)= disturbance_dens;\n\n\n    frame_disturbance_asym_add (1+ frame) = ...\n        pseudo_Lp (disturbance_dens, A_POW_F);    \nend\n% fid= fopen( 'tmp_mat.txt', 'wt');\n% fprintf( fid, '%f\\n', frame_disturbance);\n% fclose( fid);\n\nframe_was_skipped (1: 1+ stop_frame) = FALSE;\n\nfor utt = 2: Nutterances\n    frame1 = floor (((Utt_Start(utt)- 1- SEARCHBUFFER )* Downsample+ 1+ ...\n        Utt_Delay(utt))/ (Nf/ 2));\n    j = floor( floor(((Utt_End(utt-1)- 1- SEARCHBUFFER)* Downsample+ 1+ ...\n        Utt_Delay(utt-1)))/(Nf/ 2));\n    delay_jump = Utt_Delay(utt) - Utt_Delay(utt-1);\n    if (frame1 > j) \n        frame1 = j;    \n    elseif (frame1 < 0) \n        frame1 = 0;\n    end\n%     fprintf( 'frame1, j, delay_jump is %d, %d, %d\\n', frame1, ...\n%         j, delay_jump);\n\n    if (delay_jump < -(Nf/ 2)) \n        frame2 = floor (((Utt_Start(utt)- 1- SEARCHBUFFER)* Downsample+ 1 ...\n            + max (0, abs (delay_jump)))/ (Nf/ 2)) + 1; \n        \n        for frame = frame1: frame2\n            if (frame < stop_frame) \n                frame_was_skipped (1+ frame) = TRUE;\n                frame_disturbance (1+ frame) = 0;\n                frame_disturbance_asym_add (1+ frame) = 0;\n            end\n        end\n    end\nend\n\nnn = DATAPADDING_MSECS* (Fs/ 1000) + maxNsamples;\ntweaked_deg = zeros( 1, nn);\n% fprintf( 'nn is %d\\n', nn);\n\nfor i= SEARCHBUFFER* Downsample+ 1: nn- SEARCHBUFFER* Downsample\n    utt = Nutterances;\n    \n    while ((utt >= 1) && ((Utt_Start (utt)- 1)* Downsample> i)) \n        utt = utt- 1;\n    end\n    if (utt >= 1) \n        delay = Utt_Delay (utt);        \n    else\n        delay = Utt_Delay (1);\n    end\n\n    j = i + delay;\n    if (j < SEARCHBUFFER * Downsample+ 1) \n        j = SEARCHBUFFER * Downsample+ 1;\n    end\n    if (j > nn - SEARCHBUFFER * Downsample) \n        j = nn - SEARCHBUFFER * Downsample;\n    end\n    tweaked_deg (i) = deg_data (j);\nend\n\nif (there_is_a_bad_frame) \n    \n    for frame = 0: stop_frame\n        frame_is_bad (1+ frame) = (frame_disturbance (1+ frame)...\n            > THRESHOLD_BAD_FRAMES);       \n        smeared_frame_is_bad (1+ frame) = FALSE;\n    end\n    frame_is_bad (1) = FALSE;\n    SMEAR_RANGE = 2;\n    \n    for frame = SMEAR_RANGE: stop_frame- 1- SMEAR_RANGE\n        max_itself_and_left = frame_is_bad (1+ frame);\n        max_itself_and_right = frame_is_bad (1+ frame);\n        \n        for i = -SMEAR_RANGE: 0\n            if (max_itself_and_left < frame_is_bad (1+ frame+ i)) \n                max_itself_and_left = frame_is_bad (1+ frame+ i);\n            end\n        end\n\n        for i = 0: SMEAR_RANGE\n            if (max_itself_and_right < frame_is_bad (1+ frame + i)) \n                max_itself_and_right = frame_is_bad (1+ frame + i);\n            end\n        end\n\n        mini = max_itself_and_left;\n        if (mini > max_itself_and_right) \n            mini = max_itself_and_right;\n        end\n\n        smeared_frame_is_bad (1+ frame) = mini;\n    end\n    \n    MINIMUM_NUMBER_OF_BAD_FRAMES_IN_BAD_INTERVAL = 5;\n    number_of_bad_intervals = 0;    \n    frame = 0; \n    while (frame <= stop_frame) \n        while ((frame <= stop_frame) && (~smeared_frame_is_bad (1+ frame)))\n            frame= frame+ 1;\n        end\n\n        if (frame <= stop_frame) \n            start_frame_of_bad_interval(1+ number_of_bad_intervals)= ...\n                1+ frame;\n            \n            while ((frame <= stop_frame) && (...\n                    smeared_frame_is_bad (1+ frame))) \n                frame= frame+ 1; \n            end\n\n            if (frame <= stop_frame)\n                stop_frame_of_bad_interval(1+ number_of_bad_intervals)= ...\n                    1+ frame; \n                if (stop_frame_of_bad_interval(1+ number_of_bad_intervals)- ...\n                        start_frame_of_bad_interval(1+ number_of_bad_intervals)...\n                        >= MINIMUM_NUMBER_OF_BAD_FRAMES_IN_BAD_INTERVAL) \n                    number_of_bad_intervals= number_of_bad_intervals+ 1;\n                end\n            end\n        end\n    end\n\n    for bad_interval = 0: number_of_bad_intervals - 1\n        start_sample_of_bad_interval(1+ bad_interval) = ...\n            (start_frame_of_bad_interval(1+ bad_interval)- 1) * (Nf/ 2) ...\n            + SEARCHBUFFER * Downsample+ 1;\n        stop_sample_of_bad_interval(1+ bad_interval) = ...\n            (stop_frame_of_bad_interval(1+ bad_interval)- 1) * (Nf/ 2) ...\n            + Nf + SEARCHBUFFER* Downsample;\n        if (stop_frame_of_bad_interval(1+ bad_interval) > stop_frame+ 1) \n            stop_frame_of_bad_interval(1+ bad_interval) = stop_frame+ 1; \n        end\n\n        number_of_samples_in_bad_interval(1+ bad_interval) = ...\n            stop_sample_of_bad_interval(1+ bad_interval) - ...\n            start_sample_of_bad_interval(1+ bad_interval)+ 1;\n    end        \n%     fprintf( 'number of bad intervals %d\\n', number_of_bad_intervals);\n%     fprintf( '%d %d\\n', number_of_samples_in_bad_interval(1), ...\n%         number_of_samples_in_bad_interval(2));\n%     fprintf( '%d %d\\n', start_sample_of_bad_interval(1), ...\n%         start_sample_of_bad_interval(2));\n\n    SEARCH_RANGE_IN_TRANSFORM_LENGTH = 4;    \n    search_range_in_samples= SEARCH_RANGE_IN_TRANSFORM_LENGTH * Nf;\n    \n    for bad_interval= 0: number_of_bad_intervals- 1\n        ref = zeros (1, 2 * search_range_in_samples + ...\n            number_of_samples_in_bad_interval (1+ bad_interval));\n        deg = zeros (1, 2 * search_range_in_samples + ...\n            number_of_samples_in_bad_interval (1+ bad_interval));\n        \n        ref(1: search_range_in_samples) = 0;\n\n        ref (search_range_in_samples+ 1: search_range_in_samples+ ...\n                number_of_samples_in_bad_interval (1+ bad_interval)) = ...\n                ref_data (start_sample_of_bad_interval( 1+ bad_interval) + 1: ...\n                start_sample_of_bad_interval( 1+ bad_interval) + ...\n                number_of_samples_in_bad_interval (1+ bad_interval));\n        \n        ref (search_range_in_samples + ...\n                number_of_samples_in_bad_interval (1+ bad_interval) + 1: ...\n                search_range_in_samples + ...\n                number_of_samples_in_bad_interval (1+ bad_interval) + ...\n                search_range_in_samples) = 0;\n        \n        for i = 0: 2 * search_range_in_samples + ...\n                number_of_samples_in_bad_interval (1+ bad_interval) - 1\n            j = start_sample_of_bad_interval (1+ bad_interval) - ...\n                search_range_in_samples + i;\n            nn = maxNsamples - SEARCHBUFFER * Downsample + ...\n                DATAPADDING_MSECS  * (Fs / 1000);\n            if (j <= SEARCHBUFFER * Downsample) \n                j = SEARCHBUFFER * Downsample+ 1;\n            end\n            if (j > nn) \n                j = nn;\n            end\n            deg (1+ i) = tweaked_deg (j);\n        end\n\n        [delay_in_samples, best_correlation]= compute_delay ...\n            (1, 2 * search_range_in_samples + ...\n            number_of_samples_in_bad_interval (1+ bad_interval), ...\n            search_range_in_samples, ref, deg);\n        delay_in_samples_in_bad_interval (1+ bad_interval) =  ...\n            delay_in_samples;\n%         fprintf( 'delay_in_samples, best_correlation is \\n\\t%d, %f\\n', ...\n%             delay_in_samples, best_correlation);\n%         \n        if (best_correlation < 0.5) \n            delay_in_samples_in_bad_interval  (1+ bad_interval) = 0;\n        end\n    end\n\n    if (number_of_bad_intervals > 0) \n        doubly_tweaked_deg = tweaked_deg( 1: maxNsamples + ...\n            DATAPADDING_MSECS  * (Fs / 1000));\n        for bad_interval= 0: number_of_bad_intervals- 1\n            delay = delay_in_samples_in_bad_interval (1+ bad_interval);\n        \n            for i = start_sample_of_bad_interval (1+ bad_interval): ...\n                    stop_sample_of_bad_interval (1+ bad_interval)\n                j = i + delay;\n                if (j < 1) \n                    j = 1;\n                end\n                if (j > maxNsamples) \n                    j = maxNsamples;\n                end\n                h = tweaked_deg (j);\n                doubly_tweaked_deg (i) = h;\n            end\n        end\n\n        untweaked_deg = deg_data;\n        deg_data = doubly_tweaked_deg;\n        \n        for bad_interval= 0: number_of_bad_intervals- 1\n            for frame = start_frame_of_bad_interval (1+ bad_interval): ...\n                    stop_frame_of_bad_interval (1+ bad_interval)- 1\n                frame= frame- 1;\n                start_sample_ref = SEARCHBUFFER * Downsample + ...\n                    frame * Nf / 2+ 1;\n                start_sample_deg = start_sample_ref;\n                hz_spectrum_deg= short_term_fft (Nf, deg_data, ...\n                    Whanning, start_sample_deg);    \n                pitch_pow_dens_deg( 1+ frame, :)= freq_warping (...\n                    hz_spectrum_deg, Nb, frame);\n            end\n\n            oldScale = 1;\n            for frame = start_frame_of_bad_interval (1+ bad_interval): ...\n                    stop_frame_of_bad_interval (1+ bad_interval)- 1\n                frame= frame- 1;    \n                % see implementation for detail why 1 needed to be\n                % subtracted\n                total_audible_pow_ref = total_audible (frame, ...\n                    pitch_pow_dens_ref, 1);\n                total_audible_pow_deg = total_audible (frame, ...\n                    pitch_pow_dens_deg, 1);        \n                scale = (total_audible_pow_ref + 5e3) / ...\n                    (total_audible_pow_deg + 5e3);\n                if (frame > 0) \n                    scale = 0.2 * oldScale + 0.8*scale;\n                end\n                oldScale = scale;\n                if (scale > MAX_SCALE) \n                    scale = MAX_SCALE;\n                end\n                if (scale < MIN_SCALE) \n                    scale = MIN_SCALE;   \n                end\n\n                pitch_pow_dens_deg (1+ frame, :) = ...\n                    pitch_pow_dens_deg (1+ frame, :)* scale;\n                loudness_dens_ref= intensity_warping_of (frame, ...\n                    pitch_pow_dens_ref); \n                loudness_dens_deg= intensity_warping_of (frame, ...\n                    pitch_pow_dens_deg); \n                disturbance_dens = loudness_dens_deg - loudness_dens_ref;\n                \n                for band = 1: Nb\n                    deadzone(band) = min (loudness_dens_deg(band), ...\n                        loudness_dens_ref(band));    \n                    deadzone(band) = deadzone(band)* 0.25;\n                end\n\n                for band = 1: Nb\n                    d = disturbance_dens (band);\n                    m = deadzone (band);\n                    \n                    if (d > m) \n                        disturbance_dens (band) = ...\n                            disturbance_dens (band)- m;\n                    else\n                        if (d < -m) \n                            disturbance_dens (band) = ...\n                                disturbance_dens (band)+ m;\n                        else\n                            disturbance_dens (band) = 0;\n                        end\n                    end\n                end\n\n                frame_disturbance( 1+ frame) = min (...\n                    frame_disturbance( 1+ frame), pseudo_Lp(...\n                    disturbance_dens, D_POW_F));\n                disturbance_dens= multiply_with_asymmetry_factor ...\n                    (disturbance_dens, frame, pitch_pow_dens_ref, ...\n                    pitch_pow_dens_deg);\n                frame_disturbance_asym_add(1+ frame) = min (...\n                    frame_disturbance_asym_add(1+ frame), ...\n                    pseudo_Lp (disturbance_dens, A_POW_F));    \n            end\n        end\n        deg_data = untweaked_deg;\n    end\nend     \n\nfor frame = 0: stop_frame\n    h = 1;\n    if (stop_frame + 1 > 1000) \n        n = floor( (maxNsamples - 2 * SEARCHBUFFER * Downsample)...\n            / (Nf / 2)) - 1;\n        timeWeightFactor = (n - 1000) / 5500;\n        if (timeWeightFactor > 0.5) \n            timeWeightFactor = 0.5;\n        end\n        h = (1.0 - timeWeightFactor) + timeWeightFactor * frame / n;\n    end\n\n    time_weight (1 +frame) = h;\nend\n\n% fid= fopen( 'tmp_mat1.txt', 'at');\n% fprintf( '\\n');\nfor frame = 0: stop_frame\n    h = ((total_power_ref (1+ frame) + 1e5) / 1e7)^ 0.04; \n%     if (frame== 118)\n%         fprintf( '%f\\n', h);    \n%         fprintf( '%f\\n', frame_disturbance( 1+ frame));\n%     end\n    frame_disturbance( 1+ frame) = frame_disturbance( 1+ frame)/ h;\n    \n%     if (frame== 118)\n%         fprintf( '%f\\n', frame_disturbance( 1+ frame));\n%     end\n%         \n    frame_disturbance_asym_add( 1+ frame) = ...\n        frame_disturbance_asym_add( 1+ frame)/ h;\n    if (frame_disturbance( 1+ frame) > 45) \n        frame_disturbance( 1+ frame) = 45;  \n    end\n    if (frame_disturbance_asym_add( 1+ frame)> 45) \n        frame_disturbance_asym_add( 1+ frame) = 45;\n    end\nend\n% fclose ( fid);\n\nd_indicator = Lpq_weight (start_frame, stop_frame, ...\n    D_POW_S, D_POW_T, frame_disturbance, time_weight);\na_indicator = Lpq_weight (start_frame, stop_frame, ...\n    A_POW_S, A_POW_T, frame_disturbance_asym_add, time_weight);       \n\npesq_mos = 4.5 - D_WEIGHT * d_indicator - A_WEIGHT * a_indicator; \n\nif (Plot_Frame> 0)\n    figure;\n    subplot( 1, 2, 1);\n    mesh( 0: stop_frame, centre_of_band_hz, D_disturbance');\n    title( 'disturbance');\n    subplot( 1, 2, 2);\n    mesh( 0: stop_frame, centre_of_band_hz, DA_disturbance');\n    title( 'disturbance after asymmetry processing');\nend\n\n% fid= fopen( 'tmp_mat.txt', 'wt');\n% fprintf( fid, 'time_weight\\n');\n% fprintf( fid, '%f\\n', time_weight);\n% fprintf( fid, 'frame_disturbance:\\n');\n% fprintf( fid, '%f\\n', frame_disturbance);\n% fprintf( fid, 'frame_disturbance_asym_add\\n');\n% fprintf( fid, '%f\\n', frame_disturbance_asym_add);\n% fclose( fid);\n    \nfunction result_time= Lpq_weight(start_frame, stop_frame, ...\n        power_syllable, power_time, frame_disturbance, time_weight)\n\nglobal NUMBER_OF_PSQM_FRAMES_PER_SYLLABE\n\n% fid= fopen( 'tmp_mat1.txt', 'at');\n% fprintf( 'result_time:\\n');\n\nresult_time= 0;\ntotal_time_weight_time = 0;\n% fprintf( 'start/end frame: %d/%d\\n', start_frame, stop_frame);\nfor start_frame_of_syllable = start_frame: ...\n        NUMBER_OF_PSQM_FRAMES_PER_SYLLABE/2: stop_frame\n    result_syllable = 0;\n    count_syllable = 0;\n    \n    for frame = start_frame_of_syllable: ...\n            start_frame_of_syllable + NUMBER_OF_PSQM_FRAMES_PER_SYLLABE- 1\n        if (frame <= stop_frame) \n            h = frame_disturbance(1+ frame);\n%             if (start_frame_of_syllable== 101)\n%                 fprintf( fid, '%f\\n', h);\n%             end\n            result_syllable = result_syllable+ (h^ power_syllable);\n        end\n        count_syllable = count_syllable+ 1;\n    end\n\n    result_syllable = result_syllable/ count_syllable;\n    result_syllable = result_syllable^ (1/power_syllable);     \n    \n    result_time= result_time+ (time_weight (...\n        1+ start_frame_of_syllable - start_frame) * ...\n        result_syllable)^ power_time; \n    total_time_weight_time = total_time_weight_time+ ...\n        time_weight (1+ start_frame_of_syllable - start_frame)^ power_time;\n    \n%     fprintf( fid, '%f\\n', result_time);\nend\n% fclose (fid);\n\n% fprintf( 'total_time_weight_time is %f\\n', total_time_weight_time);\nresult_time = result_time/ total_time_weight_time;\nresult_time= result_time^ (1/ power_time);\n% fprintf( 'result_time is %f\\n\\n', result_time);\n\n    \nfunction [best_delay, max_correlation] = compute_delay (...\n    start_sample, stop_sample, search_range, ...\n    time_series1, time_series2) \n\nn = stop_sample - start_sample+ 1;   \npower_of_2 = 2^ (ceil( log2( 2 * n)));\n\npower1 = pow_of (time_series1, start_sample, stop_sample, n)* ...\n    n/ power_of_2;\npower2 = pow_of (time_series2, start_sample, stop_sample, n)* ...\n    n/ power_of_2;\nnormalization = sqrt (power1 * power2);\n% fprintf( 'normalization is %f\\n', normalization);\n\nif ((power1 <= 1e-6) || (power2 <= 1e-6)) \n    max_correlation = 0;\n    best_delay= 0;\nend\n\nx1( 1: power_of_2)= 0;\nx2( 1: power_of_2)= 0;\ny( 1: power_of_2)= 0;\n\nx1( 1: n)= abs( time_series1( start_sample: ...\n    stop_sample));\nx2( 1: n)= abs( time_series2( start_sample: ...\n    stop_sample));\n\nx1_fft= fft( x1, power_of_2)/ power_of_2;\nx2_fft= fft( x2, power_of_2);\nx1_fft_conj= conj( x1_fft);\ny= ifft( x1_fft_conj.* x2_fft, power_of_2);\n\nbest_delay = 0;\nmax_correlation = 0;\n\n% these loop can be rewritten\nfor i = -search_range: -1\n    h = abs (y (1+ i + power_of_2)) / normalization;\n    if (h > max_correlation) \n        max_correlation = h;\n        best_delay= i;\n    end\nend\nfor i = 0: search_range- 1\n    h = abs (y (1+i)) / normalization;\n    if (h > max_correlation) \n        max_correlation = h;\n        best_delay= i;\n    end\nend\nbest_delay= best_delay- 1;\n    \nfunction mod_disturbance_dens= multiply_with_asymmetry_factor (...\n    disturbance_dens, frame, pitch_pow_dens_ref, pitch_pow_dens_deg) \n\nglobal Nb\nfor i = 1: Nb\n    ratio = (pitch_pow_dens_deg(1+ frame, i) + 50)...\n        / (pitch_pow_dens_ref (1+ frame, i) + 50);\n    h = ratio^ 1.2;    \n    if (h > 12) \n        h = 12;\n    elseif (h < 3) \n        h = 0.0;\n    end\n    mod_disturbance_dens (i) = disturbance_dens (i) * h;\nend\n\n\nfunction loudness_dens = intensity_warping_of (...\n    frame, pitch_pow_dens)\n\nglobal abs_thresh_power Sl Nb centre_of_band_bark\nZWICKER_POWER= 0.23;\nfor band = 1: Nb\n    threshold = abs_thresh_power (band);\n    input = pitch_pow_dens (1+ frame, band);\n    \n    if (centre_of_band_bark (band) < 4) \n        h =  6 / (centre_of_band_bark (band) + 2);\n    else\n        h = 1;\n    end\n\n    if (h > 2) \n        h = 2;\n    end\n    h = h^ 0.15;\n    modified_zwicker_power = ZWICKER_POWER * h;\n    if (input > threshold) \n        loudness_dens (band) = ((threshold / 0.5)^ modified_zwicker_power)...\n            * ((0.5 + 0.5 * input / threshold)^ modified_zwicker_power- 1);\n    else\n        loudness_dens (band) = 0;\n    end\n\n    loudness_dens (band) = loudness_dens (band)* Sl;\nend\n    \nfunction result= pseudo_Lp (x, p)\n\nglobal Nb width_of_band_bark\ntotalWeight = 0;\nresult = 0;\nfor band = 2: Nb\n    h = abs (x (band));\n    w = width_of_band_bark (band);\n    prod = h * w;\n    \n    result = result+ prod^ p;\n    totalWeight = totalWeight+ w;\nend\nresult = (result/ totalWeight)^ (1/p);\nresult = result* totalWeight;\n\n    \nfunction mod_pitch_pow_dens_ref= freq_resp_compensation (number_of_frames, ...\n    pitch_pow_dens_ref, avg_pitch_pow_dens_ref, ...\n    avg_pitch_pow_dens_deg, constant)\n\nglobal Nb\n\nfor band = 1: Nb\n    x = (avg_pitch_pow_dens_deg (band) + constant) / ...\n        (avg_pitch_pow_dens_ref (band) + constant);\n    if (x > 100.0) \n        x = 100.0;\n    elseif (x < 0.01) \n        x = 0.01;\n    end\n\n    for frame = 1: number_of_frames\n        mod_pitch_pow_dens_ref(frame, band) = ...\n            pitch_pow_dens_ref(frame, band) * x;\n    end\nend\n\n\n\nfunction avg_pitch_pow_dens= time_avg_audible_of(number_of_frames, ...\n    silent, pitch_pow_dens, total_number_of_frames) \n\nglobal Nb abs_thresh_power\n\nfor band = 1: Nb\n    result = 0;\n    for frame = 1: number_of_frames\n        if (~silent (frame)) \n            h = pitch_pow_dens (frame, band);\n            if (h > 100 * abs_thresh_power (band)) \n                result = result + h;\n            end\n        end\n\n        avg_pitch_pow_dens (band) = result/ total_number_of_frames;\n    end\nend  \n\n\n\nfunction hz_spectrum= short_term_fft (Nf, data, Whanning, start_sample)\n\nx1= data( start_sample: start_sample+ Nf-1).* Whanning;\nx1_fft= fft( x1);\nhz_spectrum= abs( x1_fft( 1: Nf/ 2)).^ 2;\nhz_spectrum( 1)= 0;\n\n\nfunction pitch_pow_dens= freq_warping( hz_spectrum, Nb, frame)\n\nglobal nr_of_hz_bands_per_bark_band pow_dens_correction_factor\nglobal Sp\n\nhz_band = 1;\nfor bark_band = 1: Nb\n    n = nr_of_hz_bands_per_bark_band (bark_band);    \n    sum = 0;\n    for i = 1: n\n        sum = sum+ hz_spectrum( hz_band);\n        hz_band= hz_band+ 1;\n    end\n    sum = sum* pow_dens_correction_factor (bark_band);\n    sum = sum* Sp;\n    pitch_pow_dens (bark_band) = sum;\n    \nend\n\n\nfunction total_audible_pow = total_audible (frame, ...\n    pitch_pow_dens, factor)\n\nglobal Nb abs_thresh_power\n\ntotal_audible_pow = 0;\nfor band= 2: Nb\n    h = pitch_pow_dens (frame+ 1,band);\n    threshold = factor * abs_thresh_power (band);\n    if (h > threshold) \n        total_audible_pow = total_audible_pow+ h;\n    end\nend\n\n\n\n\n\n\n\n\n", "meta": {"author": "vipchengrui", "repo": "traditional-speech-enhancement", "sha": "79cefa66c7a69587f1864a7334cc9da7e31e883d", "save_path": "github-repos/MATLAB/vipchengrui-traditional-speech-enhancement", "path": "github-repos/MATLAB/vipchengrui-traditional-speech-enhancement/traditional-speech-enhancement-79cefa66c7a69587f1864a7334cc9da7e31e883d/speech_quality_objective_evaluation/Get_PESQ/pesq_psychoacoustic_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.23999072847462585}}
{"text": "function [measure,model,stats] = bci_train(varargin)\n% Learn a predictive model given some data and approach, and estimate its performance.\n% [Loss,Model,Statistics] = bci_train(Data, Approach, TargetMarkers, EvaluatationMetric, EvaluationScheme, ...)\n%\n% Learns a model of the connection between abstract 'cognitive state' annotations/definitions in a\n% data set (e.g., event markers, target variables) and the actual biosignal data, so that the\n% learned model can subsequently be used to predict the (defined) cognitive state of the person (in\n% real time or offline). Also estimates the quality of the model's predictions, using a measure of\n% 'mismatch' between what was defined for a given time point and what the model would predict (the\n% 'loss').\n%\n%\n% Model Computation\n% =================\n%\n% The goal of BCI research is to enable a computer system to read the ongoing EEG (or other\n% brain-/biosignals) of a person and predict from it, in real time, what his/her cognitive state is.\n% Since the connection between biosignals and cognitive state includes some information that is\n% highly specific to a person or group of persons, it can only be obtained from actual data of that\n% person (or group), which is here called a 'calibration data set'. For modern expositions of the\n% general problem and solutions, see [7] or [8].\n%\n% There is currently no general automated method to learn the connection (relation) between a\n% calibration data set and the aspect of cognitive state that is to be predicted,  but there is a\n% growing body of approaches, here called 'paradigms', each of which imposes a different set of\n% assumptions about the nature of that relation. These paradigms tend to perform well if their\n% assumptions match the data and if the required information is sufficiently accessible in the\n% calibration data set. The result is a 'predictive model' in which the information about the\n% connection of interest is captured (usually in some form of statistical mapping).\n%\n% Almost all paradigms involve some parameters that can be varied to obtain a different variant of\n% the paradigm (e.g., the frequency range of interest in the EEG signal), and the better these\n% parameters are chosen, the better will be the attainable quality of the models that the paradigm\n% can compute. In addition, there is the possibility to search over different values of parameters\n% to find a good combination, if allowed by compute/time resources.\n%\n% bci_train requires that at least a paradigm is specified (predefined ones are in code/paradigms)\n% and that a calibration data set, annotated with expected cognitive state is supplied. Since\n% bci_train must learn a relation between raw signal and abstract (human-defined) cognitive state,\n% the state must be specified by the user in a machine-accessible format. A typical 'encoding' of\n% such state is created as follows. The user records a calibration data set from a person (a regular\n% EEG recording). Througout this recording, the person is in different states at different times\n% (preferably repeatedly and randomized), for example, instructed to think or feel a sequence of\n% specific things (e.g., imagine a left/right hand gesture), or exposed to a series of artificial\n% conditions (e.g., high/low excitement), such that the answer to a particular state question is\n% known at particular times in the recording (e.g. was a left or right hand gesture being imagined\n% at time X?). The times at which there is knowledge about the person's state, and its value at\n% these times is encoded into the EEG as 'events', or 'markers'. In EEGLAB data sets, this is the\n% field EEG.event, and its type (a string) would be used to encode the state value. Usually, events\n% are produced by the software that guides the person though the calibration session and are\n% recorded by the data acquisition system.\n%\n% Which events in the data set are relevant and what is the desired output of the BCI for each of\n% these events of interest is specified via the parameter TargetMarkers (or may also be added as an\n% annotation for the data itself, using set_targetmarkers).\n%\n% Aside from the chosen paradigm's parameters, this is all there is to specify to bci_train in order\n% to obtain a predictive model and its performance estimate. The paradigm's parameters are all\n% optional, and are by default set as in the representative (or most commonly) published use of the\n% paradigm, so most of them need to be specified only when the user wants to deviate from those\n% values.\n%\n%\n% Simple Example\n% ==============\n%\n% A model that predicts the laterality of imagined hand gestures can be computed as follows\n% (assuming that the data set contains events with types 'left-imag' and 'right-imag', at the time\n% points where the subject was instructed to imagine the respective action). Since the relevant\n% brain signals (Event-Related Desynchronization, see [1]) are assumed to be oscillatory processes\n% that originate in distinct areas of the brain, the CSP (Common Spatial Pattern, see, e.g., [2])\n% paradigm is used here unmodified. The approach can be specified as a string (usually the acronym\n% for one of the ParadigmXXX.m files in code/paradigms) or as a cell array containing that string\n% followed by optional name-value pairs to override/customize parameters.\n%\n%   calib = io_loadset('data_sets/john/gestures.eeg')\n%   [loss,model,stats] = bci_train('Data',calib, 'Approach','CSP', 'TargetMarkers',{'left-imag','right-imag'})\n%\n% When the loss is good (low) enough to justify online use, the model would then be loaded by the\n% user into BCILAB's online system and would predict, whenever it receives EEG that indicates an\n% imagined left hand gesture, the number 1 with high probability (and 2 with low probability), and\n% in the case of an imagined right hand gesture, the number 2 with high probability (and 1 with low\n% probability). At times where the person being measured imagines neither of the defined gestures,\n% the system may produce arbitrary predictions. To handle such cases, a further condition (the\n% 'rest' condition) can be defined for the model, by inserting 'rest' events into the data set\n% whenever the subject was in neither of the two other states. The model could then be trained as\n%\n%   [loss,model,stats] = bci_train('Data',calib, 'Approach','CSP', 'TargetMarkers',{'left-imag','right-imag','rest'}),\n%\n% and would predict 3 with high probability (and 1/2 with low probability) in periods where the\n% person being measured is in a resting state (note: the function set_insert_markers can be used to\n% insert markers of given types into specific periods of the data). Since CSP is by nature a method\n% defined for only two conditions, the framework automatically applies it on every pair of\n% conditions, which is called voting (see ml_trainvote). Another way to obtain similar results is by\n% using two separate models at the same time, one to detect the type of imagination, and the other\n% to detect whether an imagination (defined as a group of multiple event types) or resting is\n% happening:\n%\n%   [lossA,modelA] = bci_train('Data',calib, 'Approach','CSP', 'TargetMarkers',{'left-imag','right-imag'}),\n%   [lossB,modelB] = bci_train('Data',calib, 'Approach','CSP', 'TargetMarkers',{'rest', {'left-imag','right-imag'}})\n%\n% Though, in this case it is up to the application to combine the state probabilities that are\n% produced by model B with those produced by model A.\n%\n% The majority of approaches override at least one parameter of the paradigm, as for example the\n% EpochExtraction parameter of the signal processing chain, which determines the time range of\n% interest relative to the events. Thus, calibration of a BCI model usually proceeds in three steps\n% in BCILAB:\n%\n%   calib = io_loadset('data_sets/john/gestures.eeg')\n%   myapproach = {'CSP', 'SignalProcessing',{'EpochExtraction',[0.5 2.5]}};\n%   [loss,model,stats] = bci_train('Data',calib, 'Approach',myapproach, 'TargetMarkers',{'left-imag','right-imag'})\n%\n%\n% Loss Estimation\n% ===============\n%\n% The most important question to ask about a predictive model is how well it performs, i.e. how well\n% do its outputs match the desired outputs -- and for a complete system that performs actions\n% depending on a predictive model, what overall cost is incurred by (potentially sub-optimal)\n% behavior of the system. Both cases can be covered by a formal 'loss' metric [3]. Different types\n% of systems / types of predictive models require different loss metrics, which can be chosen in the\n% EvaluationMetric parameter from a set of pre-defined ones, or supplied as a custom function. An\n% introduction to various predefined loss functions and their uses is given in the help of the\n% function machine_learning/ml_calcloss.\n%\n% The loss of a model can be computed in a variety of settings. Most obviously and realistically, a\n% model can be run online, and the loss incurred by its predictions can be recorded (for example,\n% number of mis-classifications, virtual money lost by a BCI-supported gamer). This, however,\n% requires multiple (controlled) runs through an experiment to compare different models and/or\n% methods, which is usually prohibitively costly. A more effective approach is to record the online\n% EEG/biosignal data and the desired outputs of the system whenever they are known, and then\n% estimate the loss of any models \"offline\" on the data, using the loss metric that best reflects\n% the actual loss in the chosen scenario (for example mis-classification rate or ROC area); this\n% approach requires just one session, and can be used to compare arbitrarily many models post-hoc\n% (using the function bci_predict). The caveat is that any chaotic dynamics that may unfold between\n% a system mis-behaving and a user reacting are not covered by the estimate (for example, when a\n% system fails for more than a minute, the user may start to control it more aggressively, which may\n% in turn make it even more difficult for the model to interpret brain signals).\n%\n% Finally, a loss estimate can be computed directly by bci_train, on the given calibration data,\n% using cross-validation (CV) [4]. This is a data resampling procedure in which models are\n% repeatedly computed, each time on a different subset of the data (called the training set) and\n% compared on another disjoint portion of the data (called the test set) using the defined (i.e.\n% desired) outputs, and some user-selected loss measure. In the default CV, the data is partitioned\n% into 10 blocks, where for each block, a model is computed on the remaining 9 ones and tested\n% against the target values in the current block (called 10-fold blockwise CV). Other variants\n% include k-fold randomized CV, where the data trials are randomly shuffled before a regular\n% blockwise k-fold CV, n times repeated k-fold CV, in which n repeated runs over different\n% shufflings are executed and results averaged, and leave-one-out CV (LOOCV), where a model is\n% computed on all except for one trial, and is then tested on the held-out trial. The loss measure\n% is by default chosen depending on the type of target values in the calibration set and the\n% features of the paradigm so that the user rarely needs to override it (misclassification rate for\n% categorical outputs, mean-square error for continuous outputs, negative log-likelihood for\n% probabilistic regression models, etc.).\n%\n% The loss estimates of bci_train are very convenient and can be used to evaluate a large variety of\n% models on data from a single calibration session. The caveat is that that the estimate\n% systematically fails to cover certain features of actual online situations. First, chaotic\n% dynamics are not captured, as in the other offline case, and second, only a certain fraction of\n% the (time-varying) non-stationarities in the data are captured by the estimate. Most biosignals\n% contain features that vary at certain time scales, from second to second (e.g., dopamine level),\n% minute to minute (e.g., background situation), hour to hour (e.g., tiredness), day to day (e.g.,\n% medication) and year to year (e.g., long-term brain plasticity), all of which can affect the\n% output (quality) of the model. Since calibration sessions are usually short, training/test data is\n% close to each other in time, and the situation typically has little variation (e.g. it may be all\n% offline with no user control involved), the majority of non-stationarities that could degrade the\n% model's performance are not captured, and the estimate is almost surely overly optimistic. How\n% large this effect is depends among others on the stability of the features used by the model, the\n% strength of assumptions imposed by the paradigm, and the variety/coverage of situations present in\n% the calibration data.\n%\n%\n% Paradigm Customization and Structure\n% ====================================\n%\n% In the Approach declaration, a list of name-value pairs can be specified, for example\n% {'CSP', 'Resampling',200, 'SpectralSelection',[7 30], 'EpochExtraction',[-1.5 2.5]}, to override the\n% default values of the chosen paradigm for the given named parameters - practically all paradigms have\n% named parameters (although some community-supplied ones may have position-dependent parameters -\n% like most MATLAB functions). All parameters are basically passed through unmodified to the\n% paradigm in question (usually one of the paradigms/ParadigmXXX classes), so the place to\n% look up what can be specified is the help of the respective class, or by bringing up the GUI config\n% dialog for the given approach (see GUI tutorial).\n%\n% Most paradigms contain similar internal structure, and therefore share common components, which in\n% turn means that most of them share multiple common parameters. It is therefore helpful to know\n% these components. The internal structure of most paradigms contains a sequence of three overall\n% data processing stages. The first stage, Signal Processing, receives (multi-channel) signals, such\n% as EEG, and filters these signals to amplify and focus the information of interest, and to discard\n% the remaining information. The outputs of the first stage are again signals, either continuous or\n% epoched/segmented. The stage may have several successive sub-steps (most of them called filters,\n% some called data set editing operations), such as resampling, frequency filtering, spatial\n% filtering, time window selection, artifact removal, etc.. The toolbox offers a collection of\n% pre-defined filter components (in filters/flt_*) and data set operations (in dataset_ops/set_*),\n% each with their respective default parameters. Most paradigms use at least one or two of these\n% components, usually with custom parameters for them, and the user can override these parameters by\n% specifying the component name (e.g. 'resample' to control the settings of the used sampling rate\n% filter, flt_resample) followed by the parameter value to be passed (e.g. 200 for 200 Hz in the\n% case of flt_resample), or a cell array of parameters if the component accepts multiple parameters,\n% such as flt_ica does. Furthermore, most paradigms not only use a subset of the provided filters,\n% but instead use the entire default Signal Processing pipeline of the toolbox, explained in\n% filters/flt_pipeline. For this reason, all parameters of flt_pipeline can be customized by the\n% user for almost any paradigm (and not just those chosen by the paradigm), i.e. the user can enable\n% and configure stages in the default pipeline which are normally disabled in the given paradigm. Note\n% that flt_pipeline offers a few alias names for some parameters, e.g. 'channels' can be used\n% instead of 'selchans', both controlling filters/flt_selchans; these are listed in flt_pipeline.\n%\n% The second stage of most paradigms is the Feature Extraction stage, which receives the\n% preprocessed signals from the Signal Processing, and extracts certain informative features (e.g.\n% logarithm of the signal power). This stage is usually custom to the paradigm, and is therefore\n% controlled by unique parameters (e.g. 'patterns' in the Common Spatial Patterns [2] paradigm,\n% para_csp).\n%\n% Finally, the feature produced by the Feature Extraction are usually subjected to a last stage, the\n% Machine Learning. In this, a learning component, which is one of the provided\n% machine_learning/ml_train* functions, computes a statistical model of the feature distributions,\n% and their relation to the desired output values. This component is generally selected via the\n% 'learner' parameter, which is exposed by most paradigms. The learner can be specified as name tag,\n% such as 'lda', which refers to ml_trainlda. If the learner component contains parameters which shall\n% be costomized as well, a cell array is passed which contains the name tag followed by the custom\n% parameters, in the order of appearance in the respective learning function. For example,\n% 'learner',{'svmlinear',0.5} selects The linear SVM component and sets its Cost parameter to 0.5,\n% and 'learner',{'logreg',[],'variant','vb-ard'} selects the Logistic Regression component, keeps its\n% first parameter at the default value, and uses the custom variant 'vb-ard', which stands for\n% Variational Bayes with Automatic Relevance Determination (see, e.g., [7]). A small but useful subset\n% of the provided Signal Processing, Feature Extraction and Machine Learning components is compactly\n% described in [5].\n%\n%\n% Customized Example\n% ==================\n%\n% To obtain an online prediction of the working-memory load of a person, a calibration data set in\n% which the person has to maintain varying numbers of items is his/her memory (e.g., using the\n% n-back task, see [6]) can be used as a starting point. In this data set, conditions with one item\n% in memory are marked with the event 'n1', conditions with two items in memory are marked with\n% 'n2', etc. Assuming that working-memory load may be reflected in certain oscillatory processes,\n% though in unknown locations and frequency bands, the paradigm Spec-CSP ([9]) is used as a basis.\n% In its default configuration (see paradigms/ParadigmSpecCSP), it focuses on a relatively narrow\n% frequency band, which shall be relaxed here (in particular, the theta band [10] should be\n% included). Also, by default, the Spec-CSP paradigm selects data epochs at 0.5-3.5 seconds\n% following each (selected) event, which shall be modified to [-2.5 2.5], to get a time coverage\n% that is better adapted to the task. Finally, Spec-CSP by default contains a non-probabilistic\n% classifier (Linear Discriminant Analysis, see machine_learning/ml_trainlda), which we want to\n% change into a largely equivalent, but probabilistic one (Logistic regression, see\n% machine_learning/ml_trainlogreg). Since we assume that the most important part of the spectrum\n% will be the alpha and theta rhythm (peaked at ~10 and ~4Hz), but do not want to completely rule\n% out other frequencies, we additionally impose a prior as a custom in-line (lambda) function of\n% frequency). Since we have more than two classes, but the Spec-CSP is only defined for two classes,\n% the framework automatically applies it to every pair of conditions and uses voting (see\n% machine_learning/ml_trainvote) to arrive at per-class probabilities. Note that this is a major\n% customization.\n%\n%   dataset = io_loadset('data sets/mary/nback.eeg')\n%   myapproach = {'SpecCSP', ...\n%       'SignalProcessing',{'EpochExtraction',[-2.5 2.5], 'FIRFilter',{'Frequencies',[2 4 33 34],'Type','minimum-phase'}}, ...\n%       'Prediction',{'FeatureExtraction',{'SpectralPrior','@(f)1+exp(-(x-10).^2)+exp(-(x-4).^2'}, ...\n%                     'MachineLearning',{'Learner','logreg'}}};\n%   [loss,model,stats] = bci_train('Data',dataset, 'Approach',myapproach, 'TargetMarkers',{'n1','n2','n3'})\n%\n% This model will predict either 1,2, or 3 with high confidence, when the user is maintaining the\n% respective number of items in his/her working memory, but will likely be fairly specific to the\n% task on which it was calibrated.\n%\n%\n% Parameter searching\n% ===================\n%\n% In some cases, the optimal setting of certain parameters of a paradigm might not be known, but may\n% drastically affect the performance of the method. One example are the time boundaries w.r.t. to\n% the supplied events, which may depend on the reaction time of the user, among other things.\n% Another example are regularization parameters which are used to constrain the complexity of the\n% learned model (see, e.g. [11]). Regularization is a very powerful concept which enables methods\n% such as Support Vector Machines and LASSO, in which the parameter is neither designed to be\n% manually selected nor is it very interpretable in terms of brain processes. But most importantly,\n% manual selection of these parameters (by trial and error) invalidates the performance guarantees\n% that are made by the loss estimates: the performance estimate found for the hand-selected model is\n% likely far better than the actual performance of that model. This is because the influence of\n% random fluctuations in the estimate over the possible parameters is maximized by the user when\n% he/she accepts the best one as the actual performance of the method (similar in spirit to the\n% fallacy of multiple hypothesis tests without correction).\n%\n% For these reasons, bci_train offers a generic mechanism to search over parameters (or parameter\n% combinations), in user-defined intervals and granularity, and uses a nested cross-validation\n% method to give unbiased loss estimates. In this method, the search for the best parameter (using\n% cross-validation derived estimates) is done inside an outer cross-validation, in each of its\n% steps, and is restricted to the respective training set of that step. This way, the performance of\n% the search procedure itself can be objectively evaluated on held-out test data. The\n% cross-validation scheme for this inner search procedure can be specified via the OptimizationScheme\n% parameter (part of the Training-Options), which has the same format as the EvaluationScheme\n% parameter. By default, it is set to a 5-fold blockwise cross-validation with 5 trials safety\n% margin. As a downside, parameter search multiplies the time it takes to compute a model by a\n% potentially large factor; the total computation time of bci_train is (# of folds in the outer\n% cross-validation) * (# of folds in the inner cross-validation) * (# of parameter combinations) *\n% (time to compute a single model). Thus, the evaluation (outer) cross-validation may in some cases\n% be turned off ('eval_scheme' set to 0) to obtain a model in a reasonable time, e.g., between a\n% calibration session and a subsequent online session.\n%\n% Any value supplied to the paradigm can be replaced by a search range, written as search(...), to\n% indicate to bci_train that this parameter is subject to a search. The search() clause can be used\n% in any place of the data passed to the paradigm (e.g. inside cell arrays and/or structs), and can\n% run over any data type supported by MATLAB, such as numbers, strings, structs, and vectors.\n%\n%\n% Parameter Search Examples\n% =========================\n%\n% In the case of imagined hand gestures (see first example), the time period in which the user\n% performs the imaginations may not be known in advance (e.g. one user may imagine to clench the\n% fist, while another user may imagine a whole sequence of finger movements). Therefore, the exact\n% boundaries of the relevant data are not known, and can be searched (or spectral heuristics could\n% be used). We assume that the response time of the user following the instruction may vary between\n% 0.25 seconds and 0.75 seconds, and we choose to search over the range at a granualarity of 0.1\n% seconds. The time it takes until the imagination is finished may vary between 1.5 seconds and 4.5\n% seconds, and we search over values at a granularity of 0.5 seconds. Thus, para_csp's default\n% 'epoch' parameter [0.5,3.5] is replaced by [search(0.25:0.1:0.75), search(1.5:0.5:4.5)]:\n%\n%   calib = io_loadset('data sets/john/gestures.eeg')\n%   myapproach = {'CSP' 'SignalProcessing',{'EpochExtraction',[search(0.25:0.1:0.75),search(1.5:0.5:4.5)]}};\n%   [loss,model,stats] = bci_train('Data',calib, 'Approach',myapproach}, 'TargetMarkers',{'left-imag','right-imag'})\n%\n% Since the search runs over 6*7 parameters, and a 5x inner cross-validation is performed, the\n% overall running time will be 6*7*5 = 210x the default running time. If such a procedure shall be\n% run immediately prior to an online session, it is better to disable the outer cross-validation\n% altogether, which brings the time down to 21x of the default.\n%\n%\n% As a second example, suppose that the goal is to predict whether the user perceives some event as\n% being erroneous or not. A possible calibration data set could contain events of two classes, 'err'\n% and 'cor', which encode time points where the user encountered errorneous and correct events. The\n% assumption is that the user's event processing is accompanied by a characteristic slow cortical\n% potential [12] which allows to discern between the two conditions. As a paradigm, we use the\n% ERP version of the Dual-Agumented Lagrange method [13], which makes few assumptions\n% except that the cognitive process of interest is simple enough in its time/space behavior to be\n% tractably recognized. We restrict the analysis to the period of -0.2 to 0.65s around the event,\n% resample to 60Hz, filter to ~0.3-19Hz, and specify a custom parameter search range for the DAL machine\n% learning function. The complexity of the learned model is controlled via a regularization\n% parameter, called Lambda. This parameter is the first user-accessible parameter in the learning\n% function ml_traindal (its first two parameters are implicitly specified by the framework and\n% contain the actual data; this contract holds for all other learning functions\n% machine_learning/ml_train*, as well). Instead of specifying an ad hoc value here, we instead\n% let bci_train search over a large feasible interval.\n%\n%   calib = io_loadset('data sets/john/errorperception.eeg')\n%   myapproach = {'DALERP', ...\n%       'SignalProcessing',{'EpochExtraction',[-0.2 0.65]}, ...\n%       'Prediction',{'MachineLearning',{'Learner',{'dal',search(2.^(8:-0.125:1))}}}};\n%   [loss,model,stats] = bci_train('Data',calib,'Approach',myapproach, 'TargetMarkers',{'err','cor'})\n%\n% This example is for illustrative purposes because the ml_traindal has its own highly optimized\n% parameter search code, which would kick in if the first parameter was specified as an array of\n% possible values (i.e. without the search() clause).\n%\n% Statistics\n% ==========\n%\n% Aside from an average loss measure, a structure of additional statistics can be obtained from\n% bci_train via its third output parameter, Statistics. The most relevant part of the statistics are\n% the per-fold loss measures (computed in each cross-validation fold), which can be used to run\n% statistical tests on the significance of outcomes, etc.; these are in the struct array .per_fold.\n% This also includes the target values (.targ) and predicted values (.pred) for the trials in each\n% fold, as well as the indices of the fold's trials in the full original data set (.indices).\n% Depending on the type of loss measure, additional values may be available per fold (e.g. fraction\n% of true and false positives, etc).\n%\n% If the model was obtained in a parameter search, the field .modelsearch contains the complete set of\n% loss measures and computed models for each tested parameter combination (on the entire calibration\n% set), which includes, among others, the regularization path for regularized classifiers, which\n% allows for very detailed analyses of the computed models.\n%\n% Additional fields include, depending on the type of target variables, .classes and .class_ratio\n% contain the possible output values of the model (e.g. [1,2,3,4,5] in a  standard 5-class\n% classification task) as well as the fraction of data trials belonging to each class. The field\n% .model contains the computed model, the field .expression contains an expression data structure\n% which summarizes the parameters that went into the comptuation of the result(s), including those\n% that determined the data set(s) used for calibration. The function hlp_tostring can format it into\n% a human-readable string.\n%\n%\n% Model Usage\n% ===========\n%\n% The computed model can subsequently be used with other parts of the toolbox. Most importantly, the\n% model can be used with the online system of the toolbox, either via one of the provided online\n% plugins or directly through BCILAB's online application programming interface (API), explained in\n% online_analysis/onl_*. Aside from online analysis, the model can be used for offline analysis of\n% data sets, via the functions bci_predict (make predictions for every trial in a given data set),\n% onl_stream (make predictions for desired time points in a given data set), and bci_preproc\n% (preprocess a given data set into its pre-feature extraction form for analysis and visualization\n% with EEGLAB tools). Finally, model properties can be visualized and inspected using visualization\n% methods (visualizations/vis_*). The model can be saved to disk and re-loaded later.\n%\n%\n% In:\n%    --- core arguments ---\n%\n%    Data : Data set. EEGLAB data set, or stream bundle, or cell array of data sets / stream bundles\n%           to use for calibration/evaluation.\n%\n%    Approach : Computational approach. Specification of a computational approach (usually a cell\n%               array, alternatively a struct). If a cell array, the first cell is the name of the\n%               paradigm (usually just the acronym of an existing ParadigmXXX class), and the rest are\n%               name-value pairs specifying optional custom arguments for the paradigm.\n%\n%   TargetMarkers : Target markers. List of types of those markers around which data shall be used\n%                   for BCI calibration; each marker type encodes a different target class (i.e.\n%                   desired output value) to be learned by the resulting BCI model.\n%\n%                   This can be specified either as a cell array of marker-value pairs, in which\n%                   case each marker type of BCI interest is associated with a particular BCI output\n%                   value (e.g., -1/+1), or as a cell array of marker types (in which case each\n%                   marker will be associated with its respective index as corresponding BCI output\n%                   value, while nested cell arrays are also allowed to group markers that correspond\n%                   to the same output value). See help of set_targetmarkers for further explanation.\n%\n%\n%   --- computational settings ---\n%\n%   EvaluationMetric : Evaluation metric. The metric to use in the assessment of model performance\n%                      (via cross-validation). Can be empty, a string, or a function handle.\n%                      See ml_calcloss() for the options (default: [] = auto-select between\n%                      kullback-leibler divergence ('kld'), mean square error ('mse'), mis-classification\n%                      rate ('mcr') and negative log-likelihood ('nll') depending on the type of the\n%                      target and prediction variables, further detailed in ml_calcloss())\n%\n%   EvaluationScheme : Evaluation scheme. Cross-validation scheme to use for evaluation. See\n%                      utl_crossval for the default settings when operating on a single recording\n%                      (there it is called 'scheme'). When opperating on a collection of multiple\n%                      data sets, this is equivalent to the Settings argument of\n%                      utl_collection_partition (see that function for details). In the case of\n%                      single data sets, a reasonable choice for final results is {'chron',10,5}\n%                      which stands for 10-fold chronological/blockwise cross-validation with 5\n%                      trials margin between training and test sets. Default: {'chron',5,5}, which\n%                      is twice as fast, for more rapid workflow. A standard choice in machine\n%                      learning is 10-fold randomized cross-validation, which you get by setting\n%                      this parameter to 10 (though it is not ideal for time-series data).\n%                      Use the special value 0 or 'off' to disable the outer cross-validation.\n%\n%   OptimizationScheme : Optimization scheme. Cross-validation scheme to use for parameter search\n%                        (this is a nested cross-validation, only performed if there are parameters\n%                        to search). The format is the same as in EvaluationScheme; default is\n%                        {'chron',5,5}, which is a reasonable choice for final results.\n%\n%   GoalIdentifier : Goal identifier. This is used when training a model on a collection of\n%                    multiple recordings that will subsequently be used to predict given a dataset\n%                    that is somehow related to the training set (e.g., one of the subjects). It\n%                    serves to identify the data set on which the BCI shall eventually be used and\n%                    is a struct that has fields like 'subject', 'session', 'day' (e.g., the Subject\n%                    Id, Day, etc. of the goal data set); for further details, see\n%                    utl_collection_closest, which interprets these parameters to determine what\n%                    data in the collection is most relevant to the future test dataset. Note that\n%                    when one does not actually plan to use the trained model on new data (as is\n%                    often the case), it might be most efficient to just set the GoalIdentifier to\n%                    identify one of the recordings (e.g., {'subject',1}) since otherwise the final\n%                    model produced by bci_train would be trained in a way that's agnostic to which\n%                    is the future subject, and that can be quite time-consuming for some methods.\n%\n%   --- selective computation ---\n%\n%   PerFoldModels : Collect per-fold models. If true, models of each fold of the cross-validation\n%                   will be collected (uses more memory). (default: false)\n%\n%   ComputeFinalModel : Whether to compute the final model. If false, the resulting model will be\n%                       empty. (default: true)\n%\n%   NoPrechecks : Disable pre-checks. This will skip sanity checks of the data prior to launching\n%                 the actual computation. When the CV is run on a cluster on a large dataset, this\n%                 can save significant loading time. (default: false)\n%\n%   CacheFoldResults : Whether to cache the per-fold results. This is meant to be used when running\n%                      very long-running computations on machines that crash frequently enough that\n%                      partial results need to be saved. In this case, any previously computed\n%                      results will be loaded from disk. Under normal conditions caching only\n%                      sub-computations necessary for the cross-validation (which is enabled by\n%                      default) should be enough. Implies NoPrechecks. (default: false)\n%\n%   OnlyCachedResults : Load only results that are in the cache. This will not run any computations.\n%                       Implies CacheFoldResults. (default: false)\n%\n%   --- parallel computing options ---\n%\n%   CrossvalidationResources : Cross-validation parallelization. Same meaning and options as the\n%                              ParameterSearchEngine parameter, however for the cross-validations.\n%                              By default set to 'global'.\n%\n%   ParameterSearchResources : Parameter search parallelization. If set to 'global', the global BCILAB\n%                              setting (see par_globalsetting) will be used to determine when to run\n%                              this computation. If set to 'local', the computation will be done on\n%                              the local machine. Otherwise,the respective scheduler will be used to\n%                              distribute the computation across a cluster (default: 'local')\n%\n%   NestedCrossvalResources : Nested cross-validation parallelization. If set to 'global', the\n%                             global BCILAB setting will be used (see par_globalsetting) to\n%                             determine when to run this computation. If set to 'local', the\n%                             computation will be done on the local machine. Otherwise,the\n%                             respective scheduler will be used to distribute the computation across\n%                             a cluster (default: 'local')\n%\n%   ResourcePool : Parallel compute resouces. If set to ''global'', the globally set BCILAB resource\n%                  pool will be used (see par_globalsetting), otherwise this should be a cell array\n%                  of 'hostname:port' strings (default: 'global')\n%\n%   --- miscellaneous options ---\n%\n%   EpochBounds : Epoch bounds override. Tight upper bound of epoch windows used for epoching (by\n%                 default [-5 5]). This is only used if the cross-validation needs to run on\n%                 continuous data because a continuous-data statistic needs to be computed over the\n%                 training set (such as ICA).\n%\n%   EventField : Event field to search for target markers, provided as a string. If not provided,\n%                the field 'type' will be used by default.\n%\n%   PruneDatasets : Prune datasets from results. If true, any occurrence of a data set in the\n%                   resulting model or stats struct will be replaced by its symbolic expression or a\n%                   placeholder string. (default: true)\n%\n%   PruneNontargetMarkers : Prune non-target markers. This usually improves the speed of offline\n%                           processing at the cost of not being able to access misc markers in BCI\n%                           analysis. (default: false)\n%\n%   EnforceFingerprinting : Enforce use of fingerprinting. If true, this function will not accept\n%                           raw dataset structs if fingerprinting is disabled. (default: true)\n%\n%   TolerateExceptions : Tolerate and suppress exceptions during training. The affected folds will\n%                        be excluded from the statistics. (default: false)\n%\n% Out:\n%   Loss       : a measure of the overall performance of the paradigm combination, w.r.t. to the\n%                target variable returned by gettarget, computed by the specified loss metric.\n%\n%   Model      : a predictive model (\"detector\"), as computed by the specified paradigm; can be\n%                loaded into the online system via onl_loaddetector, applied offline to new data via\n%                bci_predict, and analyzed using various visualizers\n%\n%   Statistics : additional statistics, as produced by the specified metric; if the model itself is\n%                determined via parameter search, further statistics from the model searching are in\n%                the subfield stats.model\n%\n% Examples:\n%   % assuming that a data set has been loaded, and a computational approach has been defined\n%   % similarly to the following code:\n%   traindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat');\n%   myapproach = {'CSP' 'SignalProcessing',{'EpochExtraction',[0 3.5]}};\n%\n%   % learn a model and get the mis-classification rate, as well as statistics\n%   [trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\n%\n%   % as before, but use a coarser block-wise (chronological) cross-validation (5-fold, with 3 trials margin)\n%   [trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'EvaluationScheme',{'chron',5,3}'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\n%\n%   % as before, but use a 10-fold randomized cross-validation (rarely recommended)\n%   [trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'EvaluationScheme',10,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\n%\n%   % as before, using a 10-fold, 10x repeated randomized cross-validation\n%   [trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'EvaluationScheme',[10 10],'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\n%\n%   % using a different loss measure (here: mean-square error, instead of the default mis-classification rate)\n%   [trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'EvaluationMetric','mse','TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\n%\n%\n% References:\n%   [1] Pfurtscheller, G., and da Silva, L. \"Event-related EEG/MEG synchronization and desynchronization: basic principles.\"\n%       Clin Neurophysiol 110, 1842-1857, 1999\n%   [2] Ramoser, H., Mueller-Gerking, J., Pfurtscheller G. \"Optimal spatial filtering of single trial EEG during imagined hand movement.\"\n%       IEEE Trans Rehabil Eng. Dec 8 (4): 441-6, 2000\n%   [3] MacKay, D. J. C. \"Information theory, inference, and learning algorithms.\"\n%       Cambridge University Press, 2003.\n%   [4] Duda, R., Hart, P., and Stork, D., \"Pattern Classification.\", Second Ed.\n%       John Wiley & Sons, 2001.\n%   [5] Dornhege, G. \"Increasing Information Transfer Rates for Brain-Computer Interfacing.\"\n%       Ph.D Thesis, University of Potsdam, 2006.\n%   [6] Owen, A. M., McMillan, K. M., Laird, A. R. & Bullmore, E. \"N-back working memory paradigm: A meta-analysis of normative functional neuroimaging studies.\"\n%       Human Brain Mapping, 25, 46-59, 2005\n%   [7] Bishop, C. M. \"Pattern Recognition and Machine Learning.\"\n%       Information Science and Statistics. Springer, 2006.\n%   [8] Hastie, T., Tibshirani, R., and Friedman, J. H. \"The elements of statistical learning (2nd Ed.).\"\n%\t    Springer, 2009.\n%   [9] Tomioka, R., Dornhege, G., Aihara, K., and Mueller, K.-R.. \"An iterative algorithm for spatio-temporal filter optimization.\"\n%       In Proceedings of the 3rd International Brain-Computer Interface Workshop and Training Course 2006, pages 22-23. Verlag der Technischen Universitaet Graz, 2006.\n%   [10] Buzsaki, G., \"Rhythms of the brain\"\n%        Oxford University Press US, 2006\n%   [11] Tibshirani, R. . \"Regression Shrinkage and Selection via the Lasso\"\n%        Journal of the Royal Statistical Society, Series B (Methodology) 58 (1): 267-288, 1996\n%   [12] Holroyd, C.B., Coles, M.G.. \"The neural basis of human error processing: reinforcement learning, dopamine, and the error-related negativity\"\n%        Psychological Review, 109, 679-709, 2002\n%   [13] Tomioka, R. and Mueller, K.-R. \"A regularized discriminative framework for EEG analysis with application to brain-computer interface\"\n%        Neuroimage, 49 (1) pp. 415-432, 2010.\n%   [14] Onton J & Makeig S. \"Broadband high-frequency EEG dynamics during emotion imagination.\"\n%        Frontiers in Human Neuroscience, 2009.\n%\n% See also:\n%   bci_predict, bci_batchtrain, bci_visualize, bci_annotate, io_loadset,\n%   onl_simulate, onl_newpredictor, utl_crossval, utl_searchmodel,\n%   utl_nested_crossval\n%\n%                               Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                               2010-04-24\ndp;\n\n% get the options\nopts = arg_define(0,varargin, ...\n    ... % core parameters ...\n    arg_norep({'data','Data'},mandatory,[],'Data set. EEGLAB data set, or stream bundle, or cell array of data sets / stream bundles to use for calibration/evaluation.'), ...\n    arg({'approach','Approach'},[],[],'Computational approach. Specification of a computational approach (usually a cell array, alternatively a struct).','type','expression'), ...\n    arg({'markers','TargetMarkers'},{},[],'Target markers. List of types of those markers around which data shall be used for BCI calibration; each marker type encodes a different target class (i.e. desired output value) to be learned by the resulting BCI model. This can be specified either as a cell array of marker-value pairs, in which case each marker type of BCI interest is associated with a particular BCI output value (e.g., -1/+1), or as a cell array of marker types (in which case each marker will be associated with its respective index as corresponding BCI output value, while nested cell arrays are also allowed to group markers that correspond to the same output value). See help of set_targetmarkers for further explanation.'), ...\n    arg({'metric','EvaluationMetric','Metric','cvmetric'},'auto',{'auto','mcr','mse','smse','sign','nll','kld','mae','max','rms','bias','medse','auc','cond_entropy','cross_entropy','f_measure','medae','smedae'},'Evaluation metric. The metric to use in the assessment of model performance (via cross-validation); see also ml_calcloss.'), ...\n    arg({'eval_scheme','EvaluationScheme','EvalScheme'},[],[],'Evaluation scheme. Cross-validation scheme to use for evaluation. See utl_crossval for the default settings when operating on a single recording, and utl_collection_partition when operating on a collection of data sets.','type','expression'), ...\n    arg({'opt_scheme','OptimizationScheme','OptScheme'},{'chron',5,5},[],'Optimization scheme. Cross-validation scheme to use for parameter search (this is a nested cross-validation, only performed if there are parameters to search).','type','expression'), ...\n    ... % misc parameters ...\n    arg({'field','EventField'},'type',[],'Event field to search for target markers. This is the fieldname in the .event struct of a dataset.'), ...\n    arg({'goal_identifier','GoalIdentifier'},{},[],'Goal identifier. This is only used for training on multiple recordings and serves to identify the data set on which the BCI shall eventually be used (e.g., Subject Id, Day, etc.).','type','expression'), ...\n    arg({'epoch_bounds','EpochBounds'},[],[],'Epoch bounds override. Tight upper bound of epoch windows used for epoching (by default the parameter to set_makepos / EpochExtraction). This is only used if the cross-validation needs to run on continuous data because a continuous-data statistic needs to be computed over the training set (such as ICA).','shape','row'), ...\n    ... % parallel computing parameters\n    arg({'parallel_scope','ParallelScope'},[],[],'Optional parallel scope. If this is a cell array of name-value pairs, cluster resources will be acquired with these options for the duration of bci_train (and released thereafter) Options as in env_acquire_cluster.','type','expression'), ...\n    arg({'engine_cv','CrossvalidationResources'},'global',{'global','local','BLS','ParallelComputingToolbox','Reference'},'Cross-validation parallelization. If set to ''global'', the global BCILAB setting will be used to determine when to run this computation. If set to ''local'', the computation will be done on the local machine. Otherwise,the respective scheduler will be used to distribute the computation across a cluster.'), ...\n    arg({'engine_gs','GridSearchResources'},'local',{'global','local','BLS','ParallelComputingToolbox','Reference'},'Grid search parallelization. If set to ''global'', the global BCILAB setting will be used to determine when to run this computation. If set to ''local'', the computation will be done on the local machine. Otherwise,the respective scheduler will be used to distribute the computation across a cluster.'), ...\n    arg({'engine_ncv','NestedCrossvalResources'},'local',{'global','local','BLS','ParallelComputingToolbox','Reference'},'Nested Cross-validation parallelization. If set to ''global'', the global BCILAB setting will be used to determine when to run this computation. If set to ''local'', the computation will be done on the local machine. Otherwise,the respective scheduler will be used to distribute the computation across a cluster.'), ...\n    arg({'pool','ResourcePool'},'global',[],'Parallel compute resouces. If set to ''global'', the globally set BCILAB resource pool will be used, otherwise this should be a cell array of hostname:port strings.','type','expression'), ...\n    ... % some more misc parameters\n    arg({'cache_fold_results','CacheFoldResults'},false,[],'Whether to cache the per-fold results. This is meant to be used when running very long-running computations on machines that crash frequently enough that partial results need to be saved. In this case, any previously computed results will be loaded from disk.'), ...\n    arg({'only_cached_results','OnlyCachedResults'},false,[],'Load only results that are in the cache. This will not run any computations (aside from pre-checks, that can be disabled by setting NoPrechecks to true).'), ...\n    arg({'per_fold_models','PerFoldModels','ReturnPerFoldModels'},false,[],'Collect per-fold models. If true, models of each fold of the cross-validation will be collected (uses more memory).'), ...\n    arg({'compute_final_model','ComputeFinalModel'},true,[],'Whether to compute the final model. If false, the resulting model will be empty.'), ...\n    arg({'prune_datasets','PruneDatasets'},true,[],'Prune datasets from results. If true, any occurrence of a data set in the resulting model or stats struct will be replaced by its symbolic expression or a placeholder string.'), ...\n    arg({'prune_nontarget_markers','PruneNontargetMarkers'},false,[],'Prune non-target markers. This usually improves the speed of offline processing at the cost of not being able to access misc markers in BCI analysis.'), ...\n    arg({'tolerate_exceptions','TolerateExceptions'},false, [], 'Tolerate and suppress exceptions during training. The affected folds will be excluded from the statistics.'), ...\n    arg({'no_prechecks','NoPrechecks'},false,[],'Disable pre-checks. This will skip sanity checks of the data prior to launching the actual computation. When the CV is run on a cluster on a large dataset, this can save significant loading time.'), ...\n    arg_nogui({'enforce_fingerprinting','EnforceFingerprinting'},true,[],'Enforce use of fingerprinting. If true and if fingerprinting is globally disabled (perhaps for speed), this function will not accept raw dataset structs.'));\n\n% do some checks to ensure that bci_train's use of caching based on datasets' .tracking fields\n% is not derailed by unchecked direct data editing actions (e.g., in scripts)\nif opts.enforce_fingerprinting\n    % if this is set, but fingerprinting is currently globally disabled in bcilab (this would be a\n    % non-default setting mostly to optimize processing speed under some circumstances), then\n    % bci_train will only accept either raw EEGLAB dataset structs (\"payload\") without a .tracking\n    % field, or pure expressions (see exp_beginfun) that describe datasets, but will refuse to\n    % accept data structures that have *both* nontrivial data payload and .tracking information\n    % (these are called \"impure\" expressions) for which it cannot be confirmed that the data payload\n    % is consistent with the tracking expression (since it may have been modified in a MATLAB script\n    % after the tracking info has been generated); this check is to protect users from accidentally\n    % using inconsistent data for processing. Consistency matters because results may be either\n    % computed from the raw data payload or looked up based on the tracking info from a cache,\n    % depending on whether a cache record exists. If fingerprinting is enabled instead (default),\n    % then consistently will be properly handled by the rest of the pipeline.\n    if ~hlp_resolve('fingerprint_create',true) || ~hlp_resolve('fingerprint_check',true)\n        if (isstruct(opts.data) && is_impure_expression(opts.data)) || (iscell(opts.data) && any(cellfun(@is_impure_expression,opts.data)))\n            error('You can only pass raw data into bci_train if fingerprinting is enabled (see env_startup). You can, however, always pass in unevaluated expressions, such as calls to io_loadset, custom loaders, or filter applications.');\n        end\n    end\nelse\n    % if any of the following warnings is ever triggered, the state of data in the caches might have\n    % gotten seriously messed up. If disk caching is turned on, it is best to purge the recent cache\n    % entries back to when this warning first occurred. A more caching-friendly approach to edit\n    % data sets is to move the code into a dedicated 'import' function (which is characterized by\n    % exp_beginfun/endfun lines like in io_loadset).\n    if ~hlp_resolve('fingerprint_create',true)\n        disp('WARNING: Data fingerprint creation is currently disabled (fingerprint_create set to 0). If you have been modifying your data sets manually in scripts before calling bci_train, it is recommended that you re-start your session, as some of your edits might have gone unnoticed.'); end\n    if ~hlp_resolve('fingerprint_check',true)\n        disp('WARNING: Data fingerprint checking is currently disabled (fingerprint_check set to 0). You can re-enable it by calling exp_set_scoped(@fingerprint_check,1) in the command line.'); end\nend\n\n% --- validate and pre-process the inputs ---\n\n% parse the approach (either it's a paradigm name string, a cell array, or a struct)\nif ischar(opts.approach)\n    % one of the class names in code/paradigms, without the leading 'Paradigm' prefix, e.g., 'CSP'\n    opts.approach = struct('paradigm',opts.approach, 'parameters',{{}});\nelseif iscell(opts.approach) && ~isempty(opts.approach)\n    % a cell array whose first element is the paradigm name, followed by arguments to the paradigm\n    % (specifically its calibrate() method); this is easiest to type for users\n    opts.approach = struct('paradigm',opts.approach{1}, 'parameters',{opts.approach(2:end)});\nelseif all(isfield(opts.approach,{'paradigm','parameters'}))\n    % a struct array with .paradigm field (paradigm name) and .parameters field (cell array of\n    % name-value pairs); this is the internally used format, e.g., what the design GUIs generate\nelseif isa(opts.approach,'ParadigmBase')\n    % a paradigm class instance (usually not used)\n    classname = class(opts.approach);\n    opts.approach = struct('paradigm',classname(9:end), 'parameters',{{}});\nelse\n    error('The approach must be given either as struct with fields ''paradigm'' and ''parameters'' or as a cell array of the form {paradigmname, param1, param2, param3, ...}, but was: %s',hlp_tostring(opts.approach));\nend\n\n% set implied arguments\nif opts.only_cached_results\n    opts.cache_fold_results = true; end\nif opts.cache_fold_results\n    opts.no_prechecks = true; end\n\n% parse the paradigm identifier of the approach\nparadigm_ref = opts.approach.paradigm;\nif ischar(paradigm_ref)\n    if exist(['Paradigm' paradigm_ref],'class')\n        paradigm_ref = ['Paradigm' paradigm_ref]; end\n    if ~exist(paradigm_ref,'class')\n        error('A paradigm class with the name (%s) was not found.',paradigm_ref); end\nelseif isa(paradigm_ref,'function_handle')\n    info = functions(paradigm_ref);\n    paradigm_ref = class(info.workspace{1}.instance);\n    if ~strncmp(paradigm_ref,'Paradigm',8)\n        error('The paradigm referred to by the given Approach must be the name of a Paradigm class (i.e., start with ''Paradigm''), but was: %s',paradigm_ref); end\nelse\n    error('The paradigm referred to by the given Approach must be the name of a class (optionally omitting the \"Paradigm\" prefix), but was: %s',hlp_tostring(paradigm_ref));\nend\n\n% create an instance of the BCI paradigm\n[calibrate_func, predict_func] = instantiate_paradigm(paradigm_ref);\n\n\n% parse the parameters of the approach: take the cartesian product over all\n% grid search() expressions in the parameters, if any\nparadigm_parameters = hlp_flattensearch(opts.approach.parameters);\n% update the list of filters and machine learners if necessary (to get up-to-date lists of supported modules)\nflt_pipeline('update');\nml_train('update');\nif ~is_search(paradigm_parameters)\n    % use the paradigm function to fill in all defaults (etc) for unspecified arguments\n    paradigm_parameters = arg_report('vals',calibrate_func,paradigm_parameters);\nelse\n    % fill in the defaults for each individual search item\n    for k=1:length(paradigm_parameters.parts)\n        paradigm_parameters.parts{k} = arg_report('vals',calibrate_func,paradigm_parameters.parts{k}); end\nend\n\n% if the EpochBounds are undefined, see if we can infer them from the data \n% note: the EpochBounds are *not* what is passed into set_makepos -- instead they have an additional\n% buffer margin around them (to be robust against e.g., resampling or other off-by-1 jitter in\n% intermediate processing steps) that is used to determine which epochs are potentially valid and\n% which ones violate exclusion conditions (e.g., too close to dataset bounds or intermittent\n% boundary markers); the exclusion checks are done by set_targetmarkers\nmargin_seconds = 0.1;\nif isempty(opts.epoch_bounds)\n    bounds = collect_instances(paradigm_parameters,'time_bounds'); % note: direct name reference to set_makepos's parameter\n    if ~isempty(bounds)\n        bounds = vertcat(bounds{:});\n        % we use an upper bound of the encountered bounds if multiple (can be multiple if in a\n        % parameter search, or if different bounds are assigned to multiple streams) plus some slack\n        opts.epoch_bounds = [min(bounds(:,1))-margin_seconds max(bounds(:,2))+margin_seconds];\n    end\nelseif ~isequal(size(opts.epoch_bounds),[1 2]) || opts.epoch_bounds(1) > opts.epoch_bounds(2)\n    error('The give EpochBounds argument, when non-empty, must be given as [lower,upper], but was: %s',hlp_tostring(opts.epoch_bounds));\nend\n\nparadigm_parameters = {paradigm_parameters};\n\n\n\n% --- set up common arguments to the cross-validation & model search ---\n\n% turn data into a trivial collection, if necessary to unify subsequent processing\nif isstruct(opts.data)\n    opts.data = {opts.data};\nelseif ~iscell(opts.data) || ~all(cellfun('isclass',opts.data,'struct'))\n    error('The given Data argument must be either a struct or a cell array of structs, but was: %s',hlp_tostring(opts.data,1000));\nend\n\n% do some pre-processing and further uniformization of the data\nfor k=1:length(opts.data)\n    % turn each data set into a stream bundle, if necessary\n    if ~isfield(opts.data{k},'streams')\n        opts.data{k} = struct('streams',{opts.data(k)});\n    elseif ~iscell(opts.data{k}.streams) || isempty(opts.data{k}.streams) || ~all(cellfun('isclass',opts.data{k}.streams,'struct'))\n        error('The given dataset''s .streams field must be a nonempty cell array of structs, but was: %s',hlp_tostring(opts.data{k}.streams,10000));\n    end\n    % annotate target markers in 1st stream according to the specified event types\n    if ~isempty(opts.markers)\n        if ~iscell(opts.markers)\n            error('The given TargetMarkers argument must be a cell array, but was: %s',hlp_tostring(opts.markers,1000)); end\n        if isempty(opts.epoch_bounds)\n            disp('Note: TargetMarkers were specified, but epoch bounds could not be deduced from the data (likely processing is not using epoch extraction). Assuming some default bounds [-0.5 0.5].');\n            opts.epoch_bounds = [-0.5 0.5];\n        end\n        % (there are 3 possible TargetMarker formats to handle)\n        if length(opts.markers) == 1 && ischar(opts.markers{1}) && strcmp(opts.markers{1}, 'actualvalues')\n            opts.data{k}.streams{1} = set_targetmarkers('Signal',opts.data{k}.streams{1},'EventMap',opts.markers,'EpochBounds',opts.epoch_bounds, 'EventField', opts.field, 'PruneNontarget',opts.prune_nontarget_markers);\n        elseif all(cellfun('isclass',opts.markers,'char') | cellfun('isclass',opts.markers,'cell'))\n            opts.data{k}.streams{1} = set_targetmarkers('Signal',opts.data{k}.streams{1},'EventTypes',opts.markers,'EpochBounds',opts.epoch_bounds, 'EventField', opts.field, 'PruneNontarget',opts.prune_nontarget_markers);\n        else\n            opts.data{k}.streams{1} = set_targetmarkers('Signal',opts.data{k}.streams{1},'EventMap',opts.markers,'EpochBounds',opts.epoch_bounds, 'EventField', opts.field, 'PruneNontarget',opts.prune_nontarget_markers);\n        end\n    end\n    % check the bundle for consistency: in particular, whether the data matches the .tracking field\n    if ~opts.no_prechecks\n        opts.data{k} = utl_check_bundle(opts.data{k}); end\nend\n% ... and store some tracking information for the resulting model\nsource_data = opts.data;\nfor k=1:length(source_data)\n    source_data{k}.streams = cellfun(@utl_purify_expression,source_data{k}.streams,'UniformOutput',false); end\n\n% determine whether we have to send our data over the network (which prompts further optimizations)\nnonlocal = iscell(opts.parallel_scope);\nfor computescope = {'engine_cv','engine_gs','engine_ncv'}\n    if strcmp(opts.(computescope{1}),'global')\n        nonlocal = nonlocal || ~strcmp(par_globalsetting('engine'),'local');\n    else\n        nonlocal = nonlocal || ~strcmp(opts.(computescope{1}),'local');\n    end\nend\n\nif nonlocal\n    % if we're running non-locally, transfer only a minimal amount of data (i.e. just the expressions) over the network\n    opts.data = source_data;\n    % ... and make sure that these expressions get properly cached on the server side...\n    for k=1:length(opts.data)\n        opts.data{k}.streams = cellfun(@(x)exp_block({exp_rule(@memoize,{'memory',1})},x),opts.data{k}.streams,'UniformOutput',false); end\nend\n\nif isscalar(opts.data)\n    % got a single recording: cross-validate within it\n    opts.data = opts.data{1};\n    if isempty(opts.eval_scheme)\n        opts.eval_scheme = {'chron',5,5}; end\nelse\n    % got a data set collection: cross-validate across them\n    if isempty(opts.eval_scheme)\n        opts.eval_scheme = {}; end\nend\n\n% create the function handles that go into the cross-validation (we do this in a sub-function\n% because we want to keep the anonymous handle objects from picking up whether the\n% only_cached_results flag is set in opts; that's because these arguments go into the computation of\n% cache tags, which must be unchanged regardless of whether that flag is set or not; also, we want\n% to keep the actual data out of those handles, too)\ncrossval_handles = make_crossval_handles('multisubject', ~isscalar(opts.data), ...\n    'epoch_bounds',opts.epoch_bounds, 'eval_scheme',opts.eval_scheme, ...\n    'calibrate_func', calibrate_func, 'predict_func', predict_func);\n\n% define the remaining arguments for the cross-validation\ncrossval_misc = { ...\n    'metric',opts.metric, ...\n    'pool',opts.pool, ...\n    'argform','clauses', ...\n    'collect_models',opts.per_fold_models, ...\n    'cache_fold_results',opts.cache_fold_results, ...\n    'only_cached_results',opts.only_cached_results, ...\n    'no_prechecks',opts.no_prechecks, ...\n    'tolerate_exceptions', opts.tolerate_exceptions};\n\n% define the arguments to the training function (according to the given approach)\nif isscalar(opts.data)\n    % got a single recording: pass paradigm parameters right through\n    crossval_trainargs = {'args', paradigm_parameters};\nelse\n    % got a data set collection: also append the goal_identifier argument\n    crossval_trainargs = {'args', [paradigm_parameters {'goal_identifier',opts.goal_identifier}]};\nend\n\n% string the crossval args together\ncrossval_args = [crossval_handles crossval_misc crossval_trainargs];\n\n% note: the following line is a fancy way of calling [measure,model,stats] = run_computation(opts,crossval_args);\n% what is different is that the global variables fingerprint_check and fingerprint_create will be\n% set to 0 for the scope of that computation (effectively disabling some unnecessary checks that\n% have already been done at the beginning of bci_train, unless generally disabled, for performance)\n[measure,model,stats] = hlp_scope({'fingerprint_check',0,'fingerprint_create',0},@run_computation,opts,crossval_args);\n\n% annotate the result with additional info\nstats.is_result = true;\nstats.timestamp = now;\nmodel.paradigm = paradigm_ref;\nmodel.options = paradigm_parameters;\nmodel.source_data = source_data;\nmodel.control_options = rmfield(opts,'data');\nmodel.epoch_bounds = opts.epoch_bounds;\nif isfield(stats,'per_fold') && isfield(stats.per_fold,'model')\n    for k=1:length(stats.per_fold)\n        if ~isempty(stats.per_fold(k).model)\n            stats.per_fold(k).model.paradigm = paradigm_ref; end\n    end\nend\n% remove some additional data overhead from model & stats to keep them small\nif opts.prune_datasets\n    model = utl_prune_datasets(model);\n    stats = utl_prune_datasets(stats);\nend\nmodel = utl_prune_handles(model);\nstats = utl_prune_handles(stats);\nmodel.tracking.prediction_function = paradigm_ref;\nstats.model = model;\nend\n\n\nfunction [calibrate_func,predict_func] = instantiate_paradigm(paradigm_ref)\n% create a paradigm object and get handles to its calibrate and predict methods\n% (this is a separate function because the function handles have the tendency to pick up hidden\n% references to datasets etc in bci_train's workspace)\ntry\n    instance = eval(paradigm_ref); %#ok<NASGU>\ncatch e\n    error('Failed to instantiate paradigm class (%s) with error: %s',paradigm_ref,e.message);\nend\ncalibrate_func = eval('@instance.calibrate');\npredict_func = eval('@instance.predict');\nend\n\n\nfunction res = make_crossval_handles(varargin)\nargs = hlp_varargin2struct(varargin);\nif ~args.multisubject\n    % got a single recording: cross-validate within it\n    res = { ...\n        'trainer', @(trainset,varargin) utl_complete_model(args.calibrate_func('collection',{trainset},varargin{:}),args.predict_func), ...\n        'tester', @(testset,model) args.predict_func(utl_preprocess_bundle(testset,model),model), ...\n        'partitioner', @(dataset,inds) utl_partition_bundle(dataset,inds,args.epoch_bounds), ...\n        'target', @(dataset) set_gettarget(dataset.streams{1})};\nelse\n    % got a data set collection: cross-validate across them\n    res = { ...\n        'trainer', @(traincollection,varargin) utl_complete_model(args.calibrate_func('collection',traincollection,varargin{:}),args.predict_func), ...\n        'tester', @(testcollection,model) utl_collection_tester(testcollection,model,args.predict_func), ...\n        'partitioner', @(fullcollection,inds) utl_collection_partition(fullcollection,inds,args.eval_scheme), ...\n        'target', @utl_collection_targets};\nend\nend\n\n\n% run the actual computation of bci_train (model search/training, (nested) cross-validation)\nfunction [measure,model,stats] = run_computation(opts,crossval_args)\ndp;\nt0 = tic;\n\nif iscell(opts.parallel_scope)\n    if env_acquire_cluster(opts.parallel_scope{:})\n        releaser = onCleanup(@()env_release_cluster); end\nend\n\n% issue model search job, optionally in parallel\nsearchmodel_args = [crossval_args, {'scheme',opts.opt_scheme, 'engine_gs',opts.engine_gs, 'engine_ncv',opts.engine_ncv}];\nparallel_args = {'engine',opts.engine_cv, 'keep',false, 'pool',opts.pool};\nif opts.compute_final_model\n    job = par_beginschedule({{@hlp_getresult,{1:2}, @utl_searchmodel, opts.data, searchmodel_args{:}}}, parallel_args{:}); end %#ok<CCAT>\n\n% also estimate the model performance, if requested (0-fold cross-validation = cross-validation turned off)\n% this can run in parallel to the model search, if parallel computation is enabled\nif ~isequal(opts.eval_scheme,0) && ~isequal(opts.eval_scheme,'off')\n    parallel_args = hlp_struct2varargin(opts,'restrict',{'eval_scheme','opt_scheme','engine_gs','engine_cv','engine_ncv'});\n    [measure,stats] = utl_nested_crossval(opts.data, crossval_args{:}, parallel_args{:});\nelse\n    measure = NaN;\nend\n\n% collect & aggregate results\nif opts.compute_final_model\n    results = par_endschedule(job, 'keep',false);\n    [model,stats.modelsearch] = deal(results{1}{:});\nelse\n    model = struct();\n    stats.modelsearch = struct();\nend\nmodel.tracking.computation_time = toc(t0);\n\nend\n\n\n% collect all instances of values of the given field in a data structure\nfunction res = collect_instances(x,field)\nres = {};\nif isstruct(x)\n    for fn=fieldnames(x)'\n        fname = fn{1};\n        if strcmp(fname,field)\n            % this is our field: aggregate all instances as a cell array\n            tmp = {x.(fname)};\n        else\n            tmp = collect_instances({x.(fname)},field);\n        end\n        if ~isempty(tmp)\n            res = [res tmp(:)]; end %#ok<AGROW>\n    end\nelseif iscell(x)\n    for c=1:numel(x)\n        res = [res collect_instances(x{c},field)]; end %#ok<AGROW>\nend\nend\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/offline_analysis/bci_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2399622983872009}}
{"text": "load('net_weights.mat');\nload('out_0_7layer_out.mat');\noriginal_img = squeeze(original_img);\nconv1_1 = squeeze(conv1_1);\nconv1_2 = squeeze(conv1_2);\nconv2_1 = squeeze(conv2_1);\nconv2_2 = squeeze(conv2_2);\nconv3_1 = squeeze(conv3_1);\nconv3_2 = squeeze(conv3_2);\nconv3_3 = squeeze(conv3_3);\nconv4_1 = squeeze(conv4_1);\nconv4_2 = squeeze(conv4_2);\nconv4_3 = squeeze(conv4_3);\nconv5_1 = squeeze(conv5_1);\nconv5_2 = squeeze(conv5_2);\nconv5_3 = squeeze(conv5_3);\nimg_gradient = squeeze(img_gradient);\npool1 = squeeze(pool1);\npool2 = squeeze(pool2);\npool3 = squeeze(pool3);\npool4 = squeeze(pool4);\npool_5 = squeeze(pool_5);\nrpn_bbox_pred = squeeze(rpn_bbox_pred);\nrpn_cls_prob = squeeze(rpn_cls_prob);\nrpn_cls_prob_reshape = squeeze(rpn_cls_prob_reshape);\nrpn_cls_score = squeeze(rpn_cls_score);\nrpn_cls_score_reshape = squeeze(rpn_cls_score_reshape);\nrpn_conv_3x3 = squeeze(rpn_conv_3x3);\n\n%setup matconvnet\nrun /home/spc-public/Yixuan/matconvnet/matconvnet-1.0-beta24/matlab/vl_setupnn;\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/ImageSeg-master/Load_net_output.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23996229838720087}}
{"text": "function [uOutput] = cnssimp(nFunction, sFilename)\n    % CNSSIMP import data of the ANSS/CNSS raw format catalog \n    %\n% [uOutput] = cnssimp(nFunction, sFilename);\n%\n% ANSS/CNSS raw format: (http://quake.geo.berkeley.edu/ncedc/documents.html#catalog_formats)\n% Description of the parameters can be found at http://quake.geo.berkeley.edu/ftp/pub/doc/cat5/cnss.catalog.5\n%\n% updated: 15.09.03, J. Woessner\n\nif nFunction == FilterOp.getDescription\n    uOutput = 'ANSS/CNSS format (string conversion)';\nelseif nFunction == FilterOp.importCatalog\n\n    mData = textread(sFilename, '%s', 'delimiter', '\\n', 'whitespace', '');\n\n    %transform data to ZMAP format\n    uOutput = zeros(size(mData, 1), 9);\n\n\n\n    for i = 1:length(mData)\n        if rem(i,100) == 0 ; \n            disp([ num2str(i) ' of ' num2str(length(mData)) ' events processed ']); \n        end\n        try\n            %             uOutput(i,1) = str2num(mData{i}(33:41));    %lon\n            %             uOutput(i,2) = str2num(mData{i}(24:31));    %lat\n            %             uOutput(i,3) = str2num(mData{i}(1:4));      %yr\n            %             uOutput(i,4) = str2num(mData{i}(6:7));      %mo\n            %             uOutput(i,5) = str2num(mData{i}(9:10));     %da\n            %             uOutput(i,6) = str2num(mData{i}(51:54));    %mag\n\n            uOutput(i,1) = str2num(mData{i}(34:43));    %lon\n            uOutput(i,2) = str2num(mData{i}(25:33));    %lat\n            uOutput(i,3) = str2num(mData{i}(6:9));      %yr\n            uOutput(i,4) = str2num(mData{i}(10:11));      %mo\n            uOutput(i,5) = str2num(mData{i}(12:13));     %da\n            uOutput(i,6) = str2num(mData{i}(130:134));    %mag\n            str = '      ';\n            if  strcmp(mData{i}(44:51),str)== 1%strcmp(mData{i}(43:48),str)== 1\n                uOutput(i,7) = 0;\n            else\n                %uOutput(i,7) = str2num(mData{i}(43:48));%dep\n                uOutput(i,7) = str2num(mData{i}(44:51));%dep\n            end\n\n            %             uOutput(i,8) = str2num(mData{i}(12:13));    %hr\n            %             uOutput(i,9) = str2num(mData{i}(15:16));    %min\n            uOutput(i,8) = str2num(mData{i}(14:15));    %hr\n            uOutput(i,9) = str2num(mData{i}(16:17));    %min\n            %uOutput(i,:);\n        catch\n            msg.dbfprintf('Import: Problem in line %d of %s. Line ignored.\\n',i, sFilename);\n            uOutput(i,:)=nan;\n        end\n    end\n    l = isnan(uOutput(:,1));\n    uOutput(l,:) = [];\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/importfilters/other/cnssimp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.23996229838720085}}
{"text": "function [sel1, sel2] = match_str(a, b, fullout)\n\n% MATCH_STR looks for matching labels in two lists of strings\n% and returns the indices into both the 1st and 2nd list of the matches.\n% They will be ordered according to the first input argument.\n%\n% Use as\n%   [sel1, sel2] = match_str(strlist1, strlist2)\n%\n% The strings can be stored as a char matrix or as an vertical array of\n% cells, the matching is done for each row.\n%\n% When including a 1 as the third input argument, the output lists of\n% indices will be expanded to the size of the largest input argument.\n% Entries that occur only in one of the two inputs will correspond to a 0\n% in the output, in this case. This can be convenient in rare cases if the\n% size of the input lists is meaningful.\n\n% Copyright (C) 2000-2012, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% ensure that both are cell-arrays\nif isempty(a)\n  a = {};\nelseif ~iscell(a)\n  a = cellstr(a);\nend\nif isempty(b)\n  b = {};\nelseif ~iscell(b)\n  b = cellstr(b);\nend\n\n% regardless of what optimizations are implemented, the code should remain\n% functionally compatible to the original, which is\n% sel1 = [];\n% sel2 = [];\n% for i=1:length(a)\n%   for j=1:length(b)\n%     if strcmp(a(i),b(j))\n%        sel1 = [sel1; i];\n%        sel2 = [sel2; j];\n%      end\n%    end\n% end\n\n% ensure that both are column vectors\na = a(:);\nb = b(:);\nNa = numel(a);\nNb = numel(b);\n\n% According to the original implementation empty numeric elements are\n% allowed, but are not returned as match. This is different to empty string\n% elements, which are returned as match.\n% See also http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1808\nempty_a = cellfun(@isnumeric, a) & cellfun(@isempty, a);\nempty_b = cellfun(@isnumeric, b) & cellfun(@isempty, b);\n% the following allows the unique function to operate normally\na(empty_a) = {''};\nb(empty_b) = {''};\n\n% replace all unique strings by a unique number and use the fact that\n% numeric comparisons are much faster than string comparisons\n[dum1, dum2, c] = unique([a; b]);\na = c(1:Na);\nb = c((Na+1):end);\n\n% empty numeric elements should never be returned as a match\na(empty_a) = nan;\nb(empty_b) = nan;\n\nif nargin < 3 || ~fullout\n  sel1 = [];\n  sel2 = [];\n  for i=1:length(a)\n    % s = find(strcmp(a(i), b));  % for string comparison\n    s = find(a(i)==b);            % for numeric comparison\n    sel2 = [sel2; s];\n    s(:) = i;\n    sel1 = [sel1; s];\n  end\nelse\n  sel1 = zeros(max(Na,Nb),1);\n  sel2 = zeros(max(Na,Nb),1);\n  for i=1:length(a)\n    s = find(a(i)==b);\n    sel2(s) = s;\n    sel1(s) = i;\n  end\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/utilities/match_str.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23988794777431952}}
{"text": "function printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,outputString,metaboliteList)\n% printFluxes\n%   Prints reactions and fluxes to the screen or to a file\n%\n%   model           a model structure\n%   fluxes          a vector with fluxes\n%   onlyExchange    only print exchange fluxes (opt, default true)\n%   cutOffFlux      only print fluxes with absolute values above or equal to this\n%                   value (opt, default 10^-8)\n%   outputFile      a file to save the print-out to (opt, default is output to\n%                   the command window)\n%   outputString    a string that specifies the output of each reaction (opt,\n%                   default '%rxnID\\t(%rxnName):\\t%flux\\n')\n%   metaboliteList  cell array of metabolite names. Only reactions\n%                   involving any of these metabolites will be\n%                   printed (opt)\n%\n%   The following codes are available for user-defined output strings:\n%\n%   %rxnID      reaction ID\n%   %rxnName    reaction name\n%   %lower      lower bound\n%   %upper      upper bound\n%   %obj        objective coefficient\n%   %eqn        equation\n%   %flux       flux\n%   %element    equation using the metabolite formulas rather than\n%               metabolite names\n%   %unbalanced \"(*)\" if the reaction is unbalanced and \"(-)\" if it could not\n%               be parsed\n%   %lumped     equation where the elemental compositions for the left/right\n%               hand sides are lumped\n%\n%   Usage: printFluxes(model, fluxes, onlyExchange, cutOffFlux,\n%           outputFile,outputString,metaboliteList)\n\nif nargin<3\n    onlyExchange=true;\nend\nif nargin<4\n    cutOffFlux=10^-8;\nend\nif isempty(cutOffFlux)\n    cutOffFlux=10^-8;\nend\nif nargin<5\n    fid=1;\nelse\n    if ~isempty(outputFile)\n        outputFile=char(outputFile);\n        fid=fopen(outputFile,'w');\n    else\n        fid=1;\n    end\nend\nif nargin<6 || isempty(outputString)\n    outputString='%rxnID\\t(%rxnName):\\t%flux\\n';\nelse\n    outputString=char(outputString);\nend\nif nargin<7\n    metaboliteList={};\nelse\n    metaboliteList=convertCharArray(metaboliteList);\nend\nif size(fluxes,1)~=numel(model.rxns)\n    EM='The number of fluxes and the number of reactions must be the same';\n    dispEM(EM);\nend\n\n%Only keep reactions involving the defined metabolites\nif ~isempty(metaboliteList)\n    I=ismember(upper(model.metNames),upper(metaboliteList));\n    [~, K]=find(model.S(I,:));\n    \n    %Delete all other reactions\n    toDelete=true(numel(model.rxns),1);\n    toDelete(K)=false;\n    model=removeReactions(model,toDelete);\n    fluxes(toDelete,:)=[];\nend\n\nif onlyExchange==true\n    fprintf(fid,'EXCHANGE FLUXES:\\n');\nelse\n    fprintf(fid,'FLUXES:\\n');\nend\n\n%Remove reactions which are below the cut off\ntoDelete=abs(fluxes)<cutOffFlux;\ntoDelete=all(toDelete,2);\nmodel=removeReactions(model,toDelete,true,true);\nfluxes(toDelete,:)=[];\n\nif any(strfind(outputString,'%eqn'))\n    %Construct the equations\n    eqn=constructEquations(model);\nelse\n    eqn=cell(numel(model.rxns),1);\n    eqn(:)={''};\nend\nif any(strfind(outputString,'%element'))\n    %For printing equations using the composition\n    cModel=model;\n    cModel.metNames=cModel.metFormulas;\n    cModel.metNames(cellfun(@isempty,cModel.metNames))={'?'};\n    element=constructEquations(cModel);\nelse\n    element=cell(numel(model.rxns),1);\n    element(:)={''};\nend\n\nif any(strfind(outputString,'%unbalanced')) || any(strfind(outputString,'%lumped'))\n    balanceStructure=getElementalBalance(model);\nend\n\nunbalanced=cell(numel(model.rxns),1);\nunbalanced(:)={''};\nif any(strfind(outputString,'%unbalanced'))\n    unbalanced(balanceStructure.balanceStatus==0)={'(*)'};\n    unbalanced(balanceStructure.balanceStatus<0)={'(-)'};\nend\n\nlumped=cell(numel(model.rxns),1);\nlumped(:)={''};\nif any(strfind(outputString,'%lumped'))\n    for i=1:numel(model.rxns)\n        leftGroup='';\n        rightGroup='';\n        for j=1:numel(balanceStructure.elements.names)\n            I=balanceStructure.leftComp(i,j);\n            if I~=0\n                if I==1\n                    leftGroup=[leftGroup balanceStructure.elements.abbrevs{j}];\n                else\n                    leftGroup=[leftGroup balanceStructure.elements.abbrevs{j} num2str(I)];\n                end\n            end\n            I=balanceStructure.rightComp(i,j);\n            if I~=0\n                if I==1\n                    rightGroup=[rightGroup balanceStructure.elements.abbrevs{j}];\n                else\n                    rightGroup=[rightGroup balanceStructure.elements.abbrevs{j} num2str(I)];\n                end\n            end\n        end\n        if model.rev(i)\n            lumped{i}=[leftGroup ' <=> ' rightGroup];\n        else\n            lumped{i}=[leftGroup ' => ' rightGroup];\n        end\n    end\nend\n\nfor i=1:numel(model.rxns)\n    %Only print if it's an exchange reaction or if all reactions should be\n    %printed. Exchange reactions only have reactants or only products.\n    reactants=model.S(:,i)<0;\n    products=model.S(:,i)>0;\n    \n    %Only print if the absolute value is >= cutOffFlux\n    if (onlyExchange==false || (~any(reactants) || ~any(products)))\n        printString=outputString;\n        \n        %Produce the final string\n        printString=strrep(printString,'%rxnID',model.rxns{i});\n        printString=strrep(printString,'%eqn',eqn{i});\n        printString=strrep(printString,'%rxnName',model.rxnNames{i});\n        printString=strrep(printString,'%lower',num2str(model.lb(i)));\n        printString=strrep(printString,'%upper',num2str(model.ub(i)));\n        printString=strrep(printString,'%obj',num2str(model.c(i)));\n        printString=strrep(printString,'%flux',num2str(fluxes(i,:)));\n        printString=strrep(printString,'%element',element{i});\n        printString=strrep(printString,'%unbalanced',unbalanced{i});\n        printString=strrep(printString,'%lumped',lumped{i});\n        fprintf(fid,printString);\n    end\nend\n\nif fid~=1\n    fprintf('File successfully saved.\\n');\n    fclose(fid);\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/core/printFluxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23988794777431952}}
{"text": "function bigclu(var1)\n    %bigclu.m                     A.Allmann\n    %function to select only clusters with spezial number values\n    %\n    % Last modification 8/95\n   global mess te1  sys\n    global tmp1 tmp2 cluslength\n    global freq_field1 freq_field2 close_button go_button\n    global backbgevent original equi bgevent backequi clu newclcat backcat\n    global equi_button bg_button\n    global plot1_h plot2_h file1 clust\n\n\n    if var1==1\n        figure_w_normalized_uicontrolunits(mess)\n        clf\n        set(gca,'visible','off');\n        set(gcf,'visible','off');\n        set(gcf,'Name','Number Selection');\n        cltemp=cluslength(equi(:,10));\n        tmp2=min(cltemp);\n        freq_field1= uicontrol('Style','edit',...\n            'Position',[.70 .60 .17 .10],...\n            'Units','normalized','String',num2str(tmp2),...\n            'Callback','tmp2=str2double(get(freq_field1,''String'')); set(freq_field1,''String'',num2str(tmp2));');\n\n        tmp1=max(cltemp);\n        freq_field2=uicontrol('Style','edit',...\n            'Position',[.70 .40 .17 .10],...\n            'Units','normalized','String',num2str(tmp1),...\n            'Callback','tmp1=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(tmp1));');\n\n        close_button=uicontrol('Style','Pushbutton',...\n            'Position', [.60 .05 .15 .15 ],...\n            'Units','normalized','Callback','welcome;done','String','Cancel');\n        go_button=uicontrol('Style','Pushbutton',...\n            'Position',[.25 .05 .15 .15 ],...\n            'Units','normalized',...\n            'Callback','welcome;done;bigclu(3);',...\n            'String','Go');\n\n\n        txt1 = text(...\n            'Color',[0 0 0 ],...\n            'EraseMode','normal',...\n            'Position',[0. 0.65 0 ],...\n            'Rotation',0 ,...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'FontWeight','bold' ,...\n            'String','Minimum Events in Cluster:');\n\n        txt2 = text(...\n            'Color',[0 0 0 ],...\n            'EraseMode','normal',...\n            'Position',[0. 0.40 0 ],...\n            'Rotation',0 ,...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'FontWeight','bold' ,...\n            'String','Maximum Events in Cluster:');\n\n        set(gcf,'visible','on')\n\n    elseif var1==3\n        figure_w_normalized_uicontrolunits(clu);\n        if isempty(newclcat)  &&  isempty(backcat)   %no selection before\n            backequi=equi;\n            backbgevent=bgevent;\n        end\n        tt= find(cluslength>=tmp2 & cluslength<=tmp1);\n        for j= tt\n            tt1=find(equi(:,10)==j);\n            if isempty(tt1)\n                tt1=0;\n            end\n            tt2(j)=tt1;\n        end\n        tmp=find(tt2);\n        equi=backequi(tmp,:);\n        bgevent=backbgevent(tmp,:);\n\n        set(equi_button,'value',1)\n        st1=get(equi_button,'Callback');\n        eval(st1);\n        pause(2);\n        tmpcat=clust(:,tmp);\n        newclcat=original(tmpcat(find(clust(:,tmp))),:);\n        plot1_h=[];plot2_h=[];\n        cluoverl(7);\n\n        strib=[' Polygon of  ' file1];\n        hold on\n        title(strib,'FontWeight','bold',...\n            'FontSize',ZmapGlobal.Data.fontsz.l,'Color','r')\n\n    end\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/declus/bigclu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23987421776365922}}
{"text": "%     THIS CODE IS FOR PLOTTING METRICS ON WAVEFORM\n%     THIS COULD BE ABSORBED INTO PLOT PANELS\n%     for arrivalnum=1:numel(arrivalobj.amp)\n%         fprintf('.');\n%         thisA = arrivalobj.subset(arrivalnum);\n%         thisW = detrend(fillgaps(w(arrivalnum),'interp')); % make sure there is no trend or offset\n% \n%         % plot waveform for arrival\n%         fh=plot_panels(thisW, false, thisA);\n%         ah=get(fh,'Children');\n%         set(fh, 'Position', [0 0 1600 1000]);\n%         hold on\n%         plot(maxSecs, misc_fields.maxAmp(arrivalnum), 'g*');\n%         plot(minSecs, misc_fields.minAmp(arrivalnum), 'r*');\n%         teststr = sprintf('maxTime = %s, minTime = %s, timeDiff = %.3f s\\namp = %.2e, maxAmp = %.2e, minAmp = %.2e\\n rms = %.2e, energy = %.2e',  ...\n%             datestr(maxTime,'HH:MM:SS.FFF'), ...\n%             datestr(minTime,'HH:MM:SS.FFF'), ...\n%             86400*(maxTime-minTime), ...\n%             amp, ...\n%             maxAmp, ...\n%             minAmp, ...\n%             stdev, ...\n%             energy);\n%         text(0.1, 0.1, teststr, 'units', 'normalized')\n%         dummy=input('Any key to continue');\n%         close\n% \n%     end", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/applications/rockets/infrasoundgt/addtoplotpanels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2398742118857534}}
{"text": "function z = minus( x, y, cheat )\n\n%   Disciplined convex programming information for MINUS:\n%      Terms in a difference must have opposite curvature. Real affine\n%      expressions are both convex and concave, so they can be involved\n%      in a difference with any nonlinear expression. Complex affine (or\n%      constant) expressions, however, are neither, so they can only be\n%      involved in differences with other affine expressions. So, for\n%      example, the following differences are valid:\n%         {convex}-{concave}   {concave}-{convex}   {affine}-{affine}\n%      The following are not:\n%         {convex}-{concave}  {convex}-{complex constant}\n%      For vectors, matrices, and arrays, these rules are verified\n%      independently for each element.\n%   \n%   Disciplined geometric programming information for MINUS:\n%      Non-constant expressions (log-convex or log-concave) may not be\n%      involved in a subtraction in disciplined geometric programs.\n\nif nargin < 3, cheat = false; end\nz = plus( x, y, true, cheat );\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23986766542353896}}
{"text": "function gptrain_options = get_GPTrainOptions(Ns_gp,hypstruct,optimState,stats,options)\n%GETGPTRAINOPTIONS Get options for training GP hyperparameters.\n\niter = optimState.iter;\nif iter > 1; rindex = stats.rindex(iter-1); else; rindex = Inf; end\n\ngptrain_options.OutwarpFun = optimState.gpOutwarpfun;\ngptrain_options.Thin = options.GPSampleThin;    % MCMC thinning\ngptrain_options.InitMethod = options.GPTrainInitMethod;\ngptrain_options.TolOpt = options.GPTolOpt;\ngptrain_options.TolOptMCMC = options.GPTolOptMCMC;\ngptrain_options.Widths = [];\n\n% Get hyperparameter posterior covariance from previous iters\nhypcov = GetHypCov(hypstruct,optimState,stats,options);    \n\n% Set up MCMC sampler\nswitch lower(options.GPHypSampler)\n    case {'slicesample'}\n        gptrain_options.Sampler = 'slicesample';        \n        if options.GPSampleWidths > 0 && ~isempty(hypcov)\n            widthmult = max(options.GPSampleWidths,rindex);\n            hypwidths = sqrt(diag(hypcov)');\n            gptrain_options.Widths = max(hypwidths,1e-3)*widthmult;\n        else\n            gptrain_options.Widths = [];\n        end\n    case {'npv'}\n        gptrain_options.Sampler = 'npv';\n    case {'mala'}\n        gptrain_options.Sampler = 'mala';        \n        if ~isempty(hypcov)\n            gptrain_options.Widths = sqrt(diag(hypcov)');\n        else\n            gptrain_options.Widths = [];\n        end\n        if isfield(optimState,'gpmala_stepsize')\n            gptrain_options.Stepsize = optimState.gpmala_stepsize;\n        end\n    case {'slicelite'}\n        gptrain_options.Sampler = 'slicelite';        \n        if options.GPSampleWidths > 0 && ~isempty(hypcov)\n            widthmult = max(options.GPSampleWidths,rindex);\n            hypwidths = sqrt(diag(hypcov)');\n            gptrain_options.Widths = max(hypwidths,1e-3)*widthmult;\n        else\n            gptrain_options.Widths = [];\n        end\n    case {'splitsample'}\n        gptrain_options.Sampler = 'splitsample';        \n        if options.GPSampleWidths > 0 && ~isempty(hypcov)\n            widthmult = max(options.GPSampleWidths,rindex);\n            hypwidths = sqrt(diag(hypcov)');\n            gptrain_options.Widths = max(hypwidths,1e-3)*widthmult;\n        else\n            gptrain_options.Widths = [];\n        end        \n    case 'covsample'\n        if options.GPSampleWidths > 0 && ~isempty(hypcov)\n            widthmult = max(options.GPSampleWidths,rindex);\n            if all(isfinite(widthmult)) && all(rindex < options.CovSampleThresh)\n                nhyp = size(hypcov,1);\n                gptrain_options.Widths = (hypcov + 1e-6*eye(nhyp))*widthmult^2;\n                gptrain_options.Sampler = 'covsample';\n                gptrain_options.Thin = gptrain_options.Thin*ceil(sqrt(nhyp));\n            else\n                hypwidths = sqrt(diag(hypcov)');\n                gptrain_options.Widths = max(hypwidths,1e-3)*widthmult;                    \n                gptrain_options.Sampler = 'slicesample';        \n            end\n        else\n            gptrain_options.Widths = [];\n            gptrain_options.Sampler = 'slicesample';        \n        end\n    case 'laplace'\n        gptrain_options.Widths = [];\n        if optimState.Neff < 30\n            gptrain_options.Sampler = 'slicesample';        \n            if options.GPSampleWidths > 0 && ~isempty(hypcov)\n                widthmult = max(options.GPSampleWidths,rindex);\n                hypwidths = sqrt(diag(hypcov)');\n                gptrain_options.Widths = max(hypwidths,1e-3)*widthmult;\n            end\n        else\n            gptrain_options.Sampler = 'laplace';\n        end\n\n    otherwise\n        error('vbmc:UnknownSampler', ...\n            'Unknown MCMC sampler for GP hyperparameters.');\nend\n\n% N-dependent initial training points\na = -(options.GPTrainNinit - options.GPTrainNinitFinal);\nb = -3*a;\nc = 3*a;\nd = options.GPTrainNinit;\nx = (optimState.Neff - options.FunEvalStart) / (min(options.MaxFunEvals,1e3)-options.FunEvalStart);\nf = @(x) a*x.^3 + b*x.^2 + c*x + d;\nNinit = max(round(f(x)),0);\n\n% Set other hyperparameter fitting parameters\nif optimState.RecomputeVarPost\n    gptrain_options.Burnin = gptrain_options.Thin*Ns_gp;\n    gptrain_options.Ninit = Ninit;\n    if Ns_gp > 0; gptrain_options.Nopts = 1; else; gptrain_options.Nopts = 2; end\nelse\n    gptrain_options.Burnin = gptrain_options.Thin*3;\n    if iter > 1 && stats.rindex(iter-1) < options.GPRetrainThreshold\n        gptrain_options.Ninit = 0;\n        if strcmpi(options.GPHypSampler,'slicelite')\n            gptrain_options.Burnin = max(1,ceil(gptrain_options.Thin*log(stats.rindex(iter-1))/log(options.GPRetrainThreshold)))*Ns_gp;\n            gptrain_options.Thin = 1;\n        end\n        if Ns_gp > 0; gptrain_options.Nopts = 0; else; gptrain_options.Nopts = 1; end            \n    else\n        gptrain_options.Ninit = Ninit;\n        if Ns_gp > 0; gptrain_options.Nopts = 1; else; gptrain_options.Nopts = 2; end\n    end\nend\n\n%gptrain_options.Burnin = 1000;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction hypcov = GetHypCov(hypstruct,optimState,stats,options)\n%GETHYPCOV Get hyperparameter posterior covariance\n\nif optimState.iter > 1\n    if options.WeightedHypCov\n        w_list = [];\n        hyp_list = [];\n        w = 1;\n        for i = 1:optimState.iter-1\n            if i > 1\n                % diff_mult = max(1,log(stats.rindex(optimState.iter-i+1)));\n                diff_mult = max(1, ...\n                    log(stats.sKL(optimState.iter-i+1) ./ (options.TolsKL*options.FunEvalsPerIter)));\n                w = w*(options.HypRunWeight^(options.FunEvalsPerIter*diff_mult));\n            end\n            if w < options.TolCovWeight; break; end     % Weight is getting too small, break\n\n            hyp = stats.gpHypFull{optimState.iter-i};\n            nhyp = size(hyp,2);\n            if isempty(hyp_list) || size(hyp_list,2) == size(hyp,1)\n                hyp_list = [hyp_list; hyp'];\n                w_list = [w_list; w*ones(nhyp,1)/nhyp];\n            end\n        end\n        \n        w_list = w_list / sum(w_list);                  % Normalize weights\n        mustar = sum(bsxfun(@times,w_list,hyp_list),1); % Weighted mean\n\n        % Weighted covariance matrix\n        nhyp = size(hyp_list,2);        \n        hypcov = zeros(nhyp,nhyp);\n        for j = 1:size(hyp_list,1)\n            hypcov = hypcov + ...\n                w_list(j)*(hyp_list(j,:)-mustar)'*(hyp_list(j,:)-mustar);            \n        end\n        hypcov = hypcov/(1-sum(w_list.^2));\n        \n    else\n        hypcov = hypstruct.runcov;\n    end\nelse\n    hypcov = [];\nend\n\nend\n", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/misc/get_GPTrainOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23986766542353893}}
{"text": "function anal = er_chopTSeriesraw(view,coords,scans,varargin);\n\n% anal = er_chopTSerieskgs(view,[roi],[scans],varargin);\n%\n% Concatenates tSeries from the selected scans together,\n% chops up according to the assigned parfiles, and returns\n% an analysis struct with the following fields:\n%\n%   allTcs:\n%   meanTcs:\n%   sems:\n%   amps:\n%   relamps:\n%   hMat:\n%   pMat:\n%\n%\n% 06/17/04 ras: wrote it.\n% 07/08/04 kgs modified\nglobal dataTYPES;\n\nif ieNotDefined('coords')\n    rois = viewGet(view,'rois');\n    selRoi = viewGet(view,'selectedroi');\n    coords = rois(selRoi).coords;\nend\n\ndt = viewGet(view,'curdt');\n\nif ieNotDefined('scans')\n    [scans dt] = er_getScanGroup(view);\n    view = viewSet(view,'curdt',dt);\nend\n\n%%%%% params/defaults %%%%%\nnormBsl = 1;            % flag to zero baseline or not 0 does not removed baseline\nalpha = 0.05;           % threshold for significant activations\nTR = dataTYPES(dt).scanParams(scans(1)).framePeriod;\nbslPeriod = [-4:0 ];  % period to use as baseline in t-tests, in seconds\npeakPeriod = 8:12; % 6:12      % period to look for peaks in t-tests, in seconds\ntimeWindow = -4:20;            % seconds relative to trial onset to take for each trial\nonsetDelta = -4;               % # secs to shift onsets in parfiles, relative to time course\nprestim=-4;                    % secs before stim onset for which the window is calculated\n\n%%%%% parse the options %%%%%\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch lower(varargin{i})\n        case 'normbsl', normBsl = varargin{i+1};\n        case 'alpha', alpha = varargin{i+1};\n        case 'peakperiod', peakPeriod = varargin{i+1};\n        case 'timewindow', timeWindow = varargin{i+1};\n        case 'scans', scans = varargin{i+1};\n        case 'dt', dt = varargin{i+1};\n        case 'onsetdelta', onsetDelta = varargin{i+1};\n        otherwise, % ignore\n        end\n    end\nend\n\n%%%%% concatenate tSeries from selected scans\nallt = [];\nfprintf('Loading tSeries from selected scans ... \\t');\nfor s = scans\n%   subt = meanTSeries(view,s,coords);\n     subt = meanTSeriesraw(view,s,coords);\n     \n % get raw detrended TC without % siganl\n\n %   another option is to use rory;s code\n %    tS = getTseriesOneROI(view,coords,s,1);\n %    get raw time series\n %    subt = mean(tS{1},2);\n   allt = [allt subt'];\n   fprintf('%i ',s);\nend\nfprintf('\\n');\n\n%%%%% get parfile info, if it's not passed in in varargin\ntrials = er_concatParfiles(view,scans);\ntrials.onsetSecs = trials.onsetSecs + onsetDelta;\ntrials.onsetFrames = trials.onsetFrames + onsetDelta/TR;\n\n%%%%% get nConds from trials struct\nnConds = max(trials.cond);\nnTrials = length(scans); % current operating assumption\n\n%%%%% get a set of label names, if they were specified in the parfiles\nfor i = 1:nConds\n    ind = find(trials.cond==i);\n    labels{i} = trials.label{ind(1)};\nend\n\n%%%%% convert params expressed in secs into frames\nframeWindow = unique(round(timeWindow./TR));\nprestim = -1 * frameWindow(1);\npeakFrames = unique(round(peakPeriod./TR))\nbslFrames = unique(round(bslPeriod./TR));\npeakFrames = find(ismember(frameWindow,peakFrames))\nbslFrames = find(ismember(frameWindow,bslFrames));\n\n%%%%% build tc matrix of trials x time points x conditions\n%%%%% take (frameWindow) secs from each trial\ntc = zeros(length(scans),length(frameWindow),nConds);\n\nfor i = 1:nConds\n   ind = find(trials.cond==i);\n   for j = 1:length(scans)\n       tstart = trials.onsetFrames(ind(j));\n       tend = min([tstart+frameWindow(end),length(allt)]);\n       rng = tstart:tend;\n\n       % add prestim\n       if ind(j)==1 \n           % for 1st trial, no baseline available -- set to 0\n           tc(j,:,i) = [zeros(1,prestim) allt(rng)];\n       else\n           % augment the range by previous [prestim] frames\n           fullrng = rng(1)-prestim:rng(end);         \n           tc(j,1:length(fullrng),i) = allt(fullrng);   \n       end\n       \n       % remove baseline estimate, if selected\n       if normBsl\n           % estimate DC offset by prestim baseline vals\n           DC = mean(tc(j,bslFrames,i));\n           tc(j,:,i) = tc(j,:,i) - DC;\n       end\n   end \nend \n\n%%%%% get tcs, sems for each condition\ntcs = zeros(length(frameWindow),nConds);\nsems = zeros(length(frameWindow),nConds);\n\nfor i = 1:nConds\n    tcs(:,i) = mean(tc(:,:,i))';\n    sems(:,i) = std(tc(:,:,i))' ./ sqrt(nTrials);\nend\n\n%%%%% do t-tests of post-baseline v. baseline\nHs = NaN*ones(1,nConds);\n\nfor i = 1:nConds\n    bsl = tc(:,bslFrames,i);\n    peak = tc(:,peakFrames,i);\n    [Hs(i) ps(i)] = ttest2(bsl(:),peak(:),alpha,-1);\n    amps(:,i) = (mean(peak,2) - mean(bsl,2))/100+1;\nend\nsize(amps)\nsize(peakFrames)\nsize(peak)\nsize(bsl)\n%%%%% compute Signal-to-Noise Ratio\nallBsl = tcs(bslFrames,:,:);\nallPk = tcs(peakFrames,:,:);\nSNR = abs(mean(allPk(:)) - mean(allBsl(:))) / std(allBsl(:));\n\n%%%%% compute relamps \n% the resulting matrix will be of size\n% nTrials x nConds (have to shuffle things around)\nrelamps = fmri_relamps(permute(tc,[2 3 1]));\n\n%%%%% assign everything to the output struct\nanal.meanTcs = tcs;\nanal.sems = sems;\nanal.Hs = Hs;\nanal.ps = ps;\nanal.labels = labels;\nanal.timeWindow = TR .* frameWindow;\nanal.peakPeriod = [min(peakPeriod):TR:max(peakPeriod)];\nanal.peakFrames=peakFrames;\nanal.bslPeriod = TR .* bslFrames;\nanal.amps = amps;\nanal.relamps = relamps;\nanal.SNR = SNR;\nanal.SNRdb = 20 * log10(SNR);\n\n% assign all time courses, but\n% shuffle it into column former -- it's nicer\nanal.allTcs = permute(tc,[2 1 3]);\n\n\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/er_chopTSeriesraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23986766542353893}}
{"text": "function [caNodeIndices, vResolution_] = ex_CreateIndexCatalog3D(mCatalog, mPolygon, bMap, nGriddingMode, fSmpValue, fSmpBnd, fSizeRectHorizontal, fSizeRectDepth)\n    % Creates a cell-array with subcatalogs for every grid node defined by mPolygon.\n    %\n    % [caNodeIndices] = ex_CreateIndexCatalog(mCatalog, mPolygon, bMap, nGriddingMode,\n    %                                                  nNumberEvents, fRadius, fSizeRectHorizontal, fSizeRectDepth)\n    % -------------------------------------------------------------------------------------------------------------\n    % Creates a cell-array with subcatalogs for every grid node defined by mPolygon. These subcatalogs\n    %   contain only indices to the earthquake \"rows\" in mCatalog.\n    %\n    % Input parameters:\n    %   mCatalog              Earthquake catalog\n    %   mPolygon              Polygon (defined by ex_selectgrid)\n    %   bMap                  Calculate cell-array for a map (true) or a cross-section (false)\n    %   nGriddingMode         Mode of creating grid node subcatalogs\n    %                         0: Constant number of events\n    %                         1: Constant radius\n    %                         2: Rectangular grid node samples\n    %                         3: Spherical grid node samples with constant no\n    %                            of events\n    %                         4: Spherical grid node samples with constant radius\n    %   nNumberEvents         Number of events per grid node (nGriddingMode == 0)\n    %   fRadius               Radius of grid node sample (nGriddingMode == 1)\n    %   fSizeRectHorizontal   Latitude/horizontal size of rectangle (nGriddingMode == 2)\n    %   fSizeRectDepth        Longitude/depth size of rectangle (nGriddingMode == 2)\n    %\n    % Output parameters:\n    %   caNodeIndices         Cell-array with index-catalogs per grid node of mPolygon\n    %\n    % Danijel Schorlemmer\n    % June 17, 2002\n    \n    report_this_filefun();\n    \n    % Create the catalogs for each node with pointers to the overall catalog\n    nNumberNodes_ = length(mPolygon(:,1));\n    caNodeIndices = cell(nNumberNodes_, 1);\n    \n    % If cross-section calculate the length along cross-section\n    if ~bMap\n        nRow_ = mCatalog.Count;\n        vXSecX_ = mCatalog(:,nColumn_);  % length along x-section\n        vXSecY_ = (-1) * mCatalog.Depth;  % depth of hypocenters\n    end\n    \n    \n    % vResolution give the radius (for nGriddingMode = 4) and no. of events\n    % (for nGriddingMode = 3)\n    vResolution_(:,1)=nan(nNumberNodes_,1)\n    if ((nGriddingMode == 3) || (nGriddingMode ==4)) clear vResolution_; end\n    \n    \n    % Loop over all points of the polygon\n    for nNode_ = 1:nNumberNodes_\n        % Get the grid node coordinates\n        fX_ = mPolygon(nNode_, 1);\n        fY_ = mPolygon(nNode_, 2);\n        if size(mPolygon,2)==3\n            fZ_ = mPolygon(nNode_, 3);\n        end\n        \n        if (nGriddingMode == 0) | (nGriddingMode == 1)  % Fixed radius or fixed number\n            % Calculate distance from center point\n            if bMap\n                vDistances_ = sqrt(((mCatalog.Longitude-fX_)*cosd(fY_)*111).^2 + ((mCatalog.Latitude-fY_)*111).^2);\n            else\n                vDistances_ = sqrt(((vXSecX_ - fX_)).^2 + ((vXSecY_ - fY_)).^2);\n            end\n            if nGriddingMode == 0 % Fixed number\n                if mCatalog.Count == 0\n                    caNodeIndices{nNode_} = [];\n                    % NaN for no events\n                    vResolution_(nNode_) = nan;\n                elseif nNumberEvents > mCatalog.Count\n                    caNodeIndices{nNode_} = vIndices(1:mCatalog.Count);\n                    % take the maximal distance for all eq. in the catalog\n                    vResolution_(nNode_) = max(vdistances_);\n                else\n                    % Use first nNumberEvents events\n                    [vTmp, vIndices] = sort(vDistances_);\n                    caNodeIndices{nNode_} = vIndices(1:nNumberEvents);\n                    % radius of the nNumberEvents-th event in the sorted vDistances_\n                    vResolution_(nNode_) = vTmp(nNumberEvents);\n                end\n            else % Fixed radius\n                % Use all events within fRadius\n                caNodeIndices{nNode_} = find(vDistances_ <= fRadius);\n                vResolution_(nNode_) = length(find(vDistances_ <= fRadius));\n            end\n        elseif nGriddingMode ==2  % Rectangular gridding (nGriddingMode == 2)\n            if bMap\n                vSel_ = ((mCatalog.Longitude >= (fX_ - fSizeRectHorizontal/2)) & (mCatalog.Longitude < (fX_ + fSizeRectHorizontal/2)) & ...\n                    (mCatalog.Latitude >= (fY_ - fSizeRectDepth/2)) & (mCatalog.Latitude < (fY_ + fSizeRectDepth/2)));\n                vResolution_(nNode_) = length(find(vSel_ > 0))\n            else\n                vSel_ = ((vXSecX_ >= (fX_ - fSizeRectHorizontal/2)) & (vXSecX_ < (fX_ + fSizeRectHorizontal/2)) & ...\n                    (vXSecY_ >= (fY_ - fSizRectDepth/2)) & (vXSecY_ < (fY_ + fSizeRectDepth/2)));\n                vResolution_(nNode_) = length(find(vSel_ > 0))\n            end\n            caNodeIndices{nNode_} = find(vSel_ == 1);\n        elseif ((nGriddingMode == 3) || (nGriddingMode == 4))     % Spherical grid node samples with constant no of events\n            vDistances_ = sqrt(((mCatalog.Longitude-fX_)*cosd(fY_)*111).^2 + ((mCatalog.Latitude-fY_)*111).^2 + (mCatalog.Depth-fZ_).^2);\n            if nGriddingMode == 3  % Spherical grid node samples with constant no of events\n                nNumberEvents=fSmpValue;\n                fRadius=fSmpBnd;\n                if mCatalog.Count == 0\n                    caNodeIndices{nNode_} = [];\n                    % NaN for no events\n                    vResolution_{nNode_} = nan;\n                    %               vResolution_(nNode_) = nan;\n                elseif nNumberEvents > mCatalog.Count\n                    caNodeIndices{nNode_} = vIndices(1:mCatalog.Count);\n                    % take the maximal distance for all eq. in the catalog\n                    vResolution_{nNode_} = vdistances_;\n                    %               vResolution_(nNode_) = max(vdistances_);\n                else\n                    % Use first nNumberEvents events\n                    [vTmp, vIndices] = sort(vDistances_);\n                    caNodeIndices{nNode_} = vIndices(1:nNumberEvents);\n                    % radius of the nNumberEvents-th event in the sorted vDistances_\n                    vResolution_{nNode_} = vTmp(nNumberEvents);\n                    %               vResolution_(nNode_) = vTmp(nNumberEvents);\n                end\n            elseif nGriddingMode == 4     % Spherical grid node samples with constant radius\n                nNumberEvents=fSmpBnd;\n                fRadius=fSmpValue;\n                %  muss noch gemacht werden....\n                \n            end\n        end\n    end % of for nNode_\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/thomas/slabanalysis/ex_CreateIndexCatalog3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23986765986737874}}
{"text": "%% KUKA sunrise toolbox example.\n% moving end-effector of the robot on an ellipse by utilizing the point to\n% point elliptical motion functions of the KST\n\n% Copy right: Mohammad SAFEEA\n% 30-April-2018\n\nglobal t_Kuka;\nip='172.31.1.147';\nt_Kuka=net_establishConnection(ip);\n\nif ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')\n  disp('Connection could not be establised, script aborted');\n  return;\nend\n\n%% Go to some initial configuration\ndisp('moving in joint space to initial configuration');\njPos={0., pi / 180 * 30, 0, -pi / 180 * 60, 0,...\n                        pi / 180 * 90, 0};\ndisp(jPos);\nrelVel=0.15;\nmovePTPJointSpace( t_Kuka , jPos, relVel); % move to initial configuration\n\n%% move a little bit back on the X direction\ndisp('moving -60 mm in the X direction')\ndeltaX=-60;deltaY=0;deltaZ=0.;\nPos{1}=deltaX;\nPos{2}=deltaY;\nPos{3}=deltaZ;\nvel=50;\nmovePTPLineEefRelBase( t_Kuka , Pos, vel);\n   \n%% put the pen on the level of the page\ndisp('moving -85 mm in the Z direction')\ndeltaX=0;deltaY=0;deltaZ=-85.;\nPos{1}=deltaX;\nPos{2}=deltaY;\nPos{3}=deltaZ;\nvel=50;\nmovePTPLineEefRelBase( t_Kuka , Pos, vel);\npause(1);\n \n%% Define the ellipse,\ndisp('Drawing an ellipse in a plane parallel to XY axes of the base')\nc=[0; 50]; % this is the displacement of the center of the ellipse with respect to the current position of EEF,\n% taken in the XY plane of the robot base \nratio=0.5; % the radious ratio (a/b) of the ellipse\nvelocity=40;\naccel=25;\ntheta=2*pi;\nTefTool=eye(4);\nmovePTPEllipse_XY(t_Kuka,c,ratio,theta,velocity,accel,TefTool);\n\n%% Define the ellipse, dimentsions are in (meter)\ndisp('Drawing an ellipse in a plane parallel to XY axes of the base')\nc=[0; 50]; % this is the displacement of the center of the ellipse with respect to the current position of EEF,\n% taken in the XZ plane of the robot base \nratio=0.5; % the radious ratio (a/b) of the ellipse\nvelocity=40;\naccel=25;\ntheta=2*pi;\nTefTool=eye(4);\nmovePTPEllipse_XZ(t_Kuka,c,ratio,theta,velocity,accel,TefTool);\n\n%% Define the ellipse, dimentsions are in (meter)\ndisp('Drawing an ellipse in a plane parallel to XY axes of the base')\nc=[0; 50]; % this is the displacement of the center of the ellipse with respect to the current position of EEF,\n% taken in the YZ plane of the robot base \nratio=0.5; % the radious ratio (a/b) of the ellipse\nvelocity=40;\naccel=25;\ntheta=2*pi;\nTefTool=eye(4);\nmovePTPEllipse_YZ(t_Kuka,c,ratio,theta,velocity,accel,TefTool);\n\nnet_turnOffServer(t_Kuka);\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/Tutorial_moveOnEllipticalTrajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%    gb 05/05/05\n%\n% This script has to be executed directly in the command line\n% It plots the MSE graphs for all the sujects that are in the repository\n% folder : /Snarp/u1/data/reading_longitude/fmri\n%\n% After a graph is displayed, type Enter to plot the next one.\n%\n% Type Ctrl + c in the command line to terminate the program\n%\n% Just make sure the VISTASOFT directory is in the path and type :\n% scriptReadMSE\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclose all\nclear all\n\nif isunix\n    networkPath = '/snarp1/u1';\nelse\n    networkPath = '\\\\snarp\\u1\\';\nend\n\nrootDir = fullfile(networkPath,'data','reading_longitude','fmri');\n\ncd(rootDir);\n[fileNum dirName] = countDirs(pwd);\n\nfor count = 3:fileNum\n    try\n        currentDir = dirName{count};\n    \n        cd(fullfile(rootDir,currentDir));\n        motionCompPlotMSE(currentDir);\n        pause;\n          \n    end\n        \n    close all;\n    \nend    ", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/MotionComp/MI/Scripts/scriptReadMSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "function [cpulse, verbose] = tapas_physio_get_cardiac_pulses_manual_template(...\n    c, t, pulse_detect_options, verbose)\n% Detects R-peaks via matched-filter smoothing & peak detection using a\n% manually defined QRS-wave (or R-peak environment)\n%\n%   [cpulse, verbose] = tapas_physio_get_cardiac_pulses_manual_template(...\n%    c, t, thresh_min, dt120, verbose)\n%\n% IN\n%   c               [nSamples, 1] raw pulse oximeter samples\n%   t               [nSamples, 1] time vector corresponding to samples (un seconds)\n%   pulse_detect_options   \n%                   physio.thresh.cardiac.initial_cpulse_select-substructure\n%                   with elements\n%                   .method 'manual' or 'load'/'load_template'\n%                           'manual' - select template manually\n%                           'load'/'load_template' - load from template\n%                   .min     threshold for correlation with QRS-wave to find cardiac pulses\n%                   .file   variable saving an example cardiac QRS-wave to correlate with ECG time series\n%   verbose         Substructure of Physio, holding verbose.level and\n%                   verbose.fig_handles with plotted figure handles\n%                   debugging plots for thresholding are only provided, if verbose.level >=2\n%\n% OUT\n%\n% EXAMPLE\n%   tapas_physio_get_cardiac_pulses_manual_template\n%\n%   See also tapa_physio_new\n\n% Author: Lars Kasper\n% Created: 2012-02-20\n% Copyright (C) 2014 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.\n%\n% This file is part of the physIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\nif nargin < 5\n    verbose.level = 0;\n    verbose.fig_handles = [];\nend\n\n% manual peak selection, if no file selected and loading is\n% specified\n\nhasKrpeakLogfile = exist(pulse_detect_options.file,'file') || ...\n    exist([pulse_detect_options.file '.mat'],'file');\n\n% if no file exists, also do manual peak-find\ndoSelectTemplateManually = any(strcmpi(...\n    pulse_detect_options.method, ...\n    {'manual', 'manual_template'})) || ~hasKrpeakLogfile;\n\nif doSelectTemplateManually\n    pulse_detect_options.kRpeak = [];\n    hasECGMin = isfield(pulse_detect_options, 'min') && ~isempty(pulse_detect_options.min);\n    if ~hasECGMin\n        pulse_detect_options.min = 0.5;\n    end\nelse\n    fprintf('Loading %s\\n', pulse_detect_options.file);\n    ECGfile = load(pulse_detect_options.file);\n    pulse_detect_options.min = ECGfile.ECG_min;\n    pulse_detect_options.kRpeak = ECGfile.kRpeak;\nend\n\ninp_events = [];\nECG_min = pulse_detect_options.min;\nkRpeak = pulse_detect_options.kRpeak;\nif doSelectTemplateManually\n    while ECG_min\n        [cpulse, ECG_min_new, kRpeak] = tapas_physio_find_ecg_r_peaks(t,c, ECG_min, [], inp_events);\n        fprintf('Press 0, then return, if right ECG peaks were found\\n');\n        ECG_min = input('otherwise type next numerical choice for ECG_min and continue the selection: ');\n    end\nelse\n    [cpulse, ECG_min_new, kRpeak] = tapas_physio_find_ecg_r_peaks(t,c, ECG_min, kRpeak, inp_events);\nend\nECG_min = ECG_min_new;\ncpulse = t(cpulse);\n\n% save manually found peak parameters to file\nif doSelectTemplateManually\n    save(pulse_detect_options.file, 'ECG_min', 'kRpeak');\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/preproc/tapas_physio_get_cardiac_pulses_manual_template.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "function [VOLLOCS, LOCS] = tapas_physio_create_scan_timing_nominal(t, ...\n    sqpar, align_scan, durationPhyslogAfterEndOfLastScan)\n% Creates locations of scan volume and slice events in time vector of SCANPHYSLOG-files\n%\n%   [VOLLOCS, LOCS] = tapas_physio_create_scan_timing_nominal(t, sqpar);\n%\n% In cases where the SCANPHYSLOG-file has no gradient entries (column\n% 7-9), the actual time-course of the sequence has to be inferred from the\n% nominal sequence parameters in sqpar. Here, the corresponding slice scan\n% events are generated for the resampling of regressors in the GLM under\n% the assumption that the SCANPHYSLOG-file ended exactly when the scan ended\n% ...which is usually the case if a scan is not stopped manually\n% \n% Additionally, one can set a buffer end time, i.e., the duration of the\n% phys logging lasting longer after the end of the last scan\n%\n% IN\n%   t       - timing vector of SCANPHYSLOG-file, usually sampled with 500\n%             Hz (Philips)\n%   sqpar                   - sequence timing parameters\n%           .Nslices        - number of slices per volume in fMRI scan\n%           .NslicesPerBeat - usually equals Nslices, unless you trigger with the heart beat\n%           .TR             - repetition time in seconds\n%           .Ndummies       - number of dummy volumes\n%           .Nscans         - number of full volumes saved (volumes in nifti file,\n%                             usually rows in your design matrix)\n%           .Nprep          - number of non-dummy, volume like preparation pulses\n%                             before 1st dummy scan. If set, logfile is read from beginning,\n%                             otherwise volumes are counted from last detected volume in the logfile\n%           .time_slice_to_slice - time between the acquisition of 2 subsequent\n%                             slices; typically TR/Nslices or\n%                             minTR/Nslices, if minimal temporal slice\n%                             spacing was chosen\n%           .onset_slice    - slice whose scan onset determines the adjustment of the\n%                             regressor timing to a particular slice for the whole volume\n%   align_scan              'first' or 'last' (default)\n%                           'first' t == 0 will be aligned to first scan\n%                                   volume, first slice\n%                           'last'  t(end) will be aligned to last scan\n%                                   volume, last slice\n%   durationPhyslogAfterEndOfLastScan\n%                            duration (in seconds) of physiological logfile\n%                            after end of last scan volume in the run\n%                           default: 0\n% OUT\n%           VOLLOCS         - locations in time vector, when volume scan\n%                             events started\n%           LOCS            - locations in time vector, when slice or volume scan\n%                             events started\n% EXAMPLE\n%   [VOLLOCS, LOCS] = tapas_physio_create_scan_timing_nominal(t, sqpar);\n%\n%   See also\n\n% Author: Lars Kasper\n% Created: 2013-02-07\n% Copyright (C) 2013 Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\nif nargin < 3\n    align_scan = 'last';\nend\n\nif nargin < 4\n    durationPhyslogAfterEndOfLastScan = 0;\nend\n\nNscans          = sqpar.Nscans;\nNdummies        = sqpar.Ndummies;\n\nNallVols = (Ndummies+Nscans);\nVOLLOCS = NaN(NallVols,1);\nTR = sqpar.TR;\n\n\n%% First, find volume starts either forward or backward through time series\ndo_count_from_start = strcmpi(align_scan, 'first');\nif do_count_from_start % t = 0 is assumed to be the start of the scan\n    for n = 1:NallVols\n        [tmp, VOLLOCS(n)] = min(abs(t - TR*(n-1)));\n    end\nelse\n    tEndLastScan = t(end)-durationPhyslogAfterEndOfLastScan;\n    \n    tStartPhys = t(1);\n    for n = 1:NallVols\n        \n        tStartVol = (tEndLastScan-TR*(NallVols-n+1));\n        \n        if tStartPhys > tStartVol\n            VOLLOCS(n) = NaN;\n        else\n            [tmp, VOLLOCS(n)] = min(abs(t - tStartVol));\n        end\n    end\nend\n\n%% Then, find slice starts between determined volume starts\n\nLOCS = tapas_physio_create_LOCS_from_VOLLOCS(VOLLOCS, t, sqpar);\n\n\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/sync/tapas_physio_create_scan_timing_nominal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23959215602694084}}
{"text": "function build_mmx(verbose)\n% BUILD_MMX - compiles mmx() for different platforms and provides help\n%            regarding compilation.\n%\n%  BUILD_MMX will try to compile, in this order, 3 different builds of mmx:\n%  mmx_mkl_single    - linked to Intel's single-threaded MKL library (usually fastest)\n%  mmx_mkl_multi     - linked to the multithreaded BLAS/LAPACK libraries that come\n%                      with Matlab.\n%  mmx_naive         - does not link to anything, uses simple C-loops.\n%\n%  The first time BUILD_MMX succeeds, it will compile again to 'mmx', so\n%  that the mex-file mmx should be the fastest possible build on your\n%  system.\n%\n%  BUILD_MMX has been tested on Win32, Win64, OSX, Linux 64\n%\n\n% %% FOR LINUX OR MAC SYSTEMS:\n% \n% To properly link to Intel's MKL, user needs to repackage their libraries \n% into one single statically linked library. The instructions are as\n% follows:\n%\n%\n% Download Intel MKL for Linux here:\n% http://software.intel.com/en-us/articles/non-commercial-software-download/\n%\n% Donwload Intel MKL for Mac here:\n% https://registrationcenter.intel.com/RegCenter/AutoGen.aspx?ProductID=1518&AccountID=&EmailID=&ProgramID=&RequestDt=&rm=EVAL&lang=\n%\n% The Default installation directory for both Linux and Mac will be\n% /opt/intel/\n% with the MKL libraries in /opt/intel/mkl\n%\n% %% To build needed static Library\n%    assuming default installation directory\n%\n% Run the following commands in Linux/Mac terminal:\n%\n% sudo -s\n% cd /opt/intel/mkl/tools/builder\n% cat blas_example_list > blas_lapack_list\n% cat lapack_example_list >> blas_lapack_list\n%\n% For Linux 64 bit:\n% make libintel64 interface=ilp64 export=blas_lapack_list name=libsingle_mkl_ilp64 threading=sequential\n% For Linux 32 bit:\n% make libia32 interface=lp64 export=blas_lapack_list name=libsingle_mkl_32 threading=sequential\n%\n% For Mac:\n% make libuni interface=ilp64 export=blas_lapack_list name=libsingle_mkl_ilp64 threading=sequential\n%\n% A new libsingle_mkl_ilp64.so, libsingle_mkl_32.so, or \n% libsingle_mkl_ilp64.dylib will appear.\n% This needs to be copied to Matlab's external libraries directory.\n%\n% For Mac:\n% cp libsingle_mkl_ilp64* MATLAB_ROOT/extern/lib/maci64\n%\n% For Linux 64 bit:\n% cp libsingle_mkl_ilp64* MATLAB_ROOT/extern/lib/glnxa64\n% For Linux 32 bit:\n% cp libsingle_mkl_32* MATLAB_ROOT/extern/lib/glnx86\n%\n% Where MATLAB_ROOT is the installation directory of your Matlab.\n\n\nif nargin == 0\n   verbose = false;\nend\n\nclc\n\nbuild_names  = {'mmx_mkl_single', 'mmx_mkl_multi','mmx_naive'};\n\nbuilt_mmx   = false;\n\narch        = computer('arch');\n\nfor b = 1:3\n   name = build_names{b};\n   \n   [link, define]  = deal({});\n   [inc_dir, link_dir, Cflags, Lflags]  = deal('');\n   \n   switch arch\n      case {'win64','win32'}\n         switch name\n            case 'mmx_naive'\n               define   = {'WIN_SYSTEM'};\n               \n            case 'mmx_mkl_multi'\n               root     = matlabroot;\n               if strcmp(arch,'win32')\n                  inc_dir  = [root '\\extern\\lib\\win32\\microsoft'];\n               else\n                  inc_dir  = [root '\\extern\\lib\\win64\\microsoft'];\n               end\n               link     = {'libmwblas','libmwlapack'};\n               define   = {'WIN_SYSTEM','USE_BLAS'};\n               \n            case 'mmx_mkl_single'\n               root     = 'C:\\Program Files (x86)\\Intel\\Composer XE 2011 SP1\\mkl';\n               inc_dir  = [root '\\include'];\n               if strcmp(arch,'win32')\n                  link_dir  = [root '\\lib\\ia32'];\n                  link     = {'mkl_intel_c','mkl_sequential','mkl_core'};\n                  define   = {'WIN_SYSTEM','USE_BLAS','MKL_32'};\n               else\n                  link_dir  = [root '\\lib\\intel64'];\n                  link     = {'mkl_intel_ilp64','mkl_sequential','mkl_core'};\n                  define   = {'WIN_SYSTEM','USE_BLAS','MKL_ILP64'};\n               end\n         end\n      case {'glnxa64','glnx86'}\n         switch name\n            case 'mmx_naive'\n               link     = {'pthread'};\n               define   = {'UNIX_SYSTEM'};\n            case 'mmx_mkl_multi'\n               if strcmp(arch,'glnx86')\n               inc_dir  = [matlabroot '/extern/lib/glnx86'];\n               else\n               inc_dir  = [matlabroot '/extern/lib/glnxa64'];\n               end\n               link     = {'mwblas','mwlapack','pthread'};\n               define   = {'UNIX_SYSTEM','USE_BLAS'};\n            case 'mmx_mkl_single'\n               root = '/opt/intel/mkl';\n               inc_dir  = [ root '/include'];\n               if strcmp(arch,'glnx86')\n                link_dir  = [matlabroot '/extern/lib/glnx86'];\n                link     = {'single_mkl_32','pthread'};\n                define   = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_32'};\n               else\n                link_dir  = [matlabroot '/extern/lib/glnxa64'];\n                link     = {'small_mkl_ilp64','pthread'};\n                define   = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_ILP64'};\n               end\n         end\n      case {'maci64'}\n         switch name\n            case 'mmx_naive'\n               link     = {'pthread'};\n               define   = {'UNIX_SYSTEM'};\n               \n            case 'mmx_mkl_multi'\n               root     = matlabroot;\n               inc_dir  = [root '/extern/lib/maci64'];\n               link     = {'mwblas','mwlapack','pthread'};\n               define   = {'UNIX_SYSTEM','USE_BLAS'};\n               \n            case 'mmx_mkl_single'\n               root     = '/opt/intel/mkl';\n               inc_dir  = [ root '/include'];\n               link_dir = [matlabroot '/extern/lib/maci64'];\n               link     = {'single_mkl_ilp64','pthread'};\n               %link     = {'small_mkl_ilp64','pthread'};\n               define   = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_ILP64'};\n         end\n         \n      otherwise\n         error unsupported_architecture\n   end\n   \n   if ~isempty(link_dir)\n      if strcmp(arch,'glnxa64') || strcmp(arch,'maci64')\n         L_dir  = {['LDFLAGS=\"\\$LDFLAGS -L' link_dir  ' ' Lflags '\"']};\n      else\n         L_dir  = {['-L' link_dir]};\n      end\n   else\n      L_dir  = {};\n   end\n   \n   if ~isempty(inc_dir)\n      if strcmp(arch,'glnxa64') || strcmp(arch,'maci64')\n         I_dir  = {['CXXFLAGS=\"\\$CXXFLAGS -I' inc_dir ' ' Cflags '\"']};\n      else\n         I_dir  = {['-I' inc_dir]};\n      end\n   else\n      I_dir  = {};\n   end\n   \n   prefix   = @(pref,str_array) cellfun(@(x)[pref x],str_array,'UniformOutput',0);\n   l_link   = prefix('-l',link);\n   D_define = prefix('-D',define);\n   \n   if verbose\n      verb  = {'-v'};\n   else\n      verb  = {};\n   end\n   \n   try\n      check_dir(link_dir, link)\n      check_dir(inc_dir)\n      clear(name)\n      command = {verb{:}, I_dir{:}, L_dir{:}, l_link{:}, D_define{:}}; %#ok<*CCAT>\n      fprintf('==========\\nTrying to compile ''%s'', using \\n',name);\n      fprintf('%s, ',command{:})\n      fprintf('\\n')\n      mex(command{:}, '-output', name, 'mmx.cpp');\n      fprintf('Compilation of ''%s'' succeeded.\\n',name);\n      if ~built_mmx\n         fprintf('Compiling again to ''mmx'' target using ''%s'' build.\\n',name);\n         mex(command{:}, '-output','mmx','mmx.cpp');\n         built_mmx = true;\n      end\n   catch err\n      fprintf('Compilation of ''%s'' failed with error:\\n%s\\n',name,err.message);\n   end\nend\n\nfunction check_dir(dir,files)\nif ~isempty(dir)\n   here = cd(dir);\n   if nargin == 2\n      for i = 1:size(files)\n         if isempty(ls(['*' files{i} '.*']))\n            cd(here);\n            error('could not find file %s', files{i});\n         end\n      end\n   end\n   cd(here);\nend\n\n\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/tests/test_multi/mmx-master/src/build_mmx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23959215063535605}}
{"text": "% Copyright 2011 Zdenek Kalal\n%\n% This file is part of TLD.\n% \n% TLD is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TLD is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TLD.  If not, see <http://www.gnu.org/licenses/>.\n\n% modified by Yu Xiang\n\nfunction tracker = LK_tracking(frame_id, dres_image, dres_det, tracker)\n\n% current frame + motion\nJ = dres_image.Igray{frame_id};\nctrack = apply_motion_prediction(frame_id, tracker);\nw = tracker.dres.w(end);\nh = tracker.dres.h(end);\nBB3 = [ctrack(1)-w/2; ctrack(2)-h/2; ctrack(1)+w/2; ctrack(2)+h/2]; \n[J_crop, BB3_crop, bb_crop, s] = LK_crop_image_box(J, BB3, tracker);\n\nnum_det = numel(dres_det.x);\nfor i = 1:tracker.num\n    BB1 = [tracker.x1(i); tracker.y1(i); tracker.x2(i); tracker.y2(i)];\n    I_crop = tracker.Is{i};\n    BB1_crop = tracker.BBs{i};\n    \n    % LK tracking\n    [BB2, xFJ, flag, medFB, medNCC, medFB_left, medFB_right, medFB_up, medFB_down] = LK(I_crop, J_crop, ...\n        BB1_crop, BB3_crop, tracker.margin_box, tracker.level_track);\n    \n    BB2 = bb_shift_absolute(BB2, [bb_crop(1) bb_crop(2)]);\n    BB2 = [BB2(1)/s(1); BB2(2)/s(2); BB2(3)/s(1); BB2(4)/s(2)];\n\n    ratio = (BB2(4)-BB2(2)) / (BB1(4)-BB1(2));\n    ratio = min(ratio, 1/ratio);\n    \n    if isnan(medFB) || isnan(medFB_left) || isnan(medFB_right) || isnan(medFB_up) || isnan(medFB_down) ...\n            || isnan(medNCC) || ~bb_isdef(BB2) || ratio < tracker.max_ratio\n        medFB = inf;\n        medFB_left = inf;\n        medFB_right = inf;\n        medFB_up = inf;\n        medFB_down = inf;\n        medNCC = 0;\n        o = 0;\n        score = 0;\n        ind = 1;\n        angle = -1;\n        flag = 2;\n        BB2 = [NaN; NaN; NaN; NaN];\n    else\n        % compute overlap\n        dres.x = BB2(1);\n        dres.y = BB2(2);\n        dres.w = BB2(3) - BB2(1);\n        dres.h = BB2(4) - BB2(2);\n        if isempty(dres_det.fr) == 0\n            overlap = calc_overlap(dres, 1, dres_det, 1:num_det);\n            [o, ind] = max(overlap);\n            score = dres_det.r(ind);\n        else\n            o = 0;\n            score = -1;\n            ind = 0;\n        end\n        \n        % compute angle\n        centerI = [(BB1(1)+BB1(3))/2 (BB1(2)+BB1(4))/2];\n        centerJ = [(BB2(1)+BB2(3))/2 (BB2(2)+BB2(4))/2];\n        v = compute_velocity(tracker);\n        v_new = [centerJ(1)-centerI(1), centerJ(2)-centerI(2)] / double(frame_id - tracker.frame_ids(i));\n        if norm(v) > tracker.min_vnorm && norm(v_new) > tracker.min_vnorm\n            angle = dot(v, v_new) / (norm(v) * norm(v_new));\n        else\n            angle = 1;\n        end        \n    end\n    \n    tracker.bbs{i} = BB2;\n    tracker.points{i} = xFJ;\n    tracker.flags(i) = flag;\n    tracker.medFBs(i) = medFB;\n    tracker.medFBs_left(i) = medFB_left;\n    tracker.medFBs_right(i) = medFB_right;\n    tracker.medFBs_up(i) = medFB_up;\n    tracker.medFBs_down(i) = medFB_down;\n    tracker.medNCCs(i) = medNCC;\n    tracker.overlaps(i) = o;\n    tracker.scores(i) = score;\n    tracker.indexes(i) = ind;\n    tracker.angles(i) = angle;\n    tracker.ratios(i) = ratio;\nend\n\n% combine tracking and detection results\n% [~, ind] = min(tracker.medFBs);\nind = tracker.anchor;\nif tracker.overlaps(ind) > tracker.overlap_box\n    index = tracker.indexes(ind);\n    bb_det = [dres_det.x(index); dres_det.y(index); ...\n        dres_det.x(index)+dres_det.w(index); dres_det.y(index)+dres_det.h(index)];\n    tracker.bb = mean([repmat(tracker.bbs{ind}, 1, tracker.weight_tracking) bb_det], 2);\nelse\n    tracker.bb = tracker.bbs{ind};\nend\n\n% compute pattern similarity\nif bb_isdef(tracker.bb)\n    pattern = generate_pattern(dres_image.Igray{frame_id}, tracker.bb, tracker.patchsize);\n    nccs = distance(pattern, tracker.patterns, 1); % measure NCC to positive examples\n    tracker.nccs = nccs';\nelse\n    tracker.nccs = zeros(tracker.num, 1);\nend    \n\nif tracker.is_show\n    fprintf('\\ntarget %d: frame ids ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%d ', tracker.frame_ids(i))\n    end\n    fprintf('\\n');    \n    fprintf('target %d: medFB ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medFBs(i))\n    end\n    fprintf('\\n');\n    \n    fprintf('target %d: medFB left ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medFBs_left(i))\n    end\n    fprintf('\\n');\n    \n    fprintf('target %d: medFB right ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medFBs_right(i))\n    end\n    fprintf('\\n');\n    \n    fprintf('target %d: medFB up ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medFBs_up(i))\n    end\n    fprintf('\\n');\n    \n    fprintf('target %d: medFB down ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medFBs_down(i))\n    end\n    fprintf('\\n');       \n    \n    fprintf('target %d: medNCC ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.medNCCs(i))\n    end\n    fprintf('\\n');\n    \n    fprintf('target %d: overlap ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.overlaps(i))\n    end\n    fprintf('\\n');\n    fprintf('target %d: detection score ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.scores(i))\n    end\n    fprintf('\\n');\n    fprintf('target %d: flag ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%d ', tracker.flags(i))\n    end\n    fprintf('\\n');\n    fprintf('target %d: angle ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.angles(i))\n    end\n    fprintf('\\n');\n    fprintf('target %d: ncc ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.nccs(i))\n    end\n    fprintf('\\n\\n');\n    fprintf('target %d: bb overlaps ', tracker.target_id);\n    for i = 1:tracker.num\n        fprintf('%.2f ', tracker.bb_overlaps(i))\n    end\n    fprintf('\\n\\n');\n\n    if tracker.flags(ind) == 2\n        fprintf('target %d: bounding box out of image\\n', tracker.target_id);\n    elseif tracker.flags(ind) == 3\n        fprintf('target %d: too unstable predictions\\n', tracker.target_id);\n    end\nend", "meta": {"author": "yuxng", "repo": "MDP_Tracking", "sha": "2f452a1f7204b6e3344925b8eaf39db1c7eecf2c", "save_path": "github-repos/MATLAB/yuxng-MDP_Tracking", "path": "github-repos/MATLAB/yuxng-MDP_Tracking/MDP_Tracking-2f452a1f7204b6e3344925b8eaf39db1c7eecf2c/LK_tracking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.23951826245574254}}
{"text": "classdef ConvergencePlotComputerMaterialDesignExperimentPoisson < handle\n    \n    properties (Access = public)\n        \n    end\n    \n    properties (Access = private)\n        filesPath\n        testNames\n        linesData\n        barData\n        fieldsData\n        outPutPlotPath\n        alphas\n    end\n    \n    properties (Access = private)\n        \n    end\n    \n    methods (Access = public)\n        \n        function obj = ConvergencePlotComputerMaterialDesignExperimentPoisson()\n            obj.init();\n            obj.loadFieldsData();\n            obj.plotData();\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj)\n            obj.filesPath = '/media/alex/MyPassport/MaterialDesign/CStar/';\n            obj.outPutPlotPath = '/home/alex/Dropbox/MaterialDesign/CC/Poisson/';\n            %obj.linesData = [1:2,5:10];\n            %obj.barData = [3:4];\n            obj.linesData = [1:6,9:15];\n            obj.barData = [7:8];\n            obj.testNames = {'NegPoissonNoPerimeter5x6/'};\n        end\n        \n        function loadFieldsData(obj)\n            for iCase = 1:numel(obj.testNames)\n                testPath = fullfile(obj.filesPath,obj.testNames{iCase},'/');\n                s.testPath  = testPath;\n                s.linesData = obj.linesData;\n                s.barData   = obj.barData;\n                m = MonitoringDataLoader(s);\n                obj.fieldsData{iCase} = m.obtainData();\n            end\n        end\n        \n        function plotData(obj)\n            p{1} = obj.plotCost();\n            p{2} = obj.plotVolum();\n            f = figure(1);\n            legend({'$||\\bf{C}(\\rho) - {C}^*||_2$','$\\textrm{Vol}(\\rho)$'},'Interpreter','latex','Location','Best');\n            p = plotPrinter(f,p);\n            p.print(fullfile(obj.outPutPlotPath,'CostAndVolume'))\n        end\n        \n        function p = plotCost(obj)\n            for iCase = 1:numel(obj.testNames)\n                fieldData = obj.fieldsData{iCase};\n                fieldToPlot = 'C - C not scaled';\n                [x,y] = obj.obtainField(fieldToPlot,fieldData);\n                p = semilogy(x,y);\n                hold on\n            end\n        end\n        \n        function p = plotVolum(obj)\n            figure(1)\n            hold on\n            yyaxis right\n            for iCase = 1:numel(obj.testNames)\n                fieldData = obj.fieldsData{iCase};\n                fieldToPlot = 'Volum';\n                [x,y] = obj.obtainField(fieldToPlot,fieldData);\n                p = plot(x,y);\n                ylim([0,1])\n                hold on\n            end\n        end\n        \n    end\n    \n    methods (Access = private, Static)\n\n        function [xV,yV] = obtainField(fieldName,fieldData)\n            for iField = 1:numel(fieldData)\n                title = fieldData{iField}.title;\n                if strcmp(fieldName,title)\n                    xV = fieldData{iField}.xValue;\n                    yV = fieldData{iField}.yValue;\n                end\n            end\n        end\n        \n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/MaterialDesign/ConvergencePlotComputerMaterialDesignExperimentPoisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.23950805348964435}}
{"text": "%% Example\n% This script is used to initialize the hand guiding functionality on KUKA\n% robot remotely\n\n% Mohammad SAFEEA, 9th of June 2017\n\n% TO use this example:\n% 1- Start the server on KUKA\n% 2- Start the client on Matlab\n% 3- Press the white button and hand guide the robot\n% 4- To save the coordinates of the robot, long click on the green button\n% 5- Repeat three times\n% 6- The robot gives you an interval of five seconds, clear the area around\n% the robot directly, the robot will reproduce the motion tought.\n\nclose all;clear;clc;\nwarning('off')\n%% Create the robot object\nip='172.31.1.147'; % The IP of the controller\narg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820\narg2=KST.Medien_Flansch_Touch_pneumatisch; % choose the type of flange\nTef_flange=eye(4); % transofrm matrix of EEF with respect to flange\niiwa=KST(ip,arg1,arg2,Tef_flange); % create the object\n\n%% Start a connection with the server\nflag=iiwa.net_establishConnection();\nif flag==0\n  return;\nend\npause(1);\n\n   \niiwa.startHandGuiding()\n\np1 = iiwa.getJointsPos();\n      \niiwa.startHandGuiding()       \n \np2 = iiwa.getJointsPos();\n\niiwa.startHandGuiding()     \n \np3 = iiwa.getJointsPos();\n\niiwa.startHandGuiding()        \n \n\nfprintf('CLear the area round the robot, the robot is going to move');\n\npause(5)\n\n\nrelVel=0.1;\niiwa.movePTPJointSpace(p1, relVel)\niiwa.movePTPJointSpace(p2, relVel)\niiwa.movePTPJointSpace(p3, relVel)\n\n%% turn off the server\niiwa.net_turnOffServer();\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/KSTclass_Tutorial_HandTeaching.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23950804663043068}}
{"text": "function varargout = aibcutpush(varargin)\n% VL_AIBCUTPUSH  Quantize based on VL_AIB cut\n%  Y = VL_AIBCUTPUSH(MAP, X) maps the data X to elements of the AIB\n%  cut specified by MAP.\n%\n%  The function is equivalent to Y = MAP(X).\n%\n%  See also: VL_HELP(), VL_AIB().\n[varargout{1:nargout}] = vl_aibcutpush(varargin{:});\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/noprefix/aibcutpush.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23950804663043068}}
{"text": "function net = pairwise(arg)\n\n% PAIRWISE\n%\n% Construct a pairwise multi-class support vector classification network.\n%\n% Examples:\n%\n%    % default constructor (a 0-class pairwise network!)\n%\n%    net1 = pairwise;\n%\n%    % copy constructor\n%\n%    net2 = pairwise(net1);\n%\n%    % construct pairwise multi-class svc from a vector of two-class networks\n%\n%    net3 = pairwise(net)\n\n%\n% File        : @pairwise/pairwise.m\n%\n% Date        : Wednesday 13th September 2000\n%\n% Author      : Dr Gavin C. Cawley\n%\n% Description : Constructor for a class providing a framework for constructing\n%               multi-class support vector classification networks from a set\n%               of two-class networks using the pairwise rule.  Part of an\n%               object-oriented implementation of Vapnik's Support Vector\n%               Machine, as described in [1].\n%\n% References  : [1] V.N. Vapnik,\n%                   \"The Nature of Statistical Learning Theory\",\n%                   Springer-Verlag, New York, ISBN 0-387-94559-8,\n%                   1995.\n%\n% History     : 13/09/2000 - v1.00\n%\n% Copyright   : (c) Dr Gavin C. Cawley, September 2000\n%\n%    This program is free software; you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation; either version 2 of the License, or\n%    (at your option) any later version.\n%\n%    This program is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this program; if not, write to the Free Software\n%    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n\nif nargin == 0\n   \n   % this is the default constructor\n   \n   net.net = svc;\n   net     = class(net, 'pairwise');\n   \nelseif nargin == 1\n\n   if isa(arg, 'pairwise');\n   \n      % this is the copy constructor\n   \n      net = arg;\n\n   end\n   \nelseif nargin > 1\n\n   % there are no other constructors\n   \n   help pairwise\n\nelse\n   \n   net.net = arg;\n   net     = class(net, 'pairwise');\n   \nend\n\n% bye bye...\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/RSVista/mrMethods/svm/cawleyTools/@pairwise/pairwise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23950804663043068}}
{"text": "%kEllipse 'Ellipse Object Menuform'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Ellipse.pane file\n%\n% Parameters: \n%\n% Example: kEllipse( {})\n%\n% Khoros helpfile follows below:\n% .begin tagged\n% \n% .item \"The Ellipse Visual Object\"\n% An ellipse visual object supports the display of an ellipse annotation.\n% The (x, y) location of the ellipse, its width and height may be specified in\n% device coordinates or world coordinates by the application.  The menuform,\n% however, displays the world coordinates of the ellipse, regardless of whether \n% the application used world or device coordinates to specify that location.  \n% Attributes of the circle object that can be interactively specified in addition \n% to its world coordinates include its border width, border type, border color, \n% whether or not it is filled, and (if it is filled), its fill color.\n% \n% .item \"Filled\"\n% When set to true, this attribute indicates that the ellipse should be filled\n% with the fill color (background color).\n% \n% .item \"Border Width\"\n% This list selection allows you to set the line width used by\n% the ellipse object. Line widths range from \"Extra Fine\" to \"Extra Wide\".\n% \n% .item \"Border Type\"\n% This list selection lets you set the line type used on\n% the ellipse object. There are seven line types, including \"Solid\",\n% \"Dotted\", \"Dot Dash\", \"Short Dash\", \"Long Dash\", \"Odd Dash\", and\n% \"Grid Dotted\".\n% \n% .item \"Border Color\"\n% This stringlist selection lets you set the border color (foreground color)\n% of the ellipse object, using the color name.\n% \n% .item \"Fill Color\"\n% This stringlist selection lets you set the fill color (background color)\n% of the ellipse object, using the color name.\n% \n% .item \"X Circle, Y Circle\"\n% This pair of double values specifies the (x, y) location of the ellipse object\n% on its parent in world coordinates.  The world coordinate range of the ellipse\n% is specified by the application, and thus varies depending on context.\n% \n% .item \"Width\"\n% This double value specifies the width of the ellipse in world coordinates.\n% \n% .item \"Height\"\n% This double value specifies the height of the ellipse in world coordinates.\n% \n% .end tagged\n\n\nfunction varargout = kEllipse(varargin)\nInputs={};\nif nargin ==0\n  arglist={'',''};\nelseif nargin ==1\n  arglist=varargin{1};\nelse error('Usage: [out1,..] = kEllipse(arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={};\nmaxval={};\nminval={};\nistoggle=[];\nwas_set=istoggle * 0;\nparamtype={};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=0; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(0);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\ncallKhoros([w 'Ellipse\" '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.23950804663043065}}
{"text": "% IMAGESCTC - DEPRECATED. never completed or documented.\n% IMAGESCTC - imagesc in true color. Can help plot different\n%               colormap on the same window.\n%\n% Usage: same as imagesctc\n%\n% Example:\n%         figure; \n%         colormap(jet); \n%         subplot(1,2,1); imagesctc(rand(10,10));\n%         colormap(gray); \n%         subplot(1,2,2); imagesctc(rand(10,10));\n% \n% Author: Arnaud Delorme, CNL / Salk Institute, 31 July 2002\n%\n% See also: IMAGE, IMAGESC\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nif ~isempty(varargin)\n\timagesc(a, varargin{:});\nelse\n\timagesc(a);\nend\nc = caxis;\n\ncm = colormap;\nintervals = linspace(c(1), c(2), size(cm,1));\n[tmp dest] = histc(a(:), intervals);\n\nfor wi = 1:size(a,2)\n\tfor hi = 1:size(a,1)\n\t\taa(hi,wi,1:3) = cm(dest(hi+(wi-1)*size(a,1)),1:3);\n\tend\nend\nif ~isempty(varargin)\n\timagesc(aa, varargin{:});\nelse\n\timagesc(aa);\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/imagesctc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481726820828}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction cb = compactbit(b)\n%\n% b = bits array\n% cb = compacted string of bits (using words of 'word' bits)\n\n[nSamples nbits] = size(b);\nnwords = ceil(nbits/8);\ncb = zeros([nSamples nwords], 'uint8');\n\nfor j = 1:nbits\n    w = ceil(j/8);\n    cb(:,w) = bitset(cb(:,w), mod(j-1,8)+1, b(:,j));\nend", "meta": {"author": "willard-yuan", "repo": "hashing-baseline-for-image-retrieval", "sha": "822837884bdb5d44e297015d05ad081cea695a56", "save_path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval/hashing-baseline-for-image-retrieval-822837884bdb5d44e297015d05ad081cea695a56/utils/compactbit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481080113598}}
{"text": "%testGrowthExpMatch tests the functionality of all the components of growthExpMatch\n%\n%Procedure to run growthExpMatch:\n%(1) obtain all input files (ie. model, CompAbr, and KEGGID are from BiGG, KEGGList is from KEGG website)\n%(2) remove desired reaction from model with removeRxns, or set the model \n%       on a particular Carbon or Nitrogen source\n%(3) create an SUX Matrix by using the function MatricesSUX = \n%       generateSUXMatrix(model,Dictionary, KEGGFilename,Compartment)\n%(4) run it through growthExpMatch using [solution,b,solInt]=Smiley(MatricesSUX)\n%(5) solution.importedRxns contains the solutions to all iterations (in\n%       this particular test, we removed reaction ENO from model and\n%       obtained 'R00658_f' which is the KEGGID for ENO\n%\n%   Joseph Kang 11/16/09\n%   Adaptions to CI - Thomas Pfau Okt 2017\n\nglobal CBTDIR\n\noriFolder = pwd;\n\n%moves to testing folder that contains testGrowthExpMatch\ntest_folder = fileparts(which('testGrowthExpMatch.m'));\ncd(test_folder);\n\n%load Model\nmodel = getDistributedModel('ecoli_core_model.mat');\n\n%removes reaction ENO\ndisp('------------------------------------')\ndisp('Removing reaction, ENO, from test model:')\nmodel = removeRxns(model, 'ENO');\n\n%moves to folder w/ input files\n% w = what('testing');\n% p = w.path;\n% cd(p);\nd = load([test_folder filesep 'Dictionary.mat']);\nKEGGFilename = 'testTest_KEGG_Reaction_List.lst';\n\n%Test for the default solvers\nsolverPkgs = {'gurobi', 'glpk'};\n\nfor k = 1:length(solverPkgs)\n    fprintf('   Running solveCobraLPCPLEX using %s ... ', solverPkgs{k});\n\n    % change the COBRA solver \n    solverOKLP = changeCobraSolver(solverPkgs{k}, 'LP', 0);\n    solverOKMILP = changeCobraSolver(solverPkgs{k}, 'MILP', 0);\n    \n    if solverOKLP && solverOKMILP\n        %runs growthExpMatch and obtains solution\n        [solution]=growthExpMatch(model, KEGGFilename,'[c]', 1, d.dictionary);\n        \n        %if R00658_f is solution result, returns a positive answer, else negative\n        assert(isequal(solution.importedRxns, {{'R00658_f'}}))\n    end\nend\n%perform cleanup \nif exist([test_folder filesep 'GEMLog_solution_1.mat'],'file')\n    delete('GEMLog_solution_1.mat')\nend\nif exist([test_folder filesep 'CobraMILPSolver.log'],'file')\n    delete('CobraMILPSolver.log')\nend\nif exist([test_folder filesep 'GEMLog.txt'],'file')\n    delete('GEMLog.txt')\nend\nclose all \n\ncd(oriFolder);\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/reconstruction/testGrowthExpMatch/testGrowthExpMatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23919816829148827}}
{"text": "function makespectrogramthumbnails(spectrogramFilename, spectrogramFraction)\ndebug.printfunctionstack('>');\n\n% figure 1 should be a large spectrogram with traces, cropped nicely. Now remove labels and maximise panels.\n\nax=get(gcf, 'Children');\n\n% Work out number of channels\npos1 = get(ax(1),'position'); % top trace\npos2 = get(ax(2),'position'); % top sgram\nheight_per_channel = pos1(4) + pos2(4);\nnumchannels = 0.95 / height_per_channel;\nnumpanels = numchannels * 2;\n\nnew_height_per_channel = 1 / numchannels;\n\n% Remove all axes, tickmarks, labels, and axis boxes and title from view\nfor c=1:numpanels\n    set(ax(c), 'Visible', 'off')\nend\n\n% Move panels\nfor channelNum = 1:numchannels\n    [spectrogramPosition, tracePosition] = iceweb.calculatePanelPositions(numchannels, numchannels - channelNum + 1, spectrogramFraction, 0.0, 0.0, 1, 1);\n    set(ax(channelNum*2 - 1), 'position', tracePosition);\n    set(ax(channelNum*2), 'position', spectrogramPosition);\nend\n\n% we need a name for the labelless large spectrogram\n[tmppath, tmpbase, tmpext] = fileparts(spectrogramFilename);\ntmpfile = sprintf('%s/%s_labelless%s',tmppath,tmpbase,tmpext);\n\n% print large labelless PNG\niceweb.saveImageFile(tmpfile, 72);\n\n% load then delete temporary file \nI = imread(tmpfile);\ndelete(tmpfile)\n\n% Resize the image (aspect ratio 16:21 same as 576:756) and convert it to an indexed image with 256 colors\n% (Note: we were originally creating 150x96, which is far off the aspect ratio of large spectrograms)\n%[X,map] = rgb2ind(imresize(I, [126 96]), 256);\n%thumbnailfile = sprintf('%s/smallest_%s%s',tmppath, tmpbase, tmpext);\n%imwrite(X,map,thumbnailfile,'PNG'); \n%[X,map] = rgb2ind(imresize(I, [147 112]), 256);\n%thumbnailfile = sprintf('%s/smaller_%s%s',tmppath, tmpbase, tmpext);\n%imwrite(X,map,thumbnailfile,'PNG'); \n[X,map] = rgb2ind(imresize(I, [198 151]), 256);\nthumbnailfile = sprintf('%s/%s_thumb%s',tmppath, tmpbase, tmpext);\nimwrite(X,map,thumbnailfile,'PNG'); \nclose;\n\ndebug.printfunctionstack('<');\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/applications/+iceweb/makespectrogramthumbnails.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109062}}
{"text": "% Description : This is a matlab file for video enhancement. \n% The following file works with color, b&w images. \n% User defined functions : 1) image_enhancement_sw - modified retinex algorithm\n%                          2) gray_level_images    - contrast enhancement\n% Author : Vijay Sridharan. \n% Date   : 20th July, 2012. \n%% Video Enhancement for color and black and white images    \nvideo = VideoReader('air.avi');\n    for i = 1:video.NumberOfFrames\n        img = read(video,i);\n        imwrite(img,sprintf('img%d.jpg',i));\n    end\n    fprintf('Please wait....');\n    filebase = dir('*.jpg');                      % If you are using a continous frame of images, start from here. \n    num_files = numel(filebase);\n    images = cell(1, num_files);\n     MS=cell(1,num_files);\n     for k = 1:num_files\n         images{k} = imread(filebase(k).name);\n         [rows columns color]=size(images{1});\n         if (color==3)\n             MS{k}=image_enhancement_sw(images{k});\n             M(k)=im2frame(MS{k});\n         else\n             MS{k}=gray_level_images(images{k}); % For gray level images, movie/implay doesn't work. So, I would suggest you\n                                                 % to download FIJI or ImageJ to view the sequence of images as Videos. The                                                                                               \n         end                                     % default frame rate is 8fps in FIJI\n     end\nmovie(M)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37578-video-enhancement/video enhancement/video_enhancement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109057}}
{"text": "function Script_CECLM_cross_data()\n\naddpath(genpath('../'));\n\n[images, detections, labels] = Collect_menpo_imgs('G:\\Datasets\\menpo/');\n\n%% loading the CE-CLM model and parameters   \n[patches, pdm, clmParams, early_term_params] = Load_CECLM_general();\nviews = [0,0,0; 0,-30,0; 0,30,0; 0,-55,0; 0,55,0; 0,0,30; 0,0,-30; 0,-90,0; 0,90,0; 0,-70,40; 0,70,-40];\nviews = views * pi/180;\n        \n% As early termination weights were trained on part of menpo turn them off, \n% to perform a clean cross-data experiment\nearly_term_params.weights_scale(:) = 1;\nearly_term_params.weights_add(:) = 0;\nearly_term_params.cutoffs(:) = -0.2;\n\n% Use the multi-hypothesis model, as bounding box tells nothing about\n% orientation\nmulti_view = true;\n\n%% Setup recording\nexperiment.params = clmParams;\n\nnum_points = numel(pdm.M)/3;\n\nshapes_all = cell(numel(images), 1);\nlabels_all = cell(numel(images), 1);\nlhoods = zeros(numel(images),1);\nall_lmark_lhoods = zeros(num_points, numel(images));\nall_views_used = zeros(numel(images),1);\n\n% Change if you want to visualize the outputs\nverbose = false;\noutput_img = false;\n\nif(output_img)\n    output_root = './ceclm_gen_out/';\n    if(~exist(output_root, 'dir'))\n        mkdir(output_root);\n    end\nend\nif(verbose)\n    f = figure;\nend\n%% Fitting the model to the provided images\ntic\nfor i=1:numel(images)\n    image = imread(images(i).img);\n    image_orig = image;\n    \n    if(size(image,3) == 3)\n        image = rgb2gray(image);\n    end              \n\n    bbox = squeeze(detections(i,:));                  \n    \n    % The actual work get's done here\n    [shape,~,~,lhood,lmark_lhood,view_used] =...\n        Fitting_from_bb_multi_hyp(image, [], bbox, pdm, patches, clmParams, views, early_term_params);\n\n    all_lmark_lhoods(:,i) = lmark_lhood;\n    all_views_used(i) = view_used;\n\n    shapes_all{i} = shape;\n    labels_all{i} = labels{i};\n\n    if(mod(i, 200)==0)\n        fprintf('%d done\\n', i );\n    end\n\n    lhoods(i) = lhood;\n    \n    if(output_img)\n        v_points = logical(patches(1).visibilities(view_used,:))';\n        DrawFaceOnImg(image_orig, shape, sprintf('%s/%s%d.jpg', output_root, 'fit', i), bbox, v_points);\n    end\n    \n    if(verbose)\n        v_points = logical(patches(1).visibilities(view_used,:))';\n        DrawFaceOnFig(image_orig, shape, bbox, v_points);\n    end\n        \nend\ntoc\n\nexperiment.lhoods = lhoods;\nexperiment.shapes = shapes_all;\nexperiment.labels = labels_all;\nexperiment.all_lmark_lhoods = all_lmark_lhoods;\nexperiment.all_views_used = all_views_used;\n\n%%\noutput_results = 'results/results_ceclm_cross-data.mat';\nsave(output_results, 'experiment');\n    \nend\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/experiments_menpo/Script_CECLM_cross_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.23913813979781748}}
{"text": "function [ctHandle,cMap,window] = matRad_plotCtSlice(axesHandle,ctCube,cubeIdx,plane,slice,cMap,window)\n% matRad function that generates the plot for the CT in the GUI \n% The function can also be used in personal matlab figures by passing the\n% corresponding axes handle\n%\n% call\n%   [ctHandle,cMap,window] = matRad_plotCtSlice(axesHandle,ctCube,cubeIdx,plane,slice)\n%   [ctHandle,cMap,window] = matRad_plotCtSlice(axesHandle,ctCube,cubeIdx,plane,slice,cMap)\n%   [ctHandle,cMap,window] = matRad_plotCtSlice(axesHandle,ctCube,cubeIdx,plane,slice,window)\n%   [ctHandle,cMap,window] = matRad_plotCtSlice(axesHandle,ctCube,cubeIdx,plane,slice,cMap,window)\n%\n% input\n%   axesHandle  handle to axes the slice should be displayed in\n%   ctCube      the cell of ct cubes\n%   cubeIdx     Index of the desired cube in the ct struct\n%   plane       plane view (coronal=1,sagittal=2,axial=3)\n%   slice       slice in the selected plane of the 3D cube\n%   cMap        optional argument defining the colormap, default is bone\n%               if you want to use the default map with the window argument\n%               you can use an empty array []\n%   window      optional argument defining the displayed range. default is\n%               [min(ctCube(:)) max(ctCube(:))]\n%\n% output\n%   ctHandle    handle of the plotted CT axes\n%   cMap        used colormap (same as input if set)\n%   window      used window (same as input if set)\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmatRad_cfg = MatRad_Config.instance();\n\n%Use default colormap?\nif nargin < 6 || isempty(cMap)\n    cMap = bone(64);\nend\n\nif nargin < 7 || isempty(window)\n    window = [min(ctCube{cubeIdx}(:)) max(ctCube{cubeIdx}(:))];    \nend\n\ncMapScale = size(cMap,1) - 1;\n\n%Prepare the slice and convert it to uint8\nif plane == 1 % Coronal plane\n\tctIndexed = uint8(cMapScale*(squeeze((ctCube{cubeIdx}(slice,:,:)-window(1))/(window(2) - window(1)))));      \nelseif plane == 2 % sagittal plane\n    ctIndexed = uint8(cMapScale*(squeeze((ctCube{cubeIdx}(:,slice,:)-window(1))/(window(2) - window(1)))));\t\nelseif plane == 3 % Axial plane\n    ctIndexed = uint8(cMapScale*(squeeze((ctCube{cubeIdx}(:,:,slice)-window(1))/(window(2) - window(1)))));\nelse\n\tmatRad_cfg.dispError('Invalid plane ''%d'' selected for visualization!',plane);\nend\n\n%This circumenvents a bug in Octave when the index in the image hase the maximum value of uint8\nif matRad_cfg.isOctave\n\tctIndexed(ctIndexed == 255) = 254;\nend\n\nct_rgb = ind2rgb(ctIndexed,cMap);\n\nctHandle = image('CData',ct_rgb,'Parent',axesHandle);\n\nend\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/plotting/matRad_plotCtSlice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.23913813979781745}}
{"text": "function [f, lb, ub, A_x, be_u_abs, be_l_abs, s_current_m, error_state] = ...\n    prepareOptimizationProblem(VehicleDynamicState, dot_d_numerical, PathPos, v_traj, ...\n    ax_diff_traj, ax_traj, ay_traj, ax_lim_mps2, ay_lim_mps2, ...\n    d_lim_ub_m, d_lim_lb_m, d_Target_m, dot_d_Target_mps, ...\n    vx_lin, kappa_lin, UncertaintyTube, v_terminal_mps, ax_traj_old, ay_traj_old, solution_old, ...\n    sys, P_VDC_VirtualController, drag_coefficient, roh_air, vehiclemass_kg, ...\n    P_VDC_PositiveAxLimScale, P_VDC_EnableNumLatErrorDer_b, P_VDC_MaxTightening, ...\n    P_VDC_MinVelSlipCalc_mps)\n\n% function prepareOptimizationProblem\n% Authors:       Martin Euler\n%                Salih Guemues\n%                Alexander Wischnewski\n%\n% Description:  \n%   function used to generate the constraint matrices for the TMPC-Controller \n% Inputs/parameters:\n%   VehicleDynamicState:    Dynamic state of the racecar\n%   PathPos:                Vehicle position on the target path\n%   v_traj:                 Target trajectory for the PH (prediction horizon)\n%   ax_diff_traj:           Derivative of the target trajectory velocity in the PH\n%   ax_traj:                Longitudinal acceleration for the target trajectory in the PH\n%   ay_traj:                Lateral acceleration for the target trajectory in the PH\n%   ax_lim_mps2             Longitudinal acceleration limits of the target trajectory in the PH\n%   ay_lim_mps2             Lateral acceleration limits of the target trajectory in the PH\n%   d_lim_ub_m              Size of the driving tube to the right side\n%   d_lim_lb_m              Size of the driving tube to the left side\n%   d_Target_m              Target trajectory projected into the curvilinear coordinate frame \n%   dot_d_Target_mps        Derivative of the target trajectory projected into the c.l. coordinates\n%   vx_lin                  Linearization velocity profile \n%   kappa_lin               Linearization curvature profile \n%   UncertaintyTube         Uncertainy ellipsoids for predicted uncertainty tube\n%   v_terminal_set          Terminal set speed\n%   ax_traj_old             Previous iteration target trajectory long. acceleration \n%   ay_traj_old             Previous iteration target trajectory lat. acceleration \n%   solution_old            Previous iteration solution \n%   P_VDC_VirtualController Virtual feedback controller used for uncertainty tube calculation \n%   drag_coefficient        Vehicle drag coefficient\n%   roh_air                 Air density \n%   vehiclemass_kg          Vehicle mass\n%   P_VDC_PositiveAxLimScale Scaling factor for positive accelerations to consider RWD\n%\n% Outputs:\n%\n%   f:                      linear weight matrix for QP\n%   lb:                     lower bound vector for inequality constraints\n%   ub:                     upper bound vector for inequality constraints\n%   A_x:                    nonzero-value-vector of inequality constraint coefficient matrix A_ineq\n%   be_u_abs:               upper terminal set bounds in absolute coordinates\n%   be_l_abs:               lower terminal set bounds in absolute coordinates\n%   s_current:              Vehicle position in raceline coordinates\n%   errorState:             current errorState of the system\n\n%% ------- define optimization problem variables ----------------------- %%\n% get UNSCALED (in terms of preconditioning) constraint matrices/vectors\nA_ineq = zeros(sys.osqp_m, sys.osqp_n);\nA_ineq(sys.A_i_lin) = sys.A_x_par;\nlb = sys.l_par;\nub = sys.u_par;\n\n%% ------------------------- calculate current error state ------------------------------- %%\n% set s_0 to current distance on racetrack\ns_current_m = PathPos.s_m; \n% calculate assumed velocity. limit to lower value to prevent linearization issues. \nv_mps = max(VehicleDynamicState.v_mps, 0.5*P_VDC_MinVelSlipCalc_mps); \n% velocity difference: delta_vx = v_path - v_car;\ndelta_vx = v_traj(1) - v_mps;\n% lateral error delta_y as output from local_path_matching with added initial offset\nd = PathPos.d_m;\n% Delta between vehicle and path heading by interpolation\nd_psi = PathPos.psi_rad + VehicleDynamicState.beta_rad;    \n% lateral error dynamics (either numerical or analytical)\nif(P_VDC_EnableNumLatErrorDer_b)\n    d_dot = dot_d_numerical;\nelse\n    d_dot = v_mps * sin(d_psi);\nend\n% current state vector for controller (state vector of error diff. equat.)\nerror_state = [delta_vx; d; d_dot];\n% calculate system response to initial state\nx0_resp = sys.Ax0_MPC*error_state; \n\n%% ----------- calc linear weight matrix for QP-Solver ------------%\nf = sys.osqp_qpar + 2*(x0_resp'*sys.f_x0)' - 2*(d_Target_m'*sys.f_d_m)' ...\n    - 2*(dot_d_Target_mps'*sys.f_dot_d_mps)' ...\n    - 2*([ax_traj_old(1); ax_traj]'*sys.f_Dax)' ...\n    + 2*([ay_traj_old(1); ay_traj]'*sys.f_Day)' ...\n    + 2*(solution_old(1)*sys.f_D_deltaax)' + 2*(solution_old(2)*sys.f_D_deltaay)';\n% its minus the ax term since the definitions of delta ax and delta ay are changed\n\n%% - calculation of input and state constraints within prediction horizon - %%\nfor j = 1:1:sys.N_hor\n    % get uncertainty matrix for the inputs\n    M_states_current = UncertaintyTube(:, (j-1)*3+1:(j-1)*3+3); \n    M_inputs_current = P_VDC_VirtualController*M_states_current*P_VDC_VirtualController';\n    % calculate tightenings for all state variables and inputs \n    tight_delta_v_mps = sqrt(M_states_current(1, 1)); \n    tight_d_m = sqrt(M_states_current(2, 2)); \n    tight_dot_d_mps = sqrt(M_states_current(3, 3)); \n    % the factors here are swapped with respect to the inputs following this scheme\n    % such that only upper bounds are given as the ax_lim has to be modified for the upper bounds\n    % ay_lim*ax_util + P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    tight_tire1 = sqrt([ay_lim_mps2(j), P_VDC_PositiveAxLimScale*ax_lim_mps2(j)]*M_inputs_current*[ay_lim_mps2(j); P_VDC_PositiveAxLimScale*ax_lim_mps2(j)]); \n    % -ay_lim*ax_util + -ax_lim*ay_util <= ax_lim*ay_lim\n    tight_tire2 = sqrt([-ay_lim_mps2(j), -ax_lim_mps2(j)]*M_inputs_current*[-ay_lim_mps2(j); -ax_lim_mps2(j)]); \n    % -ay_lim*ax_util + ax_lim*ay_util <= ax_lim*ay_lim\n    tight_tire3 = sqrt([-ay_lim_mps2(j), ax_lim_mps2(j)]*M_inputs_current*[-ay_lim_mps2(j); ax_lim_mps2(j)]); \n    % ay_lim*ax_util + -P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    tight_tire4 = sqrt([ay_lim_mps2(j), -P_VDC_PositiveAxLimScale*ax_lim_mps2(j)]*M_inputs_current*[ay_lim_mps2(j); -P_VDC_PositiveAxLimScale*ax_lim_mps2(j)]); \n    % calculate normalization factor for acceleration constraints\n    norm_acc_con_upper = 1/(P_VDC_PositiveAxLimScale*ax_lim_mps2(j)*ay_lim_mps2(j));\n    norm_acc_con_lower = 1/(ax_lim_mps2(j)*ay_lim_mps2(j));\n    \n    % limit tigthening to given factor\n    tight_d_m = min(d_lim_ub_m(j)*P_VDC_MaxTightening, tight_d_m);\n    % get tightened admissible lateral error for current step\n    ub(sys.n_constr*j) = d_lim_ub_m(j) - tight_d_m - x0_resp(2+(j-1)*sys.n_sys);\n    lb(sys.n_constr*j) = d_lim_lb_m(j) + tight_d_m - x0_resp(2+(j-1)*sys.n_sys);\n    \n    % prepare linearization around d = 0, dot_d = 0 and vx = vx_pred for longitudinal acceleration\n    ax_grad_d = ax_diff_traj(j)*kappa_lin(j)*vx_lin(j);\n    ax_grad_v = ax_diff_traj(j) + roh_air*drag_coefficient*vx_lin(j)/vehiclemass_kg; \n    % prepare full gradient for easier specification of constraints \n    ax_grad_states = ay_lim_mps2(j)*[ax_grad_v, ax_grad_d, 0]; \n    ax_grad_inputs = ay_lim_mps2(j)*[-1, 0]; % this is minus one since delta_ax is different sign\n    ax_op = ax_diff_traj(j)*(2*vx_lin(j) - v_traj(j)) + 0.5*roh_air*drag_coefficient*vx_lin(j)^2/vehiclemass_kg;\n    \n    % prepare linearization around d = 0, dot_d = 0 and vx = vx_pred for lateral acceleration \n    ay_grad_d = kappa_lin(j)^2*vx_lin(j)^2; \n    ay_grad_dot_d = -ax_diff_traj(j); \n    ay_grad_v = -2*kappa_lin(j)*vx_lin(j);\n    % prepare full gradient for easier specification of constraints \n    ay_grad_states_upper = P_VDC_PositiveAxLimScale*ax_lim_mps2(j)*[ay_grad_v, ay_grad_d, ay_grad_dot_d]; \n    ay_grad_inputs_upper = P_VDC_PositiveAxLimScale*ax_lim_mps2(j)*[0, 1];\n    ay_grad_states_lower = ax_lim_mps2(j)*[ay_grad_v, ay_grad_d, ay_grad_dot_d]; \n    ay_grad_inputs_lower = ax_lim_mps2(j)*[0, 1];\n    ay_op = kappa_lin(j)*vx_lin(j)^2 + 2*kappa_lin(j)*vx_lin(j)*(v_traj(j) - vx_lin(j));\n      \n    % update gradients for states and inputs in constraint matrix \n    % ay_lim*ax_util + P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    A_ineq(sys.n_constr*(j-1)+1, 1:sys.N_hor*sys.m_sys) = ...\n        (ax_grad_states+ay_grad_states_upper)*sys.ABK_MPC(1+(j-1)*sys.n_sys:j*sys.n_sys, 1:sys.N_hor*sys.m_sys); \n    A_ineq(sys.n_constr*(j-1)+1, sys.m_sys*(j-1)+1:sys.m_sys*j) = ...\n        (A_ineq(sys.n_constr*(j-1)+1, sys.m_sys*(j-1)+1:sys.m_sys*j) + ax_grad_inputs + ay_grad_inputs_upper); \n    % -ay_lim*ax_util + -ax_lim*ay_util <= ax_lim*ay_lim\n    A_ineq(sys.n_constr*(j-1)+2, 1:sys.N_hor*sys.m_sys) = ...\n        -(ax_grad_states+ay_grad_states_lower)*sys.ABK_MPC(1+(j-1)*sys.n_sys:j*sys.n_sys, 1:sys.N_hor*sys.m_sys); \n    A_ineq(sys.n_constr*(j-1)+2, sys.m_sys*(j-1)+1:sys.m_sys*j) = ...\n        (A_ineq(sys.n_constr*(j-1)+2, sys.m_sys*(j-1)+1:sys.m_sys*j) - ax_grad_inputs - ay_grad_inputs_lower); \n    % -ay_lim*ax_util + ax_lim*ay_util <= ax_lim*ay_lim\n    A_ineq(sys.n_constr*(j-1)+3, 1:sys.N_hor*sys.m_sys) = ...\n        (-ax_grad_states+ay_grad_states_lower)*sys.ABK_MPC(1+(j-1)*sys.n_sys:j*sys.n_sys, 1:sys.N_hor*sys.m_sys); \n    A_ineq(sys.n_constr*(j-1)+3, sys.m_sys*(j-1)+1:sys.m_sys*j) = ...\n        (A_ineq(sys.n_constr*(j-1)+3, sys.m_sys*(j-1)+1:sys.m_sys*j) - ax_grad_inputs + ay_grad_inputs_lower); \n    % ay_lim*ax_util + -P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    A_ineq(sys.n_constr*(j-1)+4, 1:sys.N_hor*sys.m_sys) = ...\n        -(-ax_grad_states+ay_grad_states_upper)*sys.ABK_MPC(1+(j-1)*sys.n_sys:j*sys.n_sys, 1:sys.N_hor*sys.m_sys); \n    A_ineq(sys.n_constr*(j-1)+4, sys.m_sys*(j-1)+1:sys.m_sys*j) = ...\n        (A_ineq(sys.n_constr*(j-1)+4, sys.m_sys*(j-1)+1:sys.m_sys*j) + ax_grad_inputs - ay_grad_inputs_upper); \n   \n    % scale matrices appropriately \n    A_ineq(sys.n_constr*(j-1)+1, 1:sys.N_hor*sys.m_sys) = ...\n        norm_acc_con_upper*A_ineq(sys.n_constr*(j-1)+1, 1:sys.N_hor*sys.m_sys);\n    A_ineq(sys.n_constr*(j-1)+2, 1:sys.N_hor*sys.m_sys) = ...\n        norm_acc_con_lower*A_ineq(sys.n_constr*(j-1)+2, 1:sys.N_hor*sys.m_sys);\n    A_ineq(sys.n_constr*(j-1)+3, 1:sys.N_hor*sys.m_sys) = ...\n        norm_acc_con_lower*A_ineq(sys.n_constr*(j-1)+3, 1:sys.N_hor*sys.m_sys);\n    A_ineq(sys.n_constr*(j-1)+4, 1:sys.N_hor*sys.m_sys) = ...\n        norm_acc_con_upper*A_ineq(sys.n_constr*(j-1)+4, 1:sys.N_hor*sys.m_sys);\n    \n    % limit tire tightening to resonable values \n    tight_tire1 = min(P_VDC_PositiveAxLimScale*ax_lim_mps2(j)*ay_lim_mps2(j)*P_VDC_MaxTightening, ... \n                        tight_tire1); \n    tight_tire2 = min(ax_lim_mps2(j)*ay_lim_mps2(j)*P_VDC_MaxTightening, ...\n                        tight_tire2); \n    tight_tire3 = min(ax_lim_mps2(j)*ay_lim_mps2(j)*P_VDC_MaxTightening, ...\n                        tight_tire3); \n    tight_tire4 = min(P_VDC_PositiveAxLimScale*ax_lim_mps2(j)*ay_lim_mps2(j)*P_VDC_MaxTightening, ...\n                        tight_tire4); \n    \n    % ay_lim*ax_util + P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    ub(sys.n_constr*(j-1)+1) = norm_acc_con_upper*(-ax_op*ay_lim_mps2(j) ...\n        - ay_op*P_VDC_PositiveAxLimScale*ax_lim_mps2(j) ...\n        - ax_grad_states*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - ay_grad_states_upper*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - tight_tire1 + P_VDC_PositiveAxLimScale*ax_lim_mps2(j) * ay_lim_mps2(j));\n    % -ay_lim*ax_util + -ax_lim*ay_util <= ax_lim*ay_lim\n    ub(sys.n_constr*(j-1)+2) = -norm_acc_con_lower*(-ax_op*ay_lim_mps2(j) ...\n        - ay_op*ax_lim_mps2(j) ...\n        - ax_grad_states*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - ay_grad_states_lower*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        + tight_tire2 - ax_lim_mps2(j) * ay_lim_mps2(j));\n    % -ay_lim*ax_util + ax_lim*ay_util <= ax_lim*ay_lim\n    ub(sys.n_constr*(j-1)+3) = norm_acc_con_lower*(ax_op*ay_lim_mps2(j) ...\n        - ay_op*ax_lim_mps2(j) ...\n        + ax_grad_states*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - ay_grad_states_lower*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - tight_tire3 + ax_lim_mps2(j) * ay_lim_mps2(j));\n    % ay_lim*ax_util + -P_VDC_PositiveAxLimScale*ax_lim*ay_util <= P_VDC_PositiveAxLimScale*ax_lim*ay_lim\n    ub(sys.n_constr*(j-1)+4) = -norm_acc_con_upper*(ax_op*ay_lim_mps2(j) ...\n        - ay_op*P_VDC_PositiveAxLimScale*ax_lim_mps2(j) ...\n        + ax_grad_states*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        - ay_grad_states_upper*x0_resp(1+(j-1)*sys.n_sys:j*sys.n_sys) ...\n        + tight_tire4 - P_VDC_PositiveAxLimScale*ax_lim_mps2(j) * ay_lim_mps2(j));\nend\n\n%% -------------------- terminal state constraints ----------------------- %%\nbe_u = zeros(3, 1); \nbe_l = zeros(3, 1); \nbe_u(1) = inf; \nbe_l(1) = v_traj(end) - v_terminal_mps; \n\n% lateral error is constrained to be \ntight_terminal_d_m = sqrt(UncertaintyTube(2, end-1));\ntight_terminal_d_m = min(d_lim_ub_m(end)*P_VDC_MaxTightening, tight_terminal_d_m);\nbe_u(2) = d_lim_ub_m(end) - tight_terminal_d_m;\nbe_l(2) = d_lim_lb_m(end) + tight_terminal_d_m;\n% calculate lateral erorr speed as average of the last five values as they might be noisy\nbe_u(3) = mean(dot_d_Target_mps(end-5:end));\nbe_l(3) = mean(dot_d_Target_mps(end-5:end)); \n% write terminal constraints to logs\nbe_u_abs = be_u; \nbe_l_abs = be_l; \n% add offset velocity to make logging meaningful\nbe_u_abs(1) = v_traj(end) - be_u_abs(1); \nbe_l_abs(1) = v_traj(end) - be_l_abs(1); \n% calculate ub for terminal constraint on states\nub(sys.n_constr*sys.N_hor+1:sys.n_constr*sys.N_hor+sys.n_sys) = be_u - ...\n    x0_resp(sys.N_hor*sys.n_sys+1:(sys.N_hor+1)*sys.n_sys);\n% calculate lb for terminal constraint on states\nlb(sys.n_constr*sys.N_hor+1:sys.n_constr*sys.N_hor+sys.n_sys) = be_l - ...\n    x0_resp(sys.N_hor*sys.n_sys+1:sys.n_sys*(sys.N_hor+1));\n% no terminal constraints on longitudinal acceleration\nub(sys.n_constr*sys.N_hor+sys.n_sys+1) = inf;\nlb(sys.n_constr*sys.N_hor+sys.n_sys+1) = -inf;\n% lateral acceleration is constrained to be close to target \nub(sys.n_constr*sys.N_hor+sys.n_sys+2) = 0;\nlb(sys.n_constr*sys.N_hor+sys.n_sys+2) = 0;\n\n%% --------------------- setup slack constraints ------------------------------------- %%\n% limit slacks to be strictly positive \nlb(sys.N_hor*sys.n_constr+sys.n_sys+sys.m_sys+1:end) = 0;\n% upper limit of tire slacks set to certain percentage of maximum available accelerations\nub(sys.N_hor*sys.n_constr+sys.n_sys+sys.m_sys+1:sys.n_slacks:end) = sys.slack_lim_rel; \nub(sys.N_hor*sys.n_constr+sys.n_sys+sys.m_sys+2:sys.n_slacks:end) = sys.slack_lim_rel; \n% upper limit of lateral error slacks set to equal amount of allowed deviation\n% which allows to go for the double amount if required\nub(sys.N_hor*sys.n_constr+sys.n_sys+sys.m_sys+3:sys.n_slacks:end) = 0.5*(d_lim_ub_m(1)-d_lim_lb_m(1)); \nub(sys.N_hor*sys.n_constr+sys.n_sys+sys.m_sys+4:sys.n_slacks:end) = 0.5*(d_lim_ub_m(1)-d_lim_lb_m(1)); \n\n%% ----------- transform A_ineq and P to CSC compatible format using sparsity pattern ----------- %%\nA_x = A_ineq(sys.A_i_lin);\n\nend\n\n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/control/src/prepareOptimizationProblem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23903422866138604}}
{"text": "function [fg, fgRemains, fgLeft, fgRight]=dtiSplitInterhemisphericFibers(fg, dt, maxZ)\n%Split fibers that cross between hemispheres below a certain z-coordinate.\n%\n%   fg=dtiSplitInterhemisphericFibers(fg, dt, [Z=-10])\n%\n% Due to tractography artifacts, whole brain tractography often produces\n% fibers which connect homologous motor cortices, crossing between\n% hemispheres at the pons level. This is anatomically implausible: these\n% fibers mostl likely cross at the pons level, connecting spinal tract and\n% contralateral moter cortex. This function splits interhemisperic fibers,\n% sparing (dep. on option chosen) either CC, or ACPC & above. Note:\n% cerebellar fibers WILL be split as well. Too bad.\n%\n% Input parameters: \n% fg      - fiber group structure\n% dt      - dt6 (tensor) data structure\n% maxZ    - (a) maxZ=-10 (default) will split fibers, cutting them by a\n%           saggital plane 10 mm below acpc line.  We assume that no\n%           interhemispheric fiber should connect below ACPC line. Fornix &\n%           CC are comissures located above. Provide your own maxZ (the\n%           most superior z coordinate of the cutting midsaggital plane)\n%           otherwise. (b) maxZ='AllButCC' allows splitting every\n%           interhemispheric fiber except callosal.\n%\n% Example: \n% Split intehemispheric fibers below ACPC\n%   dt=dtiLoadDt6(dtFileName);\n%   fg = dtiLoadFibers(fgFileName);\n%   fg=dtiSplitInterhemisphericFibers(fg, dt, 0]);\n%\n% (c) Vistalab\n\n%HISTORY:\n% 08/2009: ER & LMP   wrote it\n% 08/24/2009 ER: drop fibers of 1 node long. \n\nif notDefined('maxZ')\n    maxZ=-10;\nend\n\nif isnumeric(maxZ) && (maxZ<dt.bb(1, 3) ||maxZ>dt.bb(2, 3))|| (~isnumeric(maxZ) && ~strcmp(maxZ, 'AllButCC'))\n    error(['The most superior point Z for cutting should be between ' num2str(dt.bb(1, 3)) ' and ' num2str(dt.bb(2, 3)) ' or \"AllButCC\"']);\nend\n\nif notDefined('dt')\n    [f,p] = uigetfile({'*.nii.gz';'*.*'},'Select dt6 file...');\n    if(isnumeric(f)), disp('User canceled.'); return; end\n    dt = fullfile(p,f);\nend\n\nmidSagThresh = 5;\nfg=dtiCleanFibers(fg);\nfgname=fg.name;\n\nif isnumeric(maxZ)\n    \n   fprintf(1, 'dtiSplitInterhemisphericFibers: Splitting every fiber below Z=%s \\n', num2str(maxZ)); \n   % Bounding Box = dt.bb  x = [-80 0]; y = [-120 90]; z = [-60 90];\n    x = [0];\n    y = [dt.bb(1, 2):dt.bb(2, 2)];\n    z = [dt.bb(1, 3): maxZ];\n    \n    [X,Y,Z] = meshgrid(x, y, z);\n    roiCoords = [X(:), Y(:), Z(:)];\n    roi = dtiNewRoi('MidSaggitalBelowACPC', 'b', roiCoords);\n    \n    [fgToChop,contentiousFibers, keep] = dtiIntersectFibersWithRoi([], {'and'}, [], roi, fg);\n    fgRemains = dtiNewFiberGroup([fg.name 'Remains']); fgRemains.fibers=fg.fibers(~keep);\n    if isfield(fg, 'subgroup') && ~isempty(fg.subgroup)\n        fgRemains.subgroup=fg.subgroup(~keep);\n    end\n    \n    fgRight = dtiNewFiberGroup([fg.name '_ChoppedR']);\n    fgLeft = dtiNewFiberGroup([fg.name '_ChoppedL']);\n        clear fg;\n    \n%emptyleft=0; \n%emptyright=0; \n    \n    keepRightID=[];keepLeftID=[];\n    for i=1:size(fgToChop.fibers)\n        pointsRight=(fgToChop.fibers{i}(1, :)>midSagThresh);\n        pointsLeft=(fgToChop.fibers{i}(1, :)<-midSagThresh);\n        RightChunk{1}=fgToChop.fibers{i}(:, pointsRight);\n        if ~isempty(RightChunk{1})\n            fgRight.fibers= [fgRight.fibers(:);RightChunk] ; %Right chunk\n            keepRightID=[keepRightID; i];\n %       else emptyright=emptyright+1; \n        end\n        LeftChunk{1}=fgToChop.fibers{i}(:,  pointsLeft);\n        \n        if ~isempty(LeftChunk{1})\n            fgLeft.fibers = [fgLeft.fibers(:); LeftChunk]; %Left chunk\n            keepLeftID=[keepLeftID; i];\n %       else emptyleft=emptyleft+1; \n        end\n    end\n      if isfield(fgToChop, 'subgroupNames') && ~isempty(fgToChop.subgroupNames)\n    fgLeft.subgroupNames=fgToChop.subgroupNames;\n    fgRight.subgroupNames=fgToChop.subgroupNames;\n      end\n    if isfield(fgToChop, 'subgroup') && ~isempty(fgToChop.subgroup)\n    fgLeft.subgroup=fgToChop.subgroup(keepLeftID);\n    fgRight.subgroup=fgToChop.subgroup(keepRightID);\n    end\n    \n%    emptyleft\n%    emptyright\nelse\n    \n    % Code that LMP wrote to take a fiber group, remove callosal fibers, split\n    % the remaining groups, then merge the two groups to create one set that\n    % is cut down the mid-line but retains the callosal fibers.\n    %Limitation: assumes CC is the only interhemispheric connection\n    fprintf(1, 'Splitting every fiber except in the CC \\n');\n    \n    ccCoords = dtiFindCallosum(dt.dt6,dt.b0,dt.xformToAcpc);\n    ccRoi = dtiNewRoi('CC','c',ccCoords);\n    ccRoi = dtiRoiClean(ccRoi, 3, {'dilate'});\n    \n    fgRemains = dtiIntersectFibersWithRoi([], {'and'}, [], ccRoi, fg);\n    fgToChop= dtiIntersectFibersWithRoi([], {'not'}, [], ccRoi, fg);\n    clear fg;\n    fgRight = dtiClipFiberGroup(fgToChop, [-80 midSagThresh],[],[]);\n    fgLeft = dtiClipFiberGroup(fgToChop, [-midSagThresh 80],[],[]);\n    \nend\n\n\nfg = dtiMergeFiberGroups(fgRight,fgLeft,fgname);\nfg = dtiMergeFiberGroups(fg,fgRemains,fgname);\nfgRemains.name  = [fgname '_NoChop'];\nfgLeft.name  = [fgname '_L'];\nfgRight.name  = [fgname '_R'];\nfg.name=[fgname '_BilaterallySplit'];\n\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%dtiWriteFibersPdb(newFg,[],newFg.name);\n\n%fgToChop.name=['allConnectingGM_withCST_Mori_ToChop'];\n%dtiWriteFiberGroup(fgRemains,fgRemains.name);\n%dtiWriteFiberGroup(newFgLeft,newFgLeft.name);\n%dtiWriteFiberGroup(newFgRight,newFgRight.name);\n%dtiWriteFiberGroup(fgToChop,fgToChop.name);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/dtiSplitInterhemisphericFibers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23903422866138604}}
{"text": "%LEARNALGOITML Wrapper class to the actual ITML code\nclassdef LearnAlgoITML < LearnAlgo\n    \n    properties \n       p %parameters \n       s %struct\n       available\n    end\n    \n    properties (Constant)\n        type = 'itml'\n    end\n    \n    methods\n        function obj = LearnAlgoITML(p)\n           if nargin < 1\n              p = struct(); \n           end\n           \n           if ~isfield(p,'roccolor')\n                p.roccolor = 'b';\n           end\n           obj.p  = p;\n           check(obj);\n        end\n        \n        function bool = check(obj)\n           bool = exist('ItmlAlg') ~= 0;\n           if ~bool\n               fprintf('Sorry %s not available\\n',obj.type);\n           end\n           obj.available = bool;\n        end\n        \n        function s = learnPairwise(obj,X,idxa,idxb,matches)\n            if ~obj.available\n                s = struct();\n                return;\n            end\n            \n            tic;\n            s.M = PairMetricLearning(@ItmlAlg, idxa', idxb', matches, X');\n            s.t = toc; \n            s.learnAlgo = obj;\n            s.roccolor = obj.p.roccolor;\n        end\n        \n        function s = learn(obj,X,y)\n            if ~obj.available\n                s = struct();\n                return;\n            end\n            \n            tic;\n            s.M = MetricLearning(@ItmlAlg, y', X');\n            s.t = toc; \n            s.learnAlgo = obj;\n            s.roccolor = obj.p.roccolor;\n        end\n        \n        function d = dist(obj, s, X, idxa,idxb)\n            d = cdistM(s.M,X,idxa,idxb); \n        end\n    end    \nend\n\n", "meta": {"author": "zhunzhong07", "repo": "IDE-baseline-Market-1501", "sha": "8be027b5e45adce1d8ea381cc5a17ec20ed521e5", "save_path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501", "path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501/IDE-baseline-Market-1501-8be027b5e45adce1d8ea381cc5a17ec20ed521e5/market_evaluation/KISSME/toolbox/learnAlgos/LearnAlgoITML.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23901246187607114}}
{"text": "function F = in_fread_compumedics_pfs(sFile, sfid, SamplesBounds, ChannelsRange)\n% IN_FREAD_COMPUMEDICS_PFS:  Read a block of recordings from a Compumedics ProFusion Sleep 4 exported binary file (.sdy/.rda).\n%\n% USAGE:  F = in_fread_compumedics_pfs(sFile, sfid, SamplesBounds=[], ChannelsRange=[])\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2015\n\n% Parse inputs\nif (nargin < 4) || isempty(ChannelsRange)\n    ChannelsRange = [1, sFile.header.nchannels];\nend\nif (nargin < 3) || isempty(SamplesBounds)\n    SamplesBounds = round(sFile.prop.times .* sFile.prop.sfreq);\nend\n\n% ===== COMPUTE OFFSETS =====\nnChannels     = double(sFile.header.nchannels);\nnReadTimes    = SamplesBounds(2) - SamplesBounds(1) + 1;\nnReadChannels = double(ChannelsRange(2) - ChannelsRange(1) + 1);\n% Everything is stored on 32 bit floats\nbytesPerVal = 4;\ndataClass = 'single';\n% Header offset\noffsetHeader = sFile.header.rda.segment(1).pos;\n% Time offset\noffsetTime = round(SamplesBounds(1) * nChannels * bytesPerVal);\n% Channel offset at the beginning and end of each channel block\noffsetChannelStart = round((ChannelsRange(1)-1) * bytesPerVal);\noffsetChannelEnd   = (nChannels - ChannelsRange(2)) * bytesPerVal;\n% Start reading at this point\noffsetStart = offsetHeader + offsetTime + offsetChannelStart;\n% Number of time samples to skip after each channel\noffsetSkip = offsetChannelStart + offsetChannelEnd; \n\n% ===== READ DATA BLOCK =====\n% Position file at the beginning of the trial\nfseek(sfid, offsetStart, 'bof');\n% Read trial data\n% => WARNING: CALL TO FREAD WITH SKIP=0 DOES NOT WORK PROPERLY\nif (offsetSkip == 0)\n    F = fread(sfid, [nReadChannels, nReadTimes], dataClass);\nelse\n    precision = sprintf('%d*%s', nReadChannels, dataClass);\n    F = fread(sfid, [nReadChannels, nReadTimes], precision, offsetSkip);\nend\n% Check that data block was fully read\nif (numel(F) < nReadTimes * nReadChannels)\n    % Error message\n    disp(sprintf('BST> ERROR: File is truncated (%d values were read instead of %d)...', numel(F), nReadTimes * nReadChannels));\n    % Pad with zeros \n    Ftmp = zeros(nReadChannels, nReadTimes);\n    Ftmp(1:numel(F)) = F(:);\n    F = Ftmp;\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_compumedics_pfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.23898528615335557}}
{"text": "function [varargout] = size2(x, dim, cellflag)\n\n% SIZE2 Size of cells in cell-array.\n% \n% Use as:\n%   [varargout] = size2(x, dim, cellflag)\n%\n% Input arguments:\n%   x   = cell-array\n%   dim = dimension argument, default []\n%   cellflag = true (default) or false. If false, size2 behaves as size,\n%     otherwise the size of each of the cells is returned.\n\nif nargin<3, cellflag = false; end\nif nargin<2, dim      = [];    end\n\nif nargout>1 && ~isempty(dim)\n  error('Too many output arguments.');\nend\n\nif ischar(cellflag) && strcmp(cellflag, 'cell')\n  cellflag = true;\nend\n\nif ~cellflag\n  % traditional functionality\n  numdim = ndims(x);\n  \n  if isempty(dim)\n    siz    = zeros(1,numdim);\n    for k = 1:numdim\n      switch k\n        case 1\n          siz(k) = numel(x(:,1,1,1,1,1,1,1,1,1));\n        case 2\n          siz(k) = numel(x(1,:,1,1,1,1,1,1,1,1));\n        case 3\n          siz(k) = numel(x(1,1,:,1,1,1,1,1,1,1));\n        case 4\n          siz(k) = numel(x(1,1,1,:,1,1,1,1,1,1));\n        case 5\n          siz(k) = numel(x(1,1,1,1,:,1,1,1,1,1));\n        case 6\n          siz(k) = numel(x(1,1,1,1,1,:,1,1,1,1));\n        case 7\n          siz(k) = numel(x(1,1,1,1,1,1,:,1,1,1));\n        case 8\n          siz(k) = numel(x(1,1,1,1,1,1,1,:,1,1));\n        case 9\n          siz(k) = numel(x(1,1,1,1,1,1,1,1,:,1));\n        case 10\n          siz(k) = numel(x(1,1,1,1,1,1,1,1,1,:));\n        otherwise\n      end\n    end\n  else\n    switch dim\n      case 1\n        siz = numel(x(:,1,1,1,1,1,1,1,1,1));\n      case 2\n        siz = numel(x(1,:,1,1,1,1,1,1,1,1));\n      case 3\n        siz = numel(x(1,1,:,1,1,1,1,1,1,1));\n      case 4\n        siz = numel(x(1,1,1,:,1,1,1,1,1,1));\n      case 5\n        siz = numel(x(1,1,1,1,:,1,1,1,1,1));\n      case 6\n        siz = numel(x(1,1,1,1,1,:,1,1,1,1));\n      case 7\n        siz = numel(x(1,1,1,1,1,1,:,1,1,1));\n      case 8\n        siz = numel(x(1,1,1,1,1,1,1,:,1,1));\n      case 9\n        siz = numel(x(1,1,1,1,1,1,1,1,:,1));\n      case 10\n        siz = numel(x(1,1,1,1,1,1,1,1,1,:));\n      otherwise\n    end\n  end\n  \n  if nargout<=1\n    varargout{1} = siz;\n  elseif nargout>=numdim\n    for k = 1:numdim,           varargout{k} = siz(k); end\n    for k = (numdim+1):nargout, varargout{k} = 1;      end\n  elseif nargout<numdim\n    for k = 1:(nargout-1),      varargout{k} = siz(k); end\n    varargout{nargout} = prod(siz((k+1):end));\n  end\n  return;\nelse\n  % operate on the individual cells\n%   siz    = ones(numel(x), 10);\n%   numdim = zeros(numel(x), 1);\n%   for k = 1:numel(x)\n%     numdim(k) = ndims(x{k});\n%     siz(k,1:numdim(k)) = size(x{k});\n%   end\n  numdim = cellfun(@ndims, x);\n  siz    = cellfun(@size,  x, 'uniformoutput', false);\n  if all(numdim==numdim(1))\n    siz = reshape(cat(2,siz{:}),numdim(1),[])';\n  end\n  \n  if isempty(dim) \n    if nargout<=1\n      varargout{1} = siz(:,1:max(numdim));\n    elseif nargout>=max(numdim)\n      for k = 1:numdim,           varargout{k} = reshape(siz(:,k), size(x)); end\n      for k = (numdim+1):nargout, varargout{k} = ones(size(x));              end  \n    end\n  else\n    varargout{1} = reshape(siz(:,dim), size(x));\n  end\n  return;\nend\n\n  \n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/cellfunction/@cell/size2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23895339102679916}}
{"text": "function Y=sum(Y)\n%SUM (overloaded)\n\nY.basis = sum(Y.basis,1);\nY.dim(1) = 1;\nY.dim(2) = 1;\n% Reset info about conic terms\nY.conicinfo = [0 0];\nY = clean(Y);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/@sdpvar/sumsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23872157975280647}}
{"text": "close all;\nclear all;\nclc;\n\ndata_file_path = 'bin/ar_omp_phase_transition_gaussian_dict_gaussian_data.mat';\noptions.export = false;\noptions.export_dir = 'bin';\noptions.export_name = 'gaussian_dict_gaussian_data';\n%options.chosen_ks = [2, 4, 8, 16, 32, 64];\nspx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ...\n    'OMP-AR', options);\n\ndata_file_path = 'bin/omp_phase_transition_gaussian_dict_gaussian_data.mat';\noptions.export = false;\noptions.export_dir = 'bin';\noptions.export_name = 'gaussian_dict_gaussian_data';\n%options.chosen_ks = [2, 4, 8, 16, 32, 64];\nspx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ...\n    'OMP', options);\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/atom_ranking_in_greedy_pursuit/print_all_graphs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23872157975280647}}
{"text": "        function polyobj = coarsen_polygon(polyobj,iboubox)\n            % Coarsen a polygon using a brute-force vertex reordering algorithm.\n            idx = find(isnan(polyobj(:,1)));\n            C = mat2cell(polyobj,diff([0;idx]),2);\n            new = cell(length(C),1);\n            % for each segment\n            for iii = 1 : length(C)\n                j = 0 ; k = 0;\n                [in] = inpoly(C{iii},iboubox(1:end-1,:));\n                % Initialise for speed\n                new{iii} = zeros(length(C{iii}),2);\n                while j < length(C{iii})-1\n                    j = j + 1 ;\n                    if in(j) % point is in domain keep it\n                        k = k + 1;\n                        new{iii}(k,:) = C{iii}(j,:);\n                    else % pt is out of domain\n                        bd = min([j+200,length(in)-1]) ;\n                        exte = min(200,bd - j);\n                        if sum(in(j:bd))==0 % if next hundred points are out, then we can decimate\n                            k = k + 1 ;\n                            new{iii}(k,:) = C{iii}(j,:);\n                            k = k + 1 ;\n                            new{iii}(k,:) = C{iii}(j+exte,:);\n                            j = j + exte ;\n                        else % otherwise keep\n                            k = k + 1 ;\n                            new{iii}(k,:) = C{iii}(j,:);\n                        end\n                        \n                    end\n                end\n                new{iii}(k+1,:) = [NaN NaN] ;\n                new{iii}(k+2:end,:) = [];\n            end\n            polyobj = cell2mat(new);\n        end", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/@geodata/private/coarsen_polygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23872157975280647}}
{"text": "classdef Bicubic < dagnn.ElementWise\n%%% Bicubic resizing layer %%%\n%\n% Performs bicubic resizing on inputs{1} and stores it in outputs{1}.\n% outputs{1} =imresize(input, obj.scale,'bicubic');\n% *Back-propagation (backward function) not implemented*\n\n    properties\n        scale = 2;\n    end\n    \n    methods\n        function outputs = forward(obj, inputs, params)\n            outputs{1} = imresize(inputs{1}, obj.scale, 'bicubic');\n        end\n        \n        function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n            derInputs{1} = 0*inputs{1} ;\n            derParams = {} ;\n        end\n        \n        function obj = Bicubic(varargin)\n            obj.load(varargin);\n            obj.scale = obj.scale;\n        end\n    end\nend\n", "meta": {"author": "sooyekim", "repo": "Deep-SR-ITM", "sha": "139ca3b8b236e599a4361dc0797a0ff0b3c67665", "save_path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM", "path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM/Deep-SR-ITM-139ca3b8b236e599a4361dc0797a0ff0b3c67665/+dagnn/Bicubic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.23850849296884977}}
{"text": "function mrAnatComputeVanatSpatialNorm(vAnatFileName, outFileName)\n% Computes an SPM2 spatial normalization and its inverse for a vAnatomy.\n%\n% mrAnatComputeVanatSpatialNorm(vAnatFileName, [outFileName])\n%\n%\n% HISTORY:\n% 2005.08.05 RFD: wrote it.\n%\n\nif(~exist('vAnatFileName','var') | isempty(vAnatFileName))\n    vAnatFileName = mrvSelectFile('r','dat',[],'Select a vAnatomy file...');\n    if isempty(vAnatFileName), return;\n    elseif ~exist(vAnatFileName,'file'), error(sprintf('%s not found.\\n',vAnatFileName));\n    end\nend\nif(~exist('outFileName','var'))\n    [p,f,e] = fileparts(vAnatFileName);\n    outFileName = fullfile(p,[f '_sn.mat']);\nend\n\n[img, mm] = readVolAnat(vAnatFileName);\nimg = uint8(img);\nxform = mrAnatXform(mm,size(img),'vanatomy2acpc');\n\n%\n% Compute the normalization params.\n%\ndisp('Computing spatial norm params...');\n[sn, Vtemplate] = mrAnatComputeSpmSpatialNorm(img, xform);\n\n%\n% Convert the SN params to a deformation field.\n%\ndisp('Computing inverse spatial norm...');\n% Build the bounding box needed to sample the deformation field. We want it\n% to capture the entire template, so we use the template vox-to-physical xform\n% (sn.VG) to generate it.\n%\n% We first extract scales from the template xform. We want the\n% defomation field to be sampled at this same scale. That makes pulling\n% values from the inverse deformation easier and saves space, since it\n% isn't necessary to sample at a higher resolution than the template.\nmmTemplate = sqrt(sum(sn.VG.mat(1:3,1:3).^2));\norigin  = sn.VG.mat\\[0 0 0 1]';\norigin  = origin(1:3)';\nbb = [-mmTemplate.*(origin-1) ; mmTemplate.*(sn.VG.dim(1:3)-origin)];\n% Now compute the deformation:\nd = single(mrAnatSnToDeformation(sn, mmTemplate, bb));\n\n% Invert the deformation. The inverse deformation is essentially a look-up\n% table that maps voxel coords to the physical space of the template. This\n% is exactly what we want.\n%\n% 4th arg is 4x4 xform from mm to voxels in the coordinate frame of the inverse deformation field\n% 5th arg is xform from voxels to mm in the coordinate frame of the forward deformation field\n[defX,defY,defZ] = spm_invdef(d(:,:,:,1), d(:,:,:,2), d(:,:,:,3), sn.VF.dim(1:3), ...\n                             inv(sn.VF.mat), sn.VG.mat);\n                         \n% We can save it as int8, since real brain templates never extend beyond\n% 128mm from the origin. But, we'll check, just to be sure.\nif(all(abs(defX(:))<128) & all(abs(defY(:))<128) & all(abs(defZ(:))<128))\n    voxToTemplateLUT = zeros([3 size(defX)], 'int8');\n    voxToTemplateLUT(1,:,:,:) = int8(round(defX));\n    voxToTemplateLUT(2,:,:,:) = int8(round(defY));\n    voxToTemplateLUT(3,:,:,:) = int8(round(defZ));\nelse\n    voxToTemplateLUT = zeros([3 size(defX)], 'int16');\n    voxToTemplateLUT(1,:,:,:) = int16(round(defX));\n    voxToTemplateLUT(2,:,:,:) = int16(round(defY));\n    voxToTemplateLUT(3,:,:,:) = int16(round(defZ));\nend\n\nfprintf('Saving to %s...\\n', outFileName);\nsave(outFileName, 'sn', 'voxToTemplateLUT');\ndisp('done.');\nreturn;\n\n\n\n% DEBUGGING CODE:\n\nmmPerVox = [1 1 1];\n\n% Get a bounding box in ac-pc space that captures the whole template image.\ntemplateMmPerVox = sqrt(sum(sn.VG(1).mat(1:3,1:3).^2));\nif det(sn.VG.mat(1:3,1:3))<0, mmPerVox(1) = -mmPerVox(1); end;\ntemplateOrigin  = sn.VG.mat\\[0 0 0 1]';\ntemplateOrigin  = templateOrigin(1:3)';\nbb = [-templateMmPerVox .* (templateOrigin-1) ; templateMmPerVox.*(sn.VG(1).dim(1:3)-templateOrigin)];\n% The code in mrAnatResliceSpm needs to know how to transform the image\n% coords from the template's ac-pc space to actual deformation-image space. \n% The following was gleaned from spm_reslice_sn. I only vaguely understand\n% it, but it seems to work.\nog  = -templateMmPerVox .* templateOrigin;\nM1  = [templateMmPerVox(1) 0 0 og(1) ; 0 templateMmPerVox(2) 0 og(2) ; 0 0 templateMmPerVox(3) og(3) ; 0 0 0 1];\noutMmPerVox = [1 1 1];\nof  = -outMmPerVox.*(round(-bb(1,:)./outMmPerVox)+1);\nM2  = [outMmPerVox(1) 0 0 of(1) ; 0 outMmPerVox(2) 0 of(2) ; 0 0 outMmPerVox(3) of(3) ; 0 0 0 1];\nd.inMat = inv(sn.VG(1).mat*inv(M1)*M2);\n\n\ndField = mrAnatSnToDeformation(sn, [1 1 1], bb);\nd.deformX = dField(:,:,:,1);\nd.deformY = dField(:,:,:,2);\nd.deformZ = dField(:,:,:,3);\nd.outMat = inv(xform);\n[imgSn, newXform] = mrAnatResliceSpm(img, d, bb, mmPerVox, [7 7 7 0 0 0]);\nimgSn(isnan(imgSn)) = 0;\n\nfigure; imagesc(makeMontage(imgSn)); axis image; colormap(gray)", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/VolumeUtilities/mrAnatComputeVanatSpatialNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23850400670551122}}
{"text": "function [bodyInfo] = getBodyInfoStructFromOrbit(inputOrbit)\n%getBodyInfoStructFromOrbit Summary of this function goes here\n%   Detailed explanation goes here\n\n%     bodyInfo = struct();\n    bodyInfo = KSPTOT_BodyInfo();\n    bodyInfo.epoch = inputOrbit(7);\n    bodyInfo.sma = inputOrbit(1);\n    bodyInfo.ecc = inputOrbit(2);\n    bodyInfo.inc = rad2deg(inputOrbit(3));\n    bodyInfo.raan = rad2deg(inputOrbit(4));\n    bodyInfo.arg = rad2deg(inputOrbit(5));\n    bodyInfo.mean = rad2deg(inputOrbit(6));\n    bodyInfo.id = rand();\n    bodyInfo.propTypeEnum = BodyPropagationTypeEnum.TwoBody;\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/getBodyInfoStructFromOrbit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2385040003718873}}
{"text": "function mfx = spm_cfg_mfx\n% SPM Configuration file for MFX\n%__________________________________________________________________________\n% Copyright (C) 2010-2014 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_cfg_mfx.m 6239 2014-10-13 14:53:48Z guillaume $\n\n%--------------------------------------------------------------------------\n% dir Directory\n%--------------------------------------------------------------------------\ndir         = cfg_files;\ndir.tag     = 'dir';\ndir.name    = 'Directory';\ndir.help    = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};\ndir.filter = 'dir';\ndir.ufilter = '.*';\ndir.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% spmmat Select SPM.mat\n%--------------------------------------------------------------------------\nspmmat         = cfg_files;\nspmmat.tag     = 'spmmat';\nspmmat.name    = 'Select SPM.mat files';\nspmmat.help    = {...\n    'Select the SPM.mat files that contains first-level designs.'\n    'They must have the same number of parameters for each session.'\n    ['These are assumed to represent session-specific realisations of ' ...\n    '2nd-level effects.']};\nspmmat.filter  = 'mat';\nspmmat.ufilter = '^SPM\\.mat$';\nspmmat.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% ffx Create first-level design\n%--------------------------------------------------------------------------\nffx       = cfg_exbranch;\nffx.tag   = 'ffx';\nffx.name  = 'FFX Specification';\nffx.val   = {dir spmmat};\nffx.help  = {'Create FFX multi-session first-level design'};\nffx.prog  = @spm_local_ffx;\nffx.vout  = @vout_ffx;\n\n%--------------------------------------------------------------------------\n% spmmat Select SPM.mat\n%--------------------------------------------------------------------------\nspmmat         = cfg_files;\nspmmat.tag     = 'spmmat';\nspmmat.name    = 'Select SPM.mat';\nspmmat.help    = {...\n    'Design and estimation structure after a 1st-level analysis.'};\nspmmat.filter  = 'mat';\nspmmat.ufilter = '^SPM\\.mat$';\nspmmat.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% con Contrast\n%--------------------------------------------------------------------------\ncon         = cfg_entry;\ncon.tag     = 'contrast';\ncon.name    = 'Contrast';\ncon.help    = {\n    'Contrast used to define 2nd level design matrix.'\n    'E.g. ones(n,1) contrast where n is the number of sessions/subjects.'\n    ['The specification of a contrast that is not ones(n,1) allows, ' ...\n    'for example, specified sessions/subjects to be ignored.']\n    ['If left empty (default), a contrast ones(n,1) will be specified ' ...\n    'automatically at run time.']\n    };\ncon.strtype = 'r';\ncon.num     = [Inf Inf];\ncon.val     = {[]};\n\n%--------------------------------------------------------------------------\n% spec MFX Specification\n%--------------------------------------------------------------------------\nspec       = cfg_exbranch;\nspec.tag   = 'spec';\nspec.name  = 'MFX Specification';\nspec.val   = {spmmat con};\nspec.help  = {'MFX Specification'};\nspec.prog  = @spm_local_mfx;\nspec.vout  = @vout_mfx;\n\n%--------------------------------------------------------------------------\n% mfx Mixed-effects (MFX) analysis\n%--------------------------------------------------------------------------\nmfx         = cfg_choice;\nmfx.tag     = 'mfx';\nmfx.name    = 'Mixed-effects (MFX) analysis';\nmfx.help    = {'Mixed-effects (MFX) analysis'};\nmfx.values  = {ffx spec};\n\n\n%==========================================================================\n% function out = spm_local_ffx(job)\n%==========================================================================\nfunction out = spm_local_ffx(job)\nspmmat = job.spmmat;\nSPMS = cell(size(spmmat));\nfor i=1:numel(spmmat)\n    load(spmmat{i},'SPM');\n    SPMS{i} = SPM;\nend\n\nmatlabbatch{1}.spm.stats.fmri_spec.dir            = cellstr(job.dir);\nmatlabbatch{1}.spm.stats.fmri_spec.timing.units   = SPMS{1}.xBF.UNITS;\nmatlabbatch{1}.spm.stats.fmri_spec.timing.RT      = SPMS{1}.xY.RT;\nmatlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t  = SPMS{1}.xBF.T;\nmatlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t0 = SPMS{1}.xBF.T0;\nswitch SPMS{1}.xBF.name\n    case 'hrf'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.hrf.derivs = [0 0];\n    case 'hrf (with time derivative)'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.hrf.derivs = [1 0];\n    case 'hrf (with time and dispersion derivatives)'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.hrf.derivs = [1 1];\n    case 'Fourier set'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.length = SPMS{1}.xBF.length;\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.order  = SPMS{1}.xBF.order;\n    case 'Fourier set (Hanning)'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.length = SPMS{1}.xBF.length;\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.order  = SPMS{1}.xBF.order;\n    case 'Gamma functions'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.length = SPMS{1}.xBF.length;\n        matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.order  = SPMS{1}.xBF.order;\n    case 'Finite Impulse Response'\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fir.length = SPMS{1}.xBF.length;\n        matlabbatch{1}.spm.stats.fmri_spec.bases.fir.order  = SPMS{1}.xBF.order;\nend\nmatlabbatch{1}.spm.stats.fmri_spec.volt   = SPMS{1}.xBF.Volterra;\nmatlabbatch{1}.spm.stats.fmri_spec.global = SPMS{1}.xGX.iGXcalc;\nif isfield(SPMS{1}.xM,'gMT')\n    matlabbatch{1}.spm.stats.fmri_spec.mthresh = SPMS{1}.xM.gMT;\nend\nif ~isempty(SPMS{1}.xM.VM)\n    matlabbatch{1}.spm.stats.fmri_spec.mask = cellstr(SPMS{1}.xM.VM.fname); % can be intersection\nend\nif strncmp('AR',SPMS{1}.xVi.form,2)\n    matlabbatch{1}.spm.stats.fmri_spec.cvi  = 'AR(1)';\nelseif strcmp(SPMS{1}.xVi.form,'FAST')\n    matlabbatch{1}.spm.stats.fmri_spec.cvi  = 'FAST';\nelse\n    %matlabbatch{1}.spm.stats.fmri_spec.cvi  = 'none';\n    disp('Forcing serial correlation modelling to be AR(1).');\n    matlabbatch{1}.spm.stats.fmri_spec.cvi  = 'AR(1)';\nend\n\nk  = 1;\nnp = zeros(1,numel(SPMS));\ndisp(' ');\nfor i=1:numel(SPMS)\n    fprintf('Subject %d:\\n',i);\n    np(i) = 0;\n    n     = cumsum([1 SPMS{i}.nscan]);\n    nSess = numel(SPMS{i}.Sess);\n    for j=1:nSess\n        fprintf(' Session %d:\\n',j);\n        matlabbatch{1}.spm.stats.fmri_spec.sess(k).scans = cellstr(SPMS{i}.xY.P(n(j):n(j+1)-1,:));\n        nCond=numel(SPMS{i}.Sess(j).U);\n        for l=1:nCond\n            matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).name = SPMS{i}.Sess(j).U(l).name{1};\n            matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).onset = SPMS{i}.Sess(j).U(l).ons;\n            matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).duration = SPMS{i}.Sess(j).U(l).dur;\n            o    = 1;\n            nReg = numel(SPMS{i}.Sess(j).U(l).P);\n            for m=1:nReg\n                fprintf('  Condition %d: Columns %d\\n',l,nReg);\n                np(i) = np(i)+nReg;\n                switch SPMS{i}.Sess(j).U(l).P(m).name\n                    case 'time'\n                        matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).tmod = SPMS{i}.Sess(j).U(l).P(m).h;\n                    case 'none'\n                    otherwise\n                        matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).name  = SPMS{i}.Sess(j).U(l).P(m).name;\n                        matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).param = SPMS{i}.Sess(j).U(l).P(m).P;\n                        matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).poly  = SPMS{i}.Sess(j).U(l).P(m).h;\n                        o = o + 1;\n                end\n            end\n        end\n        for l=1:numel(SPMS{i}.Sess(j).C.name)\n            matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).name = SPMS{i}.Sess(j).C.name{l};\n            matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).val  = SPMS{i}.Sess(j).C.C(:,l);\n        end\n        matlabbatch{1}.spm.stats.fmri_spec.sess(k).hpf = SPMS{i}.xX.K(j).HParam;\n        k = k + 1;\n    end\n    disp(' ');\nend\n\n% Output number of sessions/conditions/columns for each subject\n\nif any(np-np(1))\n    disp('Error in FFX specification: all subject should have same number of parameters');\n    return\nend\n\nspm_jobman('run',matlabbatch);\n\nout.spmmat{1} = fullfile(job.dir{1},'SPM.mat');\n\n%==========================================================================\n% function dep = vout_ffx(job)\n%==========================================================================\nfunction dep = vout_ffx(job)\ndep = cfg_dep;\ndep.sname      = 'SPM.mat File';\ndep.src_output = substruct('.','spmmat');\ndep.tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\n\n%==========================================================================\n% function out = spm_local_mfx(job)\n%==========================================================================\nfunction out = spm_local_mfx(job)\nload(job.spmmat{1},'SPM');\nc = job.contrast;\nif isempty(c)\n    n = length(SPM.Sess);\n    c = ones(n,1);\nend\nspm_mfx(SPM,c);\nout.spmmat{1} = fullfile(fileparts(job.spmmat{1}),'mfx','SPM.mat');\n\n%==========================================================================\n% function dep = vout_mfx(job)\n%==========================================================================\nfunction dep = vout_mfx(job)\ndep = cfg_dep;\ndep.sname      = 'SPM.mat File';\ndep.src_output = substruct('.','spmmat');\ndep.tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_mfx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2385039940382634}}
{"text": "rows = 240;\ncols = 360;\n%fps = 1;\nfps = 1/88800; \nblk = 5;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20160-video-surveillance-system-design-with-simulink%C2%AE-and-xilinx%C2%AE-fpgas/seminar_designs/Xilinx Section/hw_cosim_modified/init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23846091479965809}}
{"text": "function [stats, handles] = canlab_force_directed_graph(activationdata, varargin)\n% Creates a force-directed graph from a set of variables, and plots\n% clusters on 3-D brain as well if entered. Requires matlab BGL toolbox.\n%\n% :Usage:\n% ::\n%\n%    canlab_force_directed_graph(activationdata OR connection matrix, ['cl', cl])\n%\n%\n% ..\n%     Author and copyright information:\n%     -------------------------------------------------------------------------\n%     Copyright (C) 2013  Tor Wager\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n%\n% :Inputs:\n%\n%   **activationdata:**\n%        observations x variables matrix of data to be\n%        inter-correlated (variables will be inter-correlated)\n%\n%        OR\n%\n%        signed, thresholded connection matrix to be used (e.g.,\n%        average time-series correlation matrix across individuals\n%        it's also possible to use thresholded t-values from multi-subject group analysis\n%\n%        If working with multi-subject time series data, best to enter connection matrix\n%        as this function does not run models with participants as random\n%        effects.\n%\n% :Optional Inputs: Enter keyword followed by variable with values\n%\n%   **'cl':**\n%        followed by clusters or region structure with brain clusters\n%\n%   **'threshtype':**\n%        followed by threshold type; 'bonf' [default] or 'fdr'\n%\n%   **'connectmetric':**\n%        followed by node connection metric 'corr' or 'partial_corr'\n%\n%   **'sizescale':**\n%        Followed by values to use in sizing of nodes on graph\n%        'linear' 'sigmoidal' [default] or 'custom'\n%\n%   ** 'sizes' **\n%       Followed by vector of point sizes for all points - works ONLY if sizescale\n%       is set to 'custom'\n%\n%   **'rset', 'partitions':**\n%        Cell of vectors, with indices (integers) of member\n%        elements in each group, [1 x g] cell\n%        rset can ALSO be a vector of integers, i.e., output\n%        from clusterdata\n%\n%   **'setcolors', 'partitioncolors':**\n%        Cell array of colors for each group, [1 x g]\n%\n%   **'names':**\n%       followed by cell array of names for each region/object\n%\n%   **'namesfield':**\n%       followed by name of field to extract region/object names from in\n%       clusters structure\n%\n%   **'linewidth':**\n%       followed by line width\n%\n%   **'linestyle':**\n%       followed by line style. Default is 'curved', anything else is\n%       'straight'\n%\n% :Output:\n%\n%   **stats:**\n%        structure with descriptive statistics, including\n%        betweenness-centrality, degree of each node\n%\n% :Examples:\n% ::\n%\n%    [stats, handles] = canlab_force_directed_graph(activationdata, 'cl', cl, 'namesfield', 'shorttitle');\n%    [stats, handles] = canlab_force_directed_graph(activationdata, 'cl', cl, 'namesfield', 'shorttitle', 'degree');\n%    [stats, handles] = canlab_force_directed_graph(activationdata, 'cl', cl, 'namesfield', 'shorttitle', 'degree', 'rset', rset, 'setcolors', setcolors);\n%\n%    [stats, handles] = canlab_force_directed_graph(G, 'sizescale', 'custom', 'sizes', [6*ones(17, 1); 12*ones(7, 1)]);\n\n% ..\n%    DEFAULTS AND INPUTS\n% ..\n\nshan = [];              % outputs\nspherehan = [];\nhandles = [];\n\ncl = [];\nthreshtype = 'bonf';\nconnectmetric = 'corr';  % or partial_corr\nsizescale = 'sigmoid';\nsizes = ones(min(size(activationdata)), 1);\nlinestyle = 'curved';\n\nsetcolors = [];         % control of color subgroups\nrset = [];\n\nptsizetype = 'bc';\nnames = [];\nnamesfield = [];        % enter field name, e.g., 'shorttitle'\nlinewidth = 1;\n\ndofigure = true;\n\n% Variable arg inputs\n% -----------------------------------\n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch lower(varargin{i})\n            % reserved keywords\n            case 'degree', ptsizetype = 'degree';\n                %case 'design'\n                \n                % functional commands\n            case 'cl', cl = varargin{i + 1}; varargin{i + 1} = [];\n                \n            case 'linewidth', linewidth = varargin{i + 1}; varargin{i + 1} = [];\n                \n            case 'linestyle', linestyle = varargin{i + 1}; varargin{i + 1} = [];\n            \n            case 'partitions', rset = varargin{i + 1}; varargin{i + 1} = [];\n                \n            case 'partitioncolors', setcolors = varargin{i + 1}; varargin{i + 1} = [];\n                    \n            case {'threshtype' 'connectmetric' 'sizescale' 'setcolors' 'rset' 'names' 'namesfield' 'sizes' 'fdr'}\n                eval([varargin{i} ' = varargin{i + 1}; varargin{i + 1} = [];'])\n                \n            case {'nofigure', 'nofig'}\n                dofigure = false;\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n\n% Check vars, etc.\n% ---------------------------------------------------------------------\n% if isdir('/Users/tor/Documents/matlab_code_external/matlab_bgl')\n%     g = genpath('/Users/tor/Documents/matlab_code_external/matlab_bgl');\n%     addpath(g);\n% end\n% \n% if ~exist('fruchterman_reingold_force_directed_layout.m', 'file')\n%     error('Must have Matlab BGL toolbox on path (external toolbox)');\n% end\n\nactivationdata = double(activationdata);\n\nif ~isempty(cl) && (size(activationdata, 2) ~= length(cl))\n    disp('activationdata must have as many columns as clusters has elements.')\n    error('check activationdata and clusters to make sure they match.')\nend\n\nif isempty(rset)\n    rset = {1:size(activationdata, 2)};\nend\n\nif isempty(setcolors)\n    setcolors = scn_standard_colors(length(rset));\nend\n\nif ~isempty(namesfield)\n    names = {cl.(namesfield)}';\nend\n\nif ~iscell(rset) % then integer vector\n    for i = 1:max(rset)\n        rset2{i} = find(rset == i);\n    end\n    rset = rset2;\nend\n\n\n% -------------------------------------------------------------------------\n% CALCULATIONS\n% -------------------------------------------------------------------------\nif issymmetric(activationdata)\n    fprintf('Thresholded association matrix detected.\\n')\n    [b, C, r, sig] = deal(activationdata);\n    thr = NaN;\n    \nelse\n    fprintf('activationdata appears to be raw data. Running inter-correlations. See also xcorr_multisubject.\\n')\n    \n     switch connectmetric\n        case 'partial_corr'\n            \n            % Partial correlation slopes (r is actually slope)\n            [r, p] = calc_partial_r(activationdata);\n            \n            b = r;\n            \n         case 'corr' % default\n             \n            [r, p] = corr(double(activationdata));\n             \n            b = [];\n            \n         otherwise error('Unknown connectmetric');\n     end\n     \n     sz = size(r, 1);\n     \n     switch threshtype\n         case 'bonf'\n             thr = .05 ./ (sz * (sz - 1) / 2);  % bonferroni...\n             \n         case 'fdr'\n             \n             thr = p_matrix2fdrthresh(p);             \n             \n     end\n\n     C = r;\n     \n     % Threshold\n     sig = sparse(double(p < thr & r > 0));\n     signeg = sparse(-double(p < thr & r < 0));\n     sig = sig + signeg;\n     \n     C(~sig) = 0;\n     \n     \n     % Threshold based on significant partial regression effects\n     % C is connectivity matrix for graph\n     \n   \n    \n    % end if issymmetric\nend\n\n% Enforce format for graph\nC = (C + C') ./ 2;\nC = sparse(C);\n\n% Graph Stats\n% -----------------------------------------------\n\n% 2020: Use Matlab graph object\nG = graph(C);\n\n%bc = betweenness_centrality(abs(C));  % abs if ignoring neg connections\nbc = centrality(G, 'betweenness');  % 'Importance', IMP\n\n% shortest paths: used as estimate of connectivity\n% [D S] = mean_path_length(r, rset);\n% shortest path using POSITIVE edges only\nGG = G;\nGG.Edges.Weight( G.Edges.Weight < 0) = 0;\n\n[D S] = mean_path_length(GG, rset);\n\n\ndeg = full(sum(C ~= 0))';\n\nstats.names = names;\nstats.rset = rset;\nstats.C = C;\nstats.r = r;\nstats.b = b;\n\nif exist('p', 'var')\n    stats.p = p;\nend\n\nif exist('sig', 'var')\n    stats.sig = sig;\nend\n\nstats.thr = thr;\nstats.betweenness = bc;\n%stats.path_length_distance = D;\nstats.degree = deg;\n%stats.mean_path_by_rset = S;\n\n\nswitch ptsizetype\n    case 'bc'\n        ptsizemetric = bc;\n    case 'degree'\n        ptsizemetric = deg;\n    case 'none'\n        ptsizemetric = ones(size(bc));\n    otherwise error('Unknown ptsizetype');\nend\nif strcmp(sizescale,'custom')\n   fprintf('Node size reflects custom scaling\\n');\nelse\n    fprintf('Node size reflects %s\\n', ptsizetype);\nend\n% -------------------------------------------------------------------------\n% Force-directed graph\n% -------------------------------------------------------------------------\n\n% Xc is coordinate matrix\n% Xc = fruchterman_reingold_force_directed_layout(C);\n\nhan = plot(G, 'Layout', 'force');   % Get layout\nXc = [han.XData; han.YData]';\ndelete(han);                        % erase\n\n% could rotate here\n% ***\n\nif dofigure\n    if ~isempty(cl)\n        create_figure('graph', 1, 2);\n    else\n        create_figure('graph');\n    end\nend\n\nswitch lower(linestyle)\n    \n    case 'curved'\n        \n        han = nmdsfig_tools('drawlines',Xc, sig, [.5 .5 .5; 0 1 1],[{'-'} {':'}], .1);\n        handles.lh_pos = han.hhp;\n        handles.lh_neg = han.hhn;% Dots\n        %set(handles.lh_pos, 'Color', [.5 .5 .5])\n        set(handles.lh_neg, 'Color', [0 .5 1], 'LineStyle', ':')\n\n    otherwise\n        \n        gplot(sig>0, Xc, 'k');\n        axis image\n        lh = findobj(gca, 'Type', 'line');\n        set(lh, 'Color', [.5 .5 .5])\n        \n        handles.lh_pos = lh;\n        \n        gplot(sig<0, Xc, 'b');\n        lh = findobj(gca, 'Type', 'line', 'color', 'b');\n        set(lh, 'Color', [0 .5 1], 'LineStyle', ':')\n        \n        handles.lh_neg = lh;\n        \nend\n\nswitch sizescale\n    case 'linear'\n        %         sizes = 4 + 15 * intensity.(cnames{i}) ./max(intensity.(cnames{i}));  % LC none of these variables exist in the workspace\n        sizes = 4 + 15 * ptsizemetric ./ max(ptsizemetric);\n        \n    case 'sigmoid'\n        % Rationale: avoids some VERY large points in areas highly\n        % focused on as a priori ROIs, with extreme z-scores in\n        % intensity relative to other areas.\n        \n        sizes = sigmoidscale(ptsizemetric);\n        \n    case 'custom'\n        % we already have sizes\nend\n\nph = [];\ntexth = {};\n\nfor k = 1:length(rset)\n    \n    texth{k} = [];\n    \n    for j = 1:length(rset{k})\n        \n        ph(end+1) = plot(Xc(rset{k}(j), 1), Xc(rset{k}(j), 2), 'o', 'Color', setcolors{k} ./ 2, 'MarkerSize', sizes(rset{k}(j)), 'MarkerFaceColor', setcolors{k}, 'LineWidth', linewidth);\n        \n        if ~isempty(names)\n            offset = .02 * range(get(gca, 'XLim'));\n            texth{k}(end+1) = text(Xc(rset{k}(j), 1)+offset, Xc(rset{k}(j), 2), strrep(names{rset{k}(j)}, '_', ' '), 'Color', 'k', 'FontSize', 14);\n        end\n    end\n    \nend\n\nhandles.ph = ph;\nhandles.texth = texth;\n\nxlim = get(gca, 'XLim');  rg = range(xlim) * [-.05 .05]; xlim = xlim + rg;\nylim = get(gca, 'YLim'); rg = range(ylim) * [-.05 .05]; ylim = ylim + rg;\nset(gca, 'XLim', xlim, 'YLim', ylim);\naxis off\ndrawnow\n\nstats.Xc = Xc;\nstats.sizes = sizes;\n\n\n\n\nif isempty(cl), return, end\n\n% -------------------------------------------------------------------------\n% Subcortical surface\n% Only if cl is entered\n% -------------------------------------------------------------------------\n\n% NOTE: you need 3dHeadUtilityLite on your matlab path.\nsubplot(1, 2, 2)\n\n% regioncenters\nxyz = cat(1, cl.mm_center);\n\nDB = struct('xyz', xyz, 'x', xyz(:, 1), 'y', xyz(:, 2), 'z', xyz(:, 3));\n\n% sizes = sigmoidscale(ptsizemetric, 2, 6);\nsizes = sizes ./ 2.5; % rescale to avoid huge ones\n\n% Make Brain with Spheres\n% ------------------------------------------------------------\n\n[shan, spherehan] = connectivity3dbrain(xyz, rset, sizes, setcolors, names);\n\n% Add lines\n% ------------------------------------------------------------\n\n[~, linehandles] = cluster_nmdsfig_glassbrain(cl,ones(length(cl), 1), {[.5 .5 .5]}, sig, [], 'samefig', 'nobrain', 'noblobs', linestyle);\nset(linehandles, 'LineWidth', 2)\n\ndrawnow\n%saveas(gcf, fullfile(savefigdir, ['graph3d_v2_' cnames{i} '.png']));\n\nhandles.surfhan = shan;\nhandles.spherehan = spherehan;\nhandles.linehandles = linehandles;\n\nend % function\n\n\n\n\nfunction [b p] = calc_partial_r(activationdata)\n\nX = activationdata;\nX = zscore(X);\n%X(isnan(X)) = mean(X(~is;\n\nclear b p\n\nfor i = 1:size(X, 2)\n    y = X(:, i);\n    xx = X;\n    xx(:, i) = 1;  % intercept; need it, and also placeholder\n    \n    [bb, dev, statsglm] = glmfit(xx, y, 'normal', 'constant', 'off');\n    \n    b(:, i) = bb;\n    p(:, i) = statsglm.p;\n    p(i, i) = 1;\n    b(i, i) = NaN;\n    \nend\n\n\nend % function\n\n\n\n\n\nfunction sizes = sigmoidscale(sizes, varargin)\n% sizes = sigmoidscale(sizes, [lower bound], [upper bound])\n%\n% rescales a vector based on sigmoid function of zcore(input values)\n\n% Rationale: avoids some VERY large points in areas highly\n% focused on as a priori ROIs, with extreme z-scores in\n% intensity relative to other areas.\n\n% scale size of nodes - intensity, or betweenness\nsizes = zscore(sizes);\n\nA = 4; % lower asymptote\nK = 15; % upper asymptote\n\nif nargin > 2\n    A = varargin{1};\n    K = varargin{2};\nend\n\nB = 2;   % growth rate\nv = .5;  % high-growth asymptote\nQ = .5;\nM = .5;  % time of max growth, if v = Q\n\nrichards = @(x, A, K, B, v, Q, M) A + (K - A) ./ ((1+Q*exp(-B*(x-M))).^(1/v));\n\n%figure; plot(sort(sizes), richards(sort(sizes), A,K,B,v,Q,M));\nsizes = richards(sizes, A,K,B,v,Q,M);\n\nend\n\n\n\n\nfunction [C S] = mean_path_length(G, rset)\n% compute matrix of 1/path lengths for n x n matrix of regions, C (connectivity)\n% and 1 / mean path length for sets of regions specified by rset\n%\n% r is a correlation matrix\n% rset is a cell array of length k, for k sets, with vectors describing the\n% indices of members of each set.\n%\n% e.g., r = region_r{i};\n\n% 2020: Use Matlab Graph object\n% \n% r(isnan(r)) = 0;\n% r = (r' + r) ./ 2;  % enforce symmetry, just in case\n% \n% \n% % shortest paths: used to calculate connectivity\n% rtmp = sparse(r);\n% rtmp(rtmp < 0) = 0;\n\nC = distances(G);\n\n% OLDNote: Uses Floyd-Warshall method if 10% non-zero elements or more\n% C = all_shortest_paths(rtmp);\n\n\n% for each set, average elements of D corresponding to pairs of SETS\n% return averages in S\n%\n% e.g., if D is min path length, S is the average min path length for Set 1\n% vs. 2, 1 vs. 3, 2 vs. 3, etc.\n\n% for inf values, we must impute some finite value or every average is Inf\n% (i.e., if any regions are unconnected)\n% impute max:\n% but maybe better to work on unthresholded r matrix.\n% Or, even better, return 1/S, 1 / mean path length, so unconnected\n% regions/sets get 0.\n%  mx = max(D(~isinf(D)));\n%  D(isinf(D)) = mx;\n\nS = zeros(length(rset));\n\nfor m = 1:length(rset)-1\n    for n = m:length(rset)\n        \n        % set m to set n relationships (e.g., shortest path lengths)\n        vals = 1 ./ C(rset{m}, rset{n});\n        \n        % average, excluding \"self-connections\" with value Inf\n        S(m, n) = mean(vals(~isinf(vals)));\n        \n    end\nend\n\nS = S + S';\n\nend\n\n\n\nfunction [shan, spherehan] = connectivity3dbrain(regioncenters, rset, sizes, setcolors, names)\n\n% Colors\n% ----------------------------------------------------------\n\nctxcolors = cell(1, size(regioncenters, 1));\n\nfor i = 1:length(rset)\n    \n    for j = 1:length(rset{i})\n        \n        wh = rset{i}(j);\n        \n        ctxcolors(rset{i}) = setcolors(i);\n        \n    end\nend\n\n% Brain\n% ----------------------------------------------------------\n\n%create_figure('subcortex');\n\nshan = addbrain('limbic');\ndelete(shan(end));\nshan = shan(1:end-1);\n\nshan = [shan addbrain('hires left')];\nshan = [shan addbrain('brainstem')];\n\nset(shan(end-1), 'FaceColor', [.5 .5 .5], 'FaceAlpha', .15);\nset(shan(1:end-2), 'FaceColor', [.5 .5 .5], 'FaceAlpha', .3);\nset(shan(end), 'FaceColor', [.5 .5 .5], 'FaceAlpha', .3);\n\nview(89, 1);\nlightRestoreSingle;\n\nlighting gouraud;\n\n% Spheres\n% ----------------------------------------------------------\n\n% add spheres\n% cortex is special, because it involves different colors\n\n% xyz = regioncenters(rset{1}, :);\n% sz = sizes(rset{1});\n% if ~isempty(names)\n%     mynames = names(rset{1});\n% end\n\nxyz = regioncenters;\nsz = sizes;\nif ~isempty(names)\n    mynames = names;\nend\n\nfor i = 1:size(xyz, 1)\n    spherehan(i) = cluster_image_sphere(xyz(i, :), 'color', ctxcolors{i}, 'radius', sz(i));\n    \n    if ~isempty(names)\n        offset = .04 * range(get(gca, 'XLim'));\n        text(xyz(i, 1)+offset, xyz(i, 2)+offset, xyz(i, 3)+offset, mynames{i}, 'Color', 'k', 'FontSize', 14);\n    end\nend\nspherehan = {spherehan};\n\n% for i = 2:length(rset)\n%\n%     xyz = regioncenters(rset{i}, :);\n%     sz = sizes(rset{i});\n%     if ~isempty(names)\n%     mynames = names(rset{i});\n%     end\n%\n%     spherehan{i} = cluster_image_sphere(xyz, 'color', setcolors{i}, 'radius', sz);\n%\n%     if ~isempty(names)\n%         offset = .02 * range(get(gca, 'XLim'));\n%         for j = 1:size(xyz, 1)\n%             text(xyz(j, 1)+offset, xyz(j, 2)+offset, xyz(j, 3)+offset, mynames{j}, 'Color', 'k', 'FontSize', 14);\n%         end\n%     end\n%\n% end\n\n\nend % function\n\n\n\n\nfunction thr = p_matrix2fdrthresh(p)\n\ntrilp = tril(p, -1);\nwh = logical(tril(ones(size(p)), -1)); % Select off-diagonal values (lower triangle)\ntrilp = double(trilp(wh));             % Vectorize and enforce double\ntrilp(trilp < 10*eps) = 10*eps;        % Avoid exactly zero values\nfdrthr = FDR(trilp, 0.05);\n\nif isempty(fdrthr), fdrthr = -Inf; end\nthr = fdrthr;\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/canlab_force_directed_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23846091479965803}}
{"text": "function [surface_handles, colors] = isosurface(r, varargin)\n% Create a series of surfaces in different colors, one for each region\n% - Options for single color\n%\n% [surface_handles, colors] = isosurface(r, [optional arguments])\n%\n% optional arguments: \n% - Any optional inputs to imageCluster, e.g., 'alpha'\n% - 'colors', followed by single color in { } or cell array of multiple colors\n% - 'nomatchleftright' or 'nosymmetric', do not match colors across hemispheres (left/right)\n%               Note: The default matches, and may override your colors.\n%\n% Examples:\n% atlasfile = which('Morel_thalamus_atlas_object.mat');\n% load(atlasfile)\n%\n% surface_handles = isosurface(r);\n% surface_handles = isosurface(r, 'alpha', .5);\n% surface_handles = isosurface(r, 'alpha', .5, 'nomatchleftright');\n%\n% view(135, 30);\n% lightRestoreSingle;\n% lightFollowView;\n%\n% load(which('CIT168_MNI_subcortical_atlas_object.mat'));\n% r = atlas2region(atlas_obj);\n%\n% surface_handles = isosurface(r, 'alpha', .5, 'color', {[.3 .6 .4] [.5 .4 .2]});\n% surface_handles = isosurface(r, 'alpha', .5, 'color', {[.3 .6 .4] [.5 .4 .2]}, 'nomatchleftright');\n% p = addbrain('hires right');\n% lightFollowView;\n\n\nk = length(r);\n\n% ..\n%    DEFAULTS AND INPUTS\n% ..\n\n% input_args = varargin;           % save for later\ncolors = scn_standard_colors(k); % generate colors\nmatchcolorsleftright = true;\n\n% optional inputs with default values\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n\n            % do nothing for inputs passed on to imageCluster\n            case {'alpha'}  \n                \n            case {'color', 'colors'}\n                colors = varargin{i+1}; varargin{i+1} = []; varargin{i} = [];\n                if length(colors) == 1 % single color; matchcolorsleftright will overwrite this\n                    matchcolorsleftright = false;\n                end\n                \n            case {'nomatchleftright', 'nosymmetric'}, matchcolorsleftright = false; varargin{i} = [];\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n\nif iscolumn(colors), colors = colors'; end\n\n% Handle single-color input, and other cases where too few colors:\nwhile length(colors) < k, colors = [colors colors]; end\n\nif matchcolorsleftright\n    colors = match_colors_left_right(r);\nend\n\ncolors = colors(1:length(r));\n\n% -------------------------------------------------------------------------\n% Make surfaces\n% -------------------------------------------------------------------------\n\ncl = region2struct(r);\n\nsurface_handles = [];\n\nfor i = 1:k\n    \n    try\n        out = imageCluster('cluster', cl(i), 'color', colors{i}, varargin{:});\n        \n        surface_handles(i) = out;\n    catch\n        disp('Error imaging isosurface; too few voxels?')\n        %surface_handles(i) = [];\n    end\n    \n%     % Isocaps, if needed\n%     \n%     % pp = [];\n%     isocap = isocaps(mesh_struct.X, mesh_struct.Y, mesh_struct.Z, V, mythresh);\n%     p(end + 1) = patch(isocap, 'FaceColor', 'interp','EdgeColor', 'none', 'FaceAlpha',1);\n\n\nend\n\n\n% -------------------------------------------------------------------------\n% Lighting, etc.\n% -------------------------------------------------------------------------\n\nlightRestoreSingle;\nlighting gouraud;\naxis vis3d image\nmaterial dull\n\nend % function\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@region/isosurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2384021541064203}}
{"text": "%\tOVERVIEW:\n%       This is demo for the HRV PhysioNet Cardiovascular Signal Toolbox \n%       using RR intervals with annotations. \n%       Provided data are a subset from the MIT Physionet \n%       NSR dataset, which contains long-term ECG recordings of subjects \n%       in normal sinus rhythm.\n%       It shows how to automaticly import multiple files from a folder, \n%       perfrom the HRV analysis on each of them and then store the results \n%       in .csv format.  \n%       It uses the default parameters in the configuration file using \n%       'demo_NSR' option : InitializeHRVparams('demo_NSR').\n%\n%   OUTPUT:\n%       HRV Metrics exported to .cvs files\n%\n%   DEPENDENCIES & LIBRARIES:\n%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%   REFERENCE: \n%       Vest et al. \"An Open Source Benchmarked HRV Toolbox for Cardiovascular \n%       Waveform and Interval Analysis\" Physiological Measurement (In Press), 2018. \n%\tREPO:       \n%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%   ORIGINAL SOURCE AND AUTHORS:     \n%       Giulia Da Poian   \n%\tCOPYRIGHT (C) 2018 \n%   LICENSE:    \n%       This software is offered freely and without warranty under \n%       the GNU (v3 or later) public license. See license file for\n%       more information\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear; clc; close all;\n\nrun(['..' filesep 'startup.m'])\n\n% Remove old files generated by this demo\nOldFolder = [pwd,filesep, 'OutputData', filesep, 'ResultsNSR'];\nif exist(OldFolder, 'dir')\n    rmdir(OldFolder, 's');\n    fprintf('Old Demo Folder deleted \\n \\n');\nend\n\n\n% Initialize settings for demo\nHRVparams = InitializeHRVparams('demo_NSR');  \nHRVparams.MSE.on = 0; % No MSE analysis for this demo\nHRVparams.DFA.on = 0; % No DFA analysis for this demo\nHRVparams.HRT.on = 0; % No HRT analysis for this demo\nHRVparams.output.separate = 0;   % For this demo write all the results in one file \n\n\n% Check for a list of files to be analyzed in current directory in .dat format\n[subjectIDs,filesTBA] = GenerateListOfFilesTBA(HRVparams.ext, HRVparams.readdata,[]);\n\n% Prepare for parallel loop by eliminating variables\nclear nummatchingfiles x i filename flag match\nnumsub = length(subjectIDs);\nnotAnalyzed = 0;\n\n% NOTE: This loop can be run in parallel by changing the loop to a parfor\n% loop.\nfor i_patient = 1:numsub   \n    \n    thisPatient = strcat(HRVparams.readdata, filesep, subjectIDs(i_patient));\n    try\n        \n        % 1. Import Patient Data\n        RRwindowStartIndices = [];\n        tNN = [];\n        NN = [];\n        [samples,annotations] = read_ann(thisPatient{1},HRVparams.ext);\n        rr = diff(samples)./HRVparams.Fs; \n        t = cumsum(rr);\n        \n        % Demo keeps only the first 2h \n        \n        rr = rr(t<60*60*2);\n        t = t(t<60*60*2);\n               \n        % 2. Perform HRV analysis on the RR intervals\n        [results, resFilenameHRV] = Main_HRV_Analysis(rr,t,'RRIntervals',HRVparams,subjectIDs(i_patient),annotations);\n        currentFile = [HRVparams.writedata filesep resFilenameHRV.HRV '.csv'];\n\n        fprintf('\\n');\n    catch\n       \n        results = NaN;\n        col_titles = {'NaN'};\n        currentFile = '';\n        notAnalyzed = 1;\n        fprintf('Error on subject %s \\n', char(subjectIDs(i_patient)));    \n\n    end\n    \nend\n\n\n% 3. Compare generated output file with the reference one\n\nreferenceFile = ['ReferenceOutput' filesep 'NSR_HRV_allwindows_allpatients.csv'];\ntestHRV = CompareOutput(currentFile,referenceFile);\n\nif testHRV\n    fprintf('\\n ** DemoAnnotatedData: TEST SUCCEEDED ** \\n ')\nelseif notAnalyzed == 0\n    fprintf('\\n ** DemoAnnotatedData: TEST FAILED ** \\n')\n    fprintf('Error: generated output does not match reference \\n')\nelseif notAnalyzed == 1\n    fprintf('\\n** DemoAnnotatedData: TEST FAILED ** \\n')\n    fprintf('Error: analysis not performed \\n');    \nend\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Demos/DemoAnnotatedData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2384021541064202}}
{"text": "% Create new IM\nnewIndex = createNewIM();\n\n% Compute dose for a beam\ngantryAngle = 70;\nisoCenter.x = 0;\nisoCenter.y = -55;\nisoCenter.z = -115;\nnewIndex = 2;\nplanC = batchCalcDose(newIndex,gantryAngle,isoCenter);\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/sample_batchCalcDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23833124840630765}}
{"text": "function varargout = process_arima( varargin )\n% PROCESS_ARIMA: Auto-regressive Moving Average filter \n%\n% USAGE:   sProcess = process_arima('GetDescription')\n%            sInput = process_arima('Run', sProcess, sInput, method=[])\n%                 F = process_arima('Compute', F, Fbase, Order)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2010-2015\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'ARIMA filter';\n    sProcess.FileTag     = 'arima';\n    sProcess.Category    = 'Filter';\n    sProcess.SubGroup    = 'Pre-process';\n    sProcess.Index       = 68;\n    sProcess.Description = '';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data', 'results', 'raw', 'matrix'};\n    sProcess.OutputTypes = {'data', 'results', 'raw', 'matrix'};\n    sProcess.nInputs     = 1;\n    sProcess.nMinFiles   = 1;\n    sProcess.processDim  = 1;   % Process channel by channel\n    \n    % Definition of the options\n    % === Baseline time window\n    sProcess.options.baseline.Comment = 'Baseline:';\n    sProcess.options.baseline.Type    = 'baseline';\n    sProcess.options.baseline.Value   = [];\n    % === Filter order\n    sProcess.options.order.Comment = 'Order of the filter:';\n    sProcess.options.order.Type    = 'value';\n    sProcess.options.order.Value   = {5,'',0};\n    % === Sensor types\n    sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): ';\n    sProcess.options.sensortypes.Type    = 'text';\n    sProcess.options.sensortypes.Value   = 'MEG, EEG';\n    sProcess.options.sensortypes.InputTypes = {'data', 'raw'};\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n    Order = sProcess.options.order.Value{1};\n    if isfield(sProcess.options, 'baseline') && isfield(sProcess.options.baseline, 'Value') && iscell(sProcess.options.baseline.Value) && ~isempty(sProcess.options.baseline.Value) && ~isempty(sProcess.options.baseline.Value{1})\n        Time = sProcess.options.baseline.Value{1};\n    else\n        Time = [];\n    end\n    if isempty(Time)\n        Comment = 'ARIMA(%d,1,0) - Baseline: [All file]';\n    elseif any(abs(Time) > 2)\n        Comment = sprintf('ARIMA(%d,1,0) - Baseline: [%1.3fs,%1.3fs]', Order, Time(1), Time(2));\n    else\n        Comment = sprintf('ARIMA(%d,1,0) - Baseline: [%dms,%dms]', Order, round(Time(1)*1000), round(Time(2)*1000));\n    end\nend\n\n\n%% ===== RUN =====\nfunction sInput = Run(sProcess, sInput) %#ok<DEFNU>\n    % Get options\n    Order = sProcess.options.order.Value{1};\n    if isfield(sProcess.options, 'baseline') && isfield(sProcess.options.baseline, 'Value') && iscell(sProcess.options.baseline.Value) && ~isempty(sProcess.options.baseline.Value) && ~isempty(sProcess.options.baseline.Value{1})\n        BaselineBounds = sProcess.options.baseline.Value{1};\n    else\n        BaselineBounds = [];\n    end\n    % Get baseline indices\n    if ~isempty(BaselineBounds)\n        iBaseline = panel_time('GetTimeIndices', sInput.TimeVector, BaselineBounds);\n        if isempty(iBaseline)\n            bst_report('Error', sProcess, [], 'Invalid baseline definition.');\n            sInput = [];\n            return;\n        end\n    % Get all file\n    else\n        iBaseline = 1:size(sInput.A,2);\n    end\n    % Filter data\n    sInput.A = Compute(sInput.A, sInput.A(:,iBaseline), Order);\n    % Error handling \n    if isempty(sInput.A)\n        bst_report('Error', sProcess, [], 'Error while filtering the signal.');\n        sInput = [];\n        return;\n    end\n    % Do not keep the Std field in the output\n    if isfield(sInput, 'Std') && ~isempty(sInput.Std)\n        sInput.Std = [];\n    end\nend\n\n\n%% ===== EXTERNAL CALL =====\n% USAGE: process_arima('Compute', F, Fbase=[], Order=5)\nfunction F = Compute(F, Fbase, Order)\n    % Default order: 5\n    if (nargin < 3) || isempty(Order)\n        Order = 5;\n    end\n    % If there is no baseline, use the whole time segment\n    if (nargin < 2) || isempty(Fbase)\n        Fbase = F;\n    end\n    Nsig = size(F,1);\n    \n    % If order is 0, just diff the signal\n    if (Order == 0)\n        % Detrend and diff data to filter\n        F = diff(detrend(F'))';\n        % Add one sample at the beginning to account for the diff\n        F = [F(:,2), F];\n    else\n        % Detrend and diff baseline\n        Fbase = diff(detrend(Fbase'));\n        % Compute AR model for each signal\n        if bst_get('UseSigProcToolbox')\n            arm = lpc(Fbase, Order);\n        else\n            arm = zeros(Nsig, Order+1);\n            for i = 1:Nsig\n                arm(i,:) = oc_lpc(Fbase(:,i), Order);\n            end\n        end\n        % Remove the ones for each it cannot be estimated\n        arm(any(isnan(arm),2),:) = [];\n        % If there is nothing left, error\n        if isempty(arm)\n            F = [];\n        end\n        % Average all the models\n        arm = mean(arm,1);\n\n        % Detrend and diff data to filter\n        F = diff(detrend(F'));\n        % Add a few samples of mirrored signal at the beginning to minimize the edge effects\n        F = [F(length(arm)+1:-1:1,:); F];\n        % Apply filter to the data\n        F = filter(arm, 1, F)';\n        % Remove the mirrored samples (keep one, to account for the diff)\n        F(:,1:length(arm)) = [];\n    end\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_arima.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23833124840630765}}
{"text": "function plotPredictionResults_STS(pathResults,fSetName,metrics,maxOrder)\n% -------------------------------------------------------------------------\n% function plotPredictionResults_STS(pathResults,fSetName,metrics,maxOrder)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function plots prediction performance estimation results for all the\n% different feature set types entered as inputs. See ref. [1] for more\n% details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% - pathResults: Full path to the 'RESULTS' folder where prediction results\n%                are saved.\n% - fSetName: Cell of strings specifying the name of the type of feature \n%                 sets to analyze.\n%                 Example: fSetName = {'PET','SEPARATE','FUSED'}\n% - metrics: Name of the metrics to show in the plots. \n%            Example: metrics = {'AUC632','Sensitivity632','Specificity632'}\n% - maxOrder: Integer specifying the maximal multivariable model order. \n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: May 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ncd(pathResults)\n\nsigns = {'-r',':b','--g'};\nnFSET = numel(fSetName);\nnMetrics = numel(metrics);\nfigure\nfor i = 1:nFSET\n    val = zeros(maxOrder,numel(metrics));\n    val_SE = zeros(maxOrder,nMetrics);\n    results = load(['RESULTS_',fSetName{i},'_BEST']); results = struct2cell(results); results = results{1};\n    for j = 1:maxOrder\n        orderName = ['Order',num2str(j)];\n        for k =1:nMetrics\n            val(j,k) = results.(orderName).(metrics{k});\n            val_SE(j,k) = results.(orderName).(['SE_',metrics{k}]);\n        end\n    end\n    subplot(1,nFSET,i)\n    for k = 1:nMetrics\n        errorbar(1:maxOrder,val(:,k),val_SE(:,k),signs{k},'LineWidth',2,'MarkerFaceColor',signs{k}(end),'MarkerSize',4)\n        hold on\n    end\n    xlabel('Model Order','FontSize',24)\n    ylabel('Prediction performance','FontSize',24)\n    title(fSetName{i},'FontSize',30,'FontWeight','bold')\n    legend(metrics,'Location','SouthEast')\n    axis([0 maxOrder+1 0.5 1])\n    set(gca,'FontSize',20)\n    set(gca,'XTick',[1 2 3 4 5 6 7 8 9 10])\n    hold off\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/STS_study/Functions/plotPredictionResults_STS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.23818812057617444}}
{"text": "%-----------------------------------------------------------------------\n% Job saved on 02-Jul-2014 11:27:33 by cfg_util (rev $Rev$)\n% spm SPM - SPM12b (5672)\n% cfg_basicio BasicIO - Unknown\n%-----------------------------------------------------------------------\nmatlabbatch{1}.spm.spatial.smooth.data = '<UNDEFINED>';\nmatlabbatch{1}.spm.spatial.smooth.fwhm = [8 8 8];\nmatlabbatch{1}.spm.spatial.smooth.dtype = 0;\nmatlabbatch{1}.spm.spatial.smooth.im = 0;\nmatlabbatch{1}.spm.spatial.smooth.prefix = 's';\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImageSpm4D/matlabbatch/mb_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.23818812057617444}}
{"text": "% PURPOSE: subroutine for ploterpGUI.m\n%          identifies minimum and maximum values of ERP amplitudes for Y scaling.\n%\n% FORMAT\n%\n%  [yylim, serror] = erpAutoYLim(ERP, binArray, chanArray, xxlim)\n%\n% INPUTS\n%\n% ERP         - ERPset\n% binArray    - indices of bins from where to get the amplitude values\n% chanArray   - indices of channels from where to get the amplitude values\n% xxlim       - current scale for time ([min max] in ms)\n%\n%\n% OUTPUT\n%\n% yylim       - range for Y scale\n% serror      - error flag. 0 means no errors.\n%\n% *** This function is part of ERPLAB Toolbox ***\n% Author: Javier Lopez-Calderon & Steven Luck\n% Center for Mind and Brain\n% University of California, Davis,\n% Davis, CA\n% 2013\n\nfunction [yylim, serror] = erpAutoYLim(ERP, binArray, chanArray, xxlim,blcorrdata)\n%ams updated blcorrdata\nserror = 0;\nif nargin<1\n        error('erpAutoYLim needs 1 input argument at least.')\nend\n\ndatatype = checkdatatype(ERP);\n\nif nargin<5\n    blcorrdata = 'no';\nend\n\n\nif nargin<4\n        if strcmpi(datatype, 'ERP')\n                xxlim = [ERP.xmin ERP.xmax]*1000;\n        else\n                xxlim = [ERP.xmin ERP.xmax];\n        end\nend\nif nargin<3\n        chanArray = 1:ERP.nchan;\nend\nif nargin<2\n        binArray = 1:ERP.nbin;\nend\nif isempty(binArray)\n        binArray = 1:ERP.nbin;\nend\nif isempty(chanArray)\n        chanArray = 1:ERP.nchan;\nend\nif isempty(xxlim)\n    if strcmpi(datatype, 'ERP')\n        if strcmp(datatype,'CSD')\n            datatype = 'ERP';     % if CSD data, treat as ERP data here\n        end\n        xxlim = [ERP.xmin ERP.xmax]*1000;\n    else\n        xxlim = [ERP.xmin ERP.xmax];\n    end\nend\ntry\n        nbin  = length(binArray);\n        nchan = length(chanArray);\n        fs    = ERP.srate;\n        \n        if strcmpi(datatype,'CSD')\n            datatype = 'ERP';     % if CSD data, treat as ERP data here\n        end\n        \n        if strcmpi(datatype, 'ERP')\n            \n\n            if xxlim(1)<round(ERP.xmin*1000)\n                aux_xxlim(1) = round(ERP.xmin*1000);\n            else\n                aux_xxlim(1) = xxlim(1);\n            end\n            if xxlim(2)>round(ERP.xmax*1000)\n                aux_xxlim(2) = round(ERP.xmax*1000);\n            else\n                aux_xxlim(2) = xxlim(2);\n            end\n        else  % fft\n            if xxlim(1)<5\n                aux_xxlim(1) = 5; % to avoid including the spectrum under 5 Hz in calculating Y auto (too big!)\n            else\n                aux_xxlim(1) = xxlim(1);\n            end\n            if xxlim(2)>round(fs/2);\n                aux_xxlim(2) = round(fs/2);\n            else\n                aux_xxlim(2) = xxlim(2);\n            end\n        end\n        \n        %disp('start')\n        %aux_xxlim\n        %[ERP.xmin ERP.xmax]\n        %fs\n        [p1, p2, checkw] = window2sample(ERP, aux_xxlim(1:2) , fs, 'relaxed');\n        %disp('end')\n        \n\n        if strcmpi(blcorrdata,'no')\n            datresh = reshape(ERP.bindata(chanArray,p1:p2,binArray), 1, (p2-p1+1)*nbin*nchan);\n            yymax   = max(datresh);\n            yymin   = min(datresh);\n        else\n            datresh = reshape(blcorrdata(chanArray,p1:p2,binArray), 1, (p2-p1+1)*nbin*nchan);\n            yymax   = max(datresh);\n            yymin   = min(datresh);\n        end\n            \n        if abs(yymax)<1 && abs(yymin)<1\n            yylim(1:2) = [yymin*1.2 yymax*1.1]; % JLC. Mar 11, 2015\n        else\n            yylim(1:2) = round([yymin*1.2 yymax*1.1]); % JLC. Sept 26, 2012\n        end\n        \n        %\n        % in case of flatlined ERPs\n        %\n        if yylim(1)<1E-6 && yylim(2)<1E-6\n                if strcmpi(datatype, 'ERP')\n                        yylim(1:2) = [-1 1];\n                        fprintf('WARNING: It seems like erpAutoYLim() found flatlined ERPs. So auto Y-limit was set to [-1 1].\\n');\n                else\n                        yylim(1:2) = [0 1];\n                        fprintf('WARNING: It seems like erpAutoYLim() found flatlined Spectrum. So auto Y-limit was set to [0 1].\\n');\n                end\n        end\ncatch\n        if strcmpi(datatype, 'ERP')\n                yylim(1:2) = [-10 10];\n        else\n                yylim(1:2) = [0 1];\n        end\n        serror =1;\n        fprintf('WARNING: ERPLAB could not find the auto Y limits for %s.\\nPlease check your input parameters and waverforms.\\n', ERP.erpname);\n        fprintf('Default Y limit values were loaded.\\n');\n        return\nend", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/erpAutoYLim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.2381704124172609}}
{"text": "function [nav,stat]=decode_navb(nav,fid,opt,headinfo)\nglobal glc gls\nstat=1; NMAX=10000;\nnav.eph=repmat(gls.eph,NMAX,1); nav.geph=repmat(gls.geph,NMAX,1);\n\nswitch headinfo.type\n    case 'N',sys=headinfo.sys;\n    case 'G',sys=glc.SYS_GLO;\n    case 'L',sys=glc.SYS_GAL;\n    case 'J',sys=glc.SYS_QZS;\n    otherwise,stat=0;return;\nend\n\nwhile ~feof(fid)\n\n    [eph,geph,type,fid,stat0]=decode_navb_data(opt,headinfo.ver,sys,fid);\n    \n    if stat0==1\n        switch type\n            case 1\n                if nav.n+1>size(nav.eph,1)\n                    nav.eph(nav.n+1:nav.n+NMAX,1)=repmat(gls.eph,NMAX,1);\n                end\n                nav.eph(nav.n+1)=eph; \n                nav.n=nav.n+1; \n            case 2\n                if nav.ng+1>size(nav.geph,1)\n                    nav.geph(nav.ng+1:nav.ng+NMAX,1)=repmat(gls.geph,NMAX,1);\n                end\n                nav.geph(nav.ng+1)=geph; \n                nav.ng=nav.ng+1;\n        end\n    end \nend\nfclose(fid);\n\nif nav.n<size(nav.eph,1)\n    nav.eph(nav.n+1:end,:)=[];\nend\nif nav.ng<size(nav.geph,1)\n    nav.geph(nav.ng+1:end,:)=[];\nend\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/read_file/decode_navb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2380574420636893}}
{"text": "function [variables, index] = findGUBGroup(p,s)\nvariables = [];index = [];\nfor i = find((p.knapsack.type == 3) | (p.knapsack.type == 5))\n    if all(ismember(s,p.knapsack.variables{i}))\n        variables = p.knapsack.variables{i};\n        index = i;\n        return\n    end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/find_gub_groups.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2380574420636893}}
{"text": "function [] = sb_fix_unwrap_manual(reset_flag,ix_reduced_list)\n% [] = sb_fix_unwrap_manual(reset_flag)\n% script to manually fix unwrapping errors in Small Baseline processing\n%\n% This function allows to manually fix unwrapping errors by iterating\n% the results of ps_plot('rsb'). You can add add or subtract an integer number\n% of 2pi cycles over a selected region, or correct with respect to the closest\n% wrap of another region. You can keep iterating till the 'rsb'\n% errors have reduced. If it goes wrong and you do want to reset your \n% unwrapped data back to that of the original you can set the reset_flag to 1;\n%\n% By Bekaert David - University of Leeds - Sept 2014\n% \n% modifications:\n% Bekaert David     05/2015     Fix in command line output, fix the code for ps_plot\n% Bekaert David     09/2015     Add file restoring.\n% Bekaert David     12/2016     Add closest wrap option, change to stamps_save code\n% Bekaert David     12/2016     Add argument which is a subset of intergerograms to reduce plotting needs.\n%\n\n% deramp IFGs\nderamp_flag =0;         % optional deramp rsb. Might be needed when processed with gamma\n% what to use as guidence 'rsb' or 'usb' to click on\nplot_option = 'usb';    % only 'rsb' or 'usb'\ndem_option = 'd';    % only 'd' or ''\n\n\n\n% flags\nif nargin<1\n    reset_flag=0;\nend\nif isempty(reset_flag)\n    reset_flag=0;\nend\nif nargin<2\n    ix_reduced_list=[];\nend\nif ~strcmpi(plot_option,'usb') && ~strcmpi(plot_option,'rsb')\n    error('Only plot_option: rsb and usb supported');\nend\nif ~strcmpi(dem_option,'d') && ~isempty(dem_option)\n    error('Only dem_option: d and [] supported');\nend\n\n\n% keeping the original data, incase user want to reset it\nif exist('phuw_sb2_original.mat','file')~=2\n    copyfile('phuw_sb2.mat','phuw_sb2_original.mat')\n    copyfile('phuw2.mat','phuw2_original.mat')\n    copyfile('phuw_sb_res2.mat','phuw_sb_res2_original.mat')\nelse\n    copyfile('phuw_sb2.mat','phuw_sb2_previous_temp.mat')\n    copyfile('phuw2.mat','phuw2_previous_temp.mat')\n    copyfile('phuw_sb_res2.mat','phuw_sb_res2_previous_temp.mat')\nend\n\n% use previous or start from scratch\nif reset_flag==1\n   fprintf('Using the original data\\n')\n   ph_input = load('phuw_sb2_original');\nelse\n   fprintf('Use data from a previous run\\n')\n   ph_input = load('phuw_sb2.mat');\nend\n\n% loading the interferogram information\nps = load('ps2.mat');\n\n\n% generating list of ifgs to be ploted\ndrop_ifg_index = getparm('drop_ifg_index');\nif ~isempty(ix_reduced_list)\n    % removing ifgs that have been dropped before\n    for k=1:length(drop_ifg_index)\n        ix_temp = find(drop_ifg_index(k)==ix_reduced_list);\n        ix_reduced_list(ix_temp)=[];\n    end\n    if sum(ix_reduced_list>ps.n_ifg)>0\n        fprintf('Your list is larger than number of IFGS, will reset to max number of IFG \\n')\n        ix_reduced_list(ix_reduced_list>ps.n_ifg)=[];\n    end\nend\n% reset the list in case nothing was left\nif isempty(ix_reduced_list)\n   ix_reduced_list = 1:ps.n_ifg;\n   ix_reduced_list(drop_ifg_index)=[];\nend \n\n% deramping\nif deramp_flag==1\n    deramp_option = ['-o'];\nelse\n    deramp_option = '';    \nend\nif ~isempty(dem_option)\n    if deramp_flag==1\n        dem_option='-do';\n    else\n        dem_option= '-d';\n    end\nend\nif strcmpi(plot_option,'usb')\n    plot_option = [plot_option dem_option];\nelseif strcmpi(plot_option,'rsb')\n    plot_option = [plot_option deramp_option];\nend\n\n\n% plotting the current rsb data\nps_plot(['rsb' deramp_option],1,0,0,ix_reduced_list);\n\n% get the interferogram that the user needs to adapt\nrepeat=1;\nwhile repeat==1\n    ix_ifg = input('Which interferogram to you want to correct? ','s');\n    ix_ifg = str2num(ix_ifg);\n    if isempty(ix_ifg) \n        repeat=1;\n    elseif ix_ifg<=ps.n_ifg\n        repeat=0;\n    else\n        fprintf(['Not that many interferograms \\n'])\n    end\nend\n\n\n% plot the rsb value for this interferogram\n% option one can use deramped rsb, this is for teh case teh interferograms\n% were not created from relative differences, i.e. each interferogram had a\n% baseline estimated and there might be some ramping errors because of that.\nh_fig = ps_plot([plot_option],1,0,0,ix_ifg);\nset(h_fig,'name',['Original interferogram']);\n\n\n% Getting a polygon of the incorrect unwrapped area \nfprintf('Define the incorrect unwrapped region through a polygon by clicking on the figure. \\n')\nrepeat_zoom=1;\nwhile repeat_zoom==1\n    action_flag= input('First, zoom to your region of interest. Press [c] to continue. ','s');\n    if strcmpi(action_flag,'c') \n        repeat_zoom=0;\n    end\nend\n\nfprintf('Now, start defining the polygon by outlining the incorrect region. \\n Press enter once done\\n')\n% call the figure in case the user clicked somewhere else\nfigure(h_fig);\npolygon=ginput;\n% plotting the polygon on top\nhold on\nplot([polygon(:,1) ;polygon(1,1)],[polygon(:,2);polygon(1,2)],'r-','linewidth',2)\n\n     \n% loop untill the user is happy with it\ncontinue_flag=1;\nwhile continue_flag==1\n    repeat=1;\n    fprintf('You can shift the whole region by an integer number of cycles or you can put all pixels to a specifc wrap \\n')\n    while repeat==1\n        ix_shift= input('By how many cycles to you want to shift this region? [+-integer or inf for wrap option] ','s');\n        ix_shift = str2num(ix_shift);\n        if isempty(ix_shift) \n            repeat=1;\n        elseif ix_shift==inf\n            repeat=0;\n        elseif (ix_shift./(round(ix_shift)))~=1\n            fprintf(['Needs to be an integer number... \\n'])\n            repeat =1;\n        else\n            repeat=0;\n        end\n    end\n\n    % finding the pixels within the polygon\n    ix = inpolygon(ps.lonlat(:,1),ps.lonlat(:,2),polygon(:,1),polygon(:,2));\n\n    % checking the option the user picked - closes wrap (inf) or shift region\n    if ix_shift==inf            % closest wrap option\n        fprintf('Define region to which you want to define as reference wrap (average will be used!). \\n Press enter once done\\n')\n        % call the figure in case the user clicked somewhere else\n        figure(h_fig);\n        polygon_ref=ginput;\n        % plotting the ploygon on top\n        hold on\n        plot([polygon_ref(:,1) ;polygon_ref(1,1)],[polygon_ref(:,2);polygon_ref(1,2)],'b-','linewidth',4)\n\n        % finding the pixels within the reference polygon\n        ix_ref = inpolygon(ps.lonlat(:,1),ps.lonlat(:,2),polygon_ref(:,1),polygon_ref(:,2));\n\n        % check to which interferograms this should be applied\n        repeat2=1;\n        while repeat2==1\n            action_flag= input('Do you want to apply this to all interferograms [y/n]? ','s');\n            if strcmpi(action_flag,'y')\n                repeat2=0;\n            elseif strcmpi(action_flag,'n')\n                repeat2=0;\n            end\n        end\n        \n        % store the orginal interferograms\n        ix_ifg_or = ix_ifg;\n        if strcmpi(action_flag,'y')  \n           ix_ifg=[1:size(ph_uw,2)];\n        end\n        \n        % do the estimation for each itnerferogram\n        ph_uw= ph_input.ph_uw;\n        ref_phase = nanmean(ph_uw(ix_ref,ix_ifg),1);\n        for k_ifgs=1:length(ix_ifg)\n           % compute the reference \n            radian_shift = round((ph_uw(ix,ix_ifg(k_ifgs))-ref_phase(k_ifgs))./(2*pi))*2*pi;\n            ph_uw(ix,ix_ifg(k_ifgs)) = ph_uw(ix,ix_ifg(k_ifgs)) - radian_shift;\n        end\n        \n        % update back to the previous interferogram to be corrected for\n        % plotting purposes\n        ix_ifg = ix_ifg_or;\n        clear ref_phase\n        \n    else        % option of shifting the interferogram\n        % the shift in radians\n        radian_shift = ix_shift*2*pi;\n\n        % modifying the interferogram\n        ph_uw= ph_input.ph_uw;\n        ph_uw(ix,ix_ifg)=ph_uw(ix,ix_ifg)+radian_shift;\n    end\n    msd = ph_input.msd;\n\n    % saving the data\n    stamps_save('phuw_sb2.mat',ph_uw,msd);\n\n    % re-running the \n    sb_invert_uw\n\n    % plot the new residuals\n    ps_plot(['rsb' deramp_option],1,0,0,ix_reduced_list);\n    h_fig_new = ps_plot([plot_option],1,0,0,ix_ifg);\n    set(h_fig_new,'name',['Corrected interferogram']);\n    \n    repeat=1;\n    while repeat==1\n        string= input('retry? [y/n] ','s');\n        if strcmpi(string,'y')\n            repeat=0;\n            continue_flag = 1;\n        elseif strcmpi(string,'n')\n            repeat=0;\n            continue_flag = 0;\n            % see if the result needs to be kept or reverted\n            repeat2=1;\n            while repeat2==1\n                action_flag= input('Keep this result [y/n]? ','s');\n                if strcmpi(action_flag,'y')\n                    repeat2=0;\n                elseif strcmpi(action_flag,'n')\n                    repeat2=0;\n                    \n                    % restore the codes\n                    copyfile('phuw_sb2_original.mat','phuw_sb2.mat')\n                    copyfile('phuw2_original.mat','phuw2.mat')\n                    copyfile('phuw_sb_res2_original.mat','phuw_sb_res2.mat')\n\n                else\n                    fprintf('y or n ...\\n')\n                end\n            end\n        else\n            fprintf('y or n ...\\n')\n        end\n    end\n    \nend\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/sb_fix_unwrap_manual_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23805744206368928}}
{"text": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction RS = relative_size(P,cover,segment)\n\n% ---------------------------------------------------------------------\n% RELATIVE_SIZE.M   Determines relative cover set size for points in new covers\n%\n% Version 2.00\n% Latest update     16 Aug 2017\n%\n% Copyright (C) 2014-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n% \n% Uses existing segmentation and its branching structure to determine\n% relative size of the cover sets distributed over new covers. The idea is \n% to decrease the relative size as the branch size decreases. This is \n% realised so that the relative size at the base of a branch is\n% proportional to the size of the stem's base, measured as number of\n% cover sets in the first few layers. Also when we approach the\n% tip of the branch, the relative size decreases to the minimum. \n% Maximum relative size is 256 at the bottom of the\n% stem and the minimum is 1 at the tip of every branch.\n%\n% Output:\n% RS    Relative size (1-256), uint8-vector, (n_points x 1)\n\nBal = cover.ball;\nCen = cover.center;\nNei = cover.neighbor;\nSegs = segment.segments;\nSChi = segment.ChildSegment;\nnp = size(P,1);     % number of points\nns = size(Segs,1);  % number of segments\n\n%% Use branching order and height as apriori info\n% Determine the branch orders of the segments\nOrd = zeros(ns,1);\nC = SChi{1};\norder = 0;\nwhile ~isempty(C)\n    order = order+order;\n    Ord(C) = order;\n    C = vertcat(SChi{C});\nend\nmaxO = order+1; % maximum branching order (plus one)\n\n% Determine tree height\nTop = max(P(Cen,3));\nBot = min(P(Cen,3));\nH = Top-Bot;\n\n%% Determine \"base size\" compared to the stem base\n% BaseSize is the relative size of the branch base compared to the stem\n% base, measured as number of cover sets in the first layers of the cover\n% sets. If it is larger than apriori upper limit based on branching order\n% and branch height, then correct to the apriori limit \nBaseSize = zeros(ns,1);\n% Determine first the base size at the stem\nS = Segs{1};\nn = size(S,1);\nif n >= 2\n    m = min([6 n]);\n    BaseSize(1) = mean(cellfun(@length,S(2:m)));\nelse\n    BaseSize(1) = length(S{1});\nend\n% Then define base size for other segments\nfor i = 2:ns\n    S = Segs{i};\n    n = size(S,1);\n    if n >= 2\n        m = min([6 n]);\n        BaseSize(i) = ceil(mean(cellfun(@length,S(2:m)))/BaseSize(1)*256);\n    else\n        BaseSize(i) = length(S{1})/BaseSize(1)*256;\n    end\n    bot = min(P(Cen(S{1}),3)); \n    h = bot-Bot; % height of the segment's base\n    BS = ceil(256*(maxO-Ord(i))/maxO*(H-h)/H); % maximum apriori base size\n    if BaseSize(i) > BS\n        BaseSize(i) = BS;\n    end\nend\nBaseSize(1) = 256;\n\n%% Determine relative size for points\nTS = 1;\nRS = zeros(np,1,'uint8');\nfor i = 1:ns\n    S = Segs{i};\n    s = size(S,1);\n    for j = 1:s\n        Q = S{j};\n        RS(vertcat(Bal{Q})) = BaseSize(i)-(BaseSize(i)-TS)*sqrt((j-1)/s);\n    end\nend\n\n%% Adjust the relative size at the base of child segments\nRS0 = RS;\nfor i = 1:ns\n    C = SChi{i};\n    n = length(C);\n    if n > 0\n        for j = 1:n\n            S = Segs{C(j)};\n            B = S{1};\n            N = vertcat(Nei{B});\n            if size(S,1) > 1\n                N = setdiff(N,S{2});\n            end\n            N = union(N,B);\n            N = vertcat(Bal{N});\n            RS(N) = RS0(N)/2;\n        end\n    end\nend\n", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/main_steps/relative_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23805434562536326}}
{"text": "port = int16(2000);\nclient = py.carla.Client('localhost', port);\nclient.set_timeout(10.0);\nworld = client.get_world();\n\n% Spawn Vehicle\nblueprint_library = world.get_blueprint_library();\ncar_list = py.list(blueprint_library.filter(\"model3\"));\ncar_bp = car_list{1};\nspawn_point = py.random.choice(world.get_map().get_spawn_points());\ntesla = world.spawn_actor(car_bp, spawn_point);\ntesla.set_autopilot(true);\n\ncarla_is_running = true;\n\n% Sensor 1\nblueprint = world.get_blueprint_library().find('sensor.camera.rgb');\nblueprint.set_attribute('image_size_x', '960')\nblueprint.set_attribute('image_size_y', '540')\n% blueprint.set_attribute('sensor_tick', '.1');\ntransform = py.carla.Transform(py.carla.Location(pyargs('x',-7.5, 'z',2.5)));\nsensor = world.spawn_actor(blueprint, transform, pyargs('attach_to',tesla));\n\npyModule = sensorBind(sensor, \"rgb\", \"rgb\", \"array\");\ncurrentImage = uint8(py.getattr(pyModule, 'array'));\nimageHandle = imshow(currentImage);\nset(gca,'units','pixels'); % set the axes units to pixels\nx = get(gca,'position'); % get the position of the axes\nset(gcf,'units','pixels'); % set the figure units to pixels\ny = get(gcf,'position'); % get the figure position\nset(gcf,'position',[y(1) y(2) x(3) x(4)]);% set the position of the figure to the length and width of the axes\nset(gca,'units','normalized','position',[0 0 1 1]); % set the axes units to pixels\nset(gcf,'menubar','none');\n% Lidar\nblueprint = world.get_blueprint_library().find('sensor.lidar.ray_cast');\nblueprint.set_attribute('points_per_second', '56000');\nblueprint.set_attribute('range', '5000');\nblueprint.set_attribute('sensor_tick', '0.1');\ntransform = py.carla.Transform(py.carla.Location(pyargs('x',0.8, 'z',1.7)));\nlidar = world.spawn_actor(blueprint, transform, pyargs('attach_to',tesla));\n\nmoduleLidar = sensorBind(lidar, 'lidar_file', 'lidar', 'array');\n\n% Spawn NPC's\nnpc_bps = blueprint_library.filter(\"vehicle\");\nnpc_to_spawn = 75;\n\n% Preallocate memory\nnpc_list = cell(1, npc_to_spawn);\n\ni = 1;\nwhile i <= npc_to_spawn\n    try\n        npc_bp = py.random.choice(npc_bps);\n        spawn_point = py.random.choice(world.get_map().get_spawn_points());\n        npc_list{i} = world.spawn_actor(npc_bp, spawn_point);\n        npc_list{i}.set_autopilot(true);\n    catch\n        % In case spawing fails due to collision, try again\n        i = i - 1;\n    end\n    i = i + 1;\nend\n\n% A bounding box detector model.\ndetectorModel = HelperBoundingBoxDetector(...\n    'XLimits',[-50 75],...              % min-max\n    'YLimits',[-5 5],...                % min-max\n    'ZLimits',[-2 5],...                % min-max\n    'SegmentationMinDistance',1.6,...   % minimum Euclidian distance\n    'MinDetectionsPerCluster',1,...     % minimum points per cluster\n    'MeasurementNoise',eye(6),...       % measurement noise in detection report\n    'GroundMaxDistance',0.3);           % maximum distance of ground points from ground plane\n\n\nassignmentGate = [10 100]; % Assignment threshold;\nconfThreshold = [7 10];    % Confirmation threshold for history logic\ndelThreshold = [8 10];     % Deletion threshold for history logic\nKc = 1e-5;                 % False-alarm rate per unit volume\n\n% IMM filter initialization function\nfilterInitFcn = @helperInitIMMFilter;\n\n% A joint probabilistic data association tracker with IMM filter\ntracker = trackerJPDA('FilterInitializationFcn',filterInitFcn,...\n    'TrackLogic','History',...\n    'AssignmentThreshold',assignmentGate,...\n    'ClutterDensity',Kc,...\n    'ConfirmationThreshold',confThreshold,...\n    'DeletionThreshold',delThreshold,...\n    'HasDetectableTrackIDsInput',true,...\n    'InitializationThreshold',0);\n\n% Create display\ndisplayObject = HelperLidarExampleDisplay(uint8(py.getattr(pyModule, 'array')),...\n    'PositionIndex',[1 3 6],...\n    'VelocityIndex',[2 4 7],...\n    'DimensionIndex',[9 10 11],...\n    'YawIndex',8,...\n    'MovieName','',...  % Specify a movie name to record a movie.\n    'RecordGIF',false); % Specify true to record new GIFs\n\n%% Loop Through Data\n% Loop through the recorded lidar data, generate detections from the\n% current point cloud using the detector model and then process the\n% detections using the tracker.\nstart_time = cputime;\n\n% Initiate all tracks.\nallTracks = struct([]);\n\n% Rotate point cloud\nA = [0 -1 0 0; ...\n     1  0 0 0; ...\n     0  0 1 0; ...\n     0  0 0 1];\ntform = affine3d(A);\n\nwhile carla_is_running\n    try\n        % Update time\n        time = cputime - start_time;\n\n        % Get current lidar scan\n        XYZI = single(py.getattr(moduleLidar, 'array'));\n        XYZ = lidarData(:, 1:3);\n        \n        % Flip the axis\n        XYZ(:, 2) = -1 * XYZ(:, 2);\n        currentLidar = pctransform(pointCloud(XYZ), tform);\n\n        % Generator detections from lidar scan.\n        [detections,obstacleIndices,groundIndices,croppedIndices] = detectorModel(currentLidar,time);\n\n        % Calculate detectability of each track.\n        detectableTracksInput = helperCalcDetectability(allTracks,[1 3 6]);\n\n        % Pass detections to track.\n        [confirmedTracks,tentativeTracks,allTracks] = tracker(detections,time,detectableTracksInput);\n\n        % Get model probabilities from IMM filter of each track using\n        % getTrackFilterProperties function of the tracker.\n        modelProbs = zeros(2,numel(confirmedTracks));\n        for k = 1:numel(confirmedTracks)\n            c1 = getTrackFilterProperties(tracker,confirmedTracks(k).TrackID,'ModelProbabilities');\n            modelProbs(:,k) = c1{1};\n        end\n\n        % Update display\n        if isvalid(displayObject.PointCloudProcessingDisplay.ObstaclePlotter)\n            % Get current image scan for reference image\n            currentImage = uint8(py.getattr(pyModule, 'array'));\n\n            set(imageHandle,'Cdata',currentImage);\n            \n            % Update display object\n            displayObject(detections,confirmedTracks,currentLidar,obstacleIndices,...\n                groundIndices,croppedIndices,[],modelProbs);\n        end\n    catch\n        carla_is_running = false;\n        close all;\n    end\nend\n\ntesla.destroy();\nsensor.destroy();\nlidar.destroy();\n\nfor i=1:npc_to_spawn\n   npc_list{i}.destroy(); \nend", "meta": {"author": "darkscyla", "repo": "MATLAB-Carla-Interface", "sha": "a089f34784b75c66490ce6055dfefaded6117409", "save_path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface", "path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface/MATLAB-Carla-Interface-a089f34784b75c66490ce6055dfefaded6117409/Proof Of Concept/Python API/Examples/7_LidarDetection/CarlaDataAcquisition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23805433908392964}}
{"text": "function h = specgram2(s, T, varargin)\n   %SPECGRAM2 - plots spectrograms of waveforms with waveform along top\n   %  h = specgram2(spectralobject, waveforms) generates a spectrogram from\n   %  the waveform(s), overwriting the current figure.  The waveform will be\n   %  displayed along the top of the spectrogram. The return value is a handle\n   %  to the spectrogram, and is optional.\n   %\n   %  The spectrograms will be created in the same shape as the passed\n   %  waveforms.  ie, if W is a 2x3 matrix of waveforms, then\n   %  specgram2(spectralobject,W) will generate a 2x3 plot of spectra.\n   %\n   %  Many additional behaviors can be modified through the passing of\n   %  additional parameters, as listed further below.  These parameters are\n   %  always passed in pairs, as such:\n   %\n   %  specgram2(spectralobject, waveforms,'PARAM1',VALUE1,...,'PARAMn',VALUEn)\n   %    Any number of these parameters may be passed to specgram2.\n   %\n   %  specgram2(..., 'axis', AXIS_HANDLE)\n   %    Specify the axis AXIS_HANDLE within which the spectrogram will be\n   %    generated.  The boundary of the axis becomes the boundary for the\n   %    entire spectra plot.  For a matrix of waveforms, this area is\n   %    subdivided into NxM subplots, where N and M are the size of the\n   %    waveform matrix.\n   %\n   %  specgram2(..., 'xunit', XUNIT)\n   %    Spedifies the x-unit scale to be used with the spectrogram.  The\n   %    default unit is 'seconds'.\n   %    valid xunits:\n   %     'seconds','minutes','hours','days','doy' (day of year),and 'date'\n   %\n   %  specgram2(..., 'colormap', ALTERNATEMAP)\n   %    Instead of using the default colormap, any colormap may be used.  An\n   %    alternate way of setting the global map is by using the SETMAP\n   %    function.  ALTERNATEMAP will either be a name (eg. grayscale) or an\n   %    Nx3 numeric. Type HELP GRAPH3D to see additional useful colormaps.\n   %\n   %\n   %  specgram2(..., 'colorbar', COLORBAR_OPTION)\n   %    Generates a spectrogram from the waveform and uses a specific map\n   %    valid COLORBAR_OPTION values: 'horiz' (default),'vert','none',\n   %      'HORIZ' places a single colorbar below all plots\n   %      'VERT' places a single colorbar to the right of all plots\n   %      'NONE' supresses the colorbar placement\n   %\n   %  specgram2(..., 'yscale', YSCALE)\n   %    Choosing 'log' Allows the y-axis to be generated on a log-frequency\n   %    scale, with uneven vertical cell spacing.  The default value is\n   %    'normal', and provides the standard spectrogram view.\n   %    valid yscales: 'normal', 'log' (see NOTE below)\n   %\n   %    NOTE: In order to use the log scale, UIMAGESC needs to be available on\n   %    the matlab path.  This routine was created by Frederic Moisy, and may\n   %    be downloaded from the maltabcentral fileexchange (File ID: 11368).\n   %    If this routine is not found,then the original spectrogram will be\n   %    created.\n   %\n   %  specgram2(..., 'fontsize', FONTSIZE)\n   %    Specify the font size for a spectrogram.  The default font size is 8.\n   %\n   %  specgram2(..., 'innerLabels', SHOWINNERLABELS)\n   %    Suppress the labling of the inside graphs by setting SHOWINNERLABELS\n   %    to false.  If this is false, then the frequency label only shows on\n   %    the leftmost spectrograms, and the X-unit label only shows on the\n   %    bottommost spectrograms.\n   %\n   %  Example 1:\n   %    % The following plots a waveform using an alternate mapping, an xunit of\n   %    % of 'hours', and with the y-axis plotted using a log scale.\n   %    specgram2(spectralobject, waveform,...\n   %      'colormap', alternateMap,'xunit','h','yscale','log')\n   %\n   %\n   %  Example 2:\n   %    % create an arbitrary subplot, and then plot multiple spectra\n   %    a = subplot(3,2,1);\n   %    specgram2(spectralobject,waves,'axis',a); % waves is an NxM waveform\n   %\n   %   See also SPECTRALOBJECT/SPECGRAM\n   \n   if ~isa(T,'TraceData')\n            try\n               T = SeismicTrace(T);\n               disp('successfully converted to a SeismicTrace');\n            catch er\n      error('Spectralobject:specgram2:invalidArgument','Should work on a trace (ex. TraceData, SeismicTrace), not a %s',class(T));\n            end\n   end\n   \n   %% search for relevent property pairs passed as parameters\n   p = parseSpecgramInputs(s, varargin);\n   \n   %% figure out exactly WHERE to plot the spectrogram(s)\n   %find out area(axis) in which the spectrograms will be plotted\n   clabel= 'Relative Amplitude  (dB)';\n   \n   if p.Results.axis == 0,\n      clf;\n      pos = get(gca,'position');\n   else\n      pos = get(p.Results.axis,'position');\n   end\n   if ~isempty(p.Results.position)\n      pos = p.Results.position;\n   end\n      \n   %% If there are multiple waveforms...\n   % subdivide the axis and loop through specgram2 with individual waveforms.\n   if numel(T) > 1\n      if p.Results.axis== 0,\n         myaxis = gca;\n      end\n      %create the colorbar if desired\n      TraceSpectra.createcolorbar(s,p.Results.colorbar, clabel, p.Results.fontsize);\n      h = TraceSpectra.subdivide_axes(myaxis, size(T));\n      % remainingproperties = TraceSpectra.property2varargin(proplist);\n      remainingproperties = TraceSpectra.buildParameterList( p.Unmatched);\n      for n=1:numel(h)\n         keepYlabel =  ~p.Results.innerlabels || (n <= size(h,1));\n         keepXlabel = ~p.Results.innerlabels || (mod(n,size(h,2))==0);\n         specgram2(s,T(n),...\n            'xunit',p.Results.xunit,...\n            'axis',h(n),...\n            'fontsize',p.Results.fontsize,...\n            'useXlabel',keepXlabel,...\n            'useYlabel',keepYlabel,...\n            'colorbar','none',...\n            remainingproperties{:});\n      end\n      return\n   end\n   \n   %% Plot the spectrogram with a wiggle on top and colorbar below\n   \n   %plot the wiggle\n   ax_wiggle = subplot('position',wigglePosition(pos));\n   plot(T,'xunit',p.Results.xunit,'autoscale',true,'fontsize',p.Results.fontsize);\n   \n   % make the axis tight, and keep axis info for later use with spectra\n   axis(ax_wiggle,'tight');\n   xAxisLims = get(ax_wiggle,'xlim');\n   ticnos = get(ax_wiggle,'xtick');\n   \n   %plot the spectra\n   ax_spectra = subplot('position',spectraPosition(pos));\n   additionalParams = TraceSpectra.buildParameterList( p.Unmatched);\n   specgram(s,T,...\n      'xunit',p.Results.xunit,...\n      'fontsize',p.Results.fontsize,...\n      'yscale',p.Results.yscale,...\n      'colorbar','none',...\n      'axis',ax_spectra,...\n      'suppressXlabel',p.Results.useXlabel,...\n      'suppressYlabel',p.Results.useYlabel,...\n      additionalParams{:});\n   \n   %make the axis match exactly with the waveform above\n   set(ax_spectra,'xtick',ticnos);\n   if ~strcmpi(p.Results.yscale,'log')\n      % axis scaling doesn't work quite right at a log scale\n      xlim(ax_spectra, xAxisLims);\n   end\n   \n   title(''); %clear the title\n   \n   %create the colorbar if desired\n   TraceSpectra.createcolorbar(s,p.Results.colorbar, clabel, p.Results.fontsize);\nend\n\nfunction wigPos = wigglePosition(pos)\n   % wigglePosition   wiggle occupies the top 15% of the axis\n   % pos = [ left, bottom, width, height ]   \n   % wavepos = [ left, bottom + height * 0.85,  width , height * 0.15] ;\n   wigPos = pos .* [1, 1, 1, 0.15] + [0,  pos(4) * 0.85, 0, 0] ;\nend\n\nfunction specPos = spectraPosition(pos)\n   %spectraPosition   spectra occupies the bottom 85% of the axis\n   specPos = pos .* [1, 1, 1, 0.85 ];\nend\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/dev/@TraceSpectra/specgram2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2380268596535489}}
{"text": "function [] = SLC_export(slcstack,slclist, Path, extention, InSAR_processor, reference_index)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%   This file is part of TomoSAR.\n%\n%   TomoSAR is distributed in the hope that it will be useful,\n%   but without warranty of any kind; without even the implied \n%   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n%   See the Apache License for more details.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author : Dinh Ho Tong Minh (INRAE) and Yen Nhi Ngo, Jan. 2022 \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif not(exist('InSAR_processor', 'var'))\n     InSAR_processor = 'snap';\nend\n\nif not(exist('reference_index', 'var'))\n     reference_index = 1;\nend\n\n[nlines,nwidths,n_slc] = size(slcstack);\n\nreal_index = 1:2:nwidths*2-1;\nimag_index = 2:2:nwidths*2;\nline_cpx = zeros(2*nwidths, 1); \n\nfor i = 1:n_slc  \n     switch InSAR_processor\n        case 'snap' % \n            filename = [Path,'/',num2str(slclist(i)),extention];\n            fid = fopen(filename, 'wb', 'ieee-be');\n        case 'isce'            \n            if i == reference_index\n                filename = [Path,'/reference/','reference.slc',extention];\n            else\n                filename = [Path,'/',num2str(slclist(i)),'/','secondary.slc',extention];    \n            end\n            fid = fopen(filename, 'wb'); \n        otherwise\n            disp('not yet support')\n    end\n    \n    data = squeeze(slcstack(:,:,i));\n    for k=1:nlines\n        line_cpx(real_index) = real(data(k,:));\n        line_cpx(imag_index) = imag(data(k,:));\n        line_count = fwrite(fid, line_cpx, 'float32');\n    end\n    fclose(fid);\nend\n                \n", "meta": {"author": "DinhHoTongMinh", "repo": "TomoSAR", "sha": "ea6a3306680c4cc59d6f7d764a934915186cc65e", "save_path": "github-repos/MATLAB/DinhHoTongMinh-TomoSAR", "path": "github-repos/MATLAB/DinhHoTongMinh-TomoSAR/TomoSAR-ea6a3306680c4cc59d6f7d764a934915186cc65e/Tomography/scripts/SLC_export.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23802685338731047}}
{"text": "% SP_TO_VTK: Export multipatch results to VTK format for plotting.\n%\n%  sp_to_vtk (u, space, geometry, npts, filename, fieldnames, [option], [lambda_lame, mu_lame])\n%\n% INPUT:\n%     \n%     u:           vector of dof weights\n%     space:       object representing the space of discrete functions (see sp_multipatch)\n%     geometry:    geometry structure (see geo_load)\n%     npts:        number of points along each parametric direction where to evaluate\n%     filename:    name of the output file. \n%     fieldnames:  how to name the saved variables in the vtk file\n%     options:     cell array with the fields to plot\n%                   accepted options are 'value' (default), 'gradient',\n%                   and for vectors also 'curl', 'divergence', 'stress'\n%     lambda_lame: function handle to the first Lame coefficient (only needed to compute 'stress')\n%     mu_lame:     function handle for the second Lame coefficient (only needed to compute 'stress')\n%\n% OUTPUT:\n%\n%    none    \n% \n% Copyright (C) 2010 Carlo de Falco, Rafael Vazquez\n% Copyright (C) 2011, 2012, 2015 Rafael Vazquez\n%\n%    This program is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n\n%    This program is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction sp_to_vtk (u, space, geometry, npts, filename, fieldname, varargin)\n\n  str1 = cat (2,'<?xml version=\"1.0\"?> \\n', ...\n'<VTKFile type=\"Collection\" version=\"0.1\"> \\n', ...\n'<Collection> \\n');\n\n  str2 = cat (2, '<DataSet part=\"%d\" file=\"%s.vts\"/> \\n');\n\n  str3 = cat (2, ...\n'</Collection>\\n', ...\n'</VTKFile> \\n');\n\n  if (length (filename) < 4 || ~strcmp (filename(end-3:end), '.pvd'))\n    pvd_filename = cat (2, filename, '.pvd');\n  else\n    pvd_filename = filename;\n    filename = filename (1:end-4);\n  end\n\n  fid = fopen (pvd_filename, 'w');\n  if (fid < 0)\n    error ('mp_sp_to_vtk: could not open file %s', pvd_filename);\n  end\n\n  fprintf (fid, str1);\n  ind = union (find (filename == '/', 1, 'last'), find (filename == '\\', 1, 'last')) + 1;\n  if (isempty (ind)); ind = 1; end\n  for iptc = 1:space.npatch\n    filename_patch_without_path = cat (2, filename(ind:end), '_', num2str (iptc));\n    filename_patch = cat (2, filename, '_', num2str (iptc));\n    fprintf (fid, str2, iptc, filename_patch_without_path);\n    if (isempty (space.dofs_ornt))\n      sp_to_vtk (u(space.gnum{iptc}), space.sp_patch{iptc}, geometry(iptc), npts, ...\n                           filename_patch, fieldname, varargin{:})\n    else\n      sp_to_vtk (u(space.gnum{iptc}) .* space.dofs_ornt{iptc}', space.sp_patch{iptc}, geometry(iptc), npts, ...\n                           filename_patch, fieldname, varargin{:})\n    end\n  end\n  fprintf (fid, str3);\n\n  fclose (fid);\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/multipatch/@sp_multipatch/sp_to_vtk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23802684712107197}}
{"text": "function [p,q] = detectAndMatchFeatures(image1,image1ROI,image2,image2ROI,featureOpts)\n%detectAndMatchFeatures: A wrapper for detecting and matching features\n%between two images using various feature detection methods.\n\n%Inputs\n%\n%image1: The first image (2D unit8, grayscale or rgb). \n%\n%image1ROI: A region-of-interest specifying which region(s) in image1 we\n%should detect features in. If image1ROI=[] then the whole image is used.\n%\n%image2: The second image (2D unit8, grayscale or rgb). \n%\n%image2ROI: A region-of-interest specifying which region(s) in image2 we\n%should detect features in. If image2ROI=[] then the whole image is used.\n%\n%featureOpts: Options field specifying the feature detection method.\n%Currently only SURF (matlab's built-in) and ASIFT\n%(http://www.ipol.im/pub/art/2011/my-asift/) are supported, but it is very\n%easy to introduce others. \n%for ASIFT, featureOpts should have the structures:\n%\n%   featureOpts.featureMethod = 'ASIFT';\n%   featureOpts.asiftPath (the path to the asift code & compiled executable).\n%\n%for SURF, featureOpts should have the structures:\n%\n%   featureOpts.featureMethod = 'SURF'; %careful, unlike ASIFT this only works well \n%when the plane's viewpoint is not too tilted!!\n%\n%   featureOpts.loweRatioThreshold = 1.2 (default) You need to\n%set a confidence ratio (see Lowe's SIFT paper for the explanation of\n%this). Basically, a high value means only using feature matches that are\n%likely to be correct (but at the cost of fewer feature matches). A default\n%of 1.2 is usually fine.\n%\n% outputs:\n%p : 2XN matrix holding the matched points in image1\n%q : 2XN matrix holding the matched points in image2\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of the IPPE package for fast plane-based pose\n% estimation from the paper \"Infinitesimal Plane-based Pose Estimation\" by Toby Collins and Adrien Bartoli,\n% published in the International Journal of Computer Vision, September\n% 2014. A copy of the author's pre-print version can be found here:\n%\n% http://isit.u-clermont1.fr/~ab/Publications/Collins_Bartoli_IJCV14.pdf\n%\n% This package is free and covered by the BSD licence without any warranty. We hope you find this code useful and please cite our paper in your work:\n% (c) Toby Collins 2015\n%\n%\n%@article{\n%year={2014},\n%issn={0920-5691},\n%journal={International Journal of Computer Vision},\n%volume={109},\n%number={3},\n%doi={10.1007/s11263-014-0725-5},\n%title={Infinitesimal Plane-Based Pose Estimation},\n%url={http://dx.doi.org/10.1007/s11263-014-0725-5},\n%publisher={Springer US},\n%keywords={Plane; Pose; SfM; PnP; Homography},\n%author={Collins, Toby and Bartoli, Adrien},\n%pages={252-286},\n%language={English}\n%}\n%\n%\n% This is free software covered by the FreeBSD License (see IPPE_license.txt) with Copyright (c) 2015 Toby Collins\n\n\n%basic argument checking\nif nargin~=5\n   error('detectAndMatchFeatures has 5 input arguments.');\nend\nif nargout>2\n   error('detectAndMatchFeatures has 2 output arguments.');\nend\n\nassert(nargin ==5);\nassert(size(image1,3)==1|size(image1,3)==3);\nassert(size(image2,3)==1|size(image2,3)==3);\nassert(isa(image1,'uint8'));\nassert(isa(image2,'uint8'));\n\n%check whether regions-of-interest are used:\nif isempty(image1ROI)\n    image1ROI = true(size(image1,1),size(image1,2));\nend\nif isempty(image2ROI)\n    image2ROI = true(size(image2,1),size(image2,2));\nend\n\nassert(isa(image1ROI,'logical'));\nassert(isa(image1ROI,'logical'));\n\n\n%convert image to grayscale:\nif size(image1,3)==3\n    image1 = rgb2gray(image1);\nend\n\nif size(image2,3)==3\n    image2 = rgb2gray(image2);\nend\n\n%perform detection and matching:\nswitch featureOpts.featureMethod\n    case 'SURF'\n        %detection:\n        pointsTemplate = detectSURFFeatures(image1,'MetricThreshold',200);\n        featuresTemplate = extractFeatures(image1,pointsTemplate);\n        p = pointsTemplate.Location';\n        \n        pointsInput = detectSURFFeatures(image2,'MetricThreshold',200);\n        featuresInput = extractFeatures(image2,pointsInput);\n        \n        %matching using Lowe's ratio test for rejecting bad matches (see his SIFT paper for details)\n        [IDX, D]= knnsearch(featuresInput,featuresTemplate,'K',2);\n        vlds = D(:,2)./D(:,1)> featureOpts.loweRatioThreshold;\n        q = pointsInput.Location(IDX(:,1),:)';\n        q = q(:,vlds);\n        p = p(:,vlds);\n    case 'ASIFT'\n        [p,q] = asiftWrapper(featureOpts.asiftPath,image1,image2);\n    otherwise\n        error('unknown feature detection method is specified');\nend\n\n%keep only features located in the rois:\nvlds = interp2(double(image1ROI),p(1,:),p(2,:))==1;\nvlds = vlds & interp2(double(image2ROI),q(1,:),q(2,:))==1;\np = p(:,vlds);\nq = q(:,vlds);", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/IPPE_utils/detectAndMatchFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2380185091105747}}
{"text": "function [ts] = timestamp_neuralynx(tsl, tsh)\n\n% TIMESTAMP_NEURALYNX merge the low and high part of Neuralynx timestamps\n% into a single uint64 value\n\n% Copyright (C) 2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id: timestamp_neuralynx.m 2885 2011-02-16 09:41:58Z roboos $\n\nif ~isa(tsl, 'uint32') && ~isa(tsl, 'int32')\n  error('invalid input');\nelseif ~isa(tsh, 'uint32') && ~isa(tsl, 'int32')\n  error('invalid input');\nend\n\n% convert the 32 bit low and 32 bit high timestamp into a 64 bit integer\ndum = zeros(2, length(tsh), 'uint32');\nif littleendian\n  dum(1,:) = tsl;\n  dum(2,:) = tsh;\nelse\n  dum(1,:) = tsh;\n  dum(2,:) = tsl;\nend\n\nts = typecast(dum(:), 'uint64');\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/timestamp_neuralynx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23801850911057468}}
{"text": "% totalNum = 1867290;\n% \n% loopCompress(0.1, '/home/yh/mapModel/2018/08.03/weightVector.txt', '/home/yh/mapModel/2018/08.03/visMatrix/', 50, totalNum, 2040, '/home/yh/mapModel/2018/08.03/gurobi_compress_0.2/');\n% \n% ratio = salientNumCnt( '/home/yh/mapModel/2018/08.03/gurobi_compress_0.2/', totalNum ) / totalNum", "meta": {"author": "HuanYin94", "repo": "map_compression", "sha": "3c126a5cc832bf51f0c313c6ad8aa58a2930312c", "save_path": "github-repos/MATLAB/HuanYin94-map_compression", "path": "github-repos/MATLAB/HuanYin94-map_compression/map_compression-3c126a5cc832bf51f0c313c6ad8aa58a2930312c/gurobi/before/q_ILP/UTS_run/run2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23801850306234654}}
{"text": "function [sig,delay_offset] = delayline(sig,dt,weight,conf)\n%DELAYLINE (fractional) delay line with weights\n%\n%   Usage: [sig,delay_offset] = delayline(sig,dt,weight,conf)\n%\n%   Input parameter:\n%       sig     - input signal (vector), can be in the form of [N C], or\n%                 [M C N], where\n%                     N ... samples\n%                     C ... channels (most probably 2)\n%                     M ... number of measurements\n%                 If the input is [M C N], the length of dt and weight has to be\n%                 1 or M*C. In the last case the first M entries in dt are\n%                 applied to the first channel and so on.\n%       dt      - delay / s\n%       weight  - amplitude weighting factor\n%       conf    - configuration struct (see SFS_config).\n%\n%   Output parameter:\n%       sig             - delayed signal\n%       delay_offset    - additional delay / s\n%                         This is added by the fractional delayline filters to\n%                         all channels. For integer delays this is 0.\n%\n%   DELAYLINE(sig,dt,weight,conf) implementes a delayline, that delays the given\n%   signal by dt samples and applies an amplitude weighting factor. The delay is\n%   implemented as integer delay or fractional delay filter, see delayline\n%   section in SFS_config for possible settings. As default setting an integer\n%   delayline is used.\n%\n%   See also: get_ir, driving_function_imp_wfs\n\n%*****************************************************************************\n% The MIT License (MIT)                                                      *\n%                                                                            *\n% Copyright (c) 2010-2019 SFS Toolbox Developers                             *\n%                                                                            *\n% Permission is hereby granted,  free of charge,  to any person  obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without  restriction, including without limitation *\n% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *\n% and/or  sell copies of  the Software,  and to permit  persons to whom  the *\n% Software is furnished to do so, subject to the following conditions:       *\n%                                                                            *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software.                        *\n%                                                                            *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *\n% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *\n% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *\n% DEALINGS IN THE SOFTWARE.                                                  *\n%                                                                            *\n% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics.              *\n%                                                                            *\n% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Configuration ===================================================\n% Check for old configuration\nif isfield(conf, 'usefracdelay')\n    error(['%s: conf.usefracdelay is deprecated, please use conf.delayline', ...\n           ' instead. See SFS_config for details.'],upper(mfilename));\nend\nfs = conf.fs;\ndelay = conf.delayline;\n\n\n%% ===== Preparation =====================================================\n% --- Reshape signals ---\n% Check if the signal is an impulse response given in SOFA conventions [M C N],\n% or in usual [N C] convention, where\n% M ... number of measurements\n% C ... number of channels\n% N ... number of samples\nif ndims(sig)==3\n    [M,C,samples] = size(sig);\n    channels = M * C;\n    % Reshape [M C N] => [N C*M], this will be redone at the end of the function\n    sig = reshape(sig,[channels,samples])';\n    reshaped = true;\nelse\n    % Assume standard format [N C]\n    [samples,channels] = size(sig);\n    reshaped = false;\nend\n\n\n%% ===== Resampling ======================================================\n% The resampling is applied independently from the actual fractional/integer\n% delay handling performed in the next step. The resampling is redone at the end\n% of the file.\n% If resampling is used together with the integer delay filter, this is already\n% a usage of fractional delay due to the upsampling.\n%\nswitch delay.resampling\ncase 'none'\n    rfactor = 1.0;\n    delay_offset = 0;\ncase 'matlab'\n    rfactor = delay.resamplingfactor;\n    delay_offset = 0;\n    sig = resample(sig,rfactor,1);\ncase 'pm'\n    % === Parks-McClellan linear phase FIR filter ===\n    rfactor = delay.resamplingfactor;\n    rfilt = pm_filter(rfactor*delay.resamplingorder, 0.9/rfactor, ...\n      1/rfactor);\n    delay_offset = delay.resamplingorder*rfactor/2;\n\n    sig = reshape(sig,1,channels*samples);\n    sig = [sig; zeros(rfactor-1,channels*samples)];\n    sig = reshape(sig,rfactor*samples,channels);\n\n    sig = convolution(rfactor*rfilt, sig);\notherwise\n    error('%s: \"%s\": unknown resampling method',upper(mfilename), ...\n        delay.resampling);\nend\n\n\n%% ===== Expansion of signals, delays or weights =========================\n% --- Expand channels\nif channels==1\n    channels = max(length(dt),length(weight));\n    sig = repmat(sig,[1 channels]);\nend\n\n% --- Expand dt and weight ---\n% If only single valued time delay and weight is given, create vectors\nif channels>1 && length(dt)==1, dt=repmat(dt,[1 channels]); end\nif channels>1 && length(weight)==1, weight=repmat(weight,[1 channels]); end\n\n\n%% ===== Conversion to integer delay =====================================\ndt = dt.*rfactor.*fs;  % resampled delay / samples\nsamples = rfactor.*samples;  % length of resampled signals\nswitch delay.filter\ncase 'integer'\n    % === Integer delays ===\n    idt = round(dt);  % round to nearest integer delay\n    delay_offset = delay_offset + 0;\ncase 'zoh'\n    % === Zero-order hold ===\n    idt = ceil(dt);  % round to next larger integer delay\n    delay_offset = delay_offset + 0;\ncase 'lagrange'\n    % === Lagrange polynomial interpolator ===\n    if iseven(delay.filterorder)\n        idt = round(dt);  % round delay for even order\n    else\n        idt = floor(dt);  % floor delay for odd order\n    end\n    fdt = dt - idt;  % fractional part of delays\n    b = lagrange_filter(delay.filterorder,fdt);\n    a = ones(1,channels);\n    delay_offset = delay_offset + floor(delay.filterorder/2);\ncase 'thiran'\n    % === Thiran's allpass filter for maximally flat group delay ===\n    idt = round(dt);  % integer part of delays\n    fdt = dt - idt;  % fractional part of delays\n    [b,a] = thiran_filter(delay.filterorder,fdt);\n    delay_offset = delay_offset + delay.filterorder;\ncase 'least_squares'\n    % ==== Least squares interpolation filter ===\n    idt = floor(dt);  % integer part of delays\n    fdt = dt - idt;  % fractional part of delays\n    b = zeros(delay.filterorder+1,channels);\n    for ii=1:channels\n        b(:,ii) = general_least_squares(delay.filterorder+1,fdt(ii),0.90);\n    end\n    a = ones(1,channels);\n    delay_offset = delay_offset + floor(delay.filterorder/2);\ncase 'farrow'\n    % === Farrow-structure ===\n    % Based on the assumption, that each coefficient h(n) of the fractional\n    % delay filter can be expressed as a polynomial in d (frac. delay), i.e.\n    %            __\n    %           \\  NPol\n    % h_d(n) ~=  >      c_m(n) d^m\n    %           /__m=0\n    %\n    % For some Filter design methods, e.g. Lagrange Interpolators, this is\n    % perfectly possible. For other, a uniform grid of test delays d_q is\n    % used to fit the polynomials to the desired coefficient(n) find a set\n    % polynomial which approximates each coefficient of the desired filter.\n    % This structure allows to perform the convolution independently from\n    % the delay and reuse the results of the filter for different delays.\n    %                           __\n    %                          \\  NPol\n    % y(n) = h_d(n) * x(n) ~=   >      ( c_m(n)*x(n) ) d^m\n    %                          /__m=0\n    %\n    % The above representation shows that the convolution of the input\n    % signal x can be performed by first convolving c_m and x and\n    % incorporating the delay d afterwards.\n    %\n    % number of parallel filters, i.e. order of polynomial + 1\n    % Nfilter = delay.filternumber;\n    to_be_implemented(mfilename);\notherwise\n    error('%s: \\\"%s\\\" is an unknown delayline filter', ...\n        upper(mfilename),delay.filter);\nend\n% Apply filter if needed\nif exist('a','var') && exist('b','var')\n    for ii=1:channels\n        sig(:,ii) = filter(b(:,ii),a(:,ii),sig(:,ii));\n    end\nend\n\n\n%% ===== Integer delayline ===============================================\n% Handling of too long delay values (returns vector of zeros)\nidt(abs(idt)>samples) = samples;\n% Handle positive or negative delays\nfor ii=1:channels\n    if idt(ii)>=0\n        sig(:,ii) = [zeros(idt(ii),1); weight(ii)*sig(1:end-idt(ii),ii)];\n    else\n        sig(:,ii) = [weight(ii)*sig(-idt(ii)+1:end,ii); zeros(-idt(ii),1)];\n    end\nend\n\n\n%% ===== Postprocessing ==================================================\n% --- Downsampling ---\nif rfactor~=1\n    sig = sig(1:rfactor:samples,:);\n    delay_offset = delay_offset ./ rfactor;\nend\n% --- Undo reshape ---\n% [N M*C] => [M C N]\nif reshaped\n    % C might have changed due to replication of single-channel input\n    sig = reshape(sig',M,[],size(sig,1));\nend\n% --- delay_offset in seconds ---\ndelay_offset = delay_offset / fs;\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_general/delayline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.2380055059136063}}
{"text": "function bms = spm_cfg_bms_map\n% Configuration file for BMS interface\n%__________________________________________________________________________\n% Copyright (C) 2008-2016 Wellcome Trust Centre for Neuroimaging\n\n% Maria Joao Rosa\n% $Id: spm_cfg_bms_map.m 6952 2016-11-25 16:03:13Z guillaume $\n\n%--------------------------------------------------------------------------\n% dir Directory\n%--------------------------------------------------------------------------\ndir         = cfg_files;\ndir.tag     = 'dir';\ndir.name    = 'Directory';\ndir.help    = {['Select the directory where the files containing the '...\n               'results from BMS (BMS.mat) will be written.']};\ndir.filter  = 'dir';\ndir.ufilter = '.*';\ndir.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% mod_map Log evidence maps\n%--------------------------------------------------------------------------\nmod_map         = cfg_files;\nmod_map.tag     = 'mod_map';\nmod_map.name    = 'Models';\nmod_map.help    = {['Specify the log. evidence map for each model. '...\n                    'Log-evidence maps should be specified '...\n                    'in the same order for each subject and session.']};\nmod_map.filter  = 'image';\nmod_map.ufilter = '.*';\nmod_map.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% sess_map Sessions (Maps)\n%--------------------------------------------------------------------------\nsess_map      = cfg_branch;\nsess_map.tag  = 'sess_map';\nsess_map.name = 'Session';\nsess_map.val  = {mod_map };\n\n%--------------------------------------------------------------------------\n% subj_dcm Subject (Maps)\n%--------------------------------------------------------------------------\nsubj_map         = cfg_repeat;\nsubj_map.tag     = 'subj_map';\nsubj_map.name    = 'Subject';\nsubj_map.values  = {sess_map };\n\n%--------------------------------------------------------------------------\n% map Data\n%--------------------------------------------------------------------------\nmap         = cfg_repeat;\nmap.tag     = 'map';\nmap.name    = 'Data';\nmap.help    = {['Select the log. evidence maps for each '...\n               'model, session and subject.']}';\nmap.values  = {subj_map };\nmap.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% mod_name Name\n%--------------------------------------------------------------------------\nmod_name         = cfg_entry;\nmod_name.tag     = 'mod_name';\nmod_name.name    = 'Name';\nmod_name.help    = {'Specify name for each model (optional).'};\nmod_name.strtype = 's';\nmod_name.num     = [0 Inf];\nmod_name.val     = {''};\n\n%--------------------------------------------------------------------------\n% name_mod Name models\n%--------------------------------------------------------------------------\nname_mod         = cfg_repeat;\nname_mod.tag     = 'name_mod';\nname_mod.name    = 'Name models';\nname_mod.help    = {'Specify name for each model (optional).'}';\nname_mod.values  = {mod_name };\nname_mod.num     = [0 Inf];\n\n%--------------------------------------------------------------------------\n% method_maps Inference Method (maps)\n%--------------------------------------------------------------------------\nmethod_maps         = cfg_menu;\nmethod_maps.tag     = 'method_maps';\nmethod_maps.name    = 'Inference method';\nmethod_maps.help    = {['Specify inference method: random effects '...\n                   '(2nd-level, RFX) or fixed effects (1st-level, FFX) analysis. '...\n                   'RFX uses a Variational Bayes approach.']};\nmethod_maps.labels  = {\n                  'Fixed effects (FFX)'\n                  'Random effects (RFX)'\n}';\nmethod_maps.values  = {\n                  'FFX'\n                  'RFX'\n}'; \n\n% %--------------------------------------------------------------------------\n% % priors Priors\n% %--------------------------------------------------------------------------\n% priors         = cfg_menu;\n% priors.tag     = 'priors';\n% priors.name    = 'Priors';\n% priors.help    = {['Specify priors for family-level inference (RFX only).\n% '...\n%                    'Options: ''Family'' sets alpha0=1 for each family '...\n%                    'while ''Model'' sets alpha0=1 for each model (not '...\n%                    'advised).']};\n% priors.labels  = {\n%                   'Model'\n%                   'Family'\n% }';\n% priors.values  = {\n%                   'M-unity'\n%                   'F-unity'\n% }';\n% priors.val      = {'F-unity'};\n\n%--------------------------------------------------------------------------\n% out_file Output files\n%--------------------------------------------------------------------------\nout_file         = cfg_menu;\nout_file.tag     = 'out_file';\nout_file.name    = 'Output files (RFX)';\nout_file.help    = {['Specify which output files to save (only valid for'...\n                     'RFX analyses). ']...\n                     ''...\n                    ['Default option (and faster option): '...\n                     'PPM = xppm.<ext> (Expected Posterior Probability Maps) '...\n                     'for each model ie. posterior mean.']...\n                     ''...\n                    ['Second option: PPM + EPM = xppm.<ext> + '...\n                     'epm.<ext> (Expected Posterior Probability '...\n                     'Maps + Exceedance Probability Maps) for each model.']...\n                     ''...\n                    ['Third option: PPM + EPM + Alpha = xppm.<ext> + '...\n                     'epm.<ext> + alpha.<ext> (PPM, EPM and Map of Dirichlet '...\n                     'Parameters) for each model.']};\nout_file.labels  = {\n                   'PPM'\n                   'PPM + EPM'\n                   'PPM + EPM + Alpha'\n                   \n}';\nout_file.values  = {\n                  0\n                  1\n                  2\n}';\nout_file.val     = {0};\n\n%--------------------------------------------------------------------------\n% mask Mask Image\n%--------------------------------------------------------------------------\nmask         = cfg_files;\nmask.tag     = 'mask';\nmask.name    = 'Mask Image';\nmask.help    = {['Specify an image for explicitly masking the analysis. '...\n                '(optional). '...\n                'A sensible option here is to use a segmention of '...\n                'structural images to specify a within-brain mask. '...\n                'If you select that image as an explicit mask then only '...\n                'those voxels in the brain will be analysed. This both '...\n                'speeds the inference process and restricts BMS to '...\n                'within-brain voxels. Alternatively, if such structural '...\n                'images are unavailble or no masking is required, then '...\n                'leave this field empty.']};\nmask.filter  = 'image';\nmask.ufilter = '.*';\nmask.val     = {{''}};\nmask.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% nsamp Number of samples\n%--------------------------------------------------------------------------\nnsamp         = cfg_entry;\nnsamp.tag     = 'nsamp';\nnsamp.name    = 'Number of samples';\nnsamp.help    = {['Number of samples used to compute exceedance '...\n                  'probabilities (default: 1e6). '...\n                  'To make computations faster reduce the number of '...\n                  'samples when number of models is bigger than 3.']};                 \nnsamp.strtype = 's';\nnsamp.num     = [1 Inf];\nnsamp.val     = {'1e6'};\n\n%--------------------------------------------------------------------------\n% file BMS.mat\n%--------------------------------------------------------------------------\nfile         = cfg_files;\nfile.tag     = 'file';\nfile.name    = 'BMS.mat';\nfile.help    = {['Specify the BMS (.mat) file obtained from previous BMS '...\n               'analysis (optional). Leave field empty to work on '...\n               'serial mode.']};\nfile.filter  = 'mat';\nfile.ufilter = '.*';\nfile.val     = {{''}};\nfile.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% img Map to display\n%--------------------------------------------------------------------------\nimg         = cfg_files;\nimg.tag     = 'img';\nimg.name    = 'Map to display';\nimg.help    = {['Specify map obtained from BMS Maps '...\n               '(optional). Leave field empty to work on serial mode.']};\nimg.filter  = 'image';\nimg.ufilter = '.*';\nimg.val     = {{''}};\nimg.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% thres Probability Threshold\n%--------------------------------------------------------------------------\nthres         = cfg_entry;\nthres.tag     = 'thres';\nthres.name    = 'Probability threshold';\nthres.help    = {['Specify the probability threshold to apply to the '...\n                 'image (optional). Leave field empty to work on '...\n                 'serial mode.']};                 \nthres.strtype = 'r';\nthres.num     = [0 Inf];\nthres.val     = {[]};\n\n%--------------------------------------------------------------------------\n% k Extent threshold\n%--------------------------------------------------------------------------\nk         = cfg_entry;\nk.tag     = 'k';\nk.name    = 'Extent threshold';\nk.help    = {['Specify extent threshold (minimum number of voxels '...\n                 'per cluster).']};                 \nk.strtype = 'w';\nk.num     = [0 Inf];\nk.val     = {[]};\n\n%--------------------------------------------------------------------------\n% scale Map Scale\n%--------------------------------------------------------------------------\nscale         = cfg_menu;\nscale.tag     = 'scale';\nscale.name    = 'Map scale';\nscale.help    = {['Specify scale to display maps (optional). Default: '...\n                 'empty field to work on serial mode. Other options: '...\n                 '''None'' will display image with original scale and '...\n                 '''Log-odds'' will display image in a log-odds '...\n                 ' scale (in this case image should be a '...\n                 'probability map).']};\nscale.labels  = {\n                  'Empty'\n                  'None'\n                  'Log-odds'\n}';\nscale.values  = {\n                  []\n                  0\n                  1\n}';\nscale.val     = {[]};\n\n%--------------------------------------------------------------------------\n% bms_map_inf BMS: Maps (Inference), output is BMS map \n%--------------------------------------------------------------------------\nbms_map_inf      = cfg_exbranch;\nbms_map_inf.tag  = 'inference';\nbms_map_inf.name = 'BMS: Maps (Inference)';\nbms_map_inf.val  = {dir map name_mod method_maps out_file mask nsamp };\nbms_map_inf.help = {'Bayesian Model Selection for Log-Evidence Maps.'...\n    ''...\n    ['Input: log-evidence maps for each model, session and '...\n    'subject. Note that there must be identical numbers of models for '...\n    'all sessions, and identical numbers of sessions for all '...\n    'subjects.']...\n    ''...\n    ['Output: For the fixed effects analysis, posterior probability maps '...\n    'are created for each model. '...\n    'For the random effects analysis, expected posterior probability '...\n    'and exceedance probability (i.e. the probability that this model '...\n    'is more likely than any other model) maps are created for each '...\n    'model. If there are multiple sessions per subject, the random '...\n    'effects analysis operates on the subject-specific sums of log '...\n    'evidences across sessions. In addition, a BMS.mat file will be save '...\n    'in the specified directory for both methods']};\nbms_map_inf.prog = @spm_run_bms_map;\nbms_map_inf.vout = @vout;\n\n%--------------------------------------------------------------------------\n% bms_map_vis BMS: Maps (Results), visualisation of BMS Maps results\n%--------------------------------------------------------------------------\nbms_map_vis      = cfg_exbranch;\nbms_map_vis.tag  = 'results';\nbms_map_vis.name = 'BMS: Maps (Results)';\nbms_map_vis.val  = {file img thres k scale};\nbms_map_vis.help = {['Bayesian Model Selection Maps (Results).'...\n                    'Show results from BMS Maps (Inference).']};\nbms_map_vis.prog = @spm_run_bms_vis;\n\n%--------------------------------------------------------------------------\n% bms Bayesian Model Selection\n%--------------------------------------------------------------------------\nbms         = cfg_choice;\nbms.tag     = 'bms_map';\nbms.name    = 'Bayesian Model Selection';\nbms.help    = {['Bayesian Model Selection for group studies (fixed '...\n               'effects and random effects analysis).']};\nbms.values  = { bms_map_inf bms_map_vis };\n\n\n%==========================================================================\nfunction dep = vout(varargin)\n% Output file names will be saved in a struct with field .files\ndep(1)            = cfg_dep;\ndep(1).sname      = 'BMS.mat File';\ndep(1).src_output = substruct('.','files');\ndep(1).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_bms_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23789785362482152}}
{"text": "function [ALLEEG cfg] = pop_est_fitMVAR(ALLEEG,typeproc,varargin)\n%\n% Preprocess EEG dataset(s) for connectivity analysis. See [1] for\n% mathematical details on preprocessing steps.\n%\n%\n% Input:\n%\n%   ALLEEG:         Array of EEGLAB datasets to preprocess.\n%   typeproc:       Reserved for future use. Use 0\n%\n% Optional:         \n%\n%   <'Name',value> pairs as defined in pre_prepData()\n%   \n% Output:\n%\n%   ALLEEG:         Prepocessed EEG structure(s)\n%   cfg:            Argument specification structure.\n%\n%\n% See Also: pre_prepData()\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual. Section 6.5.1 \n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift\n% \n% Author: Tim Mullen 2009, SCCN/INC, UCSD. \n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nif nargin<2\n    typeproc = 0;\nend\n\nfcnName     = strrep(mfilename,'pop_','');\nfcnHandle   = str2func(fcnName);\n\n% check the dataset\nres = hlp_checkeegset(ALLEEG,{'cat'});\nif ~isempty(res)\n    error(['SIFT:' fcnName],res{1});\nend\n\nif isfield(ALLEEG(1).CAT.configs,fcnName)\n    % get default configuration (from prior use) and merge with varargin\n    varargin = [hlp_struct2varargin(ALLEEG(1).CAT.configs.(fcnName)) varargin];\nend\n\nif strcmpi(typeproc,'nogui')\n    % get the config from function\n    cfg = arg_tovals(arg_report('rich',fcnHandle,[{'EEG',ALLEEG(1)},varargin]),false);\nelse\n    % render the GUI\n    [PGh figh] = feval(['gui_' fcnName],ALLEEG(1),varargin{:});\n    \n    if isempty(PGh)\n        % user chose to cancel\n        cfg = [];\n        return;\n    end\n    \n    % get the specification of the PropertyGrid\n    ps = PGh.GetPropertySpecification;\n    cfg = arg_tovals(ps,false);\nend\n\ndrawnow;\n\nif strcmpi(typeproc,'cfg_only')\n    return;\nend\n\n\n% initialize progress bar\nif cfg.verb==2 && length(ALLEEG)>1\n    waitbarTitle = 'Fitting VAR Models';\n    \n    multiWaitbar(waitbarTitle,'Reset');\n    multiWaitbar(waitbarTitle,'ResetCancel',true);\n    multiWaitbar(waitbarTitle,...\n                 'Color', [0.8 0.0 0.1],  ...\n                 'CanCancel','on',        ...\n                 'CancelFcn',@(a,b)disp('[Cancel requested. Please wait...]'));\nend\n\n% execute the low-level function\nfor cnd=1:length(ALLEEG)\n    [ALLEEG(cnd).CAT.MODEL] = feval(fcnHandle,'EEG',ALLEEG(cnd),cfg);\n    \n    if ~isempty(cfg)\n        % store the configuration structure\n        ALLEEG(cnd).CAT.configs.(fcnName) = cfg;\n    end\n    \n    if cfg.verb==2 && length(ALLEEG)>1\n        % update waitbar\n        drawnow;\n        cancel = multiWaitbar(waitbarTitle,cnd/length(ALLEEG));\n        if cancel && hlp_confirmWaitbarCancel(waitbarTitle)\n            break;\n        end\n    end\n    \nend\n\n% cleanup progress bar\nif cfg.verb==2 && length(ALLEEG)>1\n    multiWaitbar(waitbarTitle,'Close');\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/pop/pop_est_fitMVAR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.23789785362482152}}
{"text": "function rez = runTemplates(rez)\n\n% this function will run Kilosort2 initializing at some previously found\n% templates. These must be specified in rez.W, rez.U and rez.mu. The batch\n% number at which the new template run is started is by default 1 (modify it by changing rez.istart). \n\n% If you don't mind changes in template throughout the recording, but want\n% to use the results from a previous session after splitting and merging, just pass\n% the rez output from this previous session.\n\n% Keep in mind that these templates will nonetheless\n% change substantially as they track neurons throughout the new recording. \n% As such, it is best to use the templates obtained at the very end of the\n% previous recording, which are found in rez.WA(:,:,:,end),\n% rez.UA(:,:,:,end), rez.muA(:,end). Keep in mind that any merging and\n% splitting steps are done after running the templates, and would result in\n% difference between sessions if done separately on each session. \n\n% update: these recommendations no longer apply for the datashift version!\n\nif sum(isfield(rez, {'istart'}))<1\n    warning('if using pre-loaded templates, please specify istart, defaulting to 1');\n    rez.istart = 1;\nend\n\nif sum(isfield(rez, {'W', 'U', 'mu'}))<3\n    error('missing at least one field: W, U, mu');\nend\n\nNbatches = rez.ops.Nbatch;\n\niorder = 1:Nbatches;\n\n[rez, st3, fW,fWpc] = trackAndSort(rez, iorder);\n\n% sort all spikes by batch -- to keep similar batches together,\n% which avoids false splits in splitAllClusters. Break ties \n% [~, isort] = sortrows(st3,[5,1,2,3,4]); \n% st3 = st3(isort, :);\n% fW = fW(:, isort);\n% fWpc = fWpc(:, :, isort);\n\n% just display the total number of spikes\nfprintf( 'Number of spikes before applying cutoff: %d\\n', size(st3,1));\n\nrez.st3 = st3;\nrez.st2 = st3; % keep also an st2 copy, because st3 will be over-written by one of the post-processing steps\n\n% the template features are stored in cProj, like in Kilosort1\nrez.cProj    = fW';\n\n%  permute the PC projections in the right order\nrez.cProjPC     = permute(fWpc, [3 2 1]); %zeros(size(st3,1), 3, nNeighPC, 'single');\n% iNeighPC keeps the indices of the channels corresponding to the PC features\n\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/mainLoop/runTemplates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.23787133935866236}}
{"text": "% --------------------------------------------------------------------------- %\n% MarrRevisited - Surface Normal Estimation\n% Copyright (c) 2016 Adobe Systems Incorporated and Carnegie Mellon University. \n% All rights reserved.[see LICENSE for details]\n% -------------------------------------------------------------------------- %\n\n% Written by Aayush Bansal. Please contact ab.nsit@gmail.com\n% demo code to use the surface normal mode --\nclc; clear all;\n\n%\nconv_cache = ['./cachedir/demo_results/'];\nif(~isdir(conv_cache))\n        mkdir(conv_cache);\nend\n\n% initialize caffe\nNET_FILE_PATH = ['./cachedir/surface_normal_models/'];\nnet_file     = [NET_FILE_PATH, 'best_model.caffemodel'];\nDEPLOY_FILE_PATH = ['./net/conv/'];\ndeploy_file  = [DEPLOY_FILE_PATH, 'deploy.prototxt']; \n\n% set the gpu --\n% if not using GPU, set it to CPU mode.\ngpu_id = 0;\ncaffe.reset_all;\ncaffe.set_device(gpu_id);\ncaffe.set_mode_gpu;\nnet = caffe.Net(deploy_file, net_file, 'test');\n\ncnn_input_size = 224;\ncrop_height = 224; crop_width = 224;\nimage_mean = cat(3,  103.9390*ones(cnn_input_size),...\n\t\t     116.7700*ones(cnn_input_size),...\n\t\t     123.6800*ones(cnn_input_size));\n\n% read the image set for NYU\nimg_data = {'demo/img_000001.jpg', 'demo/img_000002.jpg'};\n\n% for each image in the img_set\nfor i = 1:length(img_data)\n\n\tdisplay(['Image : ', img_data{i}]);\n\tith_Img = im2uint8(imread(img_data{i}));\n\n\t%\n        save_file_name = [conv_cache, strrep(img_data{i}, '.jpg', '')];\n        if(exist([save_file_name, '.mat'], 'file'))\n                continue;\n        end\n\t \n        j_ims = single(ith_Img(:,:,[3 2 1]));\n        j_tmp = imresize(j_ims, [cnn_input_size, cnn_input_size], ...\n                           'bilinear', 'antialiasing', false);\n        j_tmp = j_tmp - image_mean;\n        ims(:,:,:,1) = permute(j_tmp, [2 1 3]);\t\n\n        snd(:,:,:,1) = (1/sqrt(3))*ones(cnn_input_size+200, cnn_input_size+200,3);\n        depd(:,:,:,1) = zeros(cnn_input_size+200, cnn_input_size+200);\n\n        %\n        net.blobs('data0').reshape([crop_height+200, crop_width+200, 3, 1]);\n        net.blobs('data2').reshape([crop_height+200, crop_width+200, 1, 1]);\n        net.blobs('data1').reshape([crop_height+200, crop_width+200, 3, 1]);\n\n\n        input_data = zeros(crop_height+200,crop_width+200,3,1);\n        input_data(101:crop_width+100, 101:crop_width+100, :, 1) = ims;\n        depd(101:crop_width+100, 101:crop_width+100, :, 1) = 1;\n        net.blobs('data0').set_data(input_data);\n        net.blobs('data2').set_data(depd);\n        net.blobs('data1').set_data(snd);\n\n        net.forward_prefilled();\n        out = net.blobs('fc8_hcol').get_data();\n\n        %%\n        f2 = out';\n        f2 = reshape(f2, [224, 224,3]);\n        f2 = permute(f2, [2,1,3]);\n\n        % normalize\n        nx = f2(:,:,1); ny = f2(:,:,2); nz = f2(:,:,3);\n        N = (nx.^2 + ny.^2 + nz.^2).^0.5 + eps;\n        nx = nx./N; ny = ny./N; nz = nz./N;\n\n        predns = cat(3, nx, ny, nz);\n        predns = imresize(predns,...\n                 [size(ith_Img,1), size(ith_Img,2)]);\n        pred_N = (predns(:,:,1).^2 + predns(:,:,2).^2 +...\n                                 predns(:,:,3).^2).^0.5 + eps;\n        predns(:,:,1) = predns(:,:,1)./pred_N;\n        predns(:,:,2) = predns(:,:,2)./pred_N;\n        predns(:,:,3) = predns(:,:,3)./pred_N;\n\n        predns_vis = uint8(255*(max(min(predns,1),-1)+1)/2);\n\n        % dump the nx/ny/nz\n        predns = single(predns);\n        imwrite(predns_vis, [save_file_name, '.png']);\n        save([save_file_name, '.mat'], 'predns')\n\nend\n\n% reset caffe\ncaffe.reset_all;\n", "meta": {"author": "aayushbansal", "repo": "MarrRevisited", "sha": "13ec38f9dcaa3aa88a0f4796f0c40aba8c2543a8", "save_path": "github-repos/MATLAB/aayushbansal-MarrRevisited", "path": "github-repos/MATLAB/aayushbansal-MarrRevisited/MarrRevisited-13ec38f9dcaa3aa88a0f4796f0c40aba8c2543a8/normals/demo/demo_code.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188373563072, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23771550853612544}}
{"text": "function kern = pathKernExpandParam(kern, params)\n\n% PATHKERNEXPANDPARAM Create kernel structure from PATH kernel's parameters.\n% FORMAT\n% DESC returns a path kernel structure filled with the\n% parameters in the given vector. This is used as a helper function to\n% enable parameters to be optimised in, for example, the NETLAB\n% optimisation functions.\n% ARG kern : the kernel structure in which the parameters are to be\n% placed.\n% ARG param : vector of parameters which are to be placed in the\n% kernel structure.\n% RETURN kern : kernel structure with the given parameters in the\n% relevant locations.\n%\n% SEEALSO : pathKernParamInit, pathKernExtractParam, kernExpandParam\n%\n% COPYRIGHT : Andrea Baisero, Carl Henrik Ek, 2013\n\n% SHEFFIELDML\n\n\nkern.cd=(params(1))^2;\nkern.chv=params(2);\nkern.gkern=kernExpandParam(kern.gkern,params(3:end));\n\nkern = pathKernUpdateWMat(kern,[],true);", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/pathKernExpandParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23770943289591243}}
{"text": "function output = BalancePrep(meta_meta)\n% Balances the reactions, used in `ReactionChecks`\n%\n% USAGE:\n%\n%    output = BalancePrep(meta_meta)\n%\n% INPUT:\n%    meta_meta:    matrix from `ReconstructionTool`\n%\n% OUTPUT:\n%    output:   `leftside`, `rightside`, `charge_l` and `charge_r` in `varargout`\n%\n% .. Author: - Stefan G. Thorleifsson 2010\n%\n% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+\n% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for\n% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.\n% .. rbionet@systemsbiology.is\n\noutput = [];\nif isempty(meta_meta)\n    return\nend\n\nS = size(meta_meta);\n\nfor i = 1:S(1);\n    if ismember('',meta_meta(i,6))\n        msgbox(['Reaction cannot be created with metabolites that are'...\n            'missing the charged formula. ' meta_meta(i,1)  ],...\n            'Missing charge formula','warn');\n        return\n    end\nend\n%---------- Creating formula ---------------- begin\n\n\n%initialize variables\nleftside = []; rightside = [];\ncharge_left = []; charge_right = [];\n\nfor i = 1:S(1)\n\n    %creating metabolite [compartment] ready\n    comp_str = meta_meta{i,4};\n    comp_cnt = regexpi(comp_str,'\\(');\n    comp = comp_str(comp_cnt+1);\n\n    if meta_meta{i,3} == 1 % No numbers\n        newmetab = [meta_meta{i,1} '[' comp ']'];\n    else\n        newmetab = [num2str(meta_meta{i,3}) ' ' meta_meta{i,1} '[' comp ']'];\n    end\n\n    % Dividing left from right.\n    if strmatch(meta_meta(i,5),'Substrate','exact')\n        charge_left = [charge_left str2double(meta_meta{i,7})*meta_meta{i,3}]; %adding up the charge\n\n        if isempty(leftside)\n            leftside = newmetab;\n        else\n            leftside = [leftside ' + ' newmetab];\n        end\n    elseif strmatch(meta_meta(i,5),'Product','exact')\n        charge_right = [charge_right str2double(meta_meta{i,7})*meta_meta{i,3}];%adding up the charge\n        if isempty(rightside)\n            rightside = newmetab;\n        else\n            rightside = [rightside ' + ' newmetab];\n        end\n    else\n        msgbox('Something is wrong with Substrate and Product.',...\n            'Reaction balance.','error');\n        return\n    end\nend\n\ncharge_l = sum(charge_left);\ncharge_r = sum(charge_right);\n\noutput = {leftside,rightside,charge_l,charge_r};\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/rBioNet/BalancePrep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.23770943289591243}}
{"text": "function [gp, varargout] = gp_optim(gp, x, y, varargin)\n%GP_OPTIM  Optimize paramaters of a Gaussian process \n%\n%  Description\n%    GP = GP_OPTIM(GP, X, Y, OPTIONS) optimises the parameters of a\n%    GP structure given matrix X of training inputs and vector\n%    Y of training targets.\n%\n%    [GP, OUTPUT1, OUTPUT2, ...] = GP_OPTIM(GP, X, Y, OPTIONS)\n%    optionally returns outputs of the optimization function.\n%\n%    OPTIONS is optional parameter-value pair\n%      z      - optional observed quantity in triplet (x_i,y_i,z_i)\n%               Some likelihoods may use this. For example, in case of\n%               Poisson likelihood we have z_i=E_i, that is, expected\n%               value for ith case.\n%      optimf - function handle for an optimization function, which is\n%               assumed to have similar input and output arguments\n%               as usual fmin*-functions. Default is @fminscg.\n%      opt    - options structure for the minimization function. \n%               Use optimset to set these options. By default options\n%               'GradObj' is 'on', 'LargeScale' is 'off'.\n%      loss   - 'e' to minimize the marginal posterior energy (default) or\n%               'loo' to minimize the negative leave-one-out lpd\n%               'kfcv' to minimize the negative k-fold-cv lpd\n%               'waic' to minimize the WAIC loss\n%               only 'e' and 'loo' with Gaussian likelihood have gradients\n%      k      - number of folds in kfcv\n%\n%  See also\n%    GP_SET, GP_E, GP_G, GP_EG, FMINSCG, FMINLBFGS, OPTIMSET, DEMO_REGRESSION*\n%\n% Copyright (c) 2010-2012 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nip=inputParser;\nip.FunctionName = 'GP_OPTIM';\nip.addRequired('gp',@(x) isstruct(x) || isempty(x));\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('optimf', @fminscg, @(x) isa(x,'function_handle'))\nip.addParamValue('opt', [], @isstruct)\nip.addParamValue('loss', 'e', @(x) ismember(lower(x),{'e', 'loo', 'kfcv', 'waic' 'waic' 'waicv' 'waicg'}))\nip.addParamValue('k', 10, @(x) isreal(x) && isscalar(x) && isfinite(x) && x>0)\nip.parse(gp, x, y, varargin{:});\nif isempty(gp)\n  gp=gp_set();\nend\nif isempty(gp_pak(gp))\n  % nothing to optimize\n  return\nend\nz=ip.Results.z;\noptimf=ip.Results.optimf;\nopt=ip.Results.opt;\nloss=ip.Results.loss;\nk=ip.Results.k;\n\n\nswitch lower(loss)\n  case 'e'\n    fh_eg=@(ww) gp_eg(ww, gp, x, y, 'z', z);\n    optdefault=struct('GradObj','on','LargeScale','off');\n  case 'loo'\n    fh_eg=@(ww) gp_looeg(ww, gp, x, y, 'z', z);\n    if isfield(gp.lik.fh,'trcov') || isequal(gp.latent_method, 'EP')\n      optdefault=struct('GradObj','on','LargeScale','off');\n    else\n      % Laplace-LOO does not have yet gradients\n      optdefault=struct('Algorithm','interior-point');\n      if ismember('optimf',ip.UsingDefaults)\n        optimf=@fmincon;\n      end\n    end\n  case 'kfcv'\n    % kfcv does not have yet gradients\n    fh_eg=@(ww) gp_kfcve(ww, gp, x, y, 'z', z, 'k', k);\n    optdefault=struct('Algorithm','interior-point');\n    if ismember('optimf',ip.UsingDefaults)\n      optimf=@fmincon;\n    end\n  case {'waic' 'waicv'}\n    % waic does not have yet gradients\n    fh_eg=@(ww) -gp_waic(gp_unpak(gp,ww), x, y, 'z', z);\n    optdefault=struct('Algorithm','interior-point');\n    if ismember('optimf',ip.UsingDefaults)\n      optimf=@fmincon;\n    end\n  case 'waicg'\n    % waic does not have yet gradients\n    fh_eg=@(ww) -gp_waic(gp_unpak(gp,ww), x, y, 'z', z, 'method', 'G');\n    optdefault=struct('Algorithm','interior-point');\n    if ismember('optimf',ip.UsingDefaults)\n      optimf=@fmincon;\n    end\nend\nopt=setOpt(optdefault,opt);\nw=gp_pak(gp);\nif isequal(lower(loss),'e') || (isequal(lower(loss),'loo')) && (isfield(gp.lik.fh,'trcov') || isequal(gp.latent_method, 'EP'))\n  switch nargout\n    case 6\n      [w,fval,exitflag,output,grad,hessian] = optimf(fh_eg, w, opt);\n      varargout={fval,exitflag,output,grad,hessian};\n    case 5\n      [w,fval,exitflag,output,grad] = optimf(fh_eg, w, opt);\n      varargout={fval,exitflag,output,grad};\n    case 4\n      [w,fval,exitflag,output] = optimf(fh_eg, w, opt);\n      varargout={fval,exitflag,output};\n    case 3\n      [w,fval,exitflag] = optimf(fh_eg, w, opt);\n      varargout={fval,exitflag};\n    case 2\n      [w,fval] = optimf(fh_eg, w, opt);\n      varargout={fval};\n    case 1\n      w = optimf(fh_eg, w, opt);\n      varargout={};\n  end\nelse\n  lb=repmat(-8,size(w));\n  ub=repmat(10,size(w));\n  switch nargout\n    case 6\n      [w,fval,exitflag,output,grad,hessian] = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={fval,exitflag,output,grad,hessian};\n    case 5\n      [w,fval,exitflag,output,grad] = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={fval,exitflag,output,grad};\n    case 4\n      [w,fval,exitflag,output] = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={fval,exitflag,output};\n    case 3\n      [w,fval,exitflag] = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={fval,exitflag};\n    case 2\n      [w,fval] = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={fval};\n    case 1\n      w = optimf(fh_eg, w, [], [], [], [], lb, ub, [], opt);\n      varargout={};\n  end\nend\ngp=gp_unpak(gp,w);\nend\n\nfunction opt=setOpt(optdefault, opt)\n  % Set default options\n  opttmp=optimset(optdefault,opt);\n  \n  % Set some additional options for @fminscg\n  if isfield(opt,'lambda')\n    opttmp.lambda=opt.lambda;\n  end\n  if isfield(opt,'lambdalim')\n    opttmp.lambdalim=opt.lambdalim;\n  end\n  opt=opttmp;\nend\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gp_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23767830217921007}}
{"text": "\n%%% Note: run the 'DataGen/A_data_generation.m' to generate\n%%% training data first.\nclear;\nrng('default')\naddpath(genpath('./.'));\naddpath(genpath('../.'));\naddpath(genpath('../DataGen'));\naddpath('matconvnet');\nvl_setupnn;\n\n%%%-------------------------------------------------------------------------\n%%% Data generation\n%%%-------------------------------------------------------------------------\nA_data_generation;\n\n%%%-------------------------------------------------------------------------\n%%% Configuration\n%%%-------------------------------------------------------------------------\n\nopts.gpus             = [1 2]; %%% this code can only support multi-GPU!\n\n\n\nopts.numSubBatches    = 1;\nopts.bnormLearningRate= 0;\n\n%%% solver\nopts.solver           = 'Adam';\nopts.numberImdb       = 1;\n\nopts.derOutputs       = {'objective', 1} ;\n\next               =  {'*.jpg','*.png','*.bmp'};\n\nopts.gradientClipping = false; %%% set 'true' to prevent exploding gradients in the beginning.\nopts.backPropDepth    = Inf;\n%%%-------------------------------------------------------------------------\n%%%   Initialize model and load data\n%%%---------------------------------------------------- \n\n%%%  load data\n\nglobal CurTask;\nCurTask = 'Denoising'; %% 'Deblocking' and 'SISR'\n\n\nopts.imdbDir          = '../DataGen/DN_PATCH192';\nfilepaths           =  [];\nfor i = 1 : length(ext)\n    filepaths = [filepaths; dir(fullfile(opts.imdbDir, ext{i}))];\nend\nimdb.imdbPath = opts.imdbDir;\nimdb.filepaths = filepaths;\nimdb.images.set = ones(numel(filepaths),1);\nfprintf('-----------------------------------------------------------\\n');\nfprintf('--------------------Training Number %d---------------------\\n', numel(filepaths));\nfprintf('-----------------------------------------------------------\\n');\nimage = imread(fullfile(opts.imdbDir, filepaths(1).name));\nimdb.patch_size = size(image, 1);\n\n\nopts.learningRate     = [logspace(-3, -3, 15) logspace(-3.8, -4, 20) logspace(-4.5, -5, 10)];\n\n%% for denosining, set simga to [15, 25, 50]; for SISR, set simga to [2, 3, 4], and for deblocking, set sigma to [10, 20, 30, 40]\nopts.sigma            = 50; \n\nopts.modelName        = ['MWCNN_GDSigma' num2str(opts.sigma)]; %%% model name\nimdb.modelName        = opts.modelName;\n\nopts.expDir      = fullfile('data', opts.modelName);\nopts.batchSize        = 32*numel(opts.gpus);\nnet = net_wavelet_haart_24;\n\n\n[~, ~] = cnn_train(net, imdb, ...\n    'expDir', opts.expDir, ...\n    'learningRate',opts.learningRate, ...\n    'derOutputs',opts.derOutputs, ...\n    'bnormLearningRate',opts.bnormLearningRate, ...\n    'numSubBatches',opts.numSubBatches, ...\n    'numberImdb',opts.numberImdb, ...\n    'backPropDepth',opts.backPropDepth, ...\n    'batchSize', opts.batchSize, ...\n    'modelname', opts.modelName, ...\n    'sigma', opts.sigma, ... \n    'gpus',opts.gpus) ;\n\n", "meta": {"author": "lpj0", "repo": "MWCNN", "sha": "24cee98d9b8c6d6d35549be693314c3994ef1269", "save_path": "github-repos/MATLAB/lpj0-MWCNN", "path": "github-repos/MATLAB/lpj0-MWCNN/MWCNN-24cee98d9b8c6d6d35549be693314c3994ef1269/Training_Code/Run_Demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23767830217921004}}
{"text": "function [modelMin, modelPruned, Ex_Rxns] = generateCompactExchModel(model,minGrowth,biomassRxn,prune,fastFVA)\n% This function identifies a subnetwork with the least number of possible exchange\n% reactions given the model and the applied constraints. It returns the resulting pruned model.\n%\n% USAGE:\n%\n%    [modelMin, modelPruned, Ex_Rxns] = generateCompactExchModel(model, minGrowth, biomassRxn, prune, fastFVA)\n%\n% INPUTS:\n%    model:         model structure\n%    minGrowth:     minimal Growth rate to be set on biomass reaction\n%    biomassRxn:    biomass reaction name (default: 'biomass_reaction2')\n%    prune:         optional: to prune the model based on exchange reactions\n%                   (default: 1)\n%    fastFVA:       optional: to use fastFVA instead of fluxvariability for\n%                   computing FVA results (default: 0)\n%    medium:        (default: {})\n%\n% OUTPUTS:\n%    modelUpdated:  same as input model but constraints on blocked reactions\n%                   are set to be 0\n%    modelPruned:   pruned model, where all blocked reactions are removed\n%                   (attention this seems to cause issues with GPRs)\n%    Ex_Rxns:       List of exchange reactions in pruned model\n% \n% .. Author: - Ines Thiele, 02/2014\n\nmedium={};\n\nif ~exist('biomassRxn','var')\n    biomassRxn = 'biomass_reaction2';\nend\nif ~exist('prune','var')\n    prune = 1;\nend\nif ~exist('fastFVA','var')\n    fastFVA = 0;\nend\n\n% find exchange reactions\ncnt=1;\nfor t=1:length(model.rxns)\n    if  strfind(model.rxns{t}, 'EX_')\n        Ex_Rxns1All(cnt,1) =model.rxns(t); %make exchange reaction list\n        cnt=cnt+1;\n    elseif  strfind(model.rxns{t}, 'Ex_')\n        Ex_Rxns1All(cnt,1) =model.rxns(t); %make exchange reaction list\n        cnt=cnt+1;\n    end\nend\n% exclude all exchanges that have been set\nEx_Rxns2Min = Ex_Rxns1All;\n\nmodel.lb(find(ismember(model.rxns,biomassRxn)))=minGrowth;% based on slowlest cell line in data\n\n\n% exclude ions\nEx_Rxns2Min(ismember(Ex_Rxns2Min,medium))=[];\n\n% identify iteratively the minimal exchange reaction network\nOptExchRxns = Ex_Rxns2Min;\nLO = length(OptExchRxns);\nOptExchRxnsLast = OptExchRxns;\nmodelMin = model;\nfirst = 1;\nwhile LO>0\n    if length(OptExchRxns)>0\n        [modelMin,AddedExchange] = findMinCardModel(modelMin,OptExchRxns);\n        if first == 0\n            [OptExchRxns] = findOptExchRxns(modelMin,OptExchRxns);\n        elseif first == 1\n           [OptExchRxns] = findOptExchRxns(modelMin,AddedExchange);\n            first =1;\n        end\n        LO = length(OptExchRxnsLast) - length(OptExchRxns)\n        OptExchRxnsLast = OptExchRxns;\n    else\n        LO = 0;\n    end\nend\n\nif prune == 1\n    % prune the model. modelMin has same dimension but all blockedRxns\n    % have bounds set to 0\n    [modelMin,modelPruned, Ex_Rxns] = pruneModel(modelMin,minGrowth,biomassRxn);\nelse\n    modelPruned = struct();\n    Ex_Rxns = '';\nend\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/metabotools/generateCompactExchModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.23765613952648723}}
{"text": "function eev(obj, eventnum)\n    % CATALOG.EEV - Browse an Catalog object one event at a time.\n    %  catalogObject.EEV() Browse through an Catalog object one event\n    %  at a time in a similar way to the Seisan program 'eev'.\n\n    if ~exist('eventnum','var')\n        eventnum = 1;\n    end\n\n    while 1,\n\n        % don't beyond start or end of this catalogObject object\n        if eventnum<1\n            eventnum=1;\n        end\n        if eventnum>numel(obj.otime)\n            eventnum=numel(obj.otime);\n        end           \n        % display line for this event\n        dstr=datestr(obj.otime(eventnum),31);\n        subclass=obj.etype{eventnum};\n        mag=obj.mag(eventnum);\n        outstr=sprintf('%s %7.2f %7.2f %7.2 %5.1f %s %s',dstr, obj.lon(eventnum), obj.lat(eventnum), obj.depth(eventnum), mag, obj.magtype{eventnum}, subclass);\n        choice=input([outstr,':  ?'],'s');           \n\n        % process choice\n        if isempty(choice)\n            eventnum=eventnum+1; % ENTER goes to next event \n\n        elseif (choice(1)=='c') % CLASSIFY\n            classify_event(datenum);\n% ^^ does this line need obj.otime?\n\n        elseif (choice(1)=='f') % FORWARD N EVENTS\n            num=1;\n            if length(choice)>1\n                num=str2num(choice(2:end));\n            end\n            eventnum=eventnum+num; \n\n        elseif (choice(1)=='b') % BACKWARD N EVENTS\n            num=1;\n            if length(choice)>1\n                num=str2num(choice(2:end));\n            end\n            eventnum=eventnum-num;\n\n        elseif (choice(1)=='t') % JUMP TO TIME\n            month=1;dd=1;hr=0;\n            if length(choice)>4\n                year=str2num(choice(2:5));\n            end\n            if length(choice)>6\n                month=str2num(choice(6:7));\n            end\n            if length(choice)>8\n                dd=str2num(choice(8:9));\n            end\n            if length(choice)>10\n                hr=str2num(choice(10:11));\n            end\n            jumptime=datenum(year,month,dd,hr,0,0);\n            eventnum = min(find(obj.otime >= jumptime));\n\n        elseif (choice(1)=='s') % SUMMARISE - SHOW S FILE or similar data \n            fprintf('\\nTime:\\t\\t%s\\n',dstr);\n            fprintf('Longitude:\\t%7.2f degrees\\n',obj.lon(eventnum));\n            fprintf('Latitude:\\t%7.2f degrees\\n',obj.lat(eventnum));\n            fprintf('Depth:\\t\\t%7.2f km\\n',obj.depth(eventnum));\n            fprintf('Magnitude:\\t%7.2f\\n',obj.mag(eventnum));\n            fprintf('Magnitude Type:\\t%s\\n',obj.magtype{eventnum});\n            fprintf('Event Type:\\t%s\\n',obj.etype{eventnum});\n            fprintf('\\n');\n\n        elseif (choice(1)=='x') % CLOSE ALL\n            close all;\n\n        elseif (choice=='q') % QUIT\n            break;\n\n        elseif (choice(1)=='h') % HELP\n            disp(' ');\n            disp('Options:');\n            disp('________');\n            disp(' ');\n            disp('b[num]            - go backward 1 event (or N events)');\n            disp('c                 - classify');\n            %disp('e                 - edit/generate S-file');\n            disp('f[num]            - go forward 1 event (or N events)');\n            disp('h                 - this help');\n            %disp('p                 - plot');\n            disp('s                 - summarise');\n            disp('tYYYY[MM[DD[HH]]] - jump to date/hour specified');\n            disp('x                 - close all figure windows');\n            disp('q                 - quit');\n            disp(' ');\n        end\n    end\nend  \n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@Catalog/eev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.237594056025101}}
{"text": "function [A_lh, A_rh]=cortical_label_adf(subject, p_val)\n% Computes the area of the different cortical labels \n% and compare them to the normal range\n% Uses p_value to detect the abnormal areas\n% Uses the lh/rh.parc.txt files\n%\n\n\n%\n% cortical_labeling_afd_txt.m\n%\n% Original Author: Laurence Wastiaux\n% CVS Revision Info:\n%    $Author: nicks $\n%    $Date: 2011/03/02 00:04:12 $\n%    $Revision: 1.3 $\n%\n% Copyright \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\n\nif (nargin<2 | nargin>2)\n    msg=sprintf('USAGE: [L, R]=cortical_label_adf(subject, p_val)');\n    disp(msg)\nend\n\nA_lh=zeros(1,84);\nA_rh=zeros(1,84);\nnamerh=[];\nnamelh=[];\n\nlabmapfile=('/space/lyon/1/fsdev/freesurfer_dev/Simple_surface_labels2002.txt');\n[label name val1 val2 val3 val4]=textread(labmapfile,'%d %s %d %d %d %d',85);\n\n\n%% a- Check if the left and right stats files exist %%\nLabelDir=strcat(subject, '/label');\ndlabel=dir(LabelDir);\nif(length(dlabel)<=2)\n    mess=sprintf('Directory %s is empty', LabelDir);\n    error(mess)\nend\nif(length(dlabel)>2)\n    if ((exist(strcat(LabelDir, '/rh.parc.txt'))==0) | (exist(strcat(LabelDir, '/lh.parc.txt'))==0))\n        mess=sprintf('Cannot find the stats files for subject %s', subject);\n        error(mess)\n    end\nend\n\n%% b- Read areas for each label & for both hemispheres using the lh/rh.parc.txt files %%\nsn=strread(subject, '%s', 'delimiter', '/');\nsubject_name=char(sn(length(sn)));\nrh_LabelFile=strcat(subject, '/label/rh.parc.txt');\nlh_LabelFile=strcat(subject, '/label/lh.parc.txt');\n\nlh_fid=fopen(lh_LabelFile);\nrh_fid=fopen(rh_LabelFile);\nif(lh_fid == -1)\n    msg=sprintf('Cannot open file %s', lh_LabelFile);\n    error(msg)\nelseif(rh_fid ==-1)\n    msg=sprintf('Cannot open file %s', rh_LabelFile);\n    error(msg)\nelse\n    while(feof(lh_fid)==0)\n        s=fgetl(lh_fid);\n        if(strfind(s,'structure name')>1)\n            s=fgetl(lh_fid);\n            lhpt=ftell(lh_fid);\n            break;\n        end\n    end\n    fseek(lh_fid, lhpt,'bof');\n    while(feof(lh_fid)==0)\n        s=fgetl(lh_fid);\n        a=strread(s,'%d',2);  %area\n        aa=strread(s,'%s',11); %name\n        llab=0;\n        for test=1:length(name)\n            if(strfind(char(name(test)),char(aa(11)))>=1)\n                llab=label(test);\n                break;\n            end  \n        end \n        if(llab==0)\n            disp(sprintf('impossible to find the label')); \n        elseif(A_lh(llab)~=0)\n            disp(sprintf('already attributed'));\n        else\n            A_lh(llab)=a(2);\n        end \n    end\n    while(feof(rh_fid)==0)\n        s=fgetl(rh_fid);\n        if(strfind(s,'structure name')>1)\n            s=fgetl(rh_fid);\n            rhpt=ftell(rh_fid);\n            break;\n        end\n    end\n    fseek(rh_fid, rhpt,'bof');\n    while(feof(rh_fid)==0)\n        s=fgetl(rh_fid);\n        a=strread(s,'%d',2);\n        aa=strread(s,'%s',11);\n        llab=0;\n        for test=1:length(name)\n            if(strfind(char(name(test)),char(aa(11)))>=1)\n                llab=label(test);\n                break;\n            end  \n        end \n        if(llab==0)\n            disp(sprintf('impossible to find the label')); \n        elseif(A_rh(llab)~=0)\n            disp(sprintf('already attributed'));\n        else\n            A_rh(llab)=a(2);\n        end \n    end    \nend\nnl=length(name)-1;\nif(length(A_lh)< nl)\n    for lleft=(length(A_lh)+1):nl\n        A_lh(lleft)=0;\n    end\nend\nif(length(A_rh)< nl)\n    for lleft=(length(A_rh)+1):nl\n        A_rh(lleft)=0;\n    end\nend\nif (sum(A_lh)==0 | sum(A_rh)==0)\n    msg=sprintf('Total area is null');\n    error(msg)\nelse\n    total_lharea=sum(A_lh);\n    total_rharea=sum(A_rh);\nend\nfor i=1:nl\n    A_lh(i)= 100 * A_lh(i) / total_lharea;\n    A_rh(i)= 100 * A_rh(i) / total_rharea;\nend\n% Compute p_values %\n\ncount=0;\nfor k =1:length(A_lh)\n    %disp(k)\n    \n    [Rpval_inf,Rpval_sup, Lpval_inf, Lpval_sup]=compute_pval(k,A_rh(k),A_lh(k));\n    if ((Lpval_inf<p_val | Lpval_sup <p_val) & (A_lh(k)~=0))\n        fprintf('%s, left hemisphere: percent area of %s (%d) = %g (pval_inf=%g, pval_sup=%g)\\n' ,subject_name, char(name(k+1)), k , A_lh(k),Lpval_inf, Lpval_sup);\n        count=1;\n    end\n    if ((Rpval_inf<p_val | Rpval_sup <p_val)& (A_rh(k)~=0))\n        fprintf('%s, right hemisphere: percent area of %s (%d) = %g (pval_inf=%g, pval_sup=%g)\\n' ,subject_name, char(name(k+1)),k, A_rh(k),Rpval_inf,Rpval_sup);\n        count=1;\n    end\n   \nend\nif(count==0)\n    fprintf('%s: subject is normal\\n', subject_name);\nend\n\n\n% subfunction compute_pval() %\nfunction [pinf_rh, psup_rh, pinf_lh, psup_lh]=compute_pval(llabel,R,L)\n%load('/space/okapi/3/data/laurence/ADF/cortical_labeling/PercentArea_labels.mat'); % loads D_lh and D_rh\n% load('/space/okapi/3/data/laurence/ADF/cortical_labeling/PercentArea_labels_parctxt.mat');\n% D_lh=D2_lh;\n% D_rh=D2_rh;\n%rh_stat_file='/space/okapi/3/data/laurence/ADF/cortical_labeling/rh.CorticalLabelingPercentArea_txt.adf';\n%lh_stat_file='/space/okapi/3/data/laurence/ADF/cortical_labeling/lh.CorticalLabelingPercentArea_txt.adf';\n%%% Get the table's directory %%%\nif(getenv('FREESURFER_HOME'))\n    fsh=getenv('FREESURFER_HOME');\n    fsafdDir=strcat(fsh, '/fsafd');\nelse\n    error(sprintf('Impossible to find FREESURFER_HOME\\n'));\nend\nrh_stat_file=strcat(fsafdDir, '/rh.CorticalLabelingPercentArea_txt.adf');\nlh_stat_file=strcat(fsafdDir, '/lh.CorticalLabelingPercentArea_txt.adf');\nfidrh=fopen(rh_stat_file);\nfidlh=fopen(lh_stat_file);\nif(fidrh==-1 | fidlh==-1)\n    mess=sprintf('Could not find %s or %s', rh_stat_file, lh_stat_file);\n    error(mess)\nend\nwhile(strfind(fgetl(fidrh), '#'))\n    pos=ftell(fidrh);\nend\nfseek(fidrh, pos, 'bof');\nD_rhtmp=fscanf(fidrh, '%g');\nnrowr=length(D_rhtmp)/84;\nD_rh=(reshape(D_rhtmp, [84, nrowr]))';\nwhile(strfind(fgetl(fidlh), '#'))\n    pos=ftell(fidlh);\nend\nfseek(fidlh, pos, 'bof');\nD_lhtmp=fscanf(fidlh, '%g');\nnrow=length(D_lhtmp)/84;\nD_lh=(reshape(D_lhtmp, [84,nrow]))';\n%distribution%\npas=0.01;\nx=0:pas:18;\n[h1] = hist(D_lh(:,llabel),x);\n[h2] = hist(D_rh(:,llabel),x);\n%[h1] = hist(D2_lh(:,llabel),x);\n%[h2] = hist(D2_rh(:,llabel),x);\np1 = h1/sum(h1);\np2 = h2/sum(h2);\nd1inf=find(x<=L);\nd2inf=find(x<=R);\nd1sup=find(x>L);\nd2sup=find(x>R);\nx1inf=x(d1inf);\nx1sup=x(d1sup);\nx2inf=x(d2inf);\nx2sup=x(d2sup);\np1inf=p1(1:length(x1inf));\np2inf=p2(1:length(x2inf));\np1sup=p1(length(x)-length(x1sup)+1:end);\np2sup=p2(length(x)-length(x2sup)+1:end);\nif( L>=0 & length(x1inf)>1 & length(x1sup)>1)\n    pinf_lh=trapz(x1inf,p1inf)/pas;\n    psup_lh=trapz(x1sup,p1sup)/pas;\nelse   % No subdivisions of the last intervals\n    pinf_lh=0;\n    psup_lh=0;\nend\nif(R>=0 & length(x2inf)>1 & length(x2sup)>1)\n    pinf_rh=trapz(x2inf,p2inf)/pas;\n    psup_rh=trapz(x2sup,p2sup)/pas;\nelse\n    pinf_rh=0;\n    psup_rh=0;\nend\n\n\n\n  \n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/cortical_labeling_afd_txt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2375221772078723}}
{"text": "%CAMSHIFT  Finds an object center, size, and orientation\n%\n%     box = cv.CamShift(probImage, window)\n%     [box,window] = cv.CamShift(probImage, window)\n%     [...] = cv.CamShift(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __probImage__ Back projection of the object histogram. See\n%   cv.calcBackProject for details.\n% * __window__ Initial search window `[x,y,w,h]`.\n%\n% ## Output\n% * __box__ Output rectangle with rotation. A scalar structure of the form:\n%   `struct('center',[x,y], 'size',[w,h], 'angle',a)`\n% * __window__ Converged CAMSHIFT window `[x,y,w,h]`\n%\n% ## Options\n% * __Criteria__ Stop criteria for the underlying cv.meanShift. Accepts a\n%   struct with 'type', 'maxCount', and 'epsilon' fields. Default\n%   `struct('type','Count+EPS', 'maxCount',100, 'epsilon',1.0)`\n%\n% The function implements the CAMSHIFT object tracking algorithm\n% [Bradski98]. First, it finds an object center using cv.meanShift and then\n% adjusts the window size and finds the optimal rotation. The function\n% returns the rotated rectangle structure that includes the object\n% position, size, and orientation. The next position of the search window\n% can be obtained with cv.RotatedRect.boundingRect.\n%\n% ## References\n% [Bradski98]:\n% > Gary R Bradski. Computer vision face tracking for use in a perceptual\n% > user interface. 1998.\n%\n% See also: cv.meanShift, cv.calcBackProject, vision.HistogramBasedTracker\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/CamShift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2375221772078723}}
{"text": "function dt6_new = dtiResliceTensorSn3d(dt6, sn3dParams, nonLinearFlag, mmPerVoxOut, xformToTensor, rotTensorMethod)\n% dt6_new = dtiResliceTensor(dt6, sn3dParams, [nonLinearFlag], [mmPerVoxOut], [xformToTensor], [rotTensorMethod])\n% \n% Applies spm-style sn3d parameters to a tensor volume in dt6 format.\n% These sn3d parameters include a linear (affine) component and a non-linear component.\n%\n% INPUT:\n%   dt6                 XxYxZx6 tensor array. If last dimension is 1 then data is\n%                       treated as scalar volume.\n%   sn3dParams          The sn3d parameter structure from SPM.\n%   nonLinearFlag       If 1 (default), non-linear component is included.\n%                       If 0, then non-linear component is not included.\n%   mmPerVoxOut         mm per voxel in resliced array.\n%   xformToTensor       Linear xform required with raw data. Not required if\n%                       data is in Analyze format (set to identity).\n%   rotTensorMethod     Method of tensor rotation. Ignored if data is scalar.\n%                           'SPM' (using spm_matrix.m) - default\n%                           'FS' (finite strain)\n%                           'PPD' (preservation fo principal direction)\n%                           '' (no rotation)\n%\n% OUTPUT:\n%   dt6_new             XxYxZx6 tensor array, or XxYxZ if data is scalar.\n%\n% REQUIRES:\n% spm99 or spm2 in the path.\n%\n% HISTORY:\n% 2004.09.13 ASH & RFD Wrote it.\n% 2005.01.12 RFD: Cleaning code, adding support for SPM2 spatial norm\n% params, and adding code to do a proper tensor correction with nonlinear\n% deformations.\n%\n% Example:\n% sn3dParams = load('dti_analyses/may021126_B0_sn3d.mat');\n% xformToB0 = computeCannonicalXformFromIfile('dti/B0.001');\n% xformToTensor = inv(xformToB0);\n% [eigVec,eigVal,mm] = dtiLoadTensor('/snarp/u1/dti/adultData/may021126/dti/Vectors.float');\n% dt6 = dtiRebuildTensor(eigVec, eigVal);\n% dt6_new = dtiResliceTensorSn3d(dt6, sn3dParams, mmPerVoxOut, xformToTensor);\n% [newVec, newVal] = dtiSplitTensor(dt6_new);\n% fa = dtiComputeFA(newVal);\n% figure; imagesc(fa(:,:,23)); axis equal; colormap gray; axis xy;\n\nif (size(dt6,4)~=6 & size(dt6,4)~=1),\n    error('Wrong input format')\nend\nif(~exist('nonLinearFlag') | isempty(nonLinearFlag))\n    nonLinearFlag = 1;\nend\nif(~exist('mmPerVoxOut') | isempty(mmPerVoxOut))\n    mmPerVoxOut = [2 2 2];\nend\nif(~exist('xformToTensor') | isempty(xformToTensor))\n    xformToTensor = eye(4);\nend\nif(~exist('rotTensorMethod') | isempty(rotTensorMethod))\n    rotTensorMethod = 'SPM';\nend\n\n% Create a bounding box for the resliced data.\n% The following is the spm default bounding box. Note that the box is\n% defined in Talairach space (units = mm).\nbb = [-78 -112 -50;\n       78  76   85];\n\nx = (bb(1,1):mmPerVoxOut(1):bb(2,1));\ny = (bb(1,2):mmPerVoxOut(2):bb(2,2));\nz = (bb(1,3):mmPerVoxOut(3):bb(2,3));\n\nif(isfield(sn3dParams, 'Dims'))\n    mm = sn3dParams.Dims(6,:)';\nelse\n    % support spm2 style sn params\n    mm = diag(sn3dParams.VF.mat(1:3,1:3));\nend\n\n[X,Y,Z] = meshgrid(x, y, z);\nclear x y z;\n\ntalCoords = [X(:) Y(:) Z(:)];\nnewSize = size(X);\nclear X Y Z;\n\nimgCoords = mrAnatGetImageCoordsFromSn(sn3dParams, talCoords, nonLinearFlag);\nif(isfield(sn3dParams,'VF'))\n    [trans,rot,mm,skew] = affineDecompose(sn3dParams.VF.mat);\n    imgCoords = mrAnatXformCoords(inv(sn3dParams.VF.mat)*xformToTensor, imgCoords')';\nelse\n    mm = sn3dParams.Dims(6,:)';\n    imgCoords = imgCoords./repmat(mm,1,size(imgCoords,2));\n    imgOrigin = sn3dParams.Dims(5,:)'/2;\n    imgCoords = imgCoords+repmat(imgOrigin,1,size(imgCoords,2));\n    % We now have image coords for the space defined by the bounding box (in\n    % Talairach space). These image coords are in the space of the original\n    % image that was used to compute the sn3d params. But that may not be the\n    % same space as the tensor image.\n    imgCoords = mrAnatXformCoords(xformToTensor, imgCoords);\n    imgCoords(1,:) = imgCoords(1,:).*mm(1);\n    imgCoords(2,:) = imgCoords(2,:).*mm(2);\n    imgCoords(3,:) = imgCoords(3,:).*mm(3);\nend\n\nfprintf('Interpolate coordinate grid...\\n')\nif (size(dt6,4)==6),\n    % convert from matlab 1-indexing to C 0-indexing\n\timgCoords = imgCoords - 1;\n    \n\t% *** HACK so that matlab can find the shared library\n\told = pwd;\n\tcd(fileparts(which('dtiTensorInterp_Pajevic')));\n\tdt6_new = dtiTensorInterp_Pajevic(dt6, [imgCoords(2,:);imgCoords(1,:);imgCoords(3,:)]', mm, 1, mm./2);\n\tcd(old);\n    dt6_new = reshape(dt6_new, [newSize, 6]);\nelse\n    dt6_new = myCinterp3(dt6, [size(dt6,1) size(dt6,2)], size(dt6,3), imgCoords', 0.0);\n    dt6_new = reshape(dt6_new, [newSize, 1]);\nend\ndt6_new = real(dt6_new);\n\n% ROTATE THE TENSORS\nfprintf('Rotate tensors...\\n')\nxformTalToImg = sn3dParams.MF * sn3dParams.Affine * inv(sn3dParams.MG);\nxformImgToTal = inv(xformTalToImg);\n\n% Apply just the rigid rotation component of the xform to the tensors\nif (size(dt6,4)==6),\n    switch rotTensorMethod,\n    case 'SPM',\n        % spm_matrix method\n\t\tp = spm_imatrix(xformImgToTal);\n\t\tp([1:3,10:12]) = 0; p(7:9) = 1;\n\t\trot = spm_matrix(p); rot = rot(1:3,1:3);\n     \tdt6_new = dtiXformTensors(dt6_new, rot);\n    case 'FS',\n        % Finite strain method\n    \trigidXform = dtiFiniteStrainDecompose(xformImgToTal);\n     \tdt6_new = dtiXformTensors(dt6_new, rigidXform);\n    case 'PPD',\n        % Preservation of principal direction method\n        dt6_new = dtiXformTensorsPPD(dt6_new, xformImgToTal);\n    end\nend\n% Apply cannonical transform\n% xformToTensor is same as inv(xformToTensor)\ndt6_new = dtiXformTensors(dt6_new, xformToTensor);\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/xform/dtiResliceTensorSn3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23752217100941891}}
{"text": "function MeshMat = in_tess_simnibs(MeshFile, FileFormat)\n% IN_TESS_SIMNIBS: Reads a 3D mesh from a gmsh4 file generated with SimNIBS\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Takfarinas Medani, Francois Tadel, 2022-2023\n\n% Read mesh\nm = mesh_load_gmsh4(MeshFile);\n\n% Get file name\n[fPath, fBase, fExt] = bst_fileparts(MeshFile);\n\n% Convert to bst format\nMeshMat = db_template('femmat');\nMeshMat.Comment  = fBase;\nMeshMat.Vertices = m.nodes(:,1:3);\nMeshMat.Elements = double(m.tetrahedra(:,1:4));\nMeshMat.Tissue   = double(m.tetrahedron_regions);\n\n% Swap tetrahedrons orientation\nMeshMat.Elements = MeshMat.Elements(:, [2 1 3 4]);\n\nswitch (FileFormat)\n    case 'SIMNIBS3'\n        % Replace the eyes with scalp (not used for now)\n        % MeshMat.Tissue(MeshMat.Tissue==6) = 5;\n\n        % Default tissue labels\n        switch length(unique(MeshMat.Tissue))\n            case 3\n                MeshMat.TissueLabels = {'brain', 'skull', 'scalp'};\n            case 4\n                MeshMat.TissueLabels = {'brain', 'csf', 'skull', 'scalp'};\n            case 5\n                MeshMat.TissueLabels = {'white', 'gray', 'csf', 'skull', 'scalp'};\n            otherwise\n                uniqueLabels = unique(MeshMat.Tissue);\n                for i = 1:length(uniqueLabels)\n                     MeshMat.TissueLabels{i} = num2str(uniqueLabels(i));\n                end\n        end\n\n    case 'SIMNIBS4'\n        % Relabel the electrodes and gel\n        MeshMat.Tissue(MeshMat.Tissue==100) = 11;\n        MeshMat.Tissue(MeshMat.Tissue==500) = 12;\n        % Default tissue labels (from file: final_tissues_LUT.txt)\n        MeshMat.TissueLabels = {'white', 'gray', 'csf', 'skull', 'scalp', 'eyes', 'compact', 'spongy', 'blood', 'muscle', 'electrode', 'gel'};\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_tess_simnibs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23749227143905968}}
{"text": "function runTrackerDets(isSeqDisplay, gtPath, datasetPath, detPath, resPath, seqPath, trackerName)\n\ncreatePath(resPath); % create the saving path of the tracking results\nseqList = load(seqPath); % find the sequence list\n\n% evaluate each sequence\nfor idSeq = 1:length(seqList)\n    if(mod(idSeq,10)==0)\n        disp(['tracking the sequence ' num2str(idSeq) '/' num2str(length(seqList)) '...']);\n    end\n    % load detections and sequence\n    seqID = seqList(idSeq);\n    seqName = sprintf('%05d',seqID);\n    sequence.dataset = dir(fullfile(datasetPath, [seqName '/*.jpg']));\n    sequence.seqPath = fullfile(datasetPath, seqName);\n    sequence.seqName = seqName;\n    img = imread(fullfile(datasetPath, seqName, sequence.dataset(1).name));\n    [sequence.imgHeight, sequence.imgWidth, ~] = size(img);\n    % nms processing\n    detections = [];\n    for i = 1:length(sequence.dataset)\n        det = load(fullfile(detPath, sprintf('img%03d%03d_loc.txt',seqID,i)));\n        if(size(det,2) ~= 3)\n            det = det';       \n        end\n        if(~isempty(det))\n            idx = det(:,3) > 0;\n            det = det(idx,:);  \n        end\n        numdet = size(det,1);        \n        if(numdet>0)\n            curdet = [repmat([i, -1], [numdet, 1]), det(:,1)-10, det(:,2)-10, repmat([20, 20], [numdet, 1]), det(:,3), repmat([-1, -1, -1], [numdet, 1])];\n            detections = cat(1, detections, curdet);\n        end\n    end\n    % show the tracking results\n    dlmwrite(fullfile(resPath, [seqName '_det.txt']), detections);\n\nend", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/eval/runTrackerDets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.23741461558021826}}
{"text": "function [V,compareFluxes] = exoMetLOOCV(model,measuredFluxes,param)\n% model: COBRA model\n%\n% measuredFluxes:   table with the fluxes obtained from exometabolomics experiments with the following variables \n%           * .rxns:    k x 1 cell array of reaction identifiers\n%           * .mean:    k x 1 double of measured mean flux\n%           * .SD:      k x 1 double standard deviation of the measured flux\n%           * .labels:  k x 1 cell array of labels to display on y axis\n%           * .Properties.Description: string describing the data, used in plot legend\n%\n%  param.alpha:              alpha in (alpha/2)(v-h)'*H*(v-h), default = 10000;\n%  param.metabolomicWeights: String indicating the type of weights to be applied to penalise the difference\n%                            between of predicted and experimentally measured fluxes by, where \n%                            'SD'   weights = 1/(1+exoMet.SD^2)\n%                            'mean' weights = 1/(1+exoMet.mean^2)\n%                            'RSD'  weights = 1/((exoMet.SD./exoMet.mean)^2)\n%  param.relaxBounds: True to relax bounds on reaction whose fluxes are to be fitted to exometabolomic data  \n%\n%\n% OUTPUTS:\n%  V:     table with the fluxes predicted by leave one out cross validation\n%           * .rxns:    n x 1 cell array of reaction identifiers, one for each in input model\n%           * .v:       n x 1 double of predicted mean flux\n%           * .lb:      n x 1 double lower bound on reaction flux\n%           * .ub:      n x 1 double upper bound on reaction flux\n%\n% LIBkey:             \n%\n% EXAMPLE:\n%\n% NOTE:\n%\n% Author(s):\nif ~exist('param','var')\n    param = struct;\nend\nif ~isfield(param,'alpha')\n    param.alpha=10000;\nend\nif ~isfield(param,'relaxBounds')\n    param.relaxBounds=1;\nend\nif ~isfield(param,'metabolomicWeights')\n    param.metabolomicWeights = 'mean';\nend\nif ~isfield(param,'relaxBounds')\n    param.relaxBounds=1;\nend\nif ~isfield(param,'approach')\n    param.approach='QEFBA';\nend\n            \n[~,nRxns] = size(model.S);\n            \nif param.relaxBounds\n    bool=ismember(model.rxns,measuredFluxes.rxns);\n    model.lb(bool) = model.lb_preconstrainRxns(bool);\n    model.ub(bool) = model.ub_preconstrainRxns(bool);\nend\n\nmodelOrig = model;\n\nif 1\n    [measuredFluxes,LIBkey,LOCAkey] = mapAontoB(measuredFluxes.rxns,model.rxns,measuredFluxes);\n    \n    %preallocate and add data from measurments\n    V = zeros(nRxns,nnz(LIBkey)+4);\n    varNames = cell(nnz(LIBkey)+4,1);\n    V(:,1) = measuredFluxes.mean;\n    varNames{1} = 'mean';\n    V(:,2) = measuredFluxes.SD;\n    varNames{2} = 'SD';\n    \n    %reduce to the measured fluxes part of the model\n    measuredFluxes = measuredFluxes(LIBkey,:);\nelse\n    nMeasuredRxns = size(measuredFluxes,1);\n    \n    %preallocate and add data from measurments\n    V = zeros(nRxns,nMeasuredRxns+4);\n    varNames = cell(nMeasuredRxns+4,1);\n    [V(:,1),LIBkey] = mapAontoB(measuredFluxes.rxns,model.rxns,measuredFluxes.mean);\n    varNames{1} = 'mean';\n    V(:,2) = mapAontoB(measuredFluxes.rxns,model.rxns,measuredFluxes.SD);\n    varNames{2} = 'SD';\nend\n\nnMeasuredRxns = size(measuredFluxes,1);\nbool = true(nMeasuredRxns,1);\n\n%loop through the measured fluxes, leaving one of them out each time\nfor i=1:nMeasuredRxns\n    bool(i)=0;\n    switch param.approach\n        case 'QEFBA'\n            if i==1\n                %compare without leaving any measured flux out\n                model = addExoMetToEFBA(modelOrig,measuredFluxes,param);\n                efbaParam.method = 'fluxes';\n                efbaParam.printLevel = 0;\n                model.osenseStr = 'min';\n                model.cf = 0;\n                model.cr = 0;\n                model.g = 2;\n                model.u0 = 0;\n                model.f = 1;\n                [QEFBAsolution, ~] = entropicFluxBalanceAnalysis(model,efbaParam);\n                V(:,3) = QEFBAsolution.v;\n                varNames{3}='QEFBA';\n            end\n            \n            model = changeRxnBounds(modelOrig, measuredFluxes.rxns(~bool), min(modelOrig.lb), 'l');\n            model = changeRxnBounds(model, measuredFluxes.rxns(~bool), max(modelOrig.ub), 'u');\n            model = addExoMetToEFBA(model,measuredFluxes(bool,:),param);\n            efbaParam.method = 'fluxes';\n            efbaParam.printLevel = 0;\n            model.osenseStr = 'min';\n            model.cf = 0;\n            model.cr = 0;\n            model.g = 2;\n            model.u0 = 0;\n            model.f = 1;\n            [solution, modelOut] = entropicFluxBalanceAnalysis(model,efbaParam);\n            V(:,i+4) = solution.v;\n            varNames{i+4}=measuredFluxes.rxns{~bool};\n            \n            %generate a flux vector amalgamated from all of the leave one out predictions\n            boolRxn = ismember(model.rxns,measuredFluxes.rxns(~bool));\n            V(boolRxn,4) = solution.v(boolRxn);\n            if i==1\n                varNames{4}='LOOCV';\n            end\n    end\n    bool(i)=1;\nend\n\nV = array2table(V,'VariableNames',varNames);\nV = addvars(V,model.rxns,modelOrig.lb,modelOrig.ub,'NewVariableNames',{'rxns','lb','ub'},'Before','mean');\n% V = V(LIBkey,:);\n\ncompareFluxes = mapAontoB('rxns','rxns',V,measuredFluxes);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/XomicsToModel/metabolomics/exoMetLOOCV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23729367625286418}}
{"text": "function [success,msg,...\n  arenatype,arenacenterx,arenacentery,...\n  arenaradius,arenawidth,arenaheight,...\n  pxpermm] = ...\n  ReadArenaParameters_Ctrax(varargin)\n\nsuccess = false;\nmsg = ''; %#ok<NASGU>\n\n[inmoviefile,...\n  arenatype,arenacenterx,arenacentery,...\n  arenaradius,arenawidth,arenaheight,...\n  pxpermm,intrxfile,annfile,inperframedir] = myparse(varargin,...\n  'inmoviefile','',...\n  'arenatype','None','arenacenterx',0,'arenacentery',0,...\n  'arenaradius',123,'arenawidth',123,'arenaheight',123,...\n  'pxpermm',1,'intrxfile','','annfile','','inperframedir','');\n\n% try to read from the trx file first\nif isempty(intrxfile),\n  msg = 'Input trxfile not yet set';\n  return;\nend\n\ntry\n  [trx,~,success1] = load_tracks(intrxfile,inmoviefile,...\n    'dosave',false,'annname',annfile,'verbose',false);\n  if ~success1,\n    msg = sprintf('Could not load tracks from trxfile %s',intrxfile);\n    return;\n  end\ncatch ME,\n  msg = sprintf('Could not load from trxfile %s: %s',intrxfile,getReport(ME));\n  return;\nend\n\nreadarenafrom = '';\nreadpxpermmfrom = '';\nreadoff = false;\nif isfield(trx,'pxpermm'),\n  newpxpermm = nanmean([trx.pxpermm]);\n  if ~isnan(newpxpermm) && newpxpermm > 0,\n    pxpermm = newpxpermm;\n    readpxpermmfrom = 'intrxfile';\n  end\n  if all(isfield(trx,{'x','x_mm','y','y_mm'})),\n    offx = nanmean(([trx.x] - [trx.x_mm])*pxpermm);\n    offy = nanmean(([trx.y] - [trx.y_mm])*pxpermm);\n    readoff = true;\n  end\nend\n\nif isfield(trx,'arena'),\n  \n  % in px\n  if all(isfield(trx(1).arena,{'x','y','r'})),\n    arenacenterx = trx(1).arena.x;\n    arenacentery = trx(1).arena.y;\n    arenaradius = trx(1).arena.r;\n    arenatype = 'Circle';\n    readarenafrom = 'intrxfile';\n  elseif ~isempty(readpxpermmfrom) && readoff && ...\n      all(isfield(trx(1).arena,{'arena_radius_mm','arena_center_mm_x','arena_center_mm_y'})),\n    arenacenterx = trx(1).arena_center_mm_x * pxpermm + offx;\n    arenacentery = trx(1).arena_center_mm_y * pxpermm + offy;\n    arenaradius = trx(1).arena_radius_mm * pxpermm;\n    readarenafrom = 'intrxfile';\n  elseif all(isfield(arena,{'tl_px','tr_px','bl_px','br_px'})),\n    tl_px = trx(1).arena.tl;\n    tr_px = trx(1).arena.tr;\n    bl_px = trx(1).arena.bl;\n    br_px = trx(1).arena.br;\n    arenawidth = mean([abs(tr_px(1)-tl_px(1)),abs(br_px(1)-bl_px(1))]);\n    arenaheight = mean([abs(tr_px(2)-br_px(2)),abs(tl_px(2)-bl_px(2))]);\n    arenacenterx = mean([tl_px(1),tr_px(1),bl_px(1),br_px(1)]);\n    arenacentery = mean([tl_px(2),tr_px(2),bl_px(2),br_px(2)]);\n    arenatype = 'Rectangle';\n    readarenafrom = 'intrxfile';\n  elseif ~isempty(readpxpermmfrom) && readoff && all(isfield(arena,{'tl','tr','bl','br'})),\n    tl_px = trx(1).arena.tl(:)'*pxpermm + [offx,offy];\n    tr_px = trx(1).arena.tr(:)'*pxpermm + [offx,offy];\n    bl_px = trx(1).arena.bl(:)'*pxpermm + [offx,offy];\n    br_px = trx(1).arena.br(:)'*pxpermm + [offx,offy];\n    arenawidth = mean([abs(tr_px(1)-tl_px(1)),abs(br_px(1)-bl_px(1))]);\n    arenaheight = mean([abs(tr_px(2)-br_px(2)),abs(tl_px(2)-bl_px(2))]);\n    arenacenterx = mean([tl_px(1),tr_px(1),bl_px(1),br_px(1)]);\n    arenacentery = mean([tl_px(2),tr_px(2),bl_px(2),br_px(2)]);\n    arenatype = 'Rectangle';\n    readarenafrom = 'intrxfile';\n  end\n  \nend\n\nif isempty(readarenafrom) && ~isempty(annfile),\n  % try to read from annfile\n  [newarenacenterx,newarenacentery,newarenaradius,dosetcirculararena] = ...\n    read_ann('arena_center_x','arena_center_y','arena_radius','do_set_circular_arena');\n  if dosetcirculararena && newarenaradius > 0 && ~any(isnan([newarenaradius,newarenacenterx,newarenacentery])),\n    arenacenterx = newarenacenterx;\n    arenacentery = newarenacentery;\n    arenaradius = newarenaradius;\n    arenatype = 'Circle';\n    readarenafrom = 'annfile';\n  end\nend\n\nsuccess = ~isempty(readarenafrom);\nif ~isempty(readarenafrom);\n  msg = sprintf('Read arena from %s, ',readarenafrom);\nelse\n  msg = sprintf('Did not read arena, ');\nend\nif ~isempty(readpxpermmfrom);\n  msg = [msg, sprintf('read pxpermm from %s.',readpxpermmfrom)];\nelse\n  msg = [msg, sprintf('Did not read pxpermm.')];\nend", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ReadArenaParameters_Ctrax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "%kkrect2pol 'Convert (real, imaginary) to (r, theta) Coordinates'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros krect2pol.pane file\n%\n% Parameters: \n% InputFile: i 'Input ', required: 'Input data object'\n% OutputFile: o 'Output', required: 'Resulting output data object'\n%\n% Example: o = kkrect2pol(i, {'i','';'o',''})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% krect2pol - Convert (real, imaginary) to (r, theta) Coordinates\n%\n%  DESCRIPTION\n% The \"Rect. to Polar\" operator converts data from the rectangular to the\n% polar coordinate system for each complex data point in the input data \n% object, \\fBInput\".  The conversion from rectangular to polar will result \n% in angles measured in radians.  The data type of \n% the output data object, \\fBOutput\", will be the same as the data type\n% of \\fBInput\".\n% \n% Executing \"Rect. to Polar\" runs the program \\fIkcmplx\\fP\n% with the -r2p flag.\n% \n%  \"Map Data\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/map_1input\n% \n%  \"Validity Mask\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/mask_1input\n% \n%  \"Location and Time Data\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input\n%\n%  \n%\n%  EXAMPLES\n%\n%  \"SEE ALSO\"\n% DATAMANIP::kcmplx, DATAMANIP::kpol2rect\n%\n%  RESTRICTIONS \n%\n%  REFERENCES \n%\n%  COPYRIGHT\n% Copyright (C) 1993 - 1997, Khoral Research, Inc. (\"KRI\")  All rights reserved.\n% \n\n\nfunction varargout = kkrect2pol(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kkrect2pol(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i', '__input';'o', '__output'};\nmaxval={0,0};\nminval={0,0};\nistoggle=[0,0];\nwas_set=istoggle * 0;\nparamtype={'InputFile','OutputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'kcmplx\"  -r2p'],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kkrect2pol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "function [f,the_regimes,endog,data,tex]=load_filters(m)\n\nn=numel(m);\n\nif n>1\n    \n    f=cell(size(m));\n    the_regimes=f;\n    endog=f;\n    data=f;\n    tex=f;\n    \n    for ii=1:n\n        \n        [f{ii},the_regimes{ii},endog{ii},data{ii},tex{ii}]=load_filters(m(ii));\n        \n    end\n    \n    return\n    \nend\n\nif isa(m,'abstvar')\n    \n    [~,~,~,f]=filter(m);\n    \n    the_regimes=generic.describe_regimes(m.markov_chain_info);\n    \n    data=m.estim_.data;\n    \n    endog=m.endogenous;\n    \n    tex=[];\n    \nelse\n    \n    f=filter(m);\n    \n    the_regimes=generic.describe_regimes(m.markov_chains);\n    \n    endog=m.observables.name;\n    \n    data=m.options.data;\n    \n    if isa(data,'ts')\n        \n        data=pages2struct(data);\n        \n    end\n    \n    tex=get(m,'tex');\n    \nend\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/Tutorials/SVAR/load_filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2372464746477365}}
{"text": "function d = simulateDataError(d)\nglobal ERROR_ODDS_CONST\nglobal logger\n\nlogger = InitLogger(logger);\n\nif nargin == 0\n    d = [];\n    return\nend\nif isempty(d)\n    return\nend\nif isempty(ERROR_ODDS_CONST)\n    return\nend\nif ERROR_ODDS_CONST == 0\n    return\nend\n\n% Set error odds in percent units\nr = round(ERROR_ODDS_CONST*rand()); \nif r==1\n    percentErrs = 7;\n    n = length(d(:,1));\n    idxs = floor(n * rand(1, uint32((n*percentErrs)/100)));\n    k = find(idxs==0);\n    idxs(k) = 1;\n    d0 = d;\n    d(idxs,1) = d(idxs,1) + d(idxs,1).*rand(length(idxs),1);\n    logger.Write('\\n**** Simulated %d errors:    d(%d,1) orig:  %0.4g,  d(%d,1) new:  %0.4g,  error size = %0.4g ****\\n\\n',  ...\n          length(idxs), idxs(1), d0(idxs(1),1), idxs(1), d(idxs(1),1), abs(d0(idxs(1),1)-d(idxs(1),1)));\nend\n\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/Utils/simulateDataError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773646}}
{"text": "function SPGR_PlotSimCurve(MTdata, MTnoise, Prot, Sim, SimCurveResults)\n\nleg = {};\nif ~isempty(MTdata)\n    semilogx(Prot.Offsets, MTdata,'kx', 'MarkerSize', 8); hold on;\n    leg{1} = 'Raw data';\nend\nif (Sim.Opt.AddNoise)\n    semilogx(Prot.Offsets, MTnoise,'bo','MarkerSize',8);\nend\n\nsemilogx(SimCurveResults.Offsets, SimCurveResults.curve, 'LineWidth', 2);\n\n\nif (Sim.Opt.AddNoise)\n   leg{2} = 'Noisy data';\nend\n\nnAngles  = size(SimCurveResults.curve,2);\nnOffsets = length(Prot.Offsets)/nAngles;\nfor i = 1:nAngles\n    if Prot.Angles(1) == Prot.Angles(2)\n        leg{end+1} = sprintf('Fitted curve (angle = %0.0f)',Prot.Angles(nOffsets*i));\n    else\n        leg{end+1} = sprintf('Fitted curve (angle = %0.0f)',Prot.Angles(i));\n    end        \nend\n\nif ~moxunit_util_platform_is_octave\n    hleg = legend(leg, 'FontSize', 12);\n    legend('boxoff')\n    set(hleg,'Location', 'best')\nelse\n    hleg = legend(leg);\n    set(hleg,'FontSize',8)\n    set(hleg,'location', 'southeast')    \nend\nxlabel('Offset (Hz)','FontWeight','bold','FontSize',10);\nylabel('|Mz|','FontWeight','bold','FontSize',10);\n\nset(gca, 'XScale', 'log');\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/SPGRfun/functions/SPGR_PlotSimCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773646}}
{"text": "function [scd] = ft_scalpcurrentdensity(cfg, data)\n\n% FT_SCALPCURRENTDENSITY computes an estimate of the SCD using the\n% second-order derivative (the surface Laplacian) of the EEG potential\n% distribution\n%\n% The relation between the surface Laplacian and the SCD is explained\n% in more detail on http://tinyurl.com/ptovowl.\n%\n% Use as\n%   [data] = ft_scalpcurrentdensity(cfg, data)\n% or\n%   [timelock] = ft_scalpcurrentdensity(cfg, timelock)\n% where the input data is obtained from FT_PREPROCESSING or from\n% FT_TIMELOCKANALYSIS. The output data has the same format as the input\n% and can be used in combination with most other FieldTrip functions\n% such as FT_FREQNALYSIS or FT_TOPOPLOTER.\n%\n% The configuration should contain\n%   cfg.method       = 'finite' for finite-difference method or\n%                      'spline' for spherical spline method\n%                      'hjorth' for Hjorth approximation method\n%   cfg.elec         = structure with electrode positions or filename, see FT_READ_SENS\n%   cfg.trials       = 'all' or a selection given as a 1xN vector (default = 'all')\n%   cfg.feedback     = string, 'no', 'text', 'textbar', 'gui' (default = 'text')\n%\n% The finite method require the following\n%   cfg.conductivity = conductivity of the skin (default = 0.33 S/m)\n%\n% The spline and finite method require the following\n%   cfg.conductivity = conductivity of the skin (default = 0.33 S/m)\n%   cfg.lambda       = regularization parameter (default = 1e-05)\n%   cfg.order        = order of the splines (default = 4)\n%   cfg.degree       = degree of legendre polynomials (default for\n%                       <=32 electrodes  = 9,\n%                       <=64 electrodes  = 14,\n%                       <=128 electrodes = 20,\n%                       else             = 32\n%\n% The hjorth method requires the following\n%   cfg.neighbours   = neighbourhood structure, see FT_PREPARE_NEIGHBOURS\n%\n% For the spline method you can specify the following\n%   cfg.badchannel      = cell-array, see FT_CHANNELSELECTION for details (default = [])\n%\n% Note that the skin conductivity, electrode dimensions and the potential\n% all have to be expressed in the same SI units, otherwise the units of\n% the SCD values are not scaled correctly. The spatial distribution still\n% will be correct.\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% The 'finite' method implements\n%   TF Oostendorp, A van Oosterom; The surface Laplacian of the potential:\n%   theory and application. IEEE Trans Biomed Eng, 43(4): 394-405, 1996.\n%   G Huiskamp; Difference formulas for the surface Laplacian on a\n%   triangulated sphere. Journal of Computational Physics, 2(95): 477-496,\n%   1991.\n%\n% The 'spline' method implements\n%   F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier.\n%   Spherical splines for scalp potential and curernt density mapping.\n%   Electroencephalogr Clin Neurophysiol, 72:184-187, 1989\n% including their corrections in\n%   F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier.\n%   Corrigenda: EEG 02274, Electroencephalography and Clinical\n%   Neurophysiology 76:565.\n%\n% The 'hjorth' method implements\n%   B. Hjort; An on-line transformation of EEG scalp potentials into\n%   orthogonal source derivation. Electroencephalography and Clinical\n%   Neurophysiology 39:526-530, 1975.\n%\n% See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQNALYSIS, FT_TOPOPLOTER.\n\n% Copyright (C) 2004-2012, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar data\nft_preamble provenance data\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden',  {'trial'}); % prevent accidental typos, see issue 1729\n\n% set the defaults\ncfg.method          = ft_getopt(cfg, 'method',       'spline');\ncfg.conductivity    = ft_getopt(cfg, 'conductivity', 0.33); % in S/m\ncfg.trials          = ft_getopt(cfg, 'trials',       'all', 1);\ncfg.feedback        = ft_getopt(cfg, 'feedback',     'text');\ncfg.badchannel      = ft_getopt(cfg, 'badchannel',     {});\n\nswitch cfg.method\n  case 'hjorth'\n    cfg = ft_checkconfig(cfg, 'required', {'neighbours'});\n  case 'spline'\n    cfg.lambda  = ft_getopt(cfg, 'lambda', 1e-5);\n    cfg.order   = ft_getopt(cfg, 'order', 4);\n    cfg.degree  = ft_getopt(cfg, 'degree', []);\n\n    if isempty(cfg.degree) % determines degree of Legendre polynomials bases on number of electrodes\n      nchan = numel(data.label);\n      if nchan<=32\n        cfg.degree = 9;\n      elseif nchan<=64\n        cfg.degree = 14;\n      elseif nchan<=128\n        cfg.degree = 20;\n      else\n        cfg.degree = 32;\n      end\n    end\n  otherwise\n    cfg = ft_checkconfig(cfg); % perform a simple consistency check\nend\n\n% store original datatype\ndtype = ft_datatype(data);\n\n% check if the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'ismeg', []);\n\n% get the electrode positions\ntmpcfg = cfg;\ntmpcfg.senstype = 'EEG';\nelec = ft_fetch_sens(tmpcfg, data);\n\n% select channels and trials of interest\ntmpcfg = keepfields(cfg, {'trials', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ntmpcfg.channel = elec.label;\ndata = ft_selectdata(tmpcfg, data);\n% restore the provenance information\n[cfg, data] = rollback_provenance(cfg, data);\n\nNtrials = numel(data.trial);\n\nif isempty(cfg.badchannel)\n  % check if the first sample of the first trial contains NaNs; if so treat it as a bad channel\n  cfg.badchannel = ft_channelselection(find(isnan(data.trial{1}(:,1))), data.label);\nend\n\n% match the order of the data channels with the channel positions, order them according to the data\n[datindx, elecindx] = match_str(data.label, elec.label);\n[goodindx, tmp]     = match_str(data.label, setdiff(data.label, cfg.badchannel, 'stable'));\n\nif ~isempty(cfg.badchannel)\n  ft_info('detected channel %s as bad\\n', cfg.badchannel{:});\n  tmpcfg         = [];\n  tmpcfg.channel = data.label(goodindx);\n  data           = ft_selectdata(tmpcfg, data);\nend\n\nallchanpos  = elec.chanpos(elecindx,:); % the position of all channels, ordered according to the data\ngoodchanpos = allchanpos(goodindx,:);   % the position of good channels\n\n% compute SCD for each trial\nif strcmp(cfg.method, 'spline')\n  fprintf('Checking spherical fit... ');\n  [c, r] = fitsphere(allchanpos);\n  d = allchanpos - repmat(c, size(allchanpos,1), 1);\n  d = sqrt(sum(d.^2, 2));\n  d = mean(abs(d) / r);\n  if abs(d-1) > 0.1\n    ft_warning('bad spherical fit (residual: %.2f%%). The interpolation will be inaccurate.', 100*(d-1));\n  elseif abs(d-1) < 0.01\n    fprintf('perfect spherical fit (residual: %.1f%%)\\n', 100*(d-1));\n  else\n    fprintf('good spherical fit (residual: %.1f%%)\\n', 100*(d-1));\n  end\n  % Builds the spatial filter only once.\n  fprintf('Calculating the filter to build the SCD.\\n');\n  [WVo, WLo] = sphsplint(goodchanpos, allchanpos, cfg.order, cfg.degree, cfg.lambda);\n  % Creates a montage to apply the spatial filter.\n  montage.tra      = WLo;\n  montage.labelold = elec.label(elecindx(goodindx));\n  montage.labelnew = elec.label(elecindx);\n  % Applies the montage to both the data and electrode definition\n  scd  = ft_apply_montage(data, montage);\n  elec = ft_apply_montage(elec, montage);\n\nelseif strcmp(cfg.method, 'finite')\n  if ~isempty(cfg.badchannel)\n    ft_error('the method \"%s\" does not support the specification of bad channels', cfg.method);\n  end\n  % the finite difference approach requires a triangulation\n  prj = elproj(allchanpos);\n  tri = delaunay(prj(:,1), prj(:,2));\n  % the new electrode montage only needs to be computed once for all trials\n  montage.tra = lapcal(allchanpos, tri);\n  montage.labelold = data.label;\n  montage.labelnew = data.label;\n  % apply the montage to the data, also update the electrode definition\n  scd  = ft_apply_montage(data, montage);\n  elec = ft_apply_montage(elec, montage);\n\nelseif strcmp(cfg.method, 'hjorth')\n  if ~isempty(cfg.badchannel)\n    ft_error('the method \"%s\" does not support the specification of bad channels', cfg.method);\n  end\n  % convert the neighbourhood structure into a montage\n  labelnew = {};\n  labelold = {};\n  for i=1:length(cfg.neighbours)\n    labelnew = cat(2, labelnew, cfg.neighbours(i).label);\n    labelold = cat(2, labelold, cfg.neighbours(i).neighblabel(:)');\n  end\n  labelold = cat(2, labelnew, labelold);\n  labelold = unique(labelold);\n  tra = zeros(length(labelnew), length(labelold));\n  for i=1:length(cfg.neighbours)\n    thischan   = match_str(labelold, cfg.neighbours(i).label);\n    thisneighb = match_str(labelold, cfg.neighbours(i).neighblabel);\n    tra(i, thischan) = 1;\n    tra(i, thisneighb) = -1/length(thisneighb);\n  end\n  % combine it in a montage\n  montage.tra = tra;\n  montage.labelold = labelold;\n  montage.labelnew = labelnew;\n  % apply the montage to the data, also update the electrode definition\n  scd  = ft_apply_montage(data, montage);\n  elec = ft_apply_montage(elec, montage);\n\nelse\n  ft_error('unknown method \"%s\"', cfg.method);\nend\n\nif strcmp(cfg.method, 'spline') || strcmp(cfg.method, 'finite')\n  % correct the units\n  ft_warning('trying to correct the units, assuming uV and mm');\n  for trlop=1:Ntrials\n    % The surface laplacian is proportional to potential divided by squared distance which means that, if\n    % - input potential is in uV, which is 10^6 too large\n    % - units of electrode positions are in mm, which is 10^3 too large\n    % these two cancel out against each other. Hence the computed laplacian\n    % is in SI units (MKS).\n    scd.trial{trlop} = cfg.conductivity * -1 * scd.trial{trlop};\n  end\n  fprintf('output surface laplacian is in V/m^2\\n');\nelse\n  fprintf('output Hjorth filtered potential is in uV\\n');\nend\n\n% Adds the electrode definition to the data.\nscd.elec = elec;\n\n% convert back to input type if necessary\nswitch dtype\n  case 'timelock'\n    scd = ft_checkdata(scd, 'datatype', 'timelock');\n  otherwise\n    % keep the output as it is\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous data\n\n% rename the output variable to accomodate the savevar postamble\ndata = scd;\n\nft_postamble provenance data\nft_postamble history    data\nft_postamble savevar    data\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_scalpcurrentdensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23699021745494012}}
{"text": "%cropRectanglesMex crops multiple bounding boxes from the initial image and resizes them to the standard output size.\n% The operation is performed on a GPU using NVIDIA Performance Primitives (NPP) library\n% cropRectanglesMex was created to prepare batches for training CNNs using MatConvNet (http://www.vlfeat.org/matconvnet/).\n% \n% Usage:\n% crops = cropRectanglesMex( im, boundingBoxes, outputSize);\n% \t\n% Inputs:\n% im  - the image to crop from, should be a 3 channel image (dimension order: height, width, channels) of type single. \n%        Normalization (e.g. [0,1] or [0, 255]) is not important. The image should be stored in RAM (not GPU).\n% boundingBoxes - bounding boxes to crop, double[ numBoundingBoxes x 4 ], each line corresponds to one bounding box. \n%       The bounding box format is y1, x1, y2, x2, where the origin is in the top-left corner. \n%       Pixels are indexed starting from 1 (e.g. [1 1 2 2] corresponds to the box containing the 4 top-left pixels of the image).\n%       Bounding boxes can be partially outside of the image. The default value for filling such areas is 0 in all the channels.\n% outputSize - the target size of the resized crops, double[2 x 1]. outputSize(1) - the height, outputSize(2) - the width.\n% \n% Outputs:\n% crops - the cropped and resized patches, gpuArray, single[ outputSize(1), outputSize(2), numChannels = 3, numBoundingBoxes ]\n%\n% The function can be compiled using build_cropResizeMex.m. \n% example_cropRectanglesMex.m provides the example of usage\n\n% Anton Osokin, firstname.lastname@gmail.com, March 2015\n\n", "meta": {"author": "aosokin", "repo": "cnn_head_detection", "sha": "80624e7a25c62f7b504fa6f4d830136beb66eec8", "save_path": "github-repos/MATLAB/aosokin-cnn_head_detection", "path": "github-repos/MATLAB/aosokin-cnn_head_detection/cnn_head_detection-80624e7a25c62f7b504fa6f4d830136beb66eec8/utils/cropRectanglesMex/cropRectanglesMex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23699020519434105}}
{"text": "function [im] = imgRead(iid,format)\n% function [im] = imgRead(iid,format)\n\nif nargin<2, format='color'; end\n\nim = double(imread(imgFilename(iid))) / 255;\n\nif strcmp(format,'gray'),\n  im = rgb2gray(im);\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/imgRead.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23697216163834173}}
{"text": "function [uOutput] = import_KJRelm(nFunction, sFilename)\n\n% Filter function switchyard\nif nFunction == FilterOp.getDescription\n  uOutput = 'RELM - Kagan & Jackson PDE-based catalog';\nelseif nFunction == FilterOp.importCatalog\n  % Read formated data\n  mData = textread(sFilename, '%s', 'delimiter', '\\n', 'whitespace', '');\n  % Create empty catalog\n  uOutput = zeros(length(mData), 9);\n  % Loop thru all lines of catalog and convert them\n  for i = 1:length(mData)\n    if rem(i,100) == 0 ; disp([ num2str(i) ' of ' num2str(length(mData)) ' events processed ']); end\n    try\n      uOutput(i,1) = str2num(mData{i}(33:40));  % Longitude\n      uOutput(i,2) = str2num(mData{i}(25:31));  % Latitude\n      uOutput(i,3) = str2num(mData{i}(7:10));   % Year\n      uOutput(i,4) = str2num(mData{i}(12:13));  % Month\n      uOutput(i,5) = str2num(mData{i}(15:16));  % Day\n      uOutput(i,6) = str2num(mData{i}(59:62));  % Magnitude\n      uOutput(i,7) = str2num(mData{i}(53:57));  % Depth\n      uOutput(i,8) = str2num(mData{i}(19:20));  % Hour\n      uOutput(i,9) = str2num(mData{i}(22:23));  % Minute\n      %Create decimal year\n      uOutput(i,3) = decyear([uOutput(i,3) uOutput(i,4) uOutput(i,5) uOutput(i,8) uOutput(i,9)]);\n    catch\n      msg.dbfprintf('Import: Problem in line %d of %s. Line ignored.\\n',i, sFilename);\n      uOutput(i,:)=nan;\n    end\n  end\n  l = isnan(uOutput(:,1));\n  uOutput(l,:) = [];\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/importfilters/other/import_KJRelm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23697216163834173}}
{"text": "function checkPropLevelsWarningsErrors(stateLog, celBodyData)\n%checkPropLevelsWarningsErrors Summary of this function goes here\n%   Detailed explanation goes here\n    chunkedStateLog = breakStateLogIntoSoIChunks(stateLog);\n    \n    lowFuelOxEventsBodiesWarn = zeros(0,2);\n    lowMonopropEventsBodiesWarn = zeros(0,2);\n    lowXenonEventsBodiesWarn = zeros(0,2);\n    \n    lowFuelOxEventsBodiesAlert = zeros(0,2);\n    lowMonopropEventsBodiesAlert = zeros(0,2);\n    lowXenonEventsBodiesAlert = zeros(0,2);\n    \n    minWarnThresh = 0.1;\n    minAlertThresh = 0.01;\n    \n    iniState = stateLog(1,:);\n    iniFuelOx = iniState(10);\n    iniMono = iniState(11);\n    iniXenon = iniState(12);\n    \n    for(i=1:size(chunkedStateLog,1)) %#ok<*NO4LP>\n        for(j=1:size(chunkedStateLog,2))\n            subLog = chunkedStateLog{i,j};\n            \n            if(isempty(subLog) || (size(subLog,1)==0 || size(subLog,2)==0))\n                continue;\n            end\n            \n            state = subLog(end,:);\n            \n            bodyID = state(8);\n            %bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);\n            eventNum = state(13);\n            \n            fuelOx = state(10);\n            monoprop = state(11);\n            xenon = state(12);\n            \n            if(fuelOx / iniFuelOx <= minWarnThresh && fuelOx / iniFuelOx > minAlertThresh)\n                lowFuelOxEventsBodiesWarn(end+1,:) = [eventNum, bodyID];\n            elseif(fuelOx / iniFuelOx < minAlertThresh)\n                lowFuelOxEventsBodiesAlert(end+1,:) = [eventNum, bodyID];\n            end\n            \n            if(monoprop / iniMono <= minWarnThresh && monoprop / iniMono > minAlertThresh)\n                lowMonopropEventsBodiesWarn(end+1,:) = [eventNum, bodyID];\n            elseif(monoprop / iniMono < minAlertThresh)\n                lowMonopropEventsBodiesAlert(end+1,:) = [eventNum, bodyID];\n            end\n            \n            if(xenon / iniXenon <= minWarnThresh && xenon / iniXenon > minAlertThresh)\n                lowXenonEventsBodiesWarn(end+1,:) = [eventNum, bodyID];\n            elseif(xenon / iniXenon < minAlertThresh)\n                lowXenonEventsBodiesAlert(end+1,:) = [eventNum, bodyID];\n            end\n        end\n    end\n\n    if(~isempty(lowFuelOxEventsBodiesAlert))\n        eventNum = lowFuelOxEventsBodiesAlert(1,1);\n        bodyID = lowFuelOxEventsBodiesAlert(1,2);\n        addToExecutionErrors(['Low Fuel/Ox Alert (Events: ', makeEventsStr(lowFuelOxEventsBodiesAlert), ')'], -1, -1, celBodyData);\n    end\n    \n    if(~isempty(lowFuelOxEventsBodiesWarn))\n        eventNum = lowFuelOxEventsBodiesWarn(1,1);\n        bodyID = lowFuelOxEventsBodiesWarn(1,2);\n        C = setdiff(lowFuelOxEventsBodiesWarn,lowFuelOxEventsBodiesAlert,'rows');\n        addToExecutionWarnings(['Low Fuel/Ox Warning (Events: ', makeEventsStr(C), ')'], -1, -1, celBodyData);\n    end\n    \n    if(~isempty(lowMonopropEventsBodiesAlert))\n        eventNum = lowMonopropEventsBodiesAlert(1,1);\n        bodyID = lowMonopropEventsBodiesAlert(1,2);\n        addToExecutionErrors(['Low Monoprop Alert (Events: ', makeEventsStr(lowMonopropEventsBodiesAlert), ')'], -1, -1, celBodyData);\n    end\n    \n    if(~isempty(lowMonopropEventsBodiesWarn))\n        eventNum = lowMonopropEventsBodiesWarn(1,1);\n        bodyID = lowMonopropEventsBodiesWarn(1,2);\n        C = setdiff(lowMonopropEventsBodiesWarn,lowMonopropEventsBodiesAlert,'rows');\n        addToExecutionWarnings(['Low Monoprop Warning (Events: ', makeEventsStr(C), ')'], -1, -1, celBodyData);\n    end\n    \n    if(~isempty(lowXenonEventsBodiesAlert))\n        eventNum = lowXenonEventsBodiesAlert(1,1);\n        bodyID = lowXenonEventsBodiesAlert(1,2);\n        addToExecutionErrors(['Low Xenon Alert (Events: ', makeEventsStr(lowXenonEventsBodiesAlert), ')'], -1, -1, celBodyData);\n    end\n    \n    if(~isempty(lowXenonEventsBodiesWarn))\n        eventNum = lowXenonEventsBodiesWarn(1,1);\n        bodyID = lowXenonEventsBodiesWarn(1,2);\n        C = setdiff(lowXenonEventsBodiesWarn,lowXenonEventsBodiesAlert,'rows');\n        addToExecutionWarnings(['Low Xenon Warning (Events: ', makeEventsStr(C), ')'], -1, -1, celBodyData);\n    end\nend\n\nfunction str = makeEventsStr(eventsBodies)\n    eventNums = unique(eventsBodies(:,1));\n    str = '';\n    for(i=1:length(eventNums))\n        if(i==length(eventNums))\n            endChar = '';\n        else\n            endChar = ', ';\n        end\n        \n        str = [str, num2str(eventNums(i)),endChar];\n    end\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/error_handling/postProcessedErrorsWarnings/checkPropLevelsWarningsErrors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23694470687472424}}
{"text": "%  Matlab (MatConvNet) implementation of our paper \n%  DFM: A Performance Baseline for Deep Feature Matching \n%  at CVPR 2021 Image Matching Workshop.\n% \n%  See details at https://github.com/ufukefe/DFM\n%\n% @authors: ufukefe, kutalmisince \n% Created on March 23, 2021\n% @Middle East Technical University, Center for Image Analysis\n%  Last Edited on July 1, 2021\n\nfunction [pointsA, pointsB] = DFM_VGG_stage1(imgA, imgB, model, ratios)\n    \n    resize_coeff_A = 1;\n    resize_coeff_B = 1;\n    % Check the image size\n    if size(imgA,1)>1600 || size(imgA,2)>1600\n        resize_coeff_A = 1600/max(size(imgA,1),size(imgA,2));\n        imgA = imresize(imgA,resize_coeff_A);\n    end\n    \n    if size(imgB,1)>1600 || size(imgB,2)>1600\n        resize_coeff_B = 1600/max(size(imgB,1),size(imgB,2));\n        imgB = imresize(imgB,resize_coeff_B);\n    end\n    \n    size_org_A = size(imgA);\n    size_org_B = size(imgB);\n    \n    % Normalize Images\n    imgA = single(imgA);\n    imgA = bsxfun(@minus, imgA, model.meta.normalization.averageImage);\n\n    imgB = single(imgB);\n    imgB = bsxfun(@minus, imgB, model.meta.normalization.averageImage);\n    \n    % zero padding for vgg (canvas should be a multiple of 16)\n    imgA = ZeroPadding4VGG(imgA);\n    imgB = ZeroPadding4VGG(imgB);\n    \n    % Assign layers to be used\n    layers_to_use_A = {'conv5_2';'conv4_2';'conv3_2';'conv2_2';'conv1_2'};\n    layers_to_use_B = {'conv5_2';'conv4_2';'conv3_2';'conv2_2';'conv1_2'};\n    model = ArrangeNetwork(model,layers_to_use_A);\n    \n    % Assign ratio tests for layers\n    ratios_s1 = ratios(5:-1:1);\n    \n    % get activations\n    activationsA = GetActivations(imgA, model, layers_to_use_A);\n    activationsB = GetActivations(imgB, model, layers_to_use_B);\n\n    % initiate matches\n    [pointsA, pointsB] = DenseFeatureMatching(activationsA{1,2}, activationsB{1,2},ratios_s1(1));  \n    [pointsA, pointsB] = insideImage(pointsA,pointsB,size_org_A,size_org_B,16);\n    \n    for k = 2:5\n        [pointsA, pointsB] = RefinePoints(pointsA, pointsB, activationsA{k,2}, activationsB{k,2}, ratios_s1(k));\n    end\n    \n    % Reject matches at the side of the images\n    [pointsA,pointsB] = rejectSideMatches(pointsA,pointsB,size_org_A,size_org_B,16);    \n    \n    if resize_coeff_A ~= 1\n       pointsA = (1/resize_coeff_A)*(pointsA-0.5)+0.5;\n    end\n    \n    if resize_coeff_B ~= 1\n       pointsB = (1/resize_coeff_B)*(pointsB-0.5)+0.5;\n    end\n    \nend\n", "meta": {"author": "ufukefe", "repo": "DFM", "sha": "1e8dd5425c734df7c39ac4c6bd229b058d3ace22", "save_path": "github-repos/MATLAB/ufukefe-DFM", "path": "github-repos/MATLAB/ufukefe-DFM/DFM-1e8dd5425c734df7c39ac4c6bd229b058d3ace22/matlab/DFM_VGG_stage1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23684229839681967}}
{"text": "function plotTree(nodes, cats, subTree, figLabelHierarchy)\n% plotTree(nodes, cats, subTree, figLabelHierarchy)\n%\n% Plot a tree using the results of the CocoStuffClasses.getClassHierarchyX() functions.\n%\n% subTree: (optional) +-1 for left/right sub tree, 0 for the entire tree\n% figLabelHierarchy: (optional) handle to a figure\n%\n% Copyright by Holger Caesar, 2017\n\n% By default we plot the entire tree\nif ~exist('subTree', 'var')\n    subTree = 0;\nend\n\n% Create figure if necessary\nif ~exist('figLabelHierarchy', 'var')\n    figLabelHierarchy = figure();\nend\n\n% Check that tree is binary at the top node\nfirstChildren = find(nodes == 1);\nassert(numel(firstChildren) == 2);\n\n% Get only relevant nodes and cats\nif subTree ~= 0\n    % Find descendents of the specified startTreeInd node\n    sel = false(size(nodes));\n    if subTree == -1\n        sel(firstChildren(1)) = true;\n    elseif subTree == 1\n        sel(firstChildren(2)) = true;\n    end\n    while true\n        oldSel = sel;\n        sel = sel | ismember(nodes, find(sel));\n        if isequal(sel, oldSel)\n            break;\n        end\n    end\n    nodes = nodes(sel);\n    cats = cats(sel);\n    \n    % Remap nodes in 0:x range\n    map = false(max(nodes), 1);\n    map(unique(nodes)) = true;\n    map = cumsum(map)-1;\n    nodes = map(nodes);\nend\n\n% Plot them\nax = axes('Parent', figLabelHierarchy, 'Units', 'Norm');\naxis(ax, 'off');\ntreeplot(nodes');\nmoveLeft = 0.08;\nif subTree == -1\n    set(ax, 'Position', [0-moveLeft,   0, 0.5+moveLeft, 1]);\nelseif subTree == 1\n    set(ax, 'Position', [0.5-moveLeft, 0, 0.5+moveLeft, 1]);\nend\n[xs, ys] = treelayout(nodes);\n\n% Set appearance settings and show labels\nisLeaf = ys == min(ys);\ntextInner = text(xs(~isLeaf) + 0.01, ys(~isLeaf) - 0.025, cats(~isLeaf), 'VerticalAlignment', 'Bottom', 'HorizontalAlignment', 'right'); %#ok<NASGU>\ntextLeaf  = text(xs( isLeaf) - 0.01, ys( isLeaf) - 0.02,  cats( isLeaf), 'VerticalAlignment', 'Bottom', 'HorizontalAlignment', 'left'); %#ok<NASGU>\nset(ax, 'XTick', [], 'YTick', [], 'Units', 'Normalized');\nax.XLabel.String = '';\naxis off;\n\n% Rotate view\ncamroll(90);", "meta": {"author": "nightrome", "repo": "cocostuff10k", "sha": "5fe3850d547ae4b21d73307dd156dfc5c5c61c5c", "save_path": "github-repos/MATLAB/nightrome-cocostuff10k", "path": "github-repos/MATLAB/nightrome-cocostuff10k/cocostuff10k-5fe3850d547ae4b21d73307dd156dfc5c5c61c5c/dataset/code/utils/plotTree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23684229839681967}}
{"text": "function test_example_ica_eog\n\n% MEM 8gb\n% WALLTIME 00:30:00\n\n%\n%% Use independent component analysis (ICA) to remove EOG artifacts\n%\n%% # Description\n%\n% This script demonstrates how you can use ICA for cleaning the EOG artifacts from your MEG data. It consists of three steps:\n%\n% #  decomposition of the MEG data\n% #  identifying the components that reflect eye artifacts\n% #  removing those components and backprojecting the data\n%\n%% # Example dataset\n%\n% You can run the code below on your own data. Alternatively, try with the example MEG dataset _ArtifactMEG.ds_ (available from [ftp://ftp.fieldtriptoolbox.org/pub/fieldtrip/tutorial/ArtifactMEG.zip](ftp://ftp.fieldtriptoolbox.org/pub/fieldtrip/tutorial/ArtifactMEG.zip)). This dataset was acquired continuously with trials of 10 seconds. All figures in this example script are based on these data.\n%\n% To load this dataset into MATLAB and preprocess with FieldTrip, use:\n%\n% preprocessing of example dataset\ncfg = [];\ncfg.dataset            = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/ArtifactMEG.ds');\ncfg.trialdef.eventtype = 'trial';\ncfg = ft_definetrial(cfg);\n\ncfg.channel            = 'MEG';\ncfg.continuous         = 'yes';\ndata = ft_preprocessing(cfg);\n\n% downsample the data to speed up the next step\ncfg = [];\ncfg.resamplefs = 300;\ncfg.detrend    = 'no';\ndata = ft_resampledata(cfg, data);\n\n%% # ICA decomposition\n%\n% After reading in the preprocessed data into memory in FieldTrip format, you can continue with decomposing it in independent components.\n%\n% perform the independent component analysis (i.e., decompose the data)\ncfg        = [];\ncfg.method = 'runica'; % this is the default and uses the implementation from EEGLAB\n\ncomp = ft_componentanalysis(cfg, data);\n\n% % Note that this is a time-consuming step. The output \"comp\" structure resembles the input raw data structure, i.e. it contains a time course for each component and each trial. Furthermore, it contains the spatial mixing matrix. In principle you can continue analyzing the data on the component level by doing\n% %\n%   cfg = [];\n%   cfg = ...\n%   freq = ft_freqanalysis(cfg, comp);\n%\n% % or\n% %\n%   cfg = [];\n%   cfg = ...\n%   timelock = ft_timelockanalysis(cfg, comp);\n\n% but for this example we want to analyze the data eventually on the original channel level and only remove the components that represent the artifacts.\n%\n%% # Identify the artifacts\n%\n% plot the components for visual inspection\nfigure\ncfg = [];\ncfg.component = 1:20;       % specify the component(s) that should be plotted\ncfg.layout    = 'CTF151.lay'; % specify the layout file that should be used for plotting\ncfg.comment   = 'no';\nft_topoplotIC(cfg, comp)\n\n% Make sure to plot and inspect all components. Write down the components that contain the eye artifacts. Very important is to know that on subsequent evaluations of the component decomposition result in components that **can have a different order**. That means that component numbers that you write down do not apply to another run of the ICA decomposition on the same data.\n%\n%\n% The spatial topography of the components aids in interpreting whether a component represents activity from the cortex, or non-cortical physiological activity (muscle, eyes, heart) or even non-physiological activity (line noise and other environmental noise). If you are trained in this type of analysis, you can relatively easily spot the components that represent the eye movements: 9, 14 and 10.\n%\n% Besides the spatial topography you should inspect the time course of the components, which gives additional information on separating the cortical from the non-cortical contributions to the data.\n%\n% For further inspection of the time course of the components, use:\n%\ncfg = [];\ncfg.layout = 'CTF151.lay'; % specify the layout file that should be used for plotting\ncfg.viewmode = 'component';\nft_databrowser(cfg, comp)\n\n% You can browse through the components and the trials. The EOG artifacts can be easily identified in the time course plots, see the figure below for an example.\n%\n%\n%% # Remove the artifacts\n%\n% remove the bad components and backproject the data\ncfg = [];\ncfg.component = [9 10 14 24]; % to be removed component(s)\ndata = ft_rejectcomponent(cfg, comp, data);\n\n% Compare the data before (red trace) and after (blue trace) the EOG removal - for example trial 4, channel MLF1\n%\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_example_ica_eog20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23684229205278823}}
{"text": "function dist=mrManDist_new(nodeList,edgeList,startNode,dimDist,noval,radius)\n% function [dist,pathIndices]=mrManDist_new(nodeList,edgeList,startNode,dimdist,-1,0)\n%\n% Obsolete, I think (BW)\n%\n%% ARW 031201\n% This is a wrapper to replace mrManDist with the dijkstra routine from Stanford University\n% mrManDist seems to be broken in some way. It certainly doesn't work with small floats\n% This is the sort of thing you had to do to call mrManDist....\t\n% [nodeList, edgeList]=generateManDistNodes(mesh);\n% mesh.dist = mrManDist(nodeList,edgeList,startNode,dimdist,-1,0); \n% dimdist is a scale factor for each linear dimension\n% -1 is what's returned for a node with no connection to the start node.\n% 0 says we're not sending in a list of node distances\n% Edgelist is a 2xn list of node pairs\n% Nodelist is a list of 3d node positions.\n\n% To call dijkstra we need to make a weighted sparse connection matrix\n% With each entry being the distance between the relevent nodes\n\ndisp('mrManDist_new is Obsolete. If you think it is necessary, please rename it and fix mrManDist.')\nevalin('caller','mfilename')\n\nreturn;\n\nmesh.connectionMatrix = buildConnectionMatrix(nodeList, edgeList);\n\n% Get rid of all the extra rubbish\nmesh.uniqueVertices = nodeList(1:3,:)';\n\nD = find3DNeighbourDists(mesh,dimDist);\ndist = dijkstra(D,startNode);\ndist = sqrt(dist);\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/manifold/mrManDist_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.2367923494899381}}
{"text": "function [F,TimeVector] = in_fread_mne(sFile, ChannelMat, iEpoch, SamplesBounds, iChannels)\n% IN_READ_MNE:  Read a block of recordings from a MNE-Python object\n%\n% USAGE:  [F,TimeVector] = in_fread_mne(sFile, ChannelMat, iEpoch, SamplesBounds, iChannels)\n%         [F,TimeVector] = in_fread_mne(sFile, ChannelMat, iEpoch, SamplesBounds)            : Read all the channels\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2019\n\n% Get reference to python object\npyObj = sFile.filename;\n% List of channels\nif (nargin < 5) || isempty(iChannels)\n    picks = 'all';\nelse\n    picks = {ChannelMat.Channel(iChannels).Name};\nend\n% Times\nFileBounds = [bst_py2mat(pyObj.first_samp), bst_py2mat(pyObj.last_samp)];\nif (nargin < 4) || isempty(SamplesBounds)\n    SamplesBounds = FileBounds;\nend\n\n% Raw data\n% if ~py.isinstance(pyObj, py.sys.modules{'mne.io'}.BaseRaw) || strcmpi(class(pyObj), 'py.mne.io.fiff.raw.Raw')\nif ismethod(pyObj, 'get_data')\n    % Call reading function\n    res = pyObj.get_data(pyargs('picks', picks, 'start', int32(SamplesBounds(1) - FileBounds(1)), 'stop', int32(SamplesBounds(2) - FileBounds(1) + 1), 'return_times', true));\n    F = bst_py2mat(res{1});\n    TimeVector = bst_py2mat(res{2}) + sFile.prop.times(1);\n    \n% Epoched data\nelse\n    error('todo');\n%     % Use data already read\n%     if isfield(sFile.header, 'epochData') && ~isempty(sFile.header.epochData)\n%         F = permute(sFile.header.epochData(iEpoch,:,:), [2,3,1]);\n%         TimeVector = linspace(sFile.epochs(iEpoch).times(1), sFile.epochs(iEpoch).times(2), size(F,2));\n%     % Read data from file\n%     else\n%         [F, TimeVector] = fif_read_evoked(sFile, sfid, iEpoch);\n%     end\n%     % Specific selection of channels\n%     if ~isempty(iChannels)\n%         F = F(iChannels, :);\n%     end\n%     % Specific time selection\n%     if ~isempty(SamplesBounds)\n%         iTime = SamplesBounds - round(sFile.epochs(iEpoch).times(1) .* sFile.prop.sfreq) + 1;\n%         F = F(:, iTime(1):iTime(2));\n%         TimeVector = TimeVector(iTime(1):iTime(2));\n%     end\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_mne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.23679234496189067}}
{"text": "function [seedinfo,outstate] = ncorr_gui_seedpreview(reference,current,roi,num_region,pos_seed,radius,cutoff_diffnorm,cutoff_iteration,enabled_stepanalysis,subsettrunc,num_img,total_imgs,pos_parent)\n% This is a GUI for displaying the seeds before accepting them. Its\n% possible the seeds are not correct or do not converge, so I included this\n% utility as a check.\n%\n% Inputs -----------------------------------------------------------------%\n%   reference - ncorr_class_img; used for displaying the background\n%   image and calculations\n%   current -  ncorr_class_img(s); used for displaying the background\n%   image and calculations\n%   roi - ncorr_class_roi; ROI corresponding to the reference image\n%   num_region - integer; number corresponding to the region\n%   pos_seed - integer array; 1st column is the x-position of the seed; 2nd\n%   is the y-position. Each row corresponds to a thread in ascending order\n%   (i.e. the first row is the first thread).\n%   radius - integer; radius of subset\n%   cutoff_diffnorm - double; cutoff of norm of the difference vector\n%   cutoff_iteration - integer; cutoff for number of iterations\n%   enabled_stepanalysis - logical; if true, then process as many seeds as\n%   possible. If false, process all the seeds.\n%   subsettrunc - logical; if true, then enable subset truncation\n%   num_img - integer; number of reference image being analyzed\n%   total_imgs - integer; total number of images being analyzed\n%   pos_parent - integer array; this is the position of the parent figure\n%   which determines where to position this figure\n%\n% Outputs ----------------------------------------------------------------%\n%   seedinfo - struct; contains struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{}) \n%   which is information on the location of the seed, the deformation \n%   parameters for that seed, the region number, and the thread assigned for \n%   computation.\n%   outstate - integer; returns either out.cancelled, out.failed, or\n%   out.success.\n%\n% Note that if step analysis is enabled, outstate will return success if at\n% least one image is seeded. If no seeds are found, it will return failed.\n% However, if step analysis is disabled, outstate will return success only \n% if all images are seeded correctly, or else it will return failed.\n    \n    % Data ---------------------------------------------------------------%\n    % Initialize Outputs \n    outstate = out.cancelled;\n    seedinfo = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{}); % paramvector = [x y u v du/dx du/dy dv/dx dv/dy corrcoef]\n    % Get GUI handles\n    handles_gui = init_gui();\n    % Run c-tor\n    feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));\n    \n    % Callbacks ----------------------------------------------------------%      \n    function constructor()        \n        % Calculate seeds. ncorr_alg_seedanalysis will return failed if no\n        % images are seeded correctly in the case that step analysis is\n        % enabled. If step analysis is disabled, it will return failed if\n        % any of the seeds are processed incorrectly.\n        [seedinfo_prelim,convergence_prelim,outstate_seeds] = ncorr_alg_seedanalysis(reference, ...\n                                                                                     current, ...\n                                                                                     roi, ...\n                                                                                     num_region, ...\n                                                                                     pos_seed, ...\n                                                                                     radius, ...\n                                                                                     cutoff_diffnorm, ...\n                                                                                     cutoff_iteration, ...\n                                                                                     enabled_stepanalysis, ...\n                                                                                     subsettrunc, ...\n                                                                                     num_img, ...\n                                                                                     total_imgs);      \n        \n        if (outstate_seeds == out.success)\n            % NOTE: Seeds are ordered in seedinfo_prelim WRT to thread \n            % number when processed by ncorr_alg_seedanalysis (i.e. \n            % seedinfo_prelim(i) == thread number i), so this isnt \n            % explicitly checked when displaying subsets corresponding \n            % to different threads.\n\n            % Check to see if any seeds have a relatively high\n            % correlation coefficient and warn the user about it.\n            paramvectorcollection = vertcat(seedinfo_prelim.paramvector); % The ninth column is the correlation coefficients\n            if (any(paramvectorcollection(:,9) > 0.4))\n                h_error = errordlg('High correlation coefficient detected. One of the seed points is possibly incorrect. Proceed with caution.','Error','modal');\n                uiwait(h_error);\n            end\n\n            % Precompute cirrois\n            cirrois = struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{});\n            for i = 0:size(pos_seed,1)-1\n                cirrois(i+1) = roi.get_cirroi(pos_seed(i+1,1),pos_seed(i+1,2),radius,subsettrunc);   \n            end   \n\n            % Precompute the subsets, so they do not need to be\n            % recalculated when switching between images/threads.\n            % Initialize\n            preview_subsets_ref = zeros(cirrois(1).radius*2+1,cirrois(1).radius*2+1,length(cirrois));\n            preview_subsets_cur = zeros(cirrois(1).radius*2+1,cirrois(1).radius*2+1,length(cirrois),size(seedinfo_prelim,3));\n\n            % Interpolate\n            gs_buffer_ref = reference.get_gs();\n            for i = 0:size(seedinfo_prelim,3)-1\n                % Getting bcoefficients could be time consuming if a\n                % lot of high resolution images are being processed.\n                bcoef_buffer_cur = current(i+1).get_bcoef();\n                for j = 0:size(seedinfo_prelim,1)-1                    \n                    for k = 0:size(cirrois(j+1).region.noderange,1)-1\n                        x_ref = k+(cirrois(j+1).x-cirrois(j+1).radius);\n                        for l = 0:2:cirrois(j+1).region.noderange(k+1)-1\n                            % Transform x_ref and y_ref and then\n                            % interpolate\n                            vec_y_ref = (cirrois(j+1).region.nodelist(k+1,l+1):cirrois(j+1).region.nodelist(k+1,l+2))';\n                            vec_x_ref = repmat(x_ref,length(vec_y_ref),1);\n\n                            % Fill reference subset - only do this once\n                            if (i == 0)\n                                preview_subsets_ref(vec_y_ref-(cirrois(j+1).y-cirrois(j+1).radius)+1,k+1,j+1) = gs_buffer_ref(vec_y_ref+1,x_ref+1);\n                            end\n\n                            % Transform ref coordinates\n                            vec_x_cur = vec_x_ref + seedinfo_prelim(j+1,1,i+1).paramvector(3) + seedinfo_prelim(j+1,1,i+1).paramvector(5)*(vec_x_ref-cirrois(j+1).x) + seedinfo_prelim(j+1,1,i+1).paramvector(6)*(vec_y_ref-cirrois(j+1).y);\n                            vec_y_cur = vec_y_ref + seedinfo_prelim(j+1,1,i+1).paramvector(4) + seedinfo_prelim(j+1,1,i+1).paramvector(7)*(vec_x_ref-cirrois(j+1).x) + seedinfo_prelim(j+1,1,i+1).paramvector(8)*(vec_y_ref-cirrois(j+1).y); \n\n                            % Interpolate\n                            vec_interp_cur = ncorr_alg_interpqbs([vec_x_cur vec_y_cur],bcoef_buffer_cur,0,0,current(i+1).border_bcoef);\n\n                            % Note that any values interpolated out of \n                            % the range of the bcoefficient matrix in \n                            % ncorr_alg_interpqbs is set to NaN. \n                            % Set these NaNs to zero for display\n                            % purposes.\n                            vec_interp_cur(isnan(vec_interp_cur)) = 0;\n\n                            % Fill current subset\n                            preview_subsets_cur(vec_y_ref-cirrois(j+1).y+cirrois(j+1).radius+1,k+1,j+1,i+1) = vec_interp_cur;\n                        end\n                    end\n                end\n            end\n\n            % Set Data            \n            setappdata(handles_gui.figure,'cirrois',cirrois);\n            setappdata(handles_gui.figure,'num_cur',size(seedinfo_prelim,3)-1);\n            setappdata(handles_gui.figure,'num_thread',size(pos_seed,1)-1);\n            setappdata(handles_gui.figure,'preview_subsets_ref',preview_subsets_ref);\n            setappdata(handles_gui.figure,'preview_subsets_cur',preview_subsets_cur);\n            setappdata(handles_gui.figure,'seedinfo_prelim',seedinfo_prelim);\n            setappdata(handles_gui.figure,'convergence_prelim',convergence_prelim);\n\n            % Update\n            update_axes('set');\n\n            % Set Visible\n            set(handles_gui.figure,'Visible','on'); \n        elseif (outstate_seeds == out.failed)\n            h_error = errordlg('Seed placement failed; please replace seeds.','Error','modal');\n            uiwait(h_error);\n\n            outstate = out.failed;\n                \n            % Exit\n            close(handles_gui.figure);\n        else\n            % Analysis was cancelled - exit.\n            close(handles_gui.figure);\n        end\n    end\n    \n    function callback_edit_threadnum(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        num_thread = getappdata(handles_gui.figure,'num_thread');  \n        \n        num_thread_prelim = str2double(get(handles_gui.edit_threadnum,'string'));\n        if (ncorr_util_isintbb(num_thread_prelim,1,size(pos_seed,1),'Thread number') == out.success)    \n            num_thread = num_thread_prelim-1;\n        end      \n        \n        % Set data\n        setappdata(handles_gui.figure,'num_thread',num_thread);\n        \n        % Update\n        update_axes('set');\n    end\n\n    function callback_edit_imgnum(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        num_cur = getappdata(handles_gui.figure,'num_cur');  \n        seedinfo_prelim = getappdata(handles_gui.figure,'seedinfo_prelim');\n        \n        num_cur_prelim = str2double(get(handles_gui.edit_imgnum,'string')); \n        if (ncorr_util_isintbb(num_cur_prelim,1,size(seedinfo_prelim,3),'Current image number') == out.success)    \n            num_cur = num_cur_prelim-1;\n        end     \n        \n        % Set data\n        setappdata(handles_gui.figure,'num_cur',num_cur);\n        \n        % Update\n        update_axes('set');\n    end\n\n    function callback_button_finish(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        seedinfo_prelim = getappdata(handles_gui.figure,'seedinfo_prelim');\n        \n        % Set output\n        for i = 0:size(seedinfo_prelim,3)-1\n            for j = 0:size(seedinfo_prelim,1)-1\n                seedinfo(j+1,1,i+1) = seedinfo_prelim(j+1,1,i+1);\n            end\n        end\n        outstate = out.success;              \n        \n        % Exit        \n        close(handles_gui.figure);\n    end\n\n    function callback_button_cancel(hObject,eventdata) %#ok<INUSD>\n        close(handles_gui.figure);\n    end  \n\n    function callback_button_left_thread(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        num_thread = getappdata(handles_gui.figure,'num_thread');\n        \n        % Check for overshoot\n        if (num_thread > 0) \n            num_thread = num_thread-1;\n        end    \n        \n        % Set data\n        setappdata(handles_gui.figure,'num_thread',num_thread); \n            \n        % Update\n        update_axes('set');\n    end\n\n    function callback_button_right_thread(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        num_thread = getappdata(handles_gui.figure,'num_thread');  \n        \n        % Check for overshoot\n        if (num_thread < size(pos_seed,1)-1)            \n            num_thread = num_thread+1;\n        end      \n        \n        % Set data\n        setappdata(handles_gui.figure,'num_thread',num_thread);\n        \n        % Update\n        update_axes('set');\n    end\n\n    function callback_button_left_cur(hObject,eventdata) %#ok<INUSD>\n        % Get data        \n        num_cur = getappdata(handles_gui.figure,'num_cur');\n        \n        % Check for overshoot\n        if (num_cur > 0)\n            num_cur = num_cur-1;\n        end    \n                        \n        % Set data\n        setappdata(handles_gui.figure,'num_cur',num_cur); \n            \n        % Update\n        update_axes('set');\n    end\n\n    function callback_button_right_cur(hObject,eventdata) %#ok<INUSD>\n        % Get data\n        num_cur = getappdata(handles_gui.figure,'num_cur');  \n        seedinfo_prelim = getappdata(handles_gui.figure,'seedinfo_prelim');\n        \n        % Check for overshoot\n        if (num_cur < size(seedinfo_prelim,3)-1)      \n            num_cur = num_cur+1;\n        end     \n        \n        % Set data\n        setappdata(handles_gui.figure,'num_cur',num_cur);\n        \n        % Update\n        update_axes('set');\n    end\n\n    function update_axes(action)\n        % Get data\n        num_cur = getappdata(handles_gui.figure,'num_cur');\n        num_thread = getappdata(handles_gui.figure,'num_thread');\n        preview_subsets_ref = getappdata(handles_gui.figure,'preview_subsets_ref');\n        preview_subsets_cur = getappdata(handles_gui.figure,'preview_subsets_cur');\n        cirrois = getappdata(handles_gui.figure,'cirrois');\n        seedinfo_prelim = getappdata(handles_gui.figure,'seedinfo_prelim');\n        convergence_prelim = getappdata(handles_gui.figure,'convergence_prelim');\n        \n        if (strcmp(action,'set'))\n            gs_buffer_ref = reference.get_gs();\n            gs_buffer_cur = current(num_cur+1).get_gs();\n                    \n            % Paint reference subset and subset locations     \n            preview_subsetloc_ref = gs_buffer_ref;        \n            preview_subsetloc_cur = gs_buffer_cur;         \n\n            % Iterate over num_thread last so that it highlights this\n            % subset over the others\n            for i = [0:num_thread-1 num_thread+1:size(pos_seed,1)-1 num_thread]\n                for j = 0:size(cirrois(i+1).region.noderange,1)-1\n                    x_ref = j+(cirrois(i+1).x-cirrois(i+1).radius);\n                    for k = 0:2:cirrois(i+1).region.noderange(j+1)-1\n                        for l = cirrois(i+1).region.nodelist(j+1,k+1):cirrois(i+1).region.nodelist(j+1,k+2)\n                            y_ref = l;   \n\n                            % Fill subset locations\n                            if (i == num_thread)\n                                % User brighter highlight to indicate this is\n                                % the seed corresponding to the current\n                                % threads\n                                preview_subsetloc_ref(y_ref+1,x_ref+1) = gs_buffer_ref(y_ref+1,x_ref+1)+1.75*reference.max_gs;\n                            else\n                                % Do regular highlight\n                                preview_subsetloc_ref(y_ref+1,x_ref+1) = gs_buffer_ref(y_ref+1,x_ref+1)+reference.max_gs;\n                            end\n\n                            % defvector_init(1) = u \n                            % defvector_init(2) = v \n                            % defvector_init(3) = du_dx \n                            % defvector_init(4) = du_dy \n                            % defvector_init(5) = dv_dx \n                            % defvector_init(6) = dv_dy\n                            % y_cur = y_ref + v + dv/dx*deltax + dv/dy*deltay  \n                            % x_cur = x_ref + u + du/dx*deltax + du/dy*deltay\n\n                            x_cur = x_ref + seedinfo_prelim(i+1,1,num_cur+1).paramvector(3) + seedinfo_prelim(i+1,1,num_cur+1).paramvector(5)*(x_ref-cirrois(i+1).x) + seedinfo_prelim(i+1,1,num_cur+1).paramvector(6)*(y_ref-cirrois(i+1).y);\n                            y_cur = y_ref + seedinfo_prelim(i+1,1,num_cur+1).paramvector(4) + seedinfo_prelim(i+1,1,num_cur+1).paramvector(7)*(x_ref-cirrois(i+1).x) + seedinfo_prelim(i+1,1,num_cur+1).paramvector(8)*(y_ref-cirrois(i+1).y); \n\n                            % x_cur and y_cur could be out of bounds, check\n                            % before using them\n                            if (floor(x_cur) >= 0 && floor(y_cur) >= 0 && ceil(x_cur) < size(gs_buffer_cur,2) && ceil(y_cur) < size(gs_buffer_cur,1))\n                                % Fill subset locations. This is a crude\n                                % approximation of the current subset. Use both\n                                % floor and ceil of transformed locations to \n                                % highlight the area of the current subset.\n                                if (i == num_thread)\n                                    % User brighter highlight to indicate this is\n                                    % the seed corresponding to the thread of\n                                    % interest\n                                    preview_subsetloc_cur(floor(y_cur)+1,floor(x_cur)+1) = gs_buffer_cur(floor(y_cur)+1,floor(x_cur)+1)+1.75*current(num_cur+1).max_gs;  \n                                    preview_subsetloc_cur(ceil(y_cur)+1,ceil(x_cur)+1) = gs_buffer_cur(ceil(y_cur)+1,ceil(x_cur)+1)+1.75*current(num_cur+1).max_gs; \n                                else\n                                    % Do regular highlight\n                                    preview_subsetloc_cur(floor(y_cur)+1,floor(x_cur)+1) = gs_buffer_cur(floor(y_cur)+1,floor(x_cur)+1)+current(num_cur+1).max_gs;  \n                                    preview_subsetloc_cur(ceil(y_cur)+1,ceil(x_cur)+1) = gs_buffer_cur(ceil(y_cur)+1,ceil(x_cur)+1)+current(num_cur+1).max_gs; \n                                end\n                            end\n                        end\n                    end\n                end\n            end\n\n            % Set Images\n            imshow(preview_subsets_ref(:,:,num_thread+1),[reference.min_gs reference.max_gs],'Parent',handles_gui.axes_refsubset);\n            set(handles_gui.axes_refsubset,'Visible','off');\n            imshow(preview_subsetloc_ref,[reference.min_gs 2*reference.max_gs],'Parent',handles_gui.axes_refsubsetloc);\n            set(handles_gui.axes_refsubsetloc,'Visible','off');\n\n            imshow(preview_subsets_cur(:,:,num_thread+1,num_cur+1),[current(num_cur+1).min_gs current(num_cur+1).max_gs],'Parent',handles_gui.axes_cursubset);\n            set(handles_gui.axes_cursubset,'Visible','off');\n            imshow(preview_subsetloc_cur,[current(num_cur+1).min_gs 2*current(num_cur+1).max_gs],'Parent',handles_gui.axes_cursubsetloc);\n            set(handles_gui.axes_cursubsetloc,'Visible','off');\n\n            % Set Texts\n            if (convergence_prelim(num_thread+1,1,num_cur+1).num_iterations < cutoff_iteration)\n                set(handles_gui.text_num_iterations_num,'String',num2str(convergence_prelim(num_thread+1,1,num_cur+1).num_iterations,'%6.0f'),'ForegroundColor', 'k');  \n            else\n                set(handles_gui.text_num_iterations_num,'String',[num2str(convergence_prelim(num_thread+1,1,num_cur+1).num_iterations,'%6.0f') ' (Max)' ],'ForegroundColor', 'r');  \n            end            \n            set(handles_gui.text_gradnorm_num,'String',num2str(convergence_prelim(num_thread+1,1,num_cur+1).diffnorm));\n            set(handles_gui.text_corrcoef_num,'String',num2str(seedinfo_prelim(num_thread+1,1,num_cur+1).paramvector(9)));\n            set(handles_gui.text_thread,'String', ['Thread: ' num2str(num_thread+1)]);     \n            set(handles_gui.text_cur,'String', ['Name: ' current(num_cur+1).name(1:min(end,22))]); \n            set(handles_gui.text_ref,'String', ['Name: ' reference.name(1:min(end,22))]); \n            \n            % Set buttons\n            % Set left/right buttons for current image\n            set(handles_gui.edit_imgnum,'String',num2str(num_cur+1));\n            if (size(seedinfo_prelim,3) == 1)\n                set(handles_gui.button_right_cur,'Enable','off');\n                set(handles_gui.button_left_cur,'Enable','off');\n                set(handles_gui.edit_imgnum,'Enable','off');\n            elseif (num_cur == 0)\n                set(handles_gui.button_right_cur,'Enable','on');\n                set(handles_gui.button_left_cur,'Enable','off');\n                set(handles_gui.edit_imgnum,'Enable','on');\n            elseif (num_cur == size(seedinfo_prelim,3)-1)\n                set(handles_gui.button_right_cur,'Enable','off');\n                set(handles_gui.button_left_cur,'Enable','on');\n                set(handles_gui.edit_imgnum,'Enable','on');\n            else\n                set(handles_gui.button_right_cur,'Enable','on');\n                set(handles_gui.button_left_cur,'Enable','on'); \n                set(handles_gui.edit_imgnum,'Enable','on');                                                                       \n            end\n            \n            % Set left/right buttons for thread number\n            set(handles_gui.edit_threadnum,'String',num2str(num_thread+1));\n            if (size(pos_seed,1) == 1)\n                set(handles_gui.button_right_thread,'Enable','off');\n                set(handles_gui.button_left_thread,'Enable','off');\n                set(handles_gui.edit_threadnum,'Enable','off');\n            elseif (num_thread == 0)\n                set(handles_gui.button_right_thread,'Enable','on');\n                set(handles_gui.button_left_thread,'Enable','off');\n                set(handles_gui.edit_threadnum,'Enable','on');\n            elseif (num_thread == size(pos_seed,1)-1)\n                set(handles_gui.button_right_thread,'Enable','off');\n                set(handles_gui.button_left_thread,'Enable','on');\n                set(handles_gui.edit_threadnum,'Enable','on');\n            else\n                set(handles_gui.button_right_thread,'Enable','on');\n                set(handles_gui.button_left_thread,'Enable','on');   \n                set(handles_gui.edit_threadnum,'Enable','on');                                                                     \n            end\n        end \n    end\n\n    function handles_gui = init_gui()\n    % GUI controls -------------------------------------------------------%\n        % Figure\n        handles_gui.figure = figure( ...\n            'Tag', 'figure', ...\n            'Units', 'characters', ...\n            'Position', ncorr_util_figpos(pos_parent,[56.1 167]), ...\n            'Name', 'Seed Preview', ...\n            'MenuBar', 'none', ...\n            'NumberTitle', 'off', ...\n            'Color', get(0,'DefaultUicontrolBackgroundColor'), ...\n            'handlevisibility','off', ...\n            'DockControls','off', ...\n            'WindowStyle','modal', ...\n            'Resize','off', ...\n            'Visible','off', ...\n            'IntegerHandle','off', ...\n            'Interruptible','off');\n\n        % Panels        \n        handles_gui.group_menu = uibuttongroup( ...\n            'Parent', handles_gui.figure, ...\n            'Tag', 'group_menu', ...\n            'Units', 'characters', ...\n            'Position', [2 48.7 35 6.7], ...\n            'Title', 'Menu', ...\n            'Interruptible','off');\n\n        handles_gui.group_ref = uibuttongroup( ...\n            'Parent', handles_gui.figure, ...\n            'Tag', 'group_reference', ...\n            'Units', 'characters', ...\n            'Position', [39.0 0.75 62 54.6], ...\n            'Title', 'Reference', ...\n            'Interruptible','off');\n\n        handles_gui.group_cur = uibuttongroup( ...\n            'Parent', handles_gui.figure, ...\n            'Tag', 'group_current', ...\n            'Units', 'characters', ...\n            'Position', [103 0.75 62 54.6], ...\n            'Title', 'Current', ...\n            'Interruptible','off');\n\n        % Axes\n        handles_gui.axes_refsubsetloc = axes( ...\n            'Parent', handles_gui.group_ref, ...\n            'Tag', 'axes_refsubsetloc', ...\n            'Units', 'characters', ...\n            'Visible', 'off', ...\n            'Position', [2.1 35.7 56.5 17], ...\n            'Interruptible','off');\n\n        handles_gui.axes_cursubsetloc = axes( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'axes_cursubsetloc', ...\n            'Units', 'characters', ...\n            'Visible', 'off', ...\n            'Position', [2.1 35.7 56.5 17], ...\n            'Interruptible','off');\n\n        handles_gui.axes_refsubset = axes( ...\n            'Parent', handles_gui.group_ref, ...\n            'Tag', 'axes_refsubset', ...\n            'Units', 'characters', ...\n            'Visible', 'off', ...\n            'Position', [2.1 13.1 56.5 17], ...\n            'Interruptible','off');\n\n        handles_gui.axes_cursubset = axes( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'axes_cursubset', ...\n            'Units', 'characters', ...\n            'Visible', 'off', ...\n            'Position', [2.1 13.1 56.5 17], ...\n            'Interruptible','off');\n\n        % Static Texts\n        handles_gui.text_refsubloc = uicontrol( ...\n            'Parent', handles_gui.group_ref, ...\n            'Tag', 'text_cur', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 33.6 56.5 1.2], ...\n            'String', 'Location of Reference Subset', ...\n            'Interruptible','off');\n\n        handles_gui.text_cursubloc = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_cursubloc', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 33.6 56.5 1.2], ...\n            'String', 'Approximate Location of Current Subset', ...\n            'Interruptible','off');\n\n        handles_gui.text_refsub = uicontrol( ...\n            'Parent', handles_gui.group_ref, ...\n            'Tag', 'text_refsub', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 11.0 56.5 1.2], ...\n            'String', 'Reference Subset', ...\n            'Interruptible','off');\n\n        handles_gui.text_cursub = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_cursub', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 11.0 56.5 1.2], ...\n            'String', 'Transformed Current Subset', ...\n            'Interruptible','off');\n\n        handles_gui.text_num_iterations = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_num_iterations', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 8.4 38.5 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', '# of Gauss Newton Iterations:', ...\n            'Interruptible','off');\n        \n        handles_gui.text_gradnorm = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_gradnorm', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 6.6 38.5 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', 'Norm of difference vector:', ...\n            'Interruptible','off');\n        \n        handles_gui.text_corrcoef = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_corrcoef', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 4.8 38.5 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', 'Correlation Coefficient:', ...\n            'Interruptible','off');\n        \n        handles_gui.text_num_iterations_num = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_num_iterations_num', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [41.5 8.4 13 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', '', ...\n            'Interruptible','off');\n        \n        handles_gui.text_gradnorm_num = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_gradnorm_num', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [41.5 6.6 13 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', '', ...\n            'Interruptible','off');\n        \n        handles_gui.text_corrcoef_num = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_corrcoef_num', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [41.5 4.8 13 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', '', ...\n            'Interruptible','off');       \n        \n        handles_gui.text_thread = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_thread', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 3.0 56.9 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', 'Thread:', ...\n            'Interruptible','off');   \n        \n        handles_gui.text_cur = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'text_cur', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 1.2 56.9 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', 'Name:', ...\n            'Interruptible','off');  \n        \n        handles_gui.text_ref = uicontrol( ...\n            'Parent', handles_gui.group_ref, ...\n            'Tag', 'text_ref', ...\n            'Style', 'text', ...\n            'Units', 'characters', ...\n            'Position', [2.1 1.2 56.9 1.2], ...\n            'HorizontalAlignment', 'Left', ...\n            'String', 'Name:', ...\n            'Interruptible','off');  \n        \n        % Edit\n        handles_gui.edit_threadnum = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'edit_threadnum', ...\n            'Style', 'edit', ...\n            'Units', 'characters', ...\n            'Position', [44.3 3.1 7 1.2], ...\n            'String', '', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_threadnum,handles_gui.figure), ...\n            'Enable', 'off', ...\n            'Interruptible','off');\n        \n        handles_gui.edit_imgnum = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'edit_imgnum', ...\n            'Style', 'edit', ...\n            'Units', 'characters', ...\n            'Position', [44.3 1.2 7 1.2], ...\n            'String', '', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_imgnum,handles_gui.figure), ...\n            'Enable', 'off', ...\n            'Interruptible','off');\n        \n        % Pushbuttons        \n        handles_gui.button_finish = uicontrol( ...\n            'Parent', handles_gui.group_menu, ...\n            'Tag', 'button_finish', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [2.1 3 29.7 1.7], ...\n            'String', 'Finish', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui.figure), ...\n            'Interruptible','off');\n\n        handles_gui.button_cancel = uicontrol( ...\n            'Parent', handles_gui.group_menu, ...\n            'Tag', 'button_cancel', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [2.1 1 29.7 1.7], ...\n            'String', 'Cancel', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui.figure), ...\n            'Interruptible','off');\n\n        handles_gui.button_left_thread = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'button_left_thread', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [37.3 2.9 6 1.5], ...\n            'String', '<', ...\n            'Enable', 'off', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_left_thread,handles_gui.figure), ...\n            'Interruptible','off');\n\n        handles_gui.button_right_thread = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'button_right_thread', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [52.3 2.9 6 1.5], ...\n            'String', '>', ...\n            'Enable', 'off', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_right_thread,handles_gui.figure), ...\n            'Interruptible','off');\n        \n        handles_gui.button_left_cur = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'button_left_cur', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [37.3 1.1 6 1.5], ...\n            'String', '<', ...\n            'Enable', 'off', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_left_cur,handles_gui.figure), ...\n            'Interruptible','off');\n\n        handles_gui.button_right_cur = uicontrol( ...\n            'Parent', handles_gui.group_cur, ...\n            'Tag', 'button_right_cur', ...\n            'Style', 'pushbutton', ...\n            'Units', 'characters', ...\n            'Position', [52.3 1.1 6 1.5], ...\n            'String', '>', ...\n            'Enable', 'off', ...\n            'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_right_cur,handles_gui.figure), ...\n            'Interruptible','off');\n    end\n       \n    % Pause until figure is closed ---------------------------------------%\n    waitfor(handles_gui.figure);    \nend\n", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_ext/ncorr_2D_matlab-master/ncorr_gui_seedpreview.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.23679234029676519}}
{"text": "classdef Net < handle\n    %NET  Create and manipulate comprehensive artificial neural networks\n    %\n    % This module contains:\n    %\n    % - API for new layers creation, layers are building bricks of neural\n    %   networks;\n    % - set of built-in most-useful Layers;\n    % - API to constuct and modify comprehensive neural networks from layers;\n    % - functionality for loading serialized networks models from different\n    %   frameworks.\n    %\n    % Functionality of this module is designed only for forward pass\n    % computations (i. e. network testing). A network training is in principle\n    % not supported.\n    %\n    % [Wiki](https://github.com/opencv/opencv/wiki/Deep-Learning-in-OpenCV)\n    %\n    % ## Net class\n    % Neural network is presented as directed acyclic graph (DAG), where\n    % vertices are Layer instances, and edges specify relationships between\n    % layers inputs and outputs.\n    %\n    % Each network layer has unique integer id and unique string name inside\n    % its network. LayerId can store either layer name or layer id.\n    %\n    % See also: cv.Net.Net, nnet.cnn.layer.Layer, trainNetwork,\n    %  SeriesNetwork, importCaffeNetwork, importCaffeLayers, alexnet, vgg16,\n    %  vgg19\n    %\n\n    properties (SetAccess = private)\n        % Object ID\n        id\n    end\n\n    %% Constructor/destructor\n    methods\n        function this = Net(varargin)\n            %NET  Constructor and importer of trained serialized models from different dnn-frameworks\n            %\n            %     net = cv.Net()\n            %\n            %     net = cv.Net('Caffe', prototxt)\n            %     net = cv.Net('Caffe', prototxt, caffeModel)\n            %\n            %     net = cv.Net('Tensorflow', modelmodel)\n            %     net = cv.Net('Tensorflow', model, config)\n            %\n            %     net = cv.Net('Torch', filename)\n            %     net = cv.Net('Torch', filename, isBinary)\n            %\n            %     net = cv.Net('Darknet', cfgFile)\n            %     net = cv.Net('Darknet', cfgFile, darknetModel)\n            %\n            % ## Input\n            % * __prototxt__ path to the `.prototxt` file with text\n            %   description of the network architecture.\n            % * __caffeModel__ (optional) path to the `.caffemodel` file with\n            %   learned network. Empty by default.\n            % * __model__ path to the `.pb` file with binary protobuf\n            %   description of the network architecture. Binary serialized\n            %   TensorFlow graph includes weights.\n            % * __config__ Optional path to the `.pbtxt` file that contains\n            %   text graph definition in protobuf format. Resulting net is\n            %   built by text graph using weights from a binary one. This is\n            %   more flexible than binary format and may be used to build the\n            %   network using binary format only as a weights storage. This\n            %   approach is similar to Caffe's `.prorotxt` and `.caffemodel`.\n            % * __filename__ path to the file, dumped from Torch by using\n            %   `torch.save()` function.\n            % * __isBinary__ specifies whether the network was serialized in\n            %   ascii mode or binary. default true.\n            % * __cfgFile__ path to the `.cfg` file with text description of\n            %   the network architecture.\n            % * __darknetModel__ (optional) path to the `.weights` file with\n            %   learned network.\n            %\n            % The first variant creates an empty network.\n            %\n            % The second variant reads a network model stored in\n            % [Caffe](http://caffe.berkeleyvision.org) framework's format.\n            %\n            % The third variant reads a network model stored in\n            % [TensorFlow](https://www.tensorflow.org/) framework's format.\n            %\n            % The fourth variant reads a network model stored in\n            % [Torch7](http://torch.ch) framework's format.\n            %\n            % The fifth variant reads a network model stored in\n            % [Darknet](https://pjreddie.com/darknet/) model files.\n            %\n            % The importers first create a net, add loaded layers into it, and\n            % set connections between them.\n            %\n            % ### Notes for Torch\n            %\n            % NOTE: ASCII mode of Torch serializer is more preferable, because\n            % binary mode extensively use `long` type of C language, which has\n            % various bit-length on different systems.\n            %\n            % The loading file must contain serialized\n            % [`nn.Module`](https://github.com/torch/nn/blob/master/doc/module.md)\n            % object with importing network. Try to eliminate a custom objects\n            % from serialazing data to avoid importing errors.\n            %\n            % List of supported layers (i.e. object instances derived from\n            % Torch `nn.Module` class):\n            % - `nn.Sequential`\n            % - `nn.Parallel`\n            % - `nn.Concat`\n            % - `nn.Linear`\n            % - `nn.SpatialConvolution`\n            % - `nn.SpatialMaxPooling`, `nn.SpatialAveragePooling`\n            % - `nn.ReLU`, `nn.TanH`, `nn.Sigmoid`\n            % - `nn.Reshape`\n            % - `nn.SoftMax`, `nn.LogSoftMax`\n            %\n            % Also some equivalents of these classes from cunn, cudnn, and\n            % fbcunn may be successfully imported.\n            %\n            % See also: cv.Net, cv.Net.forward\n            %\n            this.id = Net_(0, 'new', varargin{:});\n        end\n\n        function delete(this)\n            %DELETE  Destructor\n            %\n            %     net.delete()\n            %\n            % See also: cv.Net\n            %\n            if isempty(this.id), return; end\n            Net_(this.id, 'delete');\n        end\n    end\n\n    %% Net (set/get blobs and params, forward pass)\n    methods\n        function setInput(this, blob, name)\n            %SETINPUT  Sets the new value for the layer output blob\n            %\n            %     net.setInput(blob)\n            %     net.setInput(blob, name)\n            %\n            % ## Input\n            % * __blob__ new blob, constructed from an image or an array of\n            %   images.\n            % * __name__ descriptor of the updating layer output blob. See\n            %   cv.Net.connect to know format of the descriptor.\n            %\n            % NOTE: If updating blob is not empty then `blob` must have the\n            % same shape, because network reshaping is not implemented yet.\n            %\n            % The blob (4-dimensional blob, so-called batch) is constructed\n            % from image or array of images. Image is a 2-dimensional\n            % multi-channel or 3-dimensional single-channel image (or array of\n            % such images).\n            %\n            % See also: cv.Net.forward, cv.Net.blobFromImages\n            %\n            if nargin > 2\n                Net_(this.id, 'setInput', blob, name);\n            else\n                Net_(this.id, 'setInput', blob);\n            end\n        end\n\n        function setParam(this, layerId, numParam, blob)\n            %SETPARAM  Sets the new value for the learned param of the layer\n            %\n            %     net.setParam(layerId, numParam, blob)\n            %\n            % ## Input\n            % * __layerId__ name or id of the layer.\n            % * __numParam__ index of the layer parameter in the blobs array.\n            % * __blob__ the new value.\n            %\n            % NOTE: If shape of the new blob differs from the previous shape,\n            % then the following forward pass may fail.\n            %\n            % See also: cv.Net.getParam\n            %\n            Net_(this.id, 'setParam', layerId, numParam, blob);\n        end\n\n        function blob = getParam(this, layerId, numParam)\n            %GETPARAM  Returns parameter blob of the layer\n            %\n            %     blob = net.getParam(layerId)\n            %     blob = net.getParam(layerId, numParam)\n            %\n            % ## Input\n            % * __layerId__ name or id of the layer.\n            % * __numParam__ index of the layer parameter in the blobs array.\n            %   default 0.\n            %\n            % ## Output\n            % * __blob__ returned parameter blob.\n            %\n            % Parameters are the weights and biases.\n            %\n            % See also: cv.Net.setParam\n            %\n            if nargin > 2\n                blob = Net_(this.id, 'getParam', layerId, numParam);\n            else\n                blob = Net_(this.id, 'getParam', layerId);\n            end\n        end\n\n        function blob = forward(this, varargin)\n            %FORWARD  Runs forward pass\n            %\n            %     blob = net.forward()\n            %     blob = net.forward(outputName)\n            %\n            %     blobs = net.forward(outBlobNames)\n            %\n            % ## Input\n            % * __outputName__ name for layer which output is needed to get.\n            % * __outBlobNames__ names for layers which outputs are needed to\n            %   get.\n            %\n            % ## Output\n            % * __blob__ blob for first output of specified layer.\n            % * __blobs__ blobs for first outputs of specified layers\n            %   (cell array).\n            %\n            % The first form runs forward pass to compute output of layer\n            % with name `outputName`. By default (`outputName` not specified)\n            % runs forward pass for the whole network.\n            % (i.e `names = net.getLayerNames(); outputName = names(end);`).\n            % It returns blob for first output of specified layer.\n            %\n            % The second form runs forward pass to compute outputs of layers\n            % listed in `outBlobNames`. It returns blobs for first outputs of\n            % specified layers.\n            %\n            % See also: cv.Net.forwardAndRetrieve, cv.Net.Net\n            %\n            blob = Net_(this.id, 'forward', varargin{:});\n        end\n\n        function blobs = forwardAndRetrieve(this, varargin)\n            %FORWARDANDRETRIEVE  Runs forward pass\n            %\n            %     blobs = net.forwardAndRetrieve()\n            %     blobs = net.forwardAndRetrieve(outputName)\n            %\n            %     blobsArr = net.forwardAndRetrieve(outBlobNames)\n            %\n            % ## Input\n            % * __outputName__ name for layer which output is needed to get.\n            % * __outBlobNames__ names for layers which outputs are needed to\n            %   get.\n            %\n            % ## Output\n            % * __blobs__ contains all output blobs for specified layer\n            %   (cell array)\n            % * __blobsArr__ contains all output blobs for each layer\n            %   specified in `outBlobNames` (cell array of cell arrays).\n            %\n            % The first form runs forward pass to compute output of layer\n            % with name `outputName`. By default (`outputName` not specified)\n            % runs forward pass for the whole network\n            % (i.e `names = net.getLayerNames(); outputName = names(end);`).\n            % It returns all output blobs for specified layer.\n            %\n            % The second form runs forward pass to compute outputs of layers\n            % listed in `outBlobNames`. It returns all output blobs for each\n            % layer specified in `outBlobNames`.\n            %\n            % See also: cv.Net.forward, cv.Net.Net\n            %\n            blobs = Net_(this.id, 'forwardAndRetrieve', varargin{:});\n        end\n\n        function [timings, total] = getPerfProfile(this)\n            %GETPERFPROFILE  Returns overall time for inference and timings (in ticks) for layers\n            %\n            %     [timings, total] = net.getPerfProfile()\n            %\n            % ## Output\n            % * __timings__ vector for tick timings for all layers.\n            % * __total__ overall ticks for model inference.\n            %\n            % Indexes in returned vector correspond to layers ids. Some layers\n            % can be fused with others, in this case zero ticks count will be\n            % return for that skipped layers.\n            %\n            % See also: cv.Net.forward, cv.TickMeter\n            %\n            [timings, total] = Net_(this.id, 'getPerfProfile');\n        end\n    end\n\n    %% Net (network architecture)\n    methods\n        function b = empty(this)\n            %EMPTY  Returns true if there are no layers in the network.\n            %\n            %     b = net.empty()\n            %\n            % ## Output\n            % * __b__ Boolean.\n            %\n            % See also: cv.Net.Net\n            %\n            b = Net_(this.id, 'empty');\n        end\n\n        function id = addLayer(this, name, layerType, params)\n            %ADDLAYER  Adds new layer to the net\n            %\n            %     id = net.addLayer(name, layerType, params)\n            %\n            % ## Input\n            % * __name__ unique name of the adding layer.\n            % * __layerType__ typename of the adding layer (type must be\n            %   registered).\n            % * __params__ parameters which will be used to initialize the\n            %   creating layer. Scalar structure with the following fields:\n            %   * __dict__ name-value dictionary as struct, values are scalar\n            %     values (or arrays) of one of the following type: double,\n            %     integer, or string.\n            %   * __blobs__ List of learned parameters stored as blobs.\n            %   * __name__ Name of the layer instance (optional, can be used\n            %     internal purposes).\n            %   * __type__ Type name which was used for creating layer by\n            %     layer factory (optional).\n            %\n            % ## Output\n            % * __id__ unique identifier of created layer, or -1 if a failure\n            %   will happen.\n            %\n            % A LayerParams provides all data needed to initialize layer. It\n            % includes dictionary with scalar params (`params.dict` struct),\n            % blob params `params.blobs` and optional meta information\n            % `params.name` and `params.type` of layer instance.\n            %\n            % Built-in layers listed below partially reproduce functionality\n            % of corresponding Caffe and Torch7 layers. In partuclar, the\n            % following layers and Caffe importer were tested to reproduce\n            % [Caffe](http://caffe.berkeleyvision.org/tutorial/layers.html)\n            % functionality:\n            % - Convolution\n            % - Deconvolution\n            % - Pooling\n            % - InnerProduct\n            % - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal\n            % - Softmax\n            % - Reshape, Flatten, Slice, Split\n            % - LRN\n            % - MVN\n            % - Dropout (since it does nothing on forward pass)\n            %\n            % See also: cv.Net.addLayerToPrev, cv.Net.deleteLayer, cv.Net.connect\n            %\n            id = Net_(this.id, 'addLayer', name, layerType, params);\n            id = int32(id);\n        end\n\n        function id = addLayerToPrev(this, name, layerType, params)\n            %ADDLAYERTOPREV  Adds new layer and connects its first input to the first output of previously added layer\n            %\n            %     id = net.addLayerToPrev(name, layerType, params)\n            %\n            % ## Input\n            % * __name__ unique name of the adding layer.\n            % * __layerType__ typename of the adding layer (type must be\n            %   registered).\n            % * __params__ parameters which will be used to initialize the\n            %   creating layer.\n            %\n            % ## Output\n            % * __id__ unique identifier of created layer, or -1 if a failure\n            %   will happen.\n            %\n            % See also: cv.Net.addLayer, cv.Net.deleteLayer, cv.Net.connect\n            %\n            id = Net_(this.id, 'addLayerToPrev', name, layerType, params);\n            id = int32(id);\n        end\n\n        function id = getLayerId(this, name)\n            %GETLAYERID  Converts string name of the layer to the integer identifier\n            %\n            %     id = net.getLayerId(name)\n            %\n            % ## Input\n            % * __name__ string name of the layer.\n            %\n            % ## Output\n            % * __id__ id of the layer, or -1 if the layer wasn't found.\n            %\n            % See also: cv.Net.getLayer, cv.Net.getLayerNames\n            %\n            id = Net_(this.id, 'getLayerId', name);\n            id = int32(id);\n        end\n\n        function names = getLayerNames(this)\n            %GETLAYERNAMES  Get layer names\n            %\n            %     names = net.getLayerNames()\n            %\n            % ## Output\n            % * __names__ names of layers.\n            %\n            % See also: cv.Net.getLayerId, cv.Net.getLayer\n            %\n            names = Net_(this.id, 'getLayerNames');\n        end\n\n        function layer = getLayer(this, layerId)\n            %GETLAYER  Returns layer with specified id or name which the network use\n            %\n            %     layer = net.getLayer(layerId)\n            %\n            % ## Input\n            % * __layerId__ layer name or layer id.\n            %\n            % ## Output\n            % * __layer__ returned layer. Scalar structure with the following\n            %   fields:\n            %   * __blobs__ List of stored learned parameters as returned by\n            %     cv.Net.getParam.\n            %   * __name__ name of the layer instance, can be used for logging\n            %     or other internal purposes.\n            %   * __type__ Type name which was used for creating layer by\n            %     layer factory.\n            %   * __preferableTarget__ preferred target for layer forwarding\n            %     (see cv.Net.setPreferableTarget).\n            %\n            % Layers are the building blocks of networks.\n            %\n            % See also: cv.Net.getLayerId\n            %\n            layer = Net_(this.id, 'getLayer', layerId);\n        end\n\n        function layers = getLayerInputs(this, layerId)\n            %GETLAYERINPUTS  Returns input layers of specific layer\n            %\n            %     layers = net.getLayerInputs(layerId)\n            %\n            % ## Input\n            % * __layerId__ layer name or layer id.\n            %\n            % ## Output\n            % * __layers__ returned layers, struct array.\n            %\n            % See also: cv.Net.getLayerId, cv.Net.getLayer\n            %\n            layers = Net_(this.id, 'getLayerInputs', layerId);\n        end\n\n        function deleteLayer(this, layerId)\n            %DELETELAYER  Delete layer for the network\n            %\n            %     net.deleteLayer(layerId)\n            %\n            % ## Input\n            % * __layerId__ layer name or layer id.\n            %\n            % Warning: Not yet implemented.\n            %\n            % See also: cv.Net.addLayer\n            %\n            Net_(this.id, 'deleteLayer', layerId);\n        end\n\n        function connect(this, varargin)\n            %CONNECT  Connects output of the first layer to input of the second layer\n            %\n            %     net.connect(outPin, inpPin)\n            %     net.connect(outLayerId, outNum, inpLayerId, inpNum)\n            %\n            % ## Input\n            % * __outPin__ descriptor of the first layer output. See below.\n            % * __inpPin__ descriptor of the second layer input. See below.\n            %\n            % ## Input\n            % * __outLayerId__ identifier of the first layer.\n            % * __outNum__ number of the first layer output.\n            % * __inpLayerId__ identifier of the second layer.\n            % * __inpNum__ number of the second layer input.\n            %\n            % Descriptors have the following template\n            % `<layer_name>[.input_number]`:\n            % - the first part of the template `layer_name` is sting name of\n            %   the added layer. If this part is empty then the network input\n            %   pseudo layer will be used;\n            % - the second optional part of the template `input_number` is\n            %   either number of the layer input, either label one. If this\n            %   part is omitted then the first layer input will be used.\n            %\n            % See also: cv.Net.setInputsNames, cv.Net.addLayer\n            %\n            Net_(this.id, 'connect', varargin{:});\n        end\n\n        function setInputsNames(this, inputBlobNames)\n            %SETINPUTSNAMES  Sets outputs names of the network input pseudo layer\n            %\n            %     net.setInputsNames(inputBlobNames)\n            %\n            % ## Input\n            % * __inputBlobNames__ blob names.\n            %\n            % Each net always has special own the network input pseudo layer\n            % with `id=0`. This layer stores the user blobs only and don't\n            % make any computations. In fact, this layer provides the only way\n            % to pass user data into the network. As any other layer, this\n            % layer can label its outputs and this function provides an easy\n            % way to do this.\n            %\n            % See also: cv.Net.connect, cv.Net.setInput\n            %\n            Net_(this.id, 'setInputsNames', inputBlobNames);\n        end\n\n        function indices = getUnconnectedOutLayers(this)\n            %GETUNCONNECTEDOUTLAYERS  Returns indexes of layers with unconnected outputs\n            %\n            %     indices = net.getUnconnectedOutLayers()\n            %\n            % ## Output\n            % * __indices__ vector of indices.\n            %\n            % See also: cv.Net.getLayer\n            %\n            indices = Net_(this.id, 'getUnconnectedOutLayers');\n        end\n\n        function layersTypes = getLayerTypes(this)\n            %GETLAYERTYPES  Returns list of types for layer used in model\n            %\n            %     layersTypes = net.getLayerTypes()\n            %\n            % ## Output\n            % * __layersTypes__ layer types.\n            %\n            % See also: cv.Net.getLayersCount\n            %\n            layersTypes = Net_(this.id, 'getLayerTypes');\n        end\n\n        function count = getLayersCount(this, layerType)\n            %GETLAYERSCOUNT  Returns count of layers of specified type\n            %\n            %     count = net.getLayersCount(layerType)\n            %\n            % ## Input\n            % * __layerType__ type.\n            %\n            % ## Output\n            % * __count__ count of layers.\n            %\n            % See also: cv.Net.getLayerTypes\n            %\n            count = Net_(this.id, 'getLayersCount', layerType);\n        end\n\n        function enableFusion(this, fusion)\n            %ENABLEFUSION  Enables or disables layer fusion in the network\n            %\n            %     net.enableFusion(fusion)\n            %\n            % ## Input\n            % * __fusion__ true to enable the fusion, false to disable. The\n            %   fusion is enabled by default.\n            %\n            % See also: cv.Net.connect\n            %\n            Net_(this.id, 'enableFusion', fusion);\n        end\n\n        function setHalideScheduler(this, scheduler)\n            %SETHALIDESCHEDULER  Compile Halide layers\n            %\n            %     net.setHalideScheduler(scheduler)\n            %\n            % ## Input\n            % * __scheduler__ scheduler Path to YAML file with scheduling\n            %   directives.\n            %\n            % Schedule layers that support Halide backend. Then compile them\n            % for specific target. For layers that not represented in\n            % scheduling file or if no manual scheduling used at all,\n            % automatic scheduling will be applied.\n            %\n            % See also: cv.Net.setPreferableBackend\n            %\n            Net_(this.id, 'setHalideScheduler', scheduler);\n        end\n\n        function setPreferableBackend(this, backend)\n            %SETPREFERABLEBACKEND  Ask network to use specific computation backend where it supported\n            %\n            %     net.setPreferableBackend(backend)\n            %\n            % ## Input\n            % * __backend__ computation backend supported by layers, one of:\n            %   * __Default__\n            %   * __Halide__ Halide language backend.\n            %   * __InferenceEngine__ Intel's Deep Learning Inference Engine.\n            %\n            % See also: cv.Net.setPreferableTarget, cv.Net.setHalideScheduler\n            %\n            Net_(this.id, 'setPreferableBackend', backend);\n        end\n\n        function setPreferableTarget(this, target)\n            %SETPREFERABLETARGET  Ask network to make computations on specific target device\n            %\n            %     net.setPreferableTarget(target)\n            %\n            % ## Input\n            % * __target__ target device for computations, one of:\n            %   * __CPU__\n            %   * __OpenCL__\n            %\n            % See also: cv.Net.setPreferableBackend\n            %\n            Net_(this.id, 'setPreferableTarget', target);\n        end\n    end\n\n    %% Auxiliary functions\n    methods (Static)\n        function blob = readTorchBlob(filename, varargin)\n            %READTORCHBLOB  Loads blob which was serialized as torch.Tensor object of Torch7 framework\n            %\n            %     blob = cv.Net.readTorchBlob(filename)\n            %     blob = cv.Net.readTorchBlob(filename, 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __filename__ path to the blob file.\n            %\n            % ## Output\n            % * __blob__ output blob.\n            %\n            % ## Options\n            % * __IsBinary__ specifies whether blob file was serialized in\n            %   ascii mode or binary. default true.\n            %\n            % This function has the same limitations as cv.Net.Net with\n            % regards to the Torch importer.\n            %\n            % See also: cv.Net.setInput, cv.Net.blobFromImages\n            %\n            blob = Net_(0, 'readTorchBlob', filename, varargin{:});\n        end\n\n        function blob = blobFromImages(img, varargin)\n            %BLOBFROMIMAGES  Creates 4-dimensional blob from image or series of images\n            %\n            %     blob = cv.Net.blobFromImages(img)\n            %     blob = cv.Net.blobFromImages(imgs)\n            %     blob = cv.Net.blobFromImages(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __img__ input image (with 1-, 3- or 4-channels).\n            % * __imgs__ input images (all with 1-, 3- or 4-channels).\n            %\n            % ## Output\n            % * __blob__ 4-dimansional array with NCHW dimensions order.\n            %\n            % ## Options\n            % * __Size__ spatial size for output image `[w,h]`. default [0,0]\n            %   (in which case input image size is used)\n            % * __Mean__ scalar with mean values which are subtracted from\n            %   channels. Values are intended to be in\n            %   (mean-R, mean-G, mean-B) order if image has BGR ordering and\n            %   `SwapRB` is true. default [0,0,0]\n            % * __ScaleFactor__ multiplier for images values. default 1.0\n            % * __SwapRB__ flag which indicates that swap first and last\n            %   channels in 3-channel image is necessary. For instance, Caffe\n            %   models are usually trained on BGR images, while TensorFlow\n            %   models expect RGB images as input. default true\n            % * __Crop__ flag which indicates whether image will be cropped\n            %   after resize or not. default true\n            %\n            % Creates blob and optionally resizes and crops the images from\n            % center, subtracts mean values, scales values, and swaps blue and\n            % red channels.\n            %\n            % If `Crop` is true, input image is resized so one side after\n            % resize is equal to corresponding dimension in `Size` and another\n            % one is equal or larger. Then, crop from the center is performed.\n            % If `Crop` is false, direct resize without cropping and\n            % preserving aspect ratio is performed.\n            %\n            % A blob is a 4-dimensional matrix (so-called batch) with the\n            % following shape: `[num, cn, rows, cols]`.\n            %\n            % See also: cv.Net.setInput\n            %\n            blob = Net_(0, 'blobFromImages', img, varargin{:});\n        end\n\n        function imgs = imagesFromBlob(blob)\n            %IMAGESFROMBLOB  Parse a 4D blob and output the images it contains\n            %\n            %     imgs = cv.Net.imagesFromBlob(blob)\n            %\n            % ## Input\n            % * __blob__ 4-dimensional array `(images, channels, height, width)`\n            %   in floating-point precision (`single`) from which you would\n            %   like to extract the images.\n            %\n            % ## Output\n            % * __imgs__ cell-array of matrices containing the images\n            %   extracted from the blob in floating-point precision (`single`).\n            %   They are non-normalized neither mean-added. The number of\n            %   returned images equals the first dimension of the blob\n            %   (batch size). Every image has a number of channels equals to\n            %   the second dimension of the blob (depth).\n            %\n            % See also: cv.Net.blobFromImages\n            %\n            imgs = Net_(0, 'imagesFromBlob', blob);\n        end\n\n        function shrinkCaffeModel(src, dst, varargin)\n            %SHRINKCAFFEMODEL  Convert all weights of Caffe network to half precision floating point\n            %\n            %     cv.Net.shrinkCaffeModel(src, dst)\n            %     cv.Net.shrinkCaffeModel(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __src__ Path to origin model from Caffe framework contains\n            %   single precision floating point weights (usually has\n            %   `.caffemodel` extension).\n            % * __dst__ Path to destination model with updated weights.\n            %\n            % ## Options\n            % * __LayersTypes__ Set of layers types which parameters will be\n            %   converted. By default (not set), converts only Convolutional\n            %   and Fully-Connected layers' weights,\n            %   i.e `{'Convolution', 'InnerProduct'}`.\n            %\n            % Note: Shrinked model has no origin `float32` weights so it can't\n            % be used in origin Caffe framework anymore. However the structure\n            % of data is taken from NVidia's\n            % <https://github.com/NVIDIA/caffe Caffe fork>. So the resulting\n            % model may be used there.\n            %\n            Net_(0, 'shrinkCaffeModel', src, dst, varargin{:});\n        end\n\n        function indices = NMSBoxes(bboxes, scores, score_threshold, nms_threshold, varargin)\n            %NMSBOXES  Performs non-maximum suppression given boxes and corresponding scores\n            %\n            %     indices = cv.Net.NMSBoxes(bboxes, scores, score_threshold, nms_threshold)\n            %     indices = cv.Net.NMSBoxes(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __bboxes__ a set of bounding boxes to apply NMS.\n            % * __scores__ a set of corresponding confidences.\n            % * **score_threshold** a threshold used to filter boxes by score.\n            % * **nms_threshold** a threshold used in non maximum suppression.\n            %\n            % ## Output\n            % * __indices__ the kept indices of bboxes after NMS.\n            %\n            % ## Options\n            % * __Eta__ a coefficient in adaptive threshold formula:\n            %   `nms_threshold_{i+1} = eta * nms_threshold_{i}`. default 1.0\n            % * __TopK__ if `> 0`, keep at most `TopK` picked indices.\n            %   default 0\n            %\n            % See also: cv.groupRectangles\n            %\n            indices = Net_(0, 'NMSBoxes', bboxes, scores, score_threshold, nms_threshold, varargin{:});\n        end\n    end\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/Net.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23678416436935573}}
{"text": "function output = callsdplr(interfacedata)\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc       = interfacedata.c;\nK       = interfacedata.K;\nub      = interfacedata.ub;\nlb      = interfacedata.lb;\nlowrankdetails =  interfacedata.lowrankdetails;\n\n% Create the parameter structure\npars = options.sdplr;\npars.printlevel = options.verbose;\n\n% *********************************************\n% Bounded variables converted to constraints\n% N.B. Only happens when caller is BNB\n% *********************************************\nif ~isempty(ub)\n    [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\n% rmfield is slow...\nKnew.l = K.l;\nKnew.s = K.s;\nK = Knew;\n\nif options.savedebug\n    save sdplrdebug F_struc c K pars -V6\nend\n\n% *********************************************\n%FIND LOW RANK STRUCTURES\n% *********************************************\nproblem = 0;\nlrA = [];\nif ~isempty(lowrankdetails) | (options.sdplr.maxrank>0 & (K.s(1)>0))\n    showprogress('Detecting low rank data',options.showprogress);\n    sdploc = K.l+cumsum([1 K.s.^2]);\n    k = 1;\n    % FIX : Lazy code copy...\n    [ix,jx,sx] = find(F_struc);\n    if isempty(lowrankdetails)\n        % Okay, this means we have to go through everything...\n        % Get all data in F_struc for later\n        for lmiid = 1:length(K.s)\n            removethese = zeros(1,size(F_struc,2)-1);\n            for i = 1:size(F_struc,2)-1\n                Fi = reshape(F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,i+1),K.s(lmiid),K.s(lmiid));\n                if nnz(Fi)>0\n                    [D,V] = getfactors(Fi);\n                    if length(D) <= options.sdplr.maxrank\n                        lrA(k).cons = i;\n                        lrA(k).start = sdploc(lmiid);\n                        lrA(k).D = D;\n                        lrA(k).V = V;\n                        k = k+1;\n                        removethese(i) = 1;\n                    end\n                end\n            end\n            removethese = find(removethese);\n            if ~isempty(removethese)\n                these = find((sdploc(lmiid+1)-1>= ix) & (ix>=sdploc(lmiid)) & ismember(jx,1+removethese));\n                sx(these) = 0;\n            end\n        end\n    else\n        % Just check those constraints declared low-rank by user\n        for lrdef = 1:length(lowrankdetails)\n            for lrconstraint = 1:length(lowrankdetails{lrdef}.id)\n                lmiid = lowrankdetails{lrdef}.id(lrconstraint);\n                removethese = zeros(1,size(F_struc,2)-1);\n                checkthese = lowrankdetails{lrdef}.variables;\n                if isempty(checkthese)\n                    checkthese = 1:size(F_struc,2)-1;\n                end\n                for i = checkthese\n                    Fi = reshape(F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,i+1),K.s(lmiid),K.s(lmiid));\n                    if nnz(Fi)>0\n                        [D,V] = getfactors(Fi);\n                        if (options.sdplr.maxrank == 0) | (options.sdplr.maxrank ~= 0 & (length(D) <= options.sdplr.maxrank))\n                            lrA(k).cons = i;\n                            lrA(k).start = sdploc(lmiid);\n                            lrA(k).D = D;\n                            lrA(k).V = V;\n                            k = k+1;\n                            removethese(i) = 1;\n                        end\n                    end\n                end\n                removethese = find(removethese);\n                if ~isempty(removethese)\n                    these = find((sdploc(lmiid+1)-1>= ix) & (ix>=sdploc(lmiid)) & ismember(jx,1+removethese));\n                    sx(these) = 0;\n                    %F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,1+removethese) = 0;\n                end\n            end\n        end\n        F_struc = sparse(ix,jx,sx,size(F_struc,1),size(F_struc,2));\n    end\nend\n\n\n% *********************************************\n% CALL SDPLR\n% *********************************************\nif options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end\nsolvertime = tic;\nif isempty(lrA)    \n   [x_s,y_s,info] = sdplr(F_struc(:,2:end),c,F_struc(:,1),K);\nelse   \n   % pars.reduce = 0;\n    [x_s,y_s,info] = sdplr(F_struc(:,2:end),full(c),full(F_struc(:,1)),K,pars,lrA);\nend\nsolvertime = toc(solvertime);\n\n% YALMIP format\nD_struc = x_s;\nx = -y_s;\n\n% No error codes currently...\nproblem = 0;\n\n% Save ALL data sent to solver\nif options.savesolverinput\n    solverinput.A = F_struc(:,2:end);\n    solverinput.c = F_struc(:,1);\n    solverinput.b = c;\n    solverinput.K = K;\n    solverinput.pars = pars;\nelse\n    solverinput = [];\nend\n\n% Save ALL data from the solution?\nif options.savesolveroutput\n    solveroutput.x = x_s;\n    solveroutput.y = y_s;\n    solveroutput.info = info;\nelse\n    solveroutput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(x(:),D_struc,[],problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);\n\nfunction [D,V] = getfactors(Fi)\nif nnz(Fi)>0\n    [v,d] = eig(full(Fi));\n    d = diag(d);\n    keep = find(abs(d)>1e-6);\n    V = v(:,keep);\n    D = d(keep);\n    % lrA(k).cons = i;\n    % lrA(k).start = sdploc(j);\n    % lrA(k).D = D;\n    % lrA(k).V = V;\n    % k = k+1;\nelse\n    D = [];\n    V = [];\nend\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callsdplr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.236754785512713}}
{"text": "function planC = saveIVHMatrix(IVHNum, doseBinsV, volsHistV, planC)\n%\"saveIVHMatrix\"\n%   Store the doseBinsV and volsHistV with the binWidth shift removed.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n%\n%Usage:\n%   function planC = saveIVHMatrix(IVHNum, doseBinsV, volsHistV, planC)\n\nindexS = planC{end};\n\nif length(doseBinsV) == 1\n    doseBinsV(2) = 2*doseBinsV(1);\n    volsHistV(2) = 0;\nend\n\n%Calculate width of bins, use to find middle of each bin.\nbinWidthsV = diff(doseBinsV);\nlastBinWidth = binWidthsV(end);\nbinWidthsV(end+1) = lastBinWidth;\n\n%Extract dose bin values, adding half to binwidth to get lower edge.\nplanC{indexS.IVH}(IVHNum).IVHMatrix(:,1) = doseBinsV - binWidthsV/2;\nplanC{indexS.IVH}(IVHNum).IVHMatrix(:,2) = volsHistV;\nreturn;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/IntensityVolumeHistograms/saveIVHMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23675478551271298}}
{"text": "function test_pull1456\n\n% MEM 8gb\n% WALLTIME 00:20:00\n% DEPENDENCY ft_sourceanalysis ft_inverse_eloreta\n\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/pull1456.mat'));\n\n% Compute spectrum\ncfg = [];\ncfg.output = 'powandcsd';\ncfg.channel = 'all';\ncfg.method = 'mtmfft';\ncfg.taper = 'hanning';%'boxcar';\ndataFreq1 = ft_freqanalysis(cfg, dataPre);\ncfg.output = 'fourier';\ndataFreq2 = ft_freqanalysis(cfg, dataPre);\n\n% source reconstruction\ncfg = [];\ncfg.method = 'eloreta';\ncfg.sourcemodel = sourcemodel;\ncfg.headmodel = vol.vol;\nsource_eloreta1 = ft_sourceanalysis(cfg, dataFreq1); % compute the source model\n\nassert(isequal(size(source_eloreta1.avg.pow),[size(source_eloreta1.pos,1) numel(source_eloreta1.freq)]));\n\nsource_eloreta2 = ft_sourceanalysis(cfg, dataFreq2); % compute the source model\ni1 = find(source_eloreta2.inside,1,'first');\n\nassert(isequal(size(source_eloreta2.avg.mom{i1}),[3 80 193]));\n\ncfg.mne.snr = 10;\ncfg.method = 'mne';\nsource_mne1 = ft_sourceanalysis(cfg, dataFreq1);\nsource_mne2 = ft_sourceanalysis(cfg, dataFreq2);\n\n% -> this does not work. AT ALLedit f\n%cfg.method = 'harmony';\n%source_harmony1 = ft_sourceanalysis(cfg, dataFreq1);\n%source_harmony2 = ft_sourceanalysis(cfg, dataFreq2);\n\n% -> this should throw an explicit error\ncfg.method = 'music';\ntry\n  source_music1 = ft_sourceanalysis(cfg, dataFreq1);\n  ok = true;\ncatch\n  ok = false;\nend\nassert(~ok);\ntry\n  source_music2 = ft_sourceanalysis(cfg, dataFreq2);\n  ok = true;\ncatch\n  ok = false;\nend\nassert(~ok);\n\n% -> this currently also does note work, but throws a non informative error\n%cfg.method = 'rv';\n%source_rv1 = ft_sourceanalysis(cfg, dataFreq1);\n%source_rv2 = ft_sourceanalysis(cfg, dataFreq2);\n\n% -----------------------------\n\n% Compute an ERP\ncfg = [];\ncfg.covariance = 'yes';\ncfg.covariancewindow = [-1 0]; % calculate the average of the covariance matrices\n% for each trial (but using the pre-event baseline data only)\ndataAvg = ft_timelockanalysis(cfg, dataPre);\n\n% source reconstruction\ncfg = [];\ncfg.method = 'eloreta';\ncfg.sourcemodel = sourcemodel;\ncfg.headmodel = vol.vol;\nsourceTime = ft_sourceanalysis(cfg, dataAvg);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_pull1456.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.23673637085704913}}
{"text": "% The COBRAToolbox: testWriteCbModel.m\n%\n% Purpose:\n%     - test the writeCbModel function\n%\n% Authors:\n%     - Laurent Heirendt\n\nglobal CBTDIR\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testWriteCbModel'));\ncd(fileDir);\n\n% Note: test is only compatible with Matlab R2015b or later\nif ~verLessThan('matlab', '8.6')\n    % define tolerance\n    tol = 1e-6;\n\n    % load the model\n    model = getDistributedModel('ecoli_core_model.mat');\n\n    % write the model to an xls file\n    writeCbModel(model, 'xlsx', 'testData');\n\n    % read in the xls model file\n    modelIn = xls2model('testData.xlsx');\n\n    % convert an old style model\n    model = convertOldStyleModel(model);\n\n    % test\n    assert(isequal(model.lb, modelIn.lb))\n    assert(isequal(model.b, modelIn.b))\n    assert(isequal(model.ub, modelIn.ub))\n    assert(isequal(sort(model.mets), sort(modelIn.mets)))\n    assert(isequal(model.csense, modelIn.csense))\n    assert(isequal(model.osenseStr, modelIn.osenseStr))\n    assert(isequal(model.rxns, modelIn.rxns))\n    assert(isequal(sort(model.genes), sort(modelIn.genes)))\n    assert(isequal(model.c, modelIn.c))\n\n    % NOTE: model.rules and model.S are different from modelIn.S and modelIn.rules\n    %       as the metabolites are not ordered in the same way.\n\n    solverOK = changeCobraSolver('glpk');\n\n    if solverOK\n        % run an LP and compare the solutions\n        solModel = optimizeCbModel(model);\n        solModelIn = optimizeCbModel(modelIn);\n\n        assert(abs(solModel.f - solModelIn.f) < tol)\n        assert(solModel.stat == solModelIn.stat)\n    end\n\n    % remove the generated file\n    delete('testData.xlsx');\nelse\n    fprintf('\\ntestWriteCbModel is not compatible with this version of MATLAB. Please upgrade your version of MATLAB.\\n\\n');\nend\n\n% test varargin\n\n% load the model\nmodel = getDistributedModel('ecoli_core_model.mat');\n\n% write out using varargin\noutmodel1 = writeCbModel(model, 'format', 'mat', 'fileName', 'testModel1');\noutmodel2 = writeCbModel(model, 'mat', 'testModel2.mat');\n\n% read in the testModel and testModel2\ntestModel1 = readCbModel('testModel1.mat');\ntestModel2 = readCbModel('testModel2.mat');\ntestModel2.description = '';\ntestModel1.description = '';\nassert(isequal(testModel1, testModel2));\n\n% test the legacy signature with more input arguments\n[compSymbols, compNames] = getDefaultCompartmentSymbols();\noutmodel3 = writeCbModel(model, 'mat', 'testModel3.mat', compNames, compSymbols);\ntestModel3 = readCbModel('testModel3.mat');\ntestModel3.description = '';\nassert(isequal(testModel1, testModel3));\n\n% test new signature\noutmodel4 = writeCbModel(model, 'format', 'mat', 'fileName', 'testModel4.mat', 'compNames', compNames, 'compSymbols', compSymbols);\noutmodel5 = writeCbModel(model, 'format', 'mat', 'compNames', compNames, 'compSymbols', compSymbols,'fileName', 'testModel5.mat');\ntestModel4 = readCbModel('testModel4.mat');\ntestModel5 = readCbModel('testModel5.mat');\ntestModel4.description = '';\ntestModel5.description = '';\nassert(isequal(testModel4, testModel5));\n\n% remove generate files during testing\nfor i = 1:5\n    delete(['testModel', num2str(i),'.mat']);\nend\n\n% change to old directory\ncd(currentDir);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/base/testIO/testWriteCbModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23666947174091396}}
{"text": "function [success]=checksignres_favar(Sj,fj)\n % check here for success only\n\n% if there are no sign restrictions on this shock, don't do anything and automatically count as success\nif isempty(Sj)\nsuccess=1;\n% if there are sign restriction on this shock, check them\nelse\n% check if the restrictions hold\n   % if yes, count as success\n   if all(Sj*fj>=0)\n   success=1;\n%    % if the restrictions do not hold, there may still be a possibility by switching the sign of qj\n%    elseif all(Sj*(-fj)>=0)\n%    qj=-qj;\n%    success=1;\n   % else, if there is no way to have qj succesful, count as a fail\n   else\n   success=0;\n   end\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/checksignres_favar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.23666946512787246}}
{"text": "function opts = getTrainingOptions(hyperparam,imds_validation)\n\nif isempty(imds_validation) % if there is no validation set\nopts = trainingOptions('adam',...\n    'InitialLearnRate',hyperparam.InitialLearnRate,...\n    'L2Regularization',hyperparam.L2Regularization,... \t\t\n    'MiniBatchSize',hyperparam.MiniBatchSize,...\t\t\t\n    'MaxEpochs',hyperparam.MaxEpochs,...\t\t\t\n    'ExecutionEnvironment',hyperparam.ExecutionEnvironment,...\n    'VerboseFrequency',50,...\n    'Plots','training-progress');   \nelse  % if there is a validation set\nopts = trainingOptions('adam',...\n    'InitialLearnRate',hyperparam.InitialLearnRate,...\n    'ValidationData',imds_validation,...\t\t\n    'ValidationFrequency',hyperparam.ValidationFrequency,...\n    'ValidationPatience',hyperparam.ValidationPatience,...\n    'L2Regularization',hyperparam.L2Regularization,... \t\t\n    'MiniBatchSize',hyperparam.MiniBatchSize,...\t\t\t\n    'MaxEpochs',hyperparam.MaxEpochs,...\t\t\t\t\n    'ExecutionEnvironment',hyperparam.ExecutionEnvironment,...\n    'VerboseFrequency',50,...\n    'Plots','training-progress');\nend\n\nend\n", "meta": {"author": "jnkather", "repo": "MSIfromHE", "sha": "27b351b9220583271cd2bcedbc9e75459916e06c", "save_path": "github-repos/MATLAB/jnkather-MSIfromHE", "path": "github-repos/MATLAB/jnkather-MSIfromHE/MSIfromHE-27b351b9220583271cd2bcedbc9e75459916e06c/subroutines/getTrainingOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2366694651278724}}
{"text": "function [fg, fg_unclassified]=dtiFindMoriTracts(dt6File, outFile, fgFile, Atlas, showFig, saveQuench, saveMrDiffusion, useJhuFa, useInterhemisphericSplit, useRoiBasedApproach)\n%Categorizes fibers based on Mori white matter atlas.\n%\n%  dtiFindMoriTracts(dt6File, [outFile=fullfile(fileparts(dt6File), 'fibers', 'MoriGroups.mat')], fgFile,...\n%      [Atlas='MNI_JHU_tracts_prob.nii.gz'], [showFig=false],[saveQuench=false],...\n%      [saveMrDiffusion=false], [useJhuFa=false],...\n%      [useInterhemisphericSplit=true], [useRoiBasedApproach=true]);\n%\n% By default whole brain tractography is performed and then\n% Mori-classified. Otherwise, provide a file name fgFile for a fiber group\n% if willing to Mori-classify an existing fiber group.\n%\n% Input parameters: \n% fgFile                   - A file with previously tracked elsewhere fibers \n%                          to be categorized.\n% Atlas                    - probabilistic atlas defining probabilities for\n%                          each voxel to be passed by a fiber within each of\n%                          atlas fiber groups. We usually use Mori atlas\n%                          supplied with fsl: MNI_JHU_tracts_prob.nii.gz.\n%                          This atlas is not symmetric. For a \"symmetrified\"\n%                          atlas use 'MNI_JHU_tracts_prob_Symmetric.nii.gz'\n%                          but we strongly recommend using the original\n%                          atlas. \n% useInterhemisphericSplit - cut fibers crossing between hemispheres with a\n%                          midsaggital plane below z=-10. This is to get\n%                          rid of \n% useRoiBasedApproach      - use the approach describing in Zhang (2008)\n%                           Neuroimage 42. For each of the 20 Mori Groups 2\n%                           critical ROIs are computed by spatially\n%                           transforming ROIs provided in\n%                           templates/MNI_JHU_tracts_ROIs. A fiber becomes\n%                           a candidate to being labeled as a part of a\n%                           given Mori group if this fiber \"passes through\"\n%                           both critical ROIs for that Mori group. Our\n%                           modification of Zhang (2008) approach: In case\n%                           a single fiber is a candidate for >1 Mori\n%                           group, respective cumulative probabilities are\n%                           computed with probabilistic Mori atlas, then\n%                           compared. useRoiBasedApproach can take the\n%                           following values: (1) 'false' (to not use the\n%                           approach); (2) 'true'(use the approach; the\n%                           minimal distance from a fiber to ROI to count\n%                           as \"a fiber  is crossing the ROI\" minDist=2mm);\n%                           (3) a scalar value for minDist in mm; (4) a\n%                           vector with the first value being minDist and\n%                           the second value being a flag 1/0 for whether\n%                           ROIs should be recomputed (and overwritten) for\n%                           this subject (1, by default). This is useful\n%                           because sometimes if you  are rerunning\n%                           dtiFindMoriTracts with different parameters,\n%                           you do not need to recompute ROIs. E.g., to\n%                           avoid recomputing  ROIs and use minDist of 4mm\n%                           one would pass [useRoiBasedApproach=[4 0]];\n%\n% Output parameters: \n% fg              - fibers structure containing all fibers assigned to \n%                   one of Mori Groups. Respective group labeles are stored \n%                   in fg.subgroups field.\n% fg_unclassified - fiber structure containing the rest of the (not Mori) fibers. \n%\n% Example: \n%    dt6File = '/biac3/wandell4/data/reading_longitude/dti_y1234/at040918/dti06trilinrt/dt6.mat';\n%    fg = dtiFindMoriTracts(dt6File); \n%\n% See also: dtiSplitInterhemisphericFibers.m  \n%\n% Usage Notes:\n%    Text explaining the usage of this code for publication can be found at\n%    the end of this code along with references.\n%\n% (c) Stanford University, Vistalab\n    \n% HISTORY:\n% 2008.10.08 RFD wrote it. 2009.01.08 EIR added an option of Mori-categorizing \n%            a provided FG (do not supply a fgFile parameter, or supply []\n%            if want whole brain tractography performed)\n% 2009.01.09 RFD removed the feature that discarded fibers that scored too\n%            high on more than one atlas group. This was causing too many\n%            good fibers to be removed, especially for groups 19 & 20\n%            (arcuate).\n% 2009.01.30 EIR modified to write out Mori labels as fg.subgroup\n% 2009.02.01 EIR added an option to use symmetrified Mori atlas \n% 2009.05.31 EIR modified to output fghandle in addition to fg\n% 2009.07.21 EIR modified to output unclassified fibers\n% 2009.08.28 EIR added interhemispheric fiber split below ACPC and removed\n%                fghandle output (because the parent FG is modified to add\n%                split fibers.\n% 2009.09.27 ER  added useRoiBasedApproach option which implements Zhang \n%                (2008) Neuroimage 42 method.\n% 2009.10.2 ER:  no longer need to fit Quench state file labels to 8 grp \n%                limit.\n\n\n%% Check INPUTS\n\nif ~exist('showFig', 'var')|| isempty(showFig)\n    showFig= false;\nend\nif ~exist('saveQuench', 'var')|| isempty(saveQuench)\n    saveQuench = false;\nend\nif ~exist('saveMrDiffusion', 'var')|| isempty(saveMrDiffusion)\n    saveMrDiffusion= false;\nend\nif ~exist('useJhuFa', 'var')|| isempty(useJhuFa)\n    useJhuFa = false; %JhuFa should never be used\nend\nif ~exist('useInterhemisphericSplit', 'var')|| isempty(useInterhemisphericSplit)\n    useInterhemisphericSplit=true;\nend\nif ~exist('useRoiBasedApproach', 'var')|| isempty(useRoiBasedApproach)\n    useRoiBasedApproach=true;\nend\n\nif useRoiBasedApproach==false\n    recomputeROIs = false;\nelseif length(useRoiBasedApproach)<2\n    recomputeROIs=1;\nelse\n    recomputeROIs=useRoiBasedApproach(2);\nend\n\nif recomputeROIs\n    display('dtiFindMoriTracts: You chose to recompute ROIs');\nend\n\n% E.g., to avoid recomputing  ROIs and use minDist of 4mm one would pass [useRoiBasedApproach=[4 0]];\nif isnumeric(useRoiBasedApproach)\n    minDist = useRoiBasedApproach(1);\n    useRoiBasedApproach = 'true';\nelse\n    minDist=2; %.89;\nend\ndisplay(['Fibers that get as close to the ROIs as ' num2str(minDist) 'mm will become candidates for the Mori Groups']);\n\nif(~exist('Atlas','var') || isempty(Atlas))\n    % Default scenario: use original Mori Atlas\n    Atlas='MNI_JHU_tracts_prob.nii.gz';\nend\n\nif(~exist('fgFile','var') || isempty(fgFile))\n    % Default scenario: perform whole brain tractogrpahy\n    wholeBrainFlag=1;\nelse\n    wholeBrainFlag=0;\nend\n\nif(~exist('outFile','var') || isempty(outFile))\n    bd = fileparts(dt6File);\n    if(isempty(bd)), bd = pwd; end\n    outFile = fullfile(bd,'fibers', 'MoriGroups.mat');\nend\n\n\n%%\n\n% Load a dt6 file\ndt = dtiLoadDt6(dt6File);\n\ntdir = fullfile(fileparts(which('mrDiffusion.m')), 'templates');\nspm_defaults; global defaults; params = defaults.normalise.estimate;\nif(useJhuFa)\n    template = fullfile(tdir,'MNI_JHU_FA.nii.gz');\n    alignIm = dtiComputeFA(dt.dt6);\n    params.cutoff = 19;\n    params.reg = 0.09;\nelse\n    % Spatially normalize it with the MNI (ICBM) template\n    template = fullfile(tdir,'MNI_JHU_T2.nii.gz');\n    alignIm = mrAnatHistogramClip(double(dt.b0),0.3,0.99);\nend\n\n[sn, Vtemplate, invDef] = mrAnatComputeSpmSpatialNorm(alignIm, dt.xformToAcpc, template, params);\n\n% check the normalization\nmm = diag(chol(Vtemplate.mat(1:3,1:3)'*Vtemplate.mat(1:3,1:3)))';\nbb = mrAnatXformCoords(Vtemplate.mat,[1 1 1; Vtemplate.dim]);\nalignIm_sn = mrAnatResliceSpm(alignIm, sn, bb, [2 2 2], [1 1 1 0 0 0], 0);\ntIm = mrAnatResliceSpm(double(Vtemplate.dat), inv(Vtemplate.mat), bb, [2 2 2], [1 1 1 0 0 0], 0);\nim(:,:,:,1) = uint8(tIm);\nim(:,:,:,2) = uint8(round(clip(alignIm_sn)*255));\nim(:,:,:,3) = im(:,:,:,2);\n\nif(showFig)\n\n    showMontage(im);\nelse\n    if(~exist(fileparts(outFile),'dir')), mkdir(fileparts(outFile)); end\n    imwrite(makeMontage(im),[outFile(1:end-4) '_snCheck.png']);\nend\n\n% Load the Mori atlas maps and the corresponding label files\n% ldir = fileparts(which('dtiGetBrainlabel.m'));\nmoriTracts = niftiRead(fullfile(tdir, Atlas));\n% 15 is a subregion of 19 and 16 a subregion of 20. To better separate them,\n% we subtract 19 from 15 and 20 from 16.\nmoriTracts.data(:,:,:,15) = moriTracts.data(:,:,:,15)-moriTracts.data(:,:,:,19);\nmoriTracts.data(:,:,:,16) = moriTracts.data(:,:,:,16)-moriTracts.data(:,:,:,20);\n\nlabels = readTab(fullfile(tdir,'MNI_JHU_tracts_prob.txt'),',',false);\nlabels = labels(1:20,2);\n% If you wanted to inverse-normalize the maps to this subject's brain:\n% invDef.outMat = moriTracts.qto_ijk;\n% bb = mrAnatXformCoords(dt.xformToAcpc,[1 1 1; size(dt.b0)]);\n% tprob = mrAnatResliceSpm(tprob, invDef, bb, dt.mmPerVoxel, [1 1 1 0 0 0]);\n\nif wholeBrainFlag\n    % Track all white matter fibers in the native subject space. We do this by\n    % seeding all voxels with high FA (>0.3).\n    faThresh = 0.30;\n    opts.stepSizeMm = 1;\n    opts.faThresh = .2; %0.15\n    opts.lengthThreshMm = [50 250];\n    opts.angleThresh = 50;\n    opts.wPuncture = 0.2;\n    opts.whichAlgorithm = 1;\n    opts.whichInterp = 1;\n    opts.seedVoxelOffsets = [0.25 0.75];\n    opts.offsetJitter = 0.1;\n    fa = dtiComputeFA(dt.dt6);\n    fa(fa>1) = 1; fa(fa<0) = 0;\n    roiAll = dtiNewRoi('all');\n    mask = dtiCleanImageMask(fa>=faThresh);\n    [x,y,z] = ind2sub(size(mask), find(mask));\n    clear mask fa;\n    roiAll.coords = mrAnatXformCoords(dt.xformToAcpc, [x,y,z]);\n    clear x y z;\n    fg = dtiFiberTrack(dt.dt6, roiAll.coords, dt.mmPerVoxel, dt.xformToAcpc, 'wholeBrain', opts);\n    clear roiAll\n    % wholeBrainFGFile=fullfile(fileparts(dt6File), 'fibers', 'all.mat');\n    % dtiWriteFiberGroup(fg, wholeBrainFGFile);\n    % fghandle.parent=wholeBrainFGFile;\nelse\n    % get fg from a file\n    fg = fgRead(fgFile);\n    %fg = dtiLoadFiberGroup(fgFile);\n    %fghandle.parent=fgFile;\nend\n\n\n%Cut the fibers below acpc, to disentangle CST& ATL crossing at the pons\n%level.\nif useInterhemisphericSplit\n    fgname=fg.name;\n    [fg]=dtiSplitInterhemisphericFibers(fg, dt, -10);\n    fg.name=fgname; %To avoid \"bilaterally split\" extra long comment in the fg name.\nend\n\n%Because we know that we are looking for major Mori tracts, we should\n%keep only 5 points or longer fibers (otherwise spline in contrack\n%crashes).  This is important for Blue matter procedures planned, but wont hurt otherwise (for Mori detection) either.\nif sum(cellfun(@length, fg.fibers)<5)~=0\n    if isfield(fg, 'subgroup')&&~isempty(fg.subgroup)\n        fg.subgroup(cellfun(@length, fg.fibers)<5)=[];\n    end\n    if isfield(fg, 'seeds')&&~isempty(fg.seeds)\n        fg.seeds(cellfun(@length, fg.fibers)<5, :)=[];\n    end\n    fg.fibers(cellfun(@length, fg.fibers)<5)=[];\n    fprintf('dtiFindMoriTracts: Removing %s fibers with 5 points or less \\n', num2str(sum(cellfun(@length, fg.fibers)<5)));\nend\n\n\n% Warp the fibers in 'fg' to the MNI standard space:\nfg_sn = dtiXformFiberCoords(fg, invDef);\n\n% moriTracts.data is a an XxYxZx20 array contianing the 20 Mori probability\n% atlases (range is 0-100 where 100 represents p(1)).\nsz = size(moriTracts.data);\n\n% fg_sn fiber coords are in MNI space- now convert them to atlas space by\n% applying the affine xform from the atlas NIFTI header. SInce the atlas is\n% already in MNI space, this transform will just account for any\n% translation and scale differences between the atlas maps and the MNI\n% template used to compute our sn.\nfgCoords = mrAnatXformCoords(moriTracts.qto_ijk, horzcat(fg_sn.fibers{:}));\nclear fg_sn;   % what we need from fg_sn is now stored in fgCoords\nfgLen = cellfun('size',fg.fibers,2);\n\n% Now loop over the 20 atlases and get the atlas probability score for each\n% fiber point. We collapse the scores across all pints in a fiber by taking\n% the mean. Below, we will use these 20 mean scores to categorize the fibers.\n% TO DO: consider doing something more sophisticated than taking the mean.\nfp = zeros(sz(4),numel(fg.fibers));\nfor(ii=1:sz(4))\n    % Get the Mori atlas score for each point in the fibers using\n    % trilinear interpolation.\n    p = myCinterp3(double(moriTracts.data(:,:,:,ii))/100, sz([1,2]), sz(3), fgCoords(:,[2,1,3]));\n    % The previous line interpolated one giant array with all fiber points\n    % concatenated. The next loop will separate the coordinates back into\n    % fibers and take the mean score for the points within each fiber.\n    fiberCoord = 1;\n    for(jj=1:numel(fg.fibers))\n        fp(ii,jj) = nanmean(p([fiberCoord:fiberCoord+fgLen(jj)-1]));\n        fiberCoord = fiberCoord+fgLen(jj);\n    end\nend\nclear p fgCoords;\n\nif useRoiBasedApproach\n    %Warp Mori ROIs to individual space; collect candidates for each fiber\n    %group based on protocol of 2 or > ROIs a fiber should travel thru.\n    %The following ROIs are saved within\n    %trunk/mrDiffusion/templates/MNI_JHU_tracts_ROIs folder and are created using MNI template as\n    %described in Wakana et al.(2007) Neuroimage 36 with a single modification:\n    %For SLFt Roi2, they recommend drawing the ROI at the AC level, whereas we\n    %use a lisce just inferior of CC splenium. The reason for this modification\n    %is that Wakana et al. ACPC aligned images appear different from MNI images\n    %(the latter we use for defininng ROIs). If defining SLFt-Roi2 on a slice\n    %actually at the AC level (althought highly consistently across human\n    %raters), many SLFt fibers were not correctly labeled as they extend\n    %laterally into temporal lobe just above the aforementioned ROI plane.\n\n    moriRois={'ATR_roi1_L.nii.gz',  'ATR_roi2_L.nii.gz'; 'ATR_roi1_R.nii.gz', 'ATR_roi2_R.nii.gz'; ...\n        'CST_roi1_L.nii.gz', 'CST_roi2_L.nii.gz'; 'CST_roi1_R.nii.gz',  'CST_roi2_R.nii.gz'; ...\n        'CGC_roi1_L.nii.gz', 'CGC_roi2_L.nii.gz'; 'CGC_roi1_R.nii.gz', 'CGC_roi2_R.nii.gz'; ...\n        'HCC_roi1_L.nii.gz', 'HCC_roi2_L.nii.gz'; 'HCC_roi1_R.nii.gz', 'HCC_roi2_R.nii.gz';...\n        'FP_R.nii.gz', 'FP_L.nii.gz'; ...\n        'FA_L.nii.gz', 'FA_R.nii.gz'; ...\n        'IFO_roi1_L.nii.gz', 'IFO_roi2_L.nii.gz'; 'IFO_roi2_R.nii.gz', 'IFO_roi1_R.nii.gz'; ...\n        'ILF_roi1_L.nii.gz', 'ILF_roi2_L.nii.gz'; 'ILF_roi1_R.nii.gz', 'ILF_roi2_R.nii.gz'; ...\n        'SLF_roi1_L.nii.gz', 'SLF_roi2_L.nii.gz'; 'SLF_roi1_R.nii.gz', 'SLF_roi2_R.nii.gz'; ...\n        'UNC_roi1_L.nii.gz', 'UNC_roi2_L.nii.gz'; 'UNC_roi1_R.nii.gz', 'UNC_roi2_R.nii.gz'; ...\n        'SLF_roi1_L.nii.gz', 'SLFt_roi2_L.nii.gz'; 'SLF_roi1_R.nii.gz', 'SLFt_roi2_R.nii.gz'};\n\n    midSaggitalRoi = dtiRoiMakePlane([0, dt.bb(1, 2), dt.bb(1, 3); 0 , dt.bb(2, 2) , dt.bb(2, 3)], 'midsaggital', 'g');\n    \n    keep1 = zeros(length(fg.fibers), size(moriRois, 1)); keep2=zeros(length(fg.fibers), size(moriRois, 1));\n    \n    [fgOut,contentiousFibers,InterHemisphericFibers] = dtiIntersectFibersWithRoi([], 'not', [], midSaggitalRoi, fg); \n    %NOTICE: ~keep3 (not \"keep3\") will mark fibers that DO NOT cross midSaggitalRoi.\n    keep3 = repmat(InterHemisphericFibers, [1 size(moriRois, 1)]);\n\n    fgCopy=fg; fgCopy.subgroup=[];\n    for roiID=1:size(moriRois, 1)\n        \n        ROI_img_file=fullfile(tdir, 'MNI_JHU_tracts_ROIs',  [moriRois{roiID, 1}]);\n        if recomputeROIs\n            [RoiFileName, invDef, roi]=dtiCreateRoiFromMniNifti(dt6File, ROI_img_file, invDef, true);\n        else\n            RoiFileName=fullfile(fileparts(dt6File), 'ROIs',  [prefix(prefix(ROI_img_file, 'short'), 'short') '.mat']);\n            load(RoiFileName);\n\n        end\n        [fgOut,contentiousFibers, keep1(:, roiID)] = dtiIntersectFibersWithRoi([], 'and', minDist, roi, fg);\n        keepID1=find(keep1(:, roiID));\n\n        ROI_img_file=fullfile(tdir, 'MNI_JHU_tracts_ROIs',  [moriRois{roiID, 2}]);\n        if recomputeROIs\n            [RoiFileName, invDef, roi]=dtiCreateRoiFromMniNifti(dt6File, ROI_img_file, invDef, true);\n        else\n            RoiFileName=fullfile(fileparts(dt6File), 'ROIs',  [prefix(prefix(ROI_img_file, 'short'), 'short') '.mat']);\n            load(RoiFileName);\n        end\n\n        %To speed up the function, we intersect with the second ROI not all the\n        %fibers, but only those that passed first ROI.\n        fgCopy.fibers=fg.fibers(keepID1(keepID1>0));\n        [a,b, keep2given1] = dtiIntersectFibersWithRoi([], 'and', minDist, roi, fgCopy);\n        keep2(keepID1(keep2given1), roiID)=true;\n\n    end\n    clear fgOut contentiousFibers keepID\n    %Note: forceps major and minor should NOT have interhemipsheric fibers\n    %excluded\n    keep3(:, 9:10)=keep3(:, 9:10).*0;\n    fp(~(keep1'&keep2'&~keep3'))=0;\n    %Also note: Tracts that cross through slf_t rois should be automatically\n    %classified as slf_t, without considering their probs.\n    fp(19, (keep1(:, 19)'&keep2(:, 19)'&~keep3(:, 19)'))=max(fp(:));\n    fp(20, (keep1(:, 20)'&keep2(:, 20)'&~keep3(:, 20)'))=max(fp(:));\n\nend\n\n% We have a set of atlas scores for each each fiber. To categorize the\n% fibers, we will find the atlas with the highest score (using 'sort').\n[atlasScore,atlasInd] = sort(fp,1,'descend');\n% Eliminate fibers that don't match any of the atlases very well:\nunclassified=atlasScore(1,:)==0; %ER 09.15.09 dropped this threshold to zero\ngoodEnough = atlasScore(1,:)~=0; % RFD 09.01.09: removed \"& atlasScore(1,:)>sum(atlasScore(2:end,:),1);\"\n\nfor ii=1:sz(4)\n    curAtlasFibers{ii} = find(atlasInd(1,:)==ii & goodEnough);\n    %    if(showFig)\n    %        fc = round(mrAnatXformCoords(inv(dt.xformToAcpc), horzcat(fg.fibers{curAtlasFibers{ii}})));\n    %        im = dt.b0;\n    %        inds = sub2ind(size(dt.b0),fc(:,1),fc(:,2),fc(:,3));\n    %        im(inds) = 1;\n    %        makeMontage3(im,dt.b0,dt.b0);\n    %        set(gcf,'name',labels{ii},'NumberTitle','off');\n    %    end\nend\n\n% We now have a cell array (curAtlasFibers) that contains 20 arrays, each\n% listing the fiber indices for the corresponding atlas group. E.g.,\n% curAtlasFibers{3} is a list of indices into fg.fibers that specify the\n% fibers belonging to group 3.\n\n%Create a FG for unclassified fibers\nfg_unclassified=fg; \nfg_unclassified.name=[fg.name ' not Mori Groups'];\nfg_unclassified.fibers = fg.fibers(unclassified); %prepare fg output\nif ~isempty(fg.seeds)\n    fg_unclassified.seeds = fg.seeds(unclassified);\nend\nfg_unclassified.subgroup=zeros(size(fg.fibers(unclassified)))'+(1+sz(4));\nfg_unclassified.subgroupNames(1)=struct('subgroupIndex', 1+sz(4), 'subgroupName', 'NotMori');\n\n% Modify fg.fibers to discard the fibers that didn't make it into any of\n% the atlas groups:\nfg.name=[fg.name ' Mori Groups'];\n%fghandle.name=fg.name;\nfg.fibers = fg.fibers([curAtlasFibers{:}]); %prepare fg output\n%fghandle.ids=horzcat(curAtlasFibers{:}); %prepare fghandle output\n\nif ~isempty(fg.seeds)\n    fg.seeds = fg.seeds([curAtlasFibers{:}],:);\nend\n\n\n% We changed the size of fg.fibers by discarding the uncategorized fibers,\n% so we need to create a new array to categorize the fibers. This time we\n% make an array with one entry corresponding to each fiber, with integer\n% values indicating to which atlas group the corresponding fiber belongs.\nfg.subgroup = zeros(1,numel(fg.fibers));\ncurInd = 1;\nfor(ii=1:numel(curAtlasFibers))\n    fg.subgroup(curInd:curInd+numel(curAtlasFibers{ii})-1) = ii;\n    %fghandle.subgroup(curInd:curInd+numel(curAtlasFibers{ii})-1) = ii;\n    curInd = curInd+numel(curAtlasFibers{ii});\n    %Save labels for the fiber subgroups within the file\n    fg.subgroupNames(ii)=struct('subgroupIndex', ii, 'subgroupName', labels(ii));\n    %fghandle.subgroupNames(ii)=struct('subgroupIndex', ii, 'subgroupName', labels(ii));\nend\n\n% Save in mrDiffusion format:\nif (saveMrDiffusion)\n    if(~exist(fileparts(outFile),'dir')), mkdir(fileparts(outFile)); end\n    dtiWriteFiberGroup( fg, outFile);\nend\n\nif(saveQuench)\n    if(~exist(fileparts(outFile),'dir')), mkdir(fileparts(outFile)); end\n    % Also save a Quench pdb file/state file to show the fiber groups.\n    % Should we use dtiWriteFibersPdb?\n    dtiWriteFibersPdb(fg,dt.xformToAcpc, [outFile(1:end-4) '.pdb']);\n    % merge some of the groups to fit into the Quench 8-group limit:\n    fgInds = fg.subgroup;\n    dtiQuenchSaveFibersState(fgInds, [outFile(1:end-4) '.qst']);\nend\n\nreturn;\n\n%%\n\n% To run this on a bunch of subjects:\nbd = '/biac3/wandell4/data/reading_longitude/dti_y1234';\n[dt6Files,subCodes,subDirs,subIn] = findSubjects(fullfile(bd,'*'), 'dti06rt');\nsubIn = unique(subIn);\ndoThese = [1:numel(dt6Files)]; % strmatch('pt0',subCodes)';\nfor(ii=doThese)\n    fiberDir = fullfile(fileparts(dt6Files{ii}),'Mori');\n    if(~exist(fiberDir,'dir')), mkdir(fiberDir); end\n    outBase = fullfile(fiberDir,'MoriGroups');\n    if(~exist([outBase '.mat'],'file'))\n        fprintf('Processing %s...\\n',dt6Files{ii});\n        dtiFindMoriTracts(dt6Files{ii},outBase);\n    end\nend\n\nsubs = []; doThese = [];\nfor(ii=1:numel(subIn))\n    cur = strmatch([subIn{ii} '0'],subCodes);\n    if(numel(cur)==4)\n        subs = [subs cur'];\n    end\nend\nfor(ii=subs)\n    fiberDir = fullfile(fileparts(dt6Files{ii}),'Mori');\n    if(exist(fiberDir,'dir')&&exist(fullfile(fiberDir,'MoriGroups.mat')))\n        %disp([subCodes{ii} ' is finished.']);\n    else\n        disp([subCodes{ii} ' is MISSING.']);\n        doThese = [doThese ii];\n    end\nend\n\n\n% To analyze a bunch of subjects:\noutDir = '/biac3/wandell4/data/reading_longitude/moriGroupAnalysis';\nbd = '/biac3/wandell4/data/reading_longitude/dti_y1234';\n[dt6Files,subCodes,subDirs,subLetters] = findSubjects(fullfile(bd,'*'), 'dti06rt');\nnGroups = 20;\nnSubs = numel(dt6Files);\nsgVol = zeros(nSubs,nGroups);\nfor(ii=1:nSubs)\n    fname = fullfile(fileparts(dt6Files{ii}),'Mori','MoriGroups.mat');\n    fprintf('Processing %s (%d of %d)...\\n',fname,ii,numel(dt6Files));\n    fg = dtiReadFibers(fname);\n    for(jj=1:nGroups)\n        sgCoords = fg.fibers(fg.subgroup==jj);\n        % crude volume measure:\n        sgVol(ii,jj) = size(unique(round(horzcat(sgCoords{:}))','rows'),1);\n    end\nend\n\n% Get the labels for the 20 groups:\nlabels = readTab(which('MNI_JHU_tracts_prob.txt'),',',false);\nlabels = labels(:,2);\nsave(fullfile(outDir,'moriGroupSum.mat'),'bd','labels','sgVol','dt6Files','subCodes','subLetters');\n\n\noutDir = '/biac3/wandell4/data/reading_longitude/moriGroupAnalysis';\nload(fullfile(outDir,'moriGroupSum.mat'));\nnGroups = size(sgVol,2);\nnSubs = size(sgVol,1);\nmn = mean(sgVol)/1000;\nsd = std(sgVol)/1000;\nrng = [max(sgVol); min(sgVol)]/1000;\nfor(ii=1:nGroups)\n    fprintf('%50s:\\t %0.2fcc (%0.3f, %0.2f-%0.2f)\\n',labels{ii},mn(ii),sd(ii),rng(1,ii),rng(2,ii));\nend\n\n[bd, colNames, sc, subYr] = dtiGetBehavioralData(subCodes);\n\nyr = 4;\nbdVars = {'Passage Comprehension.', 'Rapid Naming.', 'Word attack ss.', 'Phonological Awareness.', 'Calculation.','WISC Full-Scale IQ.','DTI Age.','Sex (1=male)'};\nfor(ii=1:numel(bdVars))\n    for(jj=1:2:nGroups-1)\n        if(bdVars{ii}(end)=='.'), bVar = sprintf('%s%d',bdVars{ii},yr);\n        else bVar = bdVars{ii}; end\n        s = subYr==yr;\n        x = bd(s,strmatch(bVar,colNames,'exact'));\n        if(~isempty(x))\n            y = sgVol(s,jj+1)-sgVol(s,jj);  % sgVol(s,jj);\n            gv = ~isnan(x)&~isnan(y);\n            x = x(gv); y = y(gv);\n            %figure(34); plot(x,y,'.');\n            [p,r,df] = myStatTest(x,y,'r');\n            fprintf('%25s vs. %50s:\\t r=%+0.3f (p=%0.2g, df=%d)\\n',bVar,labels{jj},r,p,df);\n        end\n    end\nend\n\n\n\n%% TEXT FOR PUBLICATION\n\n% The fiber tracts from the whole brain tractography were automatically\n% classified into twenty fiber structures as defined in the JHU\n% white-matter tractography atlas (Wakana et al., 2007) using a modified\n% form of the reference ROI approach ( [Wakana et al., 2007] , [Zhang et\n% al., 2008] , [Hua et al., 2008] and [Zhang et al., 2010] ). Specifically,\n% we manually defined reference ROIs (rROIs) describing two waypoints for\n% each of the 20 major white matter tracts described in (Wakana et al.,\n% 2007). These ROIs were drawn in MNI space on the ICBM-DTI-81 atlas by two\n% experts. The rROIs were warped from MNI space into each individual's\n% diffusion space and fibers were retained if they passed through any pair\n% of rROIs. Note that some fibers passed through the rROIs for more than\n% one major tract. Thus, we applied an additional inclusion criterion by\n% warping each fiber to MNI space and measuring the approximate overlap\n% between the fiber points and each of the major tracts of the\n% probabilistic JHU tractography atlas (Wakana et al., 2007). The fiber was\n% classified as representing the JHU tract with which it had the highest\n% degree of overlap.\n% \n\n%% REFERENCES:\n% \n% Wakana, Setsu et al. 2007. \u201cReproducibility of quantitative tractography\n% methods applied to cerebral white matter.\u201d NeuroImage 36(3): 630-44.\n% \n% Zhang, Weihong, Alessandro Olivi, Samuel J Hertig, Peter van Zijl, et\n% al. 2008. \u201cAutomated fiber tracking of human brain white matter using\n% diffusion tensor imaging.\u201d NeuroImage 42(2): 771-7.\n% \n% Hua, K, J Zhang, S Wakana, H Jiang, et al. 2008. \u201cTract probability maps\n% in stereotaxic spaces: analyses of white matter anatomy and\n% tract-specific quantification.\u201d Neuroimage 39(1): 336-347.\n% \n% Zhang et al., 2010 Y. Zhang, J. Zhang, K. Oishi, A. Faria, H. Jiang, X.\n% Li, K. Akhter, P. Rosa-Neto, G. Pike, A. Evans, A. Toga, R. Woods, J.\n% Mazziotta, M. Miller, P. van Zijl and S. Mori, Atlas-guided tract\n% reconstruction for automated and comprehensive examination of the white\n% matter anatomy, . Neuroimage, 52 4 (2010), pp. 1289\u20131301 (May).\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/tractography/dtiFindMoriTracts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2366694651278724}}
{"text": "classdef TimeMagnitudePlotter < TimeSomethingPlotter\n    % Used to create time-mag plots\n    %\n    % plotting multiple times will simply replace the existing plot\n    %\n    % Example:\n    %   TimeMagnitudePlotter.plot(catalog,bigCat)\n    %   ax = TimeMagnitudePlotter.axes;\n    %   TimeMagnitudePlotter.clear();\n    \n    %TODO add ability to plot \"big\" events\n\n    \n    methods\n        function obj=TimeMagnitudePlotter()\n            obj@TimeSomethingPlotter('Magnitude','');\n        end\n        \n        function pl=plot(obj,ax,catalog,bigcat)\n            % plot plot a time-mag series for this catalog, with symbol sizes representing\n            % event size\n            % pl = plot(catalog)\n            %\n            if ~exist('ax','var') || isempty(ax)\n                % ax = findobj('Tag','time_mag_axis');\n                f=figure('Name','Time-Magnitude Plot','NumberTitle','off', ...\n                    'Tag',obj.Tags.Figure);\n                addAboutMenuItem();\n                obj.ax=axes(f);\n            else\n                obj.ax=ax;\n            end\n            if isempty(obj.ax.Tag)\n                obj.ax.Tag=obj.Tags.Axes;\n            end\n            \n            obj.ax.Visible = 'off';\n\n            % plotting from ZERO magnitude is arbitrary, and stemplot becomes unusable if all magnitudes\n            % are below zero. Therefore, make sure stems are always going up\n            minMag= min(catalog.Magnitude);\n            baseValue = min([0 , floor(minMag)]);\n            \n            \n            if obj.hasLotsOfEvents(catalog)\n                pl=obj.scatter(catalog);\n            else\n                pl=obj.stem(catalog, 'BaseValue', baseValue);\n            end\n            \n            obj.prepare_axes(catalog);\n            \n            if exist('bigcat','var')\n                obj.overlayBigEvents(bigcat);\n            end\n            obj.ax.Visible = 'on';\n        end\n        \n    end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/cgr_utils/TimeMagnitudePlotter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23666945851483082}}
{"text": "%%test network\ncam1_size=size(test_data_cam1);\ncam2_size=size(test_data_cam2);\ncam1_feature1=[];\ncam1_feature2=[];\ncam1_feature3=[];\ncam1_score=[];\ntest_batch_data=zeros(224,224,3,param.test_batch_size,'single');\nfor m=0:floor(cam1_size(1)/param.test_batch_size)-1\n    for n=1:param.test_batch_size\n        im_data=imresize((reshape(single(test_data_cam1(m*param.test_batch_size+n,:)),128,64,3)),[224 224]);\n        im_data=im_data(:,:,[3,2,1]);\n        im_data=permute(im_data,[2,1,3]);\n        test_batch_data(:,:,:,n)=im_data;\n        test_batch_data(:,:,1,n)=test_batch_data(:,:,1,n)-104;\n        test_batch_data(:,:,2,n)=test_batch_data(:,:,2,n)-117;\n        test_batch_data(:,:,3,n)=test_batch_data(:,:,3,n)-123;\n    end\n    net.blobs('data').set_data(test_batch_data);\n    net.forward_prefilled;\n    cam1_feature1=[cam1_feature1;(squeeze(net.blobs('data1_p_1').get_data))'];\n    cam1_feature2=[cam1_feature2;(squeeze(net.blobs('data1_p_2').get_data))'];\n    cam1_feature3=[cam1_feature3;(squeeze(net.blobs('data1_p_3').get_data))'];\n    cam1_score=[cam1_score;(squeeze(net.blobs('sig').get_data))'];\nend\ntest_batch_data=zeros(224,224,3,param.test_batch_size,'single');\nfor m=(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size+1:cam1_size(1)\n        count=m-(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size;\n        im_data=imresize((reshape(single(test_data_cam1(m,:)),128,64,3)),[224 224]);\n        im_data=im_data(:,:,[3,2,1]);\n        im_data=permute(im_data,[2,1,3]);\n        test_batch_data(:,:,:,count)=im_data;\n        test_batch_data(:,:,1,count)=test_batch_data(:,:,1,count)-104;\n        test_batch_data(:,:,2,count)=test_batch_data(:,:,2,count)-117;\n        test_batch_data(:,:,3,count)=test_batch_data(:,:,3,count)-123;\nend\nnet.blobs('data').set_data(test_batch_data);\nnet.forward_prefilled;\nindex=cam1_size(1)-(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size;\nresult1=(squeeze(net.blobs('data1_p_1').get_data))';\nresult2=(squeeze(net.blobs('data1_p_2').get_data))';\nresult3=(squeeze(net.blobs('data1_p_3').get_data))';\nscore=(squeeze(net.blobs('sig').get_data))';\ncam1_feature1=[cam1_feature1;result1(1:index,:)];\ncam1_feature2=[cam1_feature2;result2(1:index,:)];\ncam1_feature3=[cam1_feature3;result3(1:index,:)];\ncam1_score=[cam1_score;score(1:index,:)];\nprob_feature=[];\nname_cam1={};\nfor m=1:param.train_person_num\n    test_label_index=find(label_test_cam1==(m+param.train_person_num));\n    a=bsxfun(@times,cam1_feature1(test_label_index,:),cam1_score(test_label_index,1));\n    b=bsxfun(@times,cam1_feature2(test_label_index,:),cam1_score(test_label_index,2));\n    c=bsxfun(@times,cam1_feature3(test_label_index,:),cam1_score(test_label_index,3));\n    prob_feature=[prob_feature;sum(a/sum(cam1_score(test_label_index,1))),sum(b/sum(cam1_score(test_label_index,2))),sum(c/sum(cam1_score(test_label_index,3)))];\n%     prob_feature=[prob_feature;sum(a/sum(cam1_score(test_label_index,1)))];\n%     prob_feature=[prob_feature;sum(b/sum(cam1_score(test_label_index,2)))];\n%     prob_feature=[prob_feature;sum(c/sum(cam1_score(test_label_index,3)))];\nname_cam1=[name_cam1,test_image_name_cam1{test_label_index(1)}];\nend\n%extract feature cam2\ncam2_feature1=[];\ncam2_feature2=[];\ncam2_feature3=[];\ncam2_score=[];\ntest_batch_data=zeros(224,224,3,param.test_batch_size,'single');\nfor m=0:floor(cam2_size(1)/param.test_batch_size)-1\n    for n=1:param.test_batch_size\n        im_data=imresize((reshape(single(test_data_cam2(m*param.test_batch_size+n,:)),128,64,3)),[224 224]);\n        im_data=im_data(:,:,[3,2,1]);\n        im_data=permute(im_data,[2,1,3]);\n        test_batch_data(:,:,:,n)=im_data;\n        test_batch_data(:,:,1,n)=test_batch_data(:,:,1,n)-104;\n        test_batch_data(:,:,2,n)=test_batch_data(:,:,2,n)-117;\n        test_batch_data(:,:,3,n)=test_batch_data(:,:,3,n)-123;\n    end\n    net.blobs('data').set_data(test_batch_data);\n    net.forward_prefilled;\n    cam2_feature1=[cam2_feature1;(squeeze(net.blobs('data1_p_1').get_data))'];\n    cam2_feature2=[cam2_feature2;(squeeze(net.blobs('data1_p_2').get_data))'];\n    cam2_feature3=[cam2_feature3;(squeeze(net.blobs('data1_p_3').get_data))'];\n    cam2_score=[cam2_score;(squeeze(net.blobs('sig').get_data))'];\nend\ntest_batch_data=zeros(224,224,3,param.test_batch_size,'single');\nfor m=(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size+1:cam2_size(1)\n        count=m-(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size;\n        im_data=imresize((reshape(single(test_data_cam2(m,:)),128,64,3)),[224 224]);\n        im_data=im_data(:,:,[3,2,1]);\n        im_data=permute(im_data,[2,1,3]);\n        test_batch_data(:,:,:,count)=im_data;\n        test_batch_data(:,:,1,count)=test_batch_data(:,:,1,count)-104;\n        test_batch_data(:,:,2,count)=test_batch_data(:,:,2,count)-117;\n        test_batch_data(:,:,3,count)=test_batch_data(:,:,3,count)-123;\nend\nnet.blobs('data').set_data(test_batch_data);\nnet.forward_prefilled;\nindex=cam2_size(1)-(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size;\nresult1=(squeeze(net.blobs('data1_p_1').get_data))';\nresult2=(squeeze(net.blobs('data1_p_2').get_data))';\nresult3=(squeeze(net.blobs('data1_p_3').get_data))';\nscore=(squeeze(net.blobs('sig').get_data))';\ncam2_feature1=[cam2_feature1;result1(1:index,:)];\ncam2_feature2=[cam2_feature2;result2(1:index,:)];\ncam2_feature3=[cam2_feature3;result3(1:index,:)];\ncam2_score=[cam2_score;score(1:index,:)];\ngallery_feature=[];\nname_cam2={};\nfor m=1:param.train_person_num\n    test_label_index=find(label_test_cam2==(m+param.train_person_num));\n    a=bsxfun(@times,cam2_feature1(test_label_index,:),cam2_score(test_label_index,1));\n    b=bsxfun(@times,cam2_feature2(test_label_index,:),cam2_score(test_label_index,2));\n    c=bsxfun(@times,cam2_feature3(test_label_index,:),cam2_score(test_label_index,3));\n    gallery_feature=[gallery_feature;sum(a/sum(cam2_score(test_label_index,1))),sum(b/sum(cam2_score(test_label_index,2))),sum(c/sum(cam2_score(test_label_index,3)))];\n%     gallery_feature=[gallery_feature;sum(a/sum(cam2_score(test_label_index,1)))];\n%     gallery_feature=[gallery_feature;sum(b/sum(cam2_score(test_label_index,2)))];\n%     gallery_feature=[gallery_feature;sum(c/sum(cam2_score(test_label_index,3)))];\nname_cam2=[name_cam2,test_image_name_cam2(test_label_index(1))];\nend\n% cal cmc\nprob_norm=bsxfun(@rdivide,prob_feature,sum(abs(prob_feature).^2,2).^(1/2));\ngallery_norm=bsxfun(@rdivide,gallery_feature,sum(abs(gallery_feature).^2,2).^(1/2));\n% [~,it]=sort(prob_norm*gallery_norm',2,'descend');\nscore_matrix=prob_norm*gallery_norm';\nrank1_hit=0;\nrank5_hit=0;\nrank10_hit=0;\nrank20_hit=0;\nproblen=size(prob_feature,1);\nfor m=1:problen\n    [~,location]=sort(score_matrix(m,:),2,'descend');\n    if find(location(1)==m)\n        rank1_hit=rank1_hit+1;\n    end\n    if find(location(1:5)==m)\n        rank5_hit=rank5_hit+1;\n    end\n    if find(location(1:10)==m)\n        rank10_hit=rank10_hit+1;\n    end\n    if find(location(1:20)==m)\n        rank20_hit=rank20_hit+1;\n    end\nend\nrank_acc=[rank1_hit/problen,rank5_hit/problen,rank10_hit/problen,rank20_hit/problen];\nfin=fopen(param.result_save_file,'a');\nfprintf(fin,'2below split_index:%d,iter:%d, rank1:%f,rank5:%f,rank10:%f,rank20:%f\\n',split_index,iter,rank_acc(1),rank_acc(2),rank_acc(3),rank_acc(4));\nfprintf('split_index:%d,iter:%d, rank1:%f,rank5:%f,rank10:%f,rank20:%f\\n',split_index,iter,rank_acc(1),rank_acc(2),rank_acc(3),rank_acc(4));\nfclose(fin);", "meta": {"author": "liuyuisanai", "repo": "Quality-Aware-Network", "sha": "c1b3dadf5503938782f3c9b4560ec425a597dddb", "save_path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network", "path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network/Quality-Aware-Network-c1b3dadf5503938782f3c9b4560ec425a597dddb/train_PQAN/test_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23638734062146222}}
{"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% function [Tc,dT] = nnInterMex(T,omega,x,varargin)\n%\n% This wrapper runs a CPP file which codes the same scheme as nnInter\n% but is hopefully faster, see nnInter for details\n%==============================================================================\n\nfunction [Tc,dT] = nnInterMex(T,omega,x,varargin)\n\nTc = mfilename('fullpath'); dT = [];\nif nargin == 0\n  testOneImgModel(mfilename);\n    return\nelseif nargin == 1 && isempty(T)\n    return\nend\n\n% flag for computing the derivative\ndoDerivative = (nargout>1);\nmatrixFree   = 0;\nboundary     = 0; % boundary condition (0: zero padding; 1: replicate)\n\nfor k=1:2:length(varargin) % overwrite default parameter\n    eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend\n\ndim = length(omega)/2;\nm   = size(T);         if dim == 1, m = numel(T); end;\nn   = length(x)/dim;\n\n% call CPP subroutine\ntry\n    Tc = nnInterMexC(double(T(:)),omega,m,x(:),boundary==1);\ncatch err\n    FAIRerror(err);\nend\nif doDerivative\n    if matrixFree, dT = zeros(n,dim); else dT = sparse(n,dim*n); end\nend\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/imgModels/nnInterMex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23638273791976902}}
{"text": "function [data,interface,options,idata] = loadData(fname,type,varargin)\n% import PoleFigure, EBSD, and ODF data\n%\n% Description\n% *loadData* is a low level method for importing EBSD, PoleFigure, ODF and\n% Tensor data from external files. It autodetects the format of the file.\n% As parameters the method requires a filename and the crystal and specimen\n% @symmetry. \n%\n% Input\n%  fname     - filename\n%  cs, ss    - crystal, specimen @symmetry (optional)\n%\n% Options\n%  interface  - specific interface to be used\n%  comment    - comment to be associated with the data\n%\n% Output\n%  data - @EBSD, @PoleFigure, @SO3Fun, @tensor, @vector3d, @orientation\n%\n% See also\n% ImportEBSDData EBSD/calcODF ebsd_demo loadEBSD_generic\n\n% process input arguments\n\n% get file names\nif nargin < 1\n  [fname,PathName] = uigetfile( '*.*',...\n    'Select Data files');\n  fname = [PathName,fname];\nend\n\n% read in directory if needed\nif ischar(fname)\n  if exist(fname,'dir')\n    pname = fname;\n  else\n    pname = fileparts(fname);\n  end\n  files = dir(fname);\n  files = files(~[files.isdir]);\n  assert(~isempty(files),'No file found!');\n  if ~isempty(pname) && pname(end)~=filesep, pname = [pname,filesep];end\n  fname = strcat(pname,{files.name});\nend\n\n% get crystal directions\nif ~isempty(varargin) && checkClass(varargin{1},'Miller')\n  h = vec2cell(varargin{1});\n  varargin = varargin(2:end);\nend\n\n% get crystal and specimen symmetry\nposCS = find(cellfun(@(x) checkClass(x,'symmetry'),varargin),2);\n\nsym = {};\nif ~isempty(posCS)\n  cs = varargin{posCS(1)};\n  if strcmpi(type,'ODF')\n    sym = {'cs',cs};\n    clear cs;\n  end\n  \nend\n\nif numel(posCS) ==2\n  ss = varargin{posCS(2)};\n  if strcmpi(type,'ODF')\n    sym = [sym,'ss',{ss}];\n    clear ss;\n  end\nend\n\nvarargin(posCS) = [];\n\n% ---------- determine interface ---------------------------\n\nif ~check_option(varargin,'interface')\n  [interface,options] = check_interfaces(fname{1},type,varargin{:});\nelse\n  interface = get_option(varargin,'interface');\n  options = delete_option(varargin,'interface',1);\nend\n\nif isempty(interface), return; end\n\n% --------------- import data ---------------------------------\n\n% determine superposition - PoleFigure only\nc = get_option(options,'superposition');\nif isa(c,'double'), c = {c};end\n\nif numel(fname) <= 3\n  InfoLevel = 1;\nelse\n  InfoLevel = 0;\n  hw = waitbar(0,'Loading data files.');\nend\n\nfor k = 1:numel(fname)\n  if exist('hw','var')\n    [~,fn,ext] = fileparts(fname{k});\n    waitbar(k/numel(fname),hw,['Loading data file ',[fn ext]]);\n  end\n  \n  data{k} = feval(['load' type '_',char(interface)],...\n    fname{k},options{:},sym{:},'InfoLevel',InfoLevel);  \nend\nif exist('hw','var'), close(hw);end\n\nidata = cellfun('prodofsize',data);\n\n% ------------- apply options ----------------------------------\n\nif length(data) == 1 && iscell(data{1}), data = data{1}; end\n\n% set file name\nfor i = 1:numel(data)\n  data{i} = data{i}.setOption('file_name',ls(fname{min(i,length(fname))}));\nend\n\nif strcmpi(type,'EBSD') && check_option(varargin,'3d')\n  Z = get_option(varargin,'3d',1:numel(data),'double');\n  for k=1:numel(data)\n    data{k}.z = repmat(Z(k),length(data{k}),1);\n  end\n  data = [data{:}];\n  data.unitCell = calcUnitCell([data.x(:),data.y(:),data.z(:)],varargin{:});\nend\n\n% set crystal and specimen symmetry, specimen direction\nif ~any(strcmpi(type,{'tensor','vector3d','ODF'}))\n  if iscell(data)\n    data = cellfun(@(d,f) setOption(d,'file_name',strtrim(ls(f))),data,fname,'UniformOutput',false);\n    data = [data{:}];\n  end\n    \n  if exist('cs','var'), data.CS = cs;end\n  if exist('ss','var') && ~isa(data,'EBSD'), data.SS = ss;end % TODO\n  if exist('h','var'),  data = set(data,'h',h);end\n  if ~isempty_cell(c),  data = set(data,'c',c);end\nelseif ~any(strcmpi(type,{'ODF'}))\n  data = [data{:}];\n  \n  if exist('cs','var')\n    if iscell(data)\n      for i = 1:numel(data), data{i}.CS = cs; end\n    else\n      data.CS = cs;\n    end\n    if exist('ss','var')\n      if iscell(data)\n        for i = 1:numel(data), data{i}.SS = ss; end\n      else\n        data.SS = ss;\n      end\n    end\n  end\n  \nend\n\n% rotate data\nif check_option(varargin,'rotate')\n  data = rotate(data,axis2quat(zvector,get_option(varargin,'rotate')));\nend\n\n% --------------------------------------------------------------\nfunction v = checkClass(var,className)\n\nif iscell(var) && ~isempty(var)\n  v = any(cellfun('isclass',var,className));\nelse\n  v = isa(var,className);\nend\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/interfaces/loadData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23638273164247678}}
{"text": "function [obj] = ft_convert_units(obj, target, varargin)\n\n% FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit.\n% The units of the input object is determined from the structure field\n% object.unit, or is estimated based on the spatial extend of the structure,\n% e.g. a volume conduction model of the head should be approximately 20 cm large.\n%\n% Use as\n%   [object] = ft_convert_units(object, target)\n%\n% The following geometrical objects are supported as inputs\n%   electrode or gradiometer array, see FT_DATATYPE_SENS\n%   volume conductor, see FT_DATATYPE_HEADMODEL\n%   anatomical mri, see FT_DATATYPE_VOLUME\n%   segmented mri, see FT_DATATYPE_SEGMENTATION\n%   dipole grid definition, see FT_DATATYPE_SOURCE\n%\n% Possible target units are 'm', 'dm', 'cm ' or 'mm'. If no target units\n% are specified, this function will only determine the native geometrical\n% units of the object.\n%\n% See also FT_DETERMINE_UNITS, FT_CONVERT_COORDSYS, FT_DETERMINE_COODSYS\n\n% Copyright (C) 2005-2016, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% This function consists of three parts:\n%   1) determine the input units\n%   2) determine the requested scaling factor to obtain the output units\n%   3) try to apply the scaling to the known geometrical elements in the input object\n\n\n% the \"target\" input argument has been made required in Aug 2017\n% prior to that it was also possible to use this function to estimate units\n% the backward compatibility support can be removed in Aug 2018\nif nargin<2\n  ft_warning('calling this function only to determine units is deprecated, please use FT_DETERMINE_UNITS instead');\n  obj = ft_determine_units(obj);\n  return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% parse input options\nfeedback = ft_getopt(varargin, 'feedback', false);\n\nif isstruct(obj) && numel(obj)>1\n  % deal with a structure array\n  for i=1:numel(obj)\n    tmp(i) = ft_convert_units(obj(i), target, varargin{:});\n  end\n  obj = tmp;\n  return\nelseif iscell(obj) && numel(obj)>1\n  % deal with a cell-array\n  % this might represent combined EEG, ECoG and/or MEG\n  for i=1:numel(obj)\n    obj{i} = ft_convert_units(obj{i}, target, varargin{:});\n  end\n  return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% determine the units of the input object\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nobj = ft_determine_units(obj);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute the scaling factor from the input units to the desired ones\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isequal(obj.unit, target)\n  % there is nothing to do\n  return\nend\n\nif istrue(feedback)\n  % give some information about the conversion\n  fprintf('converting units from ''%s'' to ''%s''\\n', obj.unit, target)\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% apply the scaling factor\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nscale = ft_scalingfactor(obj.unit, target);\n\n% volume conductor model\nif isfield(obj, 'r'), obj.r = scale * obj.r; end\nif isfield(obj, 'o'), obj.o = scale * obj.o; end\nif isfield(obj, 'bnd') && isfield(obj.bnd, 'pnt')\n  for i=1:length(obj.bnd)\n    obj.bnd(i).pnt = scale * obj.bnd(i).pnt;\n  end\nend\nif isfield(obj, 'bnd') && isfield(obj.bnd, 'pos')\n  for i=1:length(obj.bnd)\n    obj.bnd(i).pos = scale * obj.bnd(i).pos;\n  end\nend\n\n% old-fashioned gradiometer array\nif isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end\nif isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end\nif isfield(obj, 'prj'),  obj.prj  = scale * obj.prj;  end\n\n% gradiometer array, electrode array, head shape or dipole grid\nif isfield(obj, 'pnt'),        obj.pnt        = scale * obj.pnt;        end\nif isfield(obj, 'pos'),        obj.pos        = scale * obj.pos;        end\nif isfield(obj, 'chanpos'),    obj.chanpos    = scale * obj.chanpos;    end\nif isfield(obj, 'chanposorg'), obj.chanposold = scale * obj.chanposorg; end % pre-2016 version\nif isfield(obj, 'chanposold'), obj.chanposold = scale * obj.chanposold; end % 2016 version and later\nif isfield(obj, 'coilpos'),    obj.coilpos    = scale * obj.coilpos;    end\nif isfield(obj, 'elecpos'),    obj.elecpos    = scale * obj.elecpos;    end\n\n% gradiometer array that combines multiple coils in one channel\nif isfield(obj, 'tra') && isfield(obj, 'chanunit')\n  % find the gradiometer channels that are expressed as unit of field strength divided by unit of distance, e.g. T/cm\n  for i=1:length(obj.chanunit)\n    tok = tokenize(obj.chanunit{i}, '/');\n    if ~isempty(regexp(obj.chanunit{i}, 'm$', 'once'))\n      % assume that it is T/m or so\n      obj.tra(i,:)    = obj.tra(i,:) / scale;\n      obj.chanunit{i} = [tok{1} '/' target];\n    elseif ~isempty(regexp(obj.chanunit{i}, '[T|V]$', 'once'))\n      % assume that it is T or V, don't do anything\n    elseif strcmp(obj.chanunit{i}, 'unknown')\n      % assume that it is T or V, don't do anything\n    elseif strcmp(obj.chanunit{i}, 'snr')\n      %\n    else\n      ft_error('unexpected units %s', obj.chanunit{i});\n    end\n  end % for\nend % if\n\n% fiducials\nif isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end\nif isfield(obj, 'fid') && isfield(obj.fid, 'pos'), obj.fid.pos = scale * obj.fid.pos; end\n\n% dipole grid\nif isfield(obj, 'resolution'), obj.resolution = scale * obj.resolution; end\n\n% x,y,zgrid can also be 'auto'\nif isfield(obj, 'xgrid') && ~ischar(obj.xgrid), obj.xgrid = scale * obj.xgrid; end\nif isfield(obj, 'ygrid') && ~ischar(obj.ygrid), obj.ygrid = scale * obj.ygrid; end\nif isfield(obj, 'zgrid') && ~ischar(obj.zgrid), obj.zgrid = scale * obj.zgrid; end\n\n% anatomical MRI or functional volume\nif isfield(obj, 'transform')\n  H = diag([scale scale scale 1]);\n  obj.transform = H * obj.transform;\nend\n\nif isfield(obj, 'transformorig')\n  H = diag([scale scale scale 1]);\n  obj.transformorig = H * obj.transformorig;\nend\n\n% remove initial and params structure if they exist\nif isfield(obj, 'initial') && ~strcmp(target, 'mm')\n  obj = rmfield(obj, 'initial');\n  ft_warning('Removing field \"initial\" because potential transformations of normalised volumes only work if geometrical values are expressed in \"mm\"');\nend\n\nif isfield(obj, 'params') && ~strcmp(target, 'mm')\n  ft_warning('Removing field \"params\" because potential transformations of normalised volumes only work if geometrical values are expressed in \"mm\"');\n  obj = rmfield(obj, 'params');\nend\n\n% sourcemodel obtained through mne also has a orig-field with the high\n% number of vertices\nif isfield(obj, 'orig')\n  if isfield(obj.orig, 'pnt')\n    obj.orig.pnt = scale * obj.orig.pnt;\n  end\n  if isfield(obj.orig, 'pos')\n    obj.orig.pos = scale * obj.orig.pos;\n  end\nend\n\n% remember the unit\nobj.unit = target;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/forward/ft_convert_units.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23638273164247672}}
{"text": "function [taskReport, essentialGenes, taskStructure]=checkTasksGenes(model,inputFile,printOutput,printOnlyFailed,getEssential,taskStructure)\n% checkTasksGenes\n%   Performs a set of simulations as defined in a task file. This function\n%   is identical to \"checkTasks\", except it allows for the determination of\n%   essential genes, rather than essential reactions.\n%\n%   model           a model structure\n%   inputFile       a task list in Excel format. See the function\n%                   parseTaskList for details (opt if taskStructure is\n%                   supplied)\n%   printOutput     true if the results of the test should be displayed\n%                   (opt, default true)\n%   printOnlyFailed true if only tasks that failed should be displayed\n%                   (opt, default false)\n%   getEssential    true if the essential genes should be calculated for\n%                   all the tasks. (opt, default false)\n%   taskStructure   structure with the tasks, as from parseTaskList. If\n%                   this is supplied then inputFile is ignored (opt)\n%\n%   taskReport          structure with the results\n%       id              cell array with the id of the task\n%       description     cell array with the description of the task\n%       ok              boolean array with true if the task was successful\n%   essentialGenes      MxN matrix with the essential genes (M) for each\n%                       task (N). An element is true if the corresponding\n%                       gene is essential in the corresponding task.\n%                       Failed tasks and SHOULD FAIL tasks are ignored.\n%                       If getEssential is false, then essentialRxns will \n%                       be returned as: false(nGenes,nTasks).\n%   taskStructure       structure with the tasks, as from parseTaskList\n%\n%   This function is used for defining a set of tasks for a model to\n%   perform. The tasks are defined by defining constraints on the model,\n%   and if the problem is feasible, then the task is considered successful.\n%   In general, each row can contain one constraint on uptakes, one\n%   constraint on outputs, one new equation, and one change of reaction\n%   bounds. If more bounds are needed to define the task, then several rows\n%   can be used for each task.\n%\n%   Usage: [taskReport, essentialGenes, taskStructure]=checkTasksGenes(model,inputFile,...\n%           printOutput,printOnlyFailed,getEssential,taskStructure)\n%\n\n\nif nargin<3 || isempty(printOutput)\n    printOutput=true;\nend\nif nargin<4 || isempty(printOnlyFailed)\n    printOnlyFailed=false;\nend\nif nargin<5 || isempty(getEssential)\n    getEssential=false;\nend\n\n%Prepare the input model\nmodel.b=zeros(numel(model.mets),2);\n\nmodelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));\nif ~isfield(model,'unconstrained')\n    EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';\n    dispEM(EM,false);\nend\n\n%Parse the task file\nif nargin<6\n    taskStructure=parseTaskList(inputFile);\nend\n\nessentialGenes=false(numel(model.genes),numel(taskStructure));\n\ntModel=model;\ntaskReport=[];\nfor i=1:numel(taskStructure)\n    taskReport.id{i,1}=taskStructure(i).id;\n    taskReport.description{i,1}=taskStructure(i).description;\n    %Set the inputs\n    if ~isempty(taskStructure(i).inputs)\n        [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);\n        J=J(I); %Only keep the ones with matches\n        K=ismember(upper(taskStructure(i).inputs),'ALLMETS');\n        L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));\n        %Check that all metabolites are either real metabolites or\n        %ALLMETS/ALLMETSIN\n        if ~all(I|K|L)\n            fprintf(['ERROR: Could not find all inputs in \"[' taskStructure(i).id '] ' taskStructure(i).description '\"\\n']);\n            taskReport.ok(i,1)=false;\n            tModel=model;\n            continue;\n        end\n        if numel(J)~=numel(unique(J))\n            EM=['The constraints on some input(s) in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" are defined more than one time'];\n            dispEM(EM);\n        end\n        %If all metabolites should be added\n        if any(K)\n            %Check if ALLMETS is the first metabolite. Otherwise print a\n            %warning since it will write over any other constraints that\n            %are set\n            if K(1)==0\n                EM=['ALLMETS is used as an input in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];\n                dispEM(EM,false);\n            end\n            %Use the first match of ALLMETS. There should only be one, but\n            %still..\n            tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;\n        end\n        %If metabolites in a specific compartment should be used\n        if any(L)\n            L=find(L);\n            for j=1:numel(L)\n                %The compartment defined\n                compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));\n                %Check if it exists in the model\n                C=find(ismember(upper(model.comps),compartment));\n                if any(C)\n                    %Match to metabolites\n                    tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;\n                else\n                    EM=['The compartment defined for ALLMETSIN in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" does not exist'];\n                    dispEM(EM);\n                end\n            end\n        end\n        %Then add the normal constraints\n        if any(J)\n            tModel.b(J,1)=taskStructure(i).UBin(I)*-1;\n            tModel.b(J,2)=taskStructure(i).LBin(I)*-1;\n        end\n    end\n    %Set the outputs\n    if ~isempty(taskStructure(i).outputs)\n        [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);\n        J=J(I); %Only keep the ones with matches\n        K=ismember(upper(taskStructure(i).outputs),'ALLMETS');\n        L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));\n        %Check that all metabolites are either real metabolites or\n        %ALLMETS/ALLMETSIN\n        if ~all(I|K|L)\n            fprintf(['ERROR: Could not find all outputs in \"[' taskStructure(i).id '] ' taskStructure(i).description '\"\\n']);\n            taskReport.ok(i,1)=false;\n            tModel=model;\n            continue;\n        end\n        if numel(J)~=numel(unique(J))\n            EM=['The constraints on some output(s) in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" are defined more than one time'];\n            dispEM(EM);\n        end\n        %If all metabolites should be added\n        if any(K)\n            %Check if ALLMETS is the first metabolite. Otherwise print a\n            %warning since it will write over any other constraints that\n            %are set\n            if K(1)==0\n                EM=['ALLMETS is used as an output in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];\n                dispEM(EM,false);\n            end\n            %Use the first match of ALLMETS. There should only be one, but\n            %still..\n            tModel.b(:,2)=taskStructure(i).UBout(find(K,1));\n        end\n        %If metabolites in a specific compartment should be used\n        if any(L)\n            L=find(L);\n            for j=1:numel(L)\n                %The compartment defined\n                compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));\n                %Check if it exists in the model\n                C=find(ismember(upper(model.comps),compartment));\n                if any(C)\n                    %Match to metabolites\n                    tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));\n                else\n                    EM=['The compartment defined for ALLMETSIN in \"[' taskStructure(i).id '] ' taskStructure(i).description '\" does not exist'];\n                    dispEM(EM);\n                end\n            end\n        end\n        %Then add the normal constraints\n        if any(J)\n            tModel.b(J,1)=taskStructure(i).LBout(I);\n            tModel.b(J,2)=taskStructure(i).UBout(I);\n        end\n    end\n    %Add new rxns\n    if ~isempty(taskStructure(i).equations)\n        rxn.equations=taskStructure(i).equations;\n        rxn.lb=taskStructure(i).LBequ;\n        rxn.ub=taskStructure(i).UBequ;\n        rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));\n        %Allow for new metabolites to be added. This is because it should\n        %be possible to add, say, a whole new pathway\n        tModel=addRxns(tModel,rxn,3,[],true);\n    end\n    %Add changed bounds\n    if ~isempty(taskStructure(i).changed)\n        tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);\n        tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);\n    end\n    \n    %Solve and print\n    sol=solveLP(tModel);\n    if ~isempty(sol.x)\n        if ~taskStructure(i).shouldFail\n            taskReport.ok(i,1)=true;\n            if printOnlyFailed==false && printOutput==true\n                fprintf(['PASS: [' taskStructure(i).id '] ' taskStructure(i).description '\\n']);\n            end\n            %Calculate the essential reactions\n            if getEssential==true\n                if ~isfield(tModel,'rules')\n                    % the getEssentialGenes function requires the model to\n                    % have a \"rules\" field\n                    tModel = generateRules(tModel);\n                end\n                [~, taskEssential]=getEssentialGenes(tModel);\n                essentialGenes(taskEssential,i)=true;\n            end\n        else\n            taskReport.ok(i,1)=false;\n            if printOutput==true\n                fprintf(['PASS (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\\n']);\n            end\n        end\n    else\n        if ~taskStructure(i).shouldFail\n            taskReport.ok(i,1)=false;\n            if printOutput==true\n                fprintf(['FAIL: [' taskStructure(i).id '] ' taskStructure(i).description '\\n']);\n            end\n        else\n            taskReport.ok(i,1)=true;\n            if printOnlyFailed==false && printOutput==true\n                fprintf(['FAIL (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\\n']);\n            end\n        end\n    end\n    if taskStructure(i).printFluxes && ~isempty(sol.x)\n        sol=solveLP(tModel,1);\n        if ~isempty(sol.x)\n            printFluxes(tModel,sol.x,false,10^-6,[],'%rxnID (%eqn):%flux\\n');\n            fprintf('\\n');\n        end\n    end\n    tModel=model;\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "Human-GEM", "sha": "0b1bd42adaa2e1d7ac52ee83b989fad8a695759d", "save_path": "github-repos/MATLAB/SysBioChalmers-Human-GEM", "path": "github-repos/MATLAB/SysBioChalmers-Human-GEM/Human-GEM-0b1bd42adaa2e1d7ac52ee83b989fad8a695759d/code/tINIT/checkTasksGenes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853784694359}}
{"text": "function [FV] = mesh_bet2matlab(fileprefix)\n\n% mesh_bet2matlab - Read FSL BET tesselation (.coo/.dat)\n% \n% USEAGE: [FV] = mesh_bet2matlab(fileprefix)\n% \n% This function will load ascii files created by the FSL\n% BET function, see http://www.fmrib.ox.ac.uk/fsl\n% \n% When used with the -x option, the FSL BET function can \n% output the tesselation of the brain surface (ie, only \n% a fairly smooth, non-detailed, surface), eg:\n% \n% bet T1 T1_brain -x\n% \n% The brain tesselation is output into two files, eg:\n% \n%   T1_brain.coo\n%   T1_brain.dat\n% \n% The T1_brain.coo file contains the co-ordinates of the\n% vertices, and the .dat file contains the details of \n% the links between vertices (each line corresponds to \n% each vertex in the .coo file, and the 1's correspond \n% to which other vertices they are connected to).\n% \n% The returned FV struct contains the 'vertices' and\n% 'faces' matrices, which can be input to the patch \n% command, eg:\n% \n% Hpatch = patch('Vertices',FV.vertices,'Faces',FV.faces,...\n%                'EdgeColor',[.8 .8 .8],...\n%                'FaceColor',[0.9 0.9 0.9]);\n% \n% This will plot the mesh as a patch object.  See the patch \n% command and matlab help for more information on coloring \n% this object.\n% \n% See also: mesh_freesurfer2matlab\n% \n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  03/02 Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~exist('fileprefix','var'),\n    error('No input fileprefix');\nend\n\nif findstr('.coo',fileprefix),\n    fprintf('MESH_BET2MATLAB: Removing .coo extension from ''%s''\\n',fileprefix);\n    fileprefix = strrep(fileprefix,'.coo','');\nend\nif findstr('.dat',fileprefix),\n    fprintf('MESH_BET2MATLAB: Removing .dat extension from ''%s''\\n',fileprefix);\n    fileprefix = strrep(fileprefix,'.dat','');\nend\n\nFV.vertices = readCOO(fileprefix);\n\nNvertices   = size(FV.vertices,1);\n\nedgematrix  = readDAT(fileprefix,Nvertices);\n\nFV.faces    = edge2face(FV.vertices,edgematrix);\n\nreturn\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction faces = edge2face(vertices,edgematrix)\n    \n    Nvertices = size(vertices,1);\n    \n    plot3(vertices(:,1),vertices(:,2),vertices(:,3),'b.'), hold on\n    \n    for i = 1:Nvertices,\n        \n        % Get current vertex XYZ coordinates\n        v  = vertices(i,:);\n        \n        plot3(v(:,1),v(:,2),v(:,3),'go');\n        \n        % Get neighbouring vertex XYZ coordinates\n        vn = vertices(find(edgematrix(i,:)),:);\n        \n        plot3(vn(:,1),vn(:,2),vn(:,3),'ro');\n        \n        \n        faces = tri([v;vn]);\n        \n        \n        \n        \n        return\n        \n        \n        \n        \n        \n    end\n    \n    faces = [];\n    \nreturn\n\n\nfunction faces = tri(V)\n    \n    % Must identify angle of rotation from\n    % central vertex, V(1,:), to all other vertices\n    % in a counterclockwise direction\n    \n    % First translate all vertices to an origin\n    % given by the central vertex\n    Vo = V - repmat(V(1,:),size(V,1),1);\n    \n    % Find direction cosines for line from centre to vertex\n    d = zeros(size(Vo,1),1);\n    l = zeros(size(Vo,1),1);\n    m = zeros(size(Vo,1),1);\n    n = zeros(size(Vo,1),1);\n    \n    for i = 1:length(Vo),\n        \n        x = Vo(i,1);  y = Vo(i,2);  z = Vo(i,3);\n        \n        d(i) = sqrt( (x)^2 + (y)^2 + (z)^2 );\n        \n        if d(i) > 0,\n            l(i) = x/d(i); % cos alpha\n            m(i) = y/d(i); % cos beta\n            n(i) = z/d(i); % cos gamma\n        end\n    end\n    \n    \n    faces = [];\n    \n    \n    %hold off\n    %plot3(Vo(:,1),Vo(:,2),Vo(:,3),'b.'), view(2), hold on\n    \n    \nreturn\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction vertices = readCOO(fileprefix)\n\t\n\t[path,name,ext] = fileparts(strcat(fileprefix,'.coo'));\n\tfile = fullfile(path,[name ext]);\n\t\n\tfid = fopen(file,'r');\n\t\n\tif isequal(fid,-1),\n        S=sprintf('Could not open file: \"%s\"',file);\n        error(S);\n\telse\n        fprintf('...Reading BET vertices...');\n        tic;\n        \n        % Read vertices\n        vertices = fscanf(fid,'%s%f%f%f',[4,inf]);\n        fclose(fid);\n        \n        % remove last row (all zeros) and translate\n        vertices = vertices(2:4,:)';\n        \n        t = toc;\n        fprintf('...done (%6.2f sec).\\n',t);\n\tend\n\nreturn\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction edgematrix = readDAT(fileprefix,Nvertices)\n\t\n\t[path,name,ext] = fileparts(strcat(fileprefix,'.dat'));\n\tfile = fullfile(path,[name ext]);\n\t\n\tfid = fopen(file,'r');\n\t\n\tif isequal(fid,-1),\n        S=sprintf('Could not open file: \"%s\"',file);\n        error(S);\n\telse\n        fprintf('...Reading BET edge matrix...');\n        tic;\n        \n        % Read faces\n        edgematrix = fscanf(fid,'%1d',[Nvertices,Nvertices]);\n        fclose(fid);\n        \n        t = toc;\n        fprintf('...done (%6.2f sec).\\n',t);\n\tend\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_bet2matlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853784694359}}
{"text": "function [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains2(markov_chains)\n% create_restrictions_and_markov_chains2 -- creates restrictions and\n% markov chains for the SVAR model in which Coefficients and variances have\n% different chains, different regimes, and different durations\n%\n% ::\n%\n%\n%   [lin_restr,nonlin_restr,tpl]=create_restrictions_and_markov_chains2(tpl)\n%\n% Args:\n%\n%    - **markov_chains** [empty|struct]: structure of previously defined\n%    markov chains\n%\n% Returns:\n%    :\n%\n%    - **lin_restr** [cell]: cell array of restrictions (see below).\n%\n%    - **nonlin_restr** [cell]: cell array of inequality restrictions\n%\n%    - **markov_chains** [struct]: modified markov chains\n%\n% Note:\n%\n%    - The syntax to construct a restriction\n%      --> ai(eqtn)\n%      --> ai(eqtn,vbl)\n%      --> ai(eqtn,vbl,chain_name,state)\n%      --> a(eqtn)\n%      --> a(eqtn,vbl)\n%      --> a(eqtn,vbl,chain_name,state)\n%      - **eqtn** [integer]: integer\n%      - **vbl** [integer|char]: integer or variable name\n%      - **i** [integer]: lag\n%      - **chain_name** [char]: name of the markov chain\n%      - **state** [integer]: state number\n%\n%    - The lag coefficients are labelled a0, a1, a2,...,ak, for a model with k\n%    lags. Obviously, a0 denotes the contemporaneous coefficients.\n%\n%    - The constant terms labelled c_1_1, c_2_2,...,c_n_n, for a model with n\n%    endogenous variables.\n%\n%    - The standard deviations labelled s_1_1, s_2_2,...,s_n_n, for a\n%    model with n endogenous variables.\n%\n% Example:\n%\n%    See also:\n\nif nargin==0||isempty(markov_chains)\n    \n    markov_chains=struct('name',{},...\n    'states_expected_duration',{},...\n    'controlled_parameters',{});\n    \nend\n\n% We borrow both the restrictions and the markov chains from the model in\n% which all coefficients across all equations switch in lockstep.\n%--------------------------------------------------------------------------\n[lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains1(markov_chains);\n\n% Then we add another chain controling all variances across all equations\n%-------------------------------------------------------------------------\n% We just make sure we do not change the restrictions\nlast=numel(markov_chains);\n\nmarkov_chains(last+1)=struct('name','syncvol',...\n    'states_expected_duration',[2+1i,2+1i,2+1i],...\n    'controlled_parameters',{{'s'}});\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/Tutorials/SVAR/+deprecated/create_restrictions_and_markov_chains2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853129793367}}
{"text": "function X = Yi2X(Y, i)\nif i == 3\n    X = shiftdim(Trans_Faces(Y),i+1);\nelseif i == 2\n    X = shiftdim(Trans_Faces(Y),i);\nelse\n    X = shiftdim(Trans_Faces(Y),i-1);\nend\nend\n   \n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/t-TNN/Yi2X.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.23622648944315855}}
{"text": "function [ cost, grad, numTotal, pred_cell ] = drdae_discrim_joint_kl_obj( ...\n    theta, eI, data_cell, targets_cell, mixture_spectrum, fprop_only, pred_out)\n% Copyright (c) 2014-present University of Illinois at Urbana-Champaign\n% All rights reserved.\n% \t\t\n% Developed by:     Po-Sen Huang, Paris Smaragdis\n%                   Department of Electrical and Computer Engineering\n%                   Department of Computer Science\n%\n% discrim. training + joint masking\n%\n%PRNN_OBJ MinFunc style objective for Deep Recurrent Denoising Autoencoder\n%   theta is the full parameter vector\n%   eI contains experiment / network architecture\n%   data_cell is a cell array of matrices. Each a distinct length is a cell\n%             entry. Each matrix has a time series example in each column\n%   targets_cell is parallel to data, but contains the labels for each time\n%   fprop_only is a flag that only computes the cost, no gradient\n%   numTotal is total number of frames evaluated\n%   pred_out is a binary flag for whether pred_cell is populated\n%            pred_cell only filled properly when utterances one per cell\n\n\n%% Debug: Turns this into an identity-function for debugging rest of system\nif isfield(eI, 'objReturnsIdentity') && eI.objReturnsIdentity\n    cost = 0; grad = 0; numTotal = 0;\n    for l = 1:numel(data_cell)\n        numUtterances = size(data_cell{l}, 2);\n        original_vector = reshape(data_cell{l}, eI.winSize*eI.featDim, []);\n        midPnt = ceil(eI.winSize/2);\n        original_vector = original_vector((midPnt-1)*14+1 : midPnt*14, :);\n        pred_cell{l} = reshape(original_vector, [], numUtterances);\n    end\n    return;\nend\n\n%if isempty(return_activation),\n  return_activation = 0;\n%end\n\n%% Load data from globals if not passed in (happens when run on RPC slave)\nglobal g_data_cell;\nglobal g_targets_cell;\nisSlave = false;\nif isempty(data_cell)\n    data_cell = g_data_cell;\n    targets_cell = g_targets_cell;\n    isSlave = true;\nend;\npred_cell = cell(1,numel(data_cell));\nact_cell = cell(1,numel(data_cell));\n%% default short circuits to false\nif ~isfield(eI, 'shortCircuit')\n    eI.shortCircuit = 0;\nend;\n\n%% default dropout to false\nif ~isfield(eI, 'dropout')\n  eI.dropout = 0;\nend;\n\n%% setup weights and accumulators\n[stack, W_t] = rnn_params2stack(theta, eI);\ncost = 0; numTotal = 0;\noutputDim = eI.layerSizes(end);\n\n%% setup structures to aggregate gradients\nstackGrad = cell(1,numel(eI.layerSizes));\n\nif isfield(eI, 'fullRNN') && eI.fullRNN==1\n   W_t_grad = cell(1,numel(eI.layerSizes)-1);\n    for l = 1:numel(eI.layerSizes)-1\n        W_t_grad{l}.W = zeros(size(W_t{l}.W));\n    end\nelse\n   W_t_grad = zeros(size(W_t));\nend\n\n\nfor l = 1:numel(eI.layerSizes)\n    stackGrad{l}.W = zeros(size(stack{l}.W));\n    stackGrad{l}.b = zeros(size(stack{l}.b));\nend\nif eI.shortCircuit\n    stackGrad{end}.W_ss = zeros(size(stack{end}.W_ss));\nend;\n%% check options\nif ~exist('fprop_only','var')\n    fprop_only = false;\nend;\nif ~exist('pred_out','var')\n    pred_out = false;\nend;\n\n% DROPOUT: vector of length of hidden layers with 0 or 1\n% (to drop or keep activation unit) with prob=0.5\nhActToDrop = cell(numel(eI.layerSizes),1);\nfor i=1:numel(eI.layerSizes)-1\n if eI.dropout\n   hActToDrop{i} = 1/eI.dropout * binornd(1,eI.dropout, eI.layerSizes(i),1);\n   %hActToDrop{i} = round(rand(eI.layerSizes(i),1));\n else\n   hActToDrop{i} = ones(eI.layerSizes(i),1);\n end\nend\n\n%% loop over each distinct length\nfor c = 1:numel(data_cell)\n    if isempty(data_cell{c}), continue; end\n\n    data = data_cell{c};\n    targets = {};\n    if ~isempty(targets_cell), targets = targets_cell{c}; end;\n    uttPred = [];\n    T =size(data,1) / eI.inputDim;\n    % store hidden unit activations at each time instant\n    hAct = cell(numel(eI.layerSizes)-1, T);\n    for t = 1:T\n        %% forward prop all hidden layers\n        for l = 1:numel(eI.layerSizes)-1\n            if l == 1\n                hAct{1,t} = stack{1}.W * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);\n            else\n                hAct{l,t} = stack{l}.W * hAct{l-1,t};\n            end;\n            hAct{l,t} = bsxfun(@plus, hAct{l,t}, stack{l}.b);\n            % temporal recurrence. limited to single layer for now\n            if t > 1\n                if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                    hAct{l,t} = hAct{l,t} + W_t{l}.W * hAct{l,t-1};\n                elseif l == eI.temporalLayer\n                    hAct{l,t} = hAct{l,t} + W_t * hAct{l,t-1};\n                end\n            end;\n\n            % nonlinearity\n            if strcmpi(eI.activationFn,'tanh')\n                hAct{l,t} = tanh(hAct{l,t});\n            elseif strcmpi(eI.activationFn,'logistic')\n                hAct{l,t} = 1./(1+exp(-hAct{l,t}));\n            elseif strcmpi(eI.activationFn,'RELU')\n                hAct{l,t} = max(0,hAct{l,t});\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n            %dropout (hActToDrop will be all ones if no dropout specified)\n            hAct{1,t} = bsxfun(@times, hAct{1,t}, hActToDrop{l});\n        end;\n        % forward prop top layer not done here to avoid caching it\n    end;\n    %% compute cost and backprop through time\n    if  eI.temporalLayer\n        if isfield(eI, 'fullRNN') && eI.fullRNN==1\n            delta_t = cell(1, numel(eI.layerSizes)-1);\n            for l = 1:numel(eI.layerSizes)-1\n                delta_t{l} = zeros(eI.layerSizes(l),size(data,2));\n            end\n        else\n            delta_t = zeros(eI.layerSizes(eI.temporalLayer),size(data,2));\n        end\n    end;\n\n    y1_dim= 1:outputDim/2;\n    y2_dim= outputDim/2+1:outputDim;\n    mixtures=mixture_spectrum{c};\n\n    for t = T:-1:1\n        l = numel(eI.layerSizes);\n        %% forward prop output layer for this timestep\n        curPred = bsxfun(@plus, stack{l}.W * hAct{l-1,t}, stack{l}.b);\n\n        if eI.outputnonlinear==1,\n           if strcmpi(eI.activationFn,'tanh')\n                curPred = tanh(curPred);\n           elseif strcmpi(eI.activationFn,'logistic')\n                curPred = 1./(1+exp(-curPred));\n           elseif strcmpi(eI.activationFn,'RELU')\n                curPred = max(0,curPred);\n           else\n                error('unrecognized activation function: %s',eI.activationFn);\n           end\n        end\n\n        mixture=mixtures((t-1)*numel(y1_dim)+1:t*numel(y1_dim),:);\n        a1 = curPred(y1_dim,:); a2 = curPred(y2_dim,:);\n\n        const=eI.const;%1e-8 ;\n        const2=eI.const2;% 1e-3;\n\n        if strcmp(eI.opt,'softlinear'),\n            y1= (a1)./((a1)+(a2)+1e-10).* mixture;\n            y2= (a2)./((a1)+(a2)+1e-10).* mixture;\n        elseif strcmp(eI.opt,'softabs'),\n            y1= abs(a1)./(abs(a1)+abs(a2)+1e-10).* mixture;\n            y2= abs(a2)./(abs(a1)+abs(a2)+1e-10).* mixture;\n        elseif strcmp(eI.opt,'softabs_const') || strcmp(eI.opt,'softabs_kl_const'),\n            y1= abs(a1)./(abs(a1)+abs(a2)+const).* mixture;\n            y2= abs(a2)./(abs(a1)+abs(a2)+const).* mixture;\n        elseif strcmp(eI.opt, 'softquad')\n            y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;\n            y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;\n        else\n        end\n        weighted_curPred=[y1; y2];\n\n        % add short circuit to regression prediction if model has it\n        if eI.shortCircuit\n            weighted_curPred = weighted_curPred + stack{end}.W_ss ...\n                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);\n        end;\n        if pred_out, uttPred = [weighted_curPred, uttPred]; end;\n        % skip loss computation if no targets given\n        if isempty(targets), continue; end;\n\n        curTargets = targets((t-1)*outputDim+1:t*outputDim, :);\n        curTargets_neg = [curTargets(outputDim/2+1:outputDim,:); curTargets(1:outputDim/2,:)];\n\n        y_t = (1- eI.r) * weighted_curPred + eI.r * curTargets_neg - curTargets;\n\n        ya_ta= y_t(y1_dim,:);\n        yb_tb= y_t(y2_dim,:);\n\n        if strcmp(eI.opt,'softlinear'),\n            delta_y1 =  (ya_ta-yb_tb).* y2./(a1+a2+1e-10);\n            delta_y2 = (-ya_ta+yb_tb) .* y1./ (a1+a2+1e-10);\n        elseif strcmp(eI.opt,'softabs'),\n            delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+1e-10);\n            delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+1e-10);\n\n            delta_y1(a1<0) = -delta_y1(a1<0);\n            delta_y2(a2<0) = -delta_y2(a2<0);\n        elseif strcmp(eI.opt,'softabs_const'),\n             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;\n             delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1+ ya_ta.* const_div;\n             delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2+ yb_tb.* const_div;\n\n             delta_y1(a1<0) =  -delta_y1(a1<0);\n             delta_y2(a2<0) =  -delta_y2(a2<0);\n        elseif strcmp(eI.opt,'softabs_kl_const'),\n             y_target_a = curTargets(y1_dim, :);\n             y_target_b = curTargets(y2_dim, :);\n             y_target_neg_a = y_target_b;\n             y_target_neg_b = y_target_a;\n\n             y_pred_a = weighted_curPred(y1_dim, :);\n             y_pred_b = weighted_curPred(y2_dim, :);\n\n             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;\n\n             delta_y1 =  (-y_target_a./(y_pred_a+const2) + y_target_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1+  (-y_target_a./(y_pred_a+const2)+1).* const_div;\n\n             delta_y2 =  (y_target_a./(y_pred_a+const2) - y_target_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2+ (-y_target_b./(y_pred_b+const2)+1) .* const_div;\n\n             % discrim part\n             delta_y1 =  delta_y1- eI.r* (-y_target_neg_a./(y_pred_a+const2) + y_target_neg_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1-   eI.r* (-y_target_neg_a./(y_pred_a+const2)+1).* const_div;\n\n             delta_y2 = delta_y2- eI.r*(y_target_neg_a./(y_pred_a+const2) - y_target_neg_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2-  eI.r*(-y_target_neg_b./(y_pred_b+const2)+1) .* const_div;\n\n             delta_y1(a1<0) =  -delta_y1(a1<0);\n             delta_y2(a2<0) =  -delta_y2(a2<0);\n        elseif strcmp(eI.opt, 'softquad')\n            delta_y1 =  (ya_ta-yb_tb).* (2*a1.*y2)./ (a1.^2+a2.^2+1e-10); %  y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;\n            delta_y2 =  (-ya_ta+yb_tb).* (2*a2.*y1)./ (a1.^2+a2.^2+1e-10);%         y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;\n        else\n        end\n\n        delta = [ delta_y1; delta_y2 ];\n        if strcmp(eI.opt,'softlinear') || strcmp(eI.opt,'softabs') || strcmp(eI.opt, 'softquad') || strcmp(eI.opt,'softabs_const'),\n             cost = cost + 0.5 * ( sum( sum((weighted_curPred - curTargets).^2)) ...\n                -  eI.r* sum( sum((weighted_curPred - curTargets_neg).^2)));\n        elseif strcmp(eI.opt,'softabs_kl_const'),\n             cost = cost +...\n             sum(sum( curTargets.*log( curTargets./(weighted_curPred + const2) + const2 )-curTargets+ weighted_curPred +const2))...\n            -eI.r* sum(sum( curTargets_neg.*log( curTargets_neg./(weighted_curPred + const2) + const2 )-curTargets_neg+ weighted_curPred +const2));\n        else\n\n        end\n\n        if eI.outputnonlinear==1,\n             if strcmpi(eI.activationFn,'tanh')\n                delta = delta .* (1 -curPred.^2);\n            elseif strcmpi(eI.activationFn,'logistic')\n                delta = delta .* curPred .* (1 - curPred);\n            elseif strcmpi(eI.activationFn,'RELU')\n                delta = delta .* double(curPred>0);\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n        end\n\n        if fprop_only, continue; end;\n        %% regression layer gradient and delta\n        stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';\n        stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);\n        % short circuit layer\n\n        if eI.shortCircuit\n            stackGrad{end}.W_ss = stackGrad{end}.W_ss + delta ...\n                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';\n        end;\n        delta = stack{l}.W' * delta;\n        %% backprop through hidden layers\n        for l = numel(eI.layerSizes)-1:-1:1\n            % aggregate temporal delta term if this is the recurrent layer\n            if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                delta = delta + delta_t{l};\n            elseif l == eI.temporalLayer\n              delta = delta + delta_t;\n            else\n            end\n            % push delta through activation function for this layer\n            % tanh unit choice assumed\n            if strcmpi(eI.activationFn,'tanh')\n                delta = delta .* (1 - hAct{l,t}.^2);\n            elseif strcmpi(eI.activationFn,'logistic')\n                delta = delta .* hAct{l,t} .* (1 - hAct{l,t});\n            elseif strcmpi(eI.activationFn,'RELU')\n                delta = delta .* double(hAct{l,t}>0);\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n            % gradient of bottom-up connection for this layer\n            if l > 1\n                stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';\n            else\n                stackGrad{l}.W = stackGrad{l}.W + delta * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';\n            end;\n            % gradient for bias\n            stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);\n\n            % compute derivative and delta for temporal connections\n            if t > 1\n                if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                     W_t_grad{l}.W = W_t_grad{l}.W + delta * hAct{l,t-1}';\n                     % push delta through temporal weights\n                     delta_t{l} = W_t{l}.W' * delta;\n                elseif l == eI.temporalLayer\n                     W_t_grad = W_t_grad + delta * hAct{l,t-1}';\n                     % push delta through temporal weights\n                     delta_t = W_t' * delta;\n                end\n            end\n            % push delta through bottom-up weights\n            if l > 1\n                delta = stack{l}.W' * delta;\n            end;\n        end\n        % reduces avg memory usage but doesn't reduce peak\n        %hAct(:,t) = [];\n    end\n    pred_cell{c} = uttPred;\n    % Return the activations for this utterance.\n    if return_activation,\n      act_cell{c} = cell2mat(hAct);\n    end\n    % keep track of how many examples seen in total\n    numTotal = numTotal + T * size(targets,2);\nend\n\n\n%% stack gradients into single vector and compute weight cost\nwCost = numTotal * eI.lambda * sum(theta.^2);\ngrad = rnn_stack2params(stackGrad, eI, W_t_grad, true);\ngrad = grad + 2 * numTotal * eI.lambda * theta;\n\n%% clipping\nif isfield(eI,'clip') && eI.clip~=0, % if eI.clip==0, no clip\n  if eI.clip > 0 % method one -clip the whole\n      norm_grad = norm(grad);  \n      fprintf('norm_grad:%f\\n', norm_grad);\n      % avoid numerial problem\n      if norm_grad <0 || norm_grad > 1e15 || isnan(norm_grad) || isinf(norm_grad),\n          grad = zeros(size(grad));\n          fprintf('set gradient to zeros\\n');\n      end  \n      if norm_grad > eI.clip \n         grad = eI.clip * grad/ norm_grad;    \n      end  \n  else % method two - clip each entry\n      clip_value = -1*eI.clip;\n      grad(grad > clip_value)=clip_value;\n      grad(grad < -clip_value)=-clip_value;     \n  end\nend\n\n%%\navCost = cost/numTotal;\navWCost = wCost/numTotal;\ncost = cost + wCost;\n\n% print output\nif ~isSlave && ~isempty(targets_cell)\n    fprintf('loss:  %f  wCost:  %f \\t',avCost, avWCost);\n\n    if isfield(eI, 'fullRNN') && eI.fullRNN==1\n        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\\n',sum(stack{1}.W(:).^2),...\n            sum(W_t{1}.W(:).^2), sum(stack{end}.W(:).^2));\n    else\n        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\\n',sum(stack{1}.W(:).^2),...\n            sum(W_t(:).^2), sum(stack{end}.W(:).^2));\n    end\nend;\n", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/codes/drdae_discrim_joint_kl_obj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.23616632083522235}}
{"text": "function [mcs, mcs_time] = calculateMCS(model_struct, n_mcs, max_len_mcs, varargin)\n% Calculate Minimal Cut Sets (MCSs) using the warm-start strategy available\n% in CPLEX, namely cplex.populate(), with or without selecting a given\n% knockout, among all the reactions included in the model or a given subset\n% of them. Tobalina et al., 2016 (Bioinformatics); von Kamp and Klamt, 2014\n% (PLoS Computational Biology).\n%\n% USAGE:\n%\n%    [mcs, mcs_time] = populateMCS(model_struct, n_mcs, max_len_mcs, options)\n%\n% INPUTS:\n%    model_struct:    Metabolic model structure (COBRA Toolbox format).\n%    n_mcs:           Number of MCSs to calculate.\n%    max_len_mcs:     Number of reactions in the largest MCS to be calculated.\n%\n% OPTIONAL INPUT:\n% OPTIONAL INPUTS:\n%    KO:                 Selected reaction knockout. (default = [])\n%    rxn_set:            Cell array containing the set of reactions among which\n%                        the MCSs are wanted to be calculated.\n%                        taken from model.rxns\n%                        (default = [], all reactions)\n%    target_b:           Desired activity level of the metabolic task to be\n%                        disrupted. (default = 1e-3)\n%    forceLength:        1 if the constraint limiting the length of the \n%                        MCSs is to be active (recommended for\n%                        enumerating low order MCSs), 0 otherwise \n%                        (default = 1)\n%    timelimit:          Time limit for the calculation of MCSs each time \n%                        the solver is called. (default = 1e75)\n%    numWorkers:         Integer: is the maximun number of workers used \n%                        by Cplex and GPR2models. 0 = automatic, \n%                        1 = sequential, > 1 = parallel. (default = 0)\n%    printLevel:         Integer. 1 if the process is wanted to be shown\n%                        on the screen, 0 otherwise. (default = 1)\n%\n% OUTPUTS:\n%    mcs:         Cell array containing the calculated MCSs.\n%    mcs_time:    Calculation times of the different processes in\n%                 the algorithm.\n%\n% EXAMPLE:\n%    %With optional values\n%    [mcs, mcs_time] = calculateMCS(modelR204, 100, 10, ...\n%                                    'KO', 'r1651', ...\n%                                    'rxn_set', {'r1652'; 'r1653'; 'r1654'}, ...\n%                                    'timelimit', 300, ...\n%                                    'target_b', 1e-4, ...\n%                                    'forceLength', 0, ...\n%                                    'printLevel', 0, ...\n%\n%    %Without optional values\n%    [mcs, mcs_time] = calculateMCS(model, 100, 10)\n%\n% .. Authors:\n%       - Inigo Apaolaza, 30/01/2017, University of Navarra, TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 19/11/2017, University of Navarra, TECNUN School of Engineering.\n%       - Francisco J. Planes, 20/11/2017, University of Navarra, TECNUN School of Engineering.\n% .. Revisions:\n%       - Inigo Apaolaza, 10/04/2018, University of Navarra, TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 17/04/2018, University of Navarra, TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 30/06/2021, University of Navarra, TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 16/09/2022, University of Navarra, TECNUN School of Engineering.\n\n% Check the installation of cplex\nglobal SOLVERS;\nglobal CBT_MILP_SOLVER;\nif SOLVERS.ibm_cplex.installed && SOLVERS.ibm_cplex.working\n    if ~strcmp(CBT_MILP_SOLVER,'ibm_cplex')\n        warning('calculateMCS will use IBM CPLEX although it is not selected for MILP')\n    end\nelse\n    error('This version calculateMCS only works with IBM CPLEX. Newer versions will include more solvers included in COBRA Toolbox')\nend\n\ntime_aa = tic;\n% Set Parameters\np = inputParser;\n% check required arguments\naddRequired(p, 'model_struct');\naddRequired(p, 'n_mcs', @isnumeric);\naddRequired(p, 'max_len_mcs', @isnumeric);\n% Add optional name-value pair argument\naddParameter(p, 'KO', [], @(x)ischar(x)||isempty(x));\naddParameter(p, 'rxn_set', [], @(x)iscell(x)||isempty(x));\naddParameter(p, 'target_b', 1e-3, @(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'timelimit', 1e75, @(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'forceLength', true, @(x)islogical(x)||(isnumeric(x)&&isscalar(x)));\naddParameter(p, 'numWorkers', 0, @(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'printLevel', 1, @(x)isnumeric(x)&&isscalar(x));\n% extract variables from parser\nparse(p, model_struct, n_mcs, max_len_mcs, varargin{:});\nmodel_struct = p.Results.model_struct;\nn_mcs = p.Results.n_mcs;\nmax_len_mcs = p.Results.max_len_mcs;\nKO = p.Results.KO;\nrxn_set = p.Results.rxn_set;\ntarget_b = p.Results.target_b;\ntimelimit = p.Results.timelimit;\nforceLength = p.Results.forceLength;\nnumWorkers = p.Results.numWorkers;\nprintLevel = p.Results.printLevel;\n\n\nintegrality_tolerance = 1e-5;\nM = 1e3;    % Big Value\nalpha = 1;  % used to relate the lower bound of v variables with z variables\nc = 1e-3;   % used to activate w variable\nb = 1e-3;   % used to activate KnockOut constraint\nphi = 1000; % b/c;\n\n% Build the K Matrix\n[~, n_ini_rxns] = size(model_struct.S);\nK = speye(n_ini_rxns);\n\n% Splitting\nS = [model_struct.S -model_struct.S(:, model_struct.lb<0)];\nK = [K K(:, model_struct.lb<0)];\nK_ind = model_struct.rxns;\nn_K_ind = length(K_ind);\n[n_mets, n_rxns] = size(S);\nnbio = find(model_struct.c);\nt = zeros(n_rxns, 1);\nt(nbio) = 1;\n\n% Permit only KOs in rxn_set\nif ~isempty(rxn_set)\n    if ~isempty(KO)\n        rxn_set = [rxn_set; {KO}];\n    end\n    rxn_set = unique(rxn_set);\n    tmp_set = cellfun(@ismember, model_struct.rxns, repmat({rxn_set}, n_ini_rxns, 1), 'UniformOutput', false);\n    pos_set = find(cell2mat(tmp_set));\n    K = K(pos_set, :);\n    K_ind = model_struct.rxns(pos_set);\n    n_K_ind = length(K_ind);\nend\n\nif isempty(KO)\n% ENUMERATE MCSs\n% Define variables\n    var.u = 1:n_mets;\n    var.vp = var.u(end)+1:var.u(end)+n_K_ind;\n    var.w = var.vp(end)+1:var.vp(end)+1;\n    var.zp = var.w(end)+1:var.w(end)+n_K_ind;\n    var.zw = var.zp(end)+1:var.zp(end)+1;\n    n_vars = var.zw(end);\n    var_group.v = [var.vp var.w];\n    var_group.z = [var.zp var.zw];\n\n% Define constraints\n    cons.Ndual = 1:size(S, 2);\n    cons.forceBioCons = cons.Ndual(end)+1:cons.Ndual(end)+1;\n    cons.forceLength = cons.forceBioCons(end)+1:cons.forceBioCons(end)+1;\n    n_cons = cons.forceLength(end);\n\n% Cplex - A matrix\n    A = sparse(zeros(n_cons, n_vars));\n    A(cons.Ndual, var.u) = S';\n    A(cons.Ndual, var.vp) = K';\n    A(cons.Ndual, var.w) = -t;\n    A(cons.forceBioCons, var.w) = -target_b;\n    if forceLength == 1\n        A(cons.forceLength, var.zp) = 1;\n    end\n\n% Cplex - rhs and lhs vectors\n    rhs = zeros(n_cons, 1);\n    rhs(cons.Ndual, 1) = inf;\n    rhs(cons.forceBioCons) = -c;\n    if forceLength == 1\n        rhs(cons.forceLength) = 1;\n    end\n    lhs = zeros(n_cons, 1);\n    lhs(cons.Ndual, 1) = 0;\n    lhs(cons.forceBioCons) = -1000;\n    if forceLength == 1\n        lhs(cons.forceLength) = 1;\n    end\n\n% Cplex - ub and lb vectors\n    ub(var.u, 1) = inf;\n    ub(var.vp) = inf;\n    ub(var.w) = inf;\n    ub(var.zp) = 1;\n    ub(var.zw) = 1;\n    lb(var.u, 1) = -inf;\n    lb(var.vp) = 0;\n    lb(var.w) = 0;\n    lb(var.zp) = 0;\n    lb(var.zw) = 0;\n\n% Cplex - obj vector\n    obj(var.u, 1) = 0;\n    obj(var.vp) = 0;\n    obj(var.w) = 0;\n    obj(var.zp) = 1;\n    obj(var.zw) = 0;\n\n% Cplex - ctype vector\n    ctype(var.u) = 'C';\n    ctype(var.vp) = 'C';\n    ctype(var.w) = 'C';\n    ctype(var.zp) = 'B';\n    ctype(var.zw) = 'B';\n\n% Cplex - sense of the optimization\n    sense = 'minimize';\n\n% Cplex - Introduce all data in a Cplex structure\n    cplex = Cplex('MCS');\n    Model = struct();\n    [Model.A, Model.rhs, Model.lhs, Model.ub, Model.lb, Model.obj, Model.ctype, Model.sense] = deal(A, rhs, lhs, ub, lb, obj, ctype, sense);\n    cplex.Model = Model;\n\n% Cplex Indicators\n    % z = 1  -->  v >= alpha\n    for ivar = 1:length(var_group.z)\n        a = zeros(n_vars, 1);\n        a(var_group.v(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 0, a, 'G', alpha);\n    end\n\n% Cplex Indicators\n    % z = 0  -->  v <= 0\n    for ivar = 1:length(var_group.z)\n        a = zeros(n_vars, 1);\n        a(var_group.v(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 1, a, 'L', 0);\n    end\n\n% Cplex Parameters\n    sP = struct();\n    [sP.mip.tolerances.integrality, sP.mip.strategy.heuristicfreq, sP.mip.strategy.rinsheur] = deal(integrality_tolerance, 1000, 50);\n    [sP.emphasis.mip, sP.output.clonelog, sP.timelimit, sP.threads] = deal(4, -1, max(10, timelimit), numWorkers);\n    [sP.preprocessing.aggregator, sP.preprocessing.boundstrength, ...\n        sP.preprocessing.coeffreduce, sP.preprocessing.dependency, ...\n        sP.preprocessing.dual, sP.preprocessing.fill,...\n        sP.preprocessing.linear, sP.preprocessing.numpass, ...\n        sP.preprocessing.presolve, sP.preprocessing.reduce,..., ...\n        sP.preprocessing.relax, sP.preprocessing.symmetry] = deal(50, 1, 2, 1, 1, 50, 1, 50, 1, 3, 1, 1);\n    cplex = setCplexParam(cplex, sP);\n\n    if printLevel == 0\n        cplex.DisplayFunc = [];\n    end\n\n% Calculation of MCSs\n    mcs_time{1, 1} = '------ TIMING ------';\n    mcs_time{1, 2} = '--- MCSs ---';\n    i = 0;\n    k = 0;\n    n_time = size(mcs_time, 1);\n    mcs_time{n_time+1, 1} = 'Preparation';\n    mcs_time{n_time+1, 2} = toc(time_aa);\n    mcs = [];\n    largest_mcs = 0;\n    while largest_mcs <= max_len_mcs && k < n_mcs && cplex.Model.rhs(cons.forceLength) <= max_len_mcs\n        ini_mcs_time = toc(time_aa);\n        cplex.Param.mip.limits.populate.Cur = 40;\n        cplex.Param.mip.pool.relgap.Cur = 0.1;\n        cplex.populate();\n        n_pool = size(cplex.Solution.pool.solution, 1);\n        if n_pool ~= 0\n            solution = cplex.Solution.pool.solution;\n            for j = 1:n_pool\n                k = k+1;\n                mcs{k, 1} = K_ind((solution(j).x(var.zp))>0.9);\n                n_cons = n_cons+1;\n                sol = solution(j).x(var.zp)>0.9;\n                cplex.Model.A(n_cons, var.zp) = sparse(double(sol));\n                cplex.Model.rhs(n_cons) = sum(sol)-1;\n                cplex.Model.lhs(n_cons) = 0;\n            end\n            i = i+1;\n            mcsi_time = toc(time_aa)-ini_mcs_time;\n            n_time = size(mcs_time, 1);\n            mcs_time{n_time+1, 1} = ['POPULATE_ORDER_' num2str(cplex.Model.rhs(cons.forceLength))];\n            mcs_time{n_time+1, 2} = mcsi_time;\n        else\n            mcsi_time = toc(time_aa)-ini_mcs_time;\n            n_time = size(mcs_time, 1);\n            mcs_time{n_time+1, 1} = ['POPULATE_ORDER_' num2str(cplex.Model.rhs(cons.forceLength)) 'NF'];\n            mcs_time{n_time+1, 2} = mcsi_time;\n            if forceLength == 1\n                cplex.Model.rhs(cons.forceLength) = cplex.Model.rhs(cons.forceLength)+1;\n                cplex.Model.lhs(cons.forceLength) = cplex.Model.lhs(cons.forceLength)+1;\n            else\n                n_time = size(mcs_time, 1);\n                mcs_time{n_time+1, 1} = 'TOTAL MCSs';\n                mcs_time{n_time+1, 2} = toc(time_aa);\n                return;\n            end\n        end\n        try save('tmp.mat', 'mcs', 'mcs_time'); end\n        try largest_mcs = max(cellfun(@length, mcs)); end\n    end\nelse\n% CALCULATE MCSs WITH A GIVEN KNOCKOUT\n% Select the row(s) in K_ind related to the KO under study\n    tmp = repmat({KO}, n_K_ind, 1);\n    dp = cellfun(@isequal, K_ind, tmp);\n\n% Define variables\n    var.u = 1:n_mets;\n    var.vp = var.u(end)+1:var.u(end)+n_K_ind;\n    var.w = var.vp(end)+1:var.vp(end)+1;\n    var.zp = var.w(end)+1:var.w(end)+n_K_ind;\n    var.zw = var.zp(end)+1:var.zp(end)+1;\n    var.epsp = var.zw(end)+1:var.zw(end)+n_K_ind;\n    var.epsw = var.epsp(end)+1:var.epsp(end)+1;\n    var.delp = var.epsw(end)+1:var.epsw(end)+n_K_ind;\n    var.delw = var.delp(end)+1:var.delp(end)+1;\n    var.x = var.delw(end)+1:var.delw(end)+n_rxns+1;\n    n_vars = var.x(end);\n    var_group.v = [var.vp var.w];\n    var_group.z = [var.zp var.zw];\n    var_group.eps = [var.epsp var.epsw];\n    var_group.del = [var.delp var.delw];\n\n% Define constraints\n    cons.Ndual = 1:size(S, 2);\n    cons.forceBioCons = cons.Ndual(end)+1:cons.Ndual(end)+1;\n    cons.forceKO = cons.forceBioCons(end)+1:cons.forceBioCons(end)+1;\n    cons.linearComb = cons.forceKO(end)+1:cons.forceKO(end)+size(S, 1)+size(K, 1)+size(t, 2);\n    cons.forceLength = cons.linearComb(end)+1:cons.linearComb(end)+1;\n    n_cons = cons.forceLength(end);\n\n% Cplex - A matrix\n    A = sparse(zeros(n_cons, n_vars));\n    A(cons.Ndual, var.u) = S';\n    A(cons.Ndual, var.vp) = K';\n    A(cons.Ndual, var.w) = -t;\n    A(cons.forceBioCons, var.w) = -target_b;\n    A(cons.forceKO, var.vp) = dp';\n    A(cons.linearComb, var.x) = [S sparse(zeros(n_mets, 1)); K sparse(zeros(n_K_ind, 1)); -t' target_b];\n    A(cons.linearComb, [var.epsp var.epsw]) = [sparse(zeros(n_mets, length(var.vp)+length(var.w))); -speye(length(var.vp)+length(var.w))];\n    A(cons.linearComb, [var.delp var.delw]) = -[sparse(zeros(n_mets, length(var.vp)+length(var.w))); -speye(length(var.vp)+length(var.w))];\n    if forceLength == 1\n        A(cons.forceLength, var.zp) = 1;\n    end\n\n% Cplex - rhs and lhs vectors\n    rhs = zeros(n_cons, 1);\n    rhs(cons.Ndual, 1) = inf;\n    rhs(cons.forceBioCons) = -c;\n    rhs(cons.forceKO) = 10000;\n    rhs(cons.linearComb) = [sparse(zeros(n_mets, 1)); dp; zeros(size(t, 2), 1)];\n    if forceLength == 1\n        rhs(cons.forceLength) = 1;\n    end\n    lhs = zeros(n_cons, 1);\n    lhs(cons.Ndual, 1) = 0;\n    lhs(cons.forceBioCons) = -1000;\n    lhs(cons.forceKO) = b*10;\n    lhs(cons.linearComb) = [sparse(zeros(n_mets, 1)); dp; zeros(size(t, 2), 1)];\n    if forceLength == 1\n        lhs(cons.forceLength) = 1;\n    end\n\n% Cplex - ub and lb vectors\n    ub(var.u, 1) = inf;\n    ub(var.vp) = inf;\n    ub(var.w) = inf;\n    ub(var.zp) = 1;\n    ub(var.zw) = 1;\n    ub(var.epsp) = inf;\n    ub(var.epsw) = 0;\n    ub(var.delp) = inf;\n    ub(var.delw) = 0;\n    ub(var.x) = inf;\n    lb(var.u, 1) = -inf;\n    lb(var.vp) = 0;\n    lb(var.w) = 0;\n    lb(var.zp) = 0;\n    lb(var.zw) = 0;\n    lb(var.epsp) = 0;\n    lb(var.epsw) = 0;\n    lb(var.delp) = 0;\n    lb(var.delw) = 0;\n    lb(var.x) = 0;\n    lb(var.x(end)) = phi;\n\n% Cplex - obj vector\n    obj(var.u, 1) = 0;\n    obj(var.vp) = 0;\n    obj(var.w) = 0;\n    obj(var.zp) = 1;\n    obj(var.zw) = 0;\n    obj(var.epsp) = 0;\n    obj(var.epsw) = 0;\n    obj(var.delp) = 0;\n    obj(var.delw) = 0;\n    obj(var.x) = 0;\n\n% Cplex - ctype vector\n    ctype(var.u) = 'C';\n    ctype(var.vp) = 'C';\n    ctype(var.w) = 'C';\n    ctype(var.zp) = 'B';\n    ctype(var.zw) = 'B';\n    ctype(var.epsp) = 'C';\n    ctype(var.epsw) = 'C';\n    ctype(var.delp) = 'C';\n    ctype(var.delw) = 'C';\n    ctype(var.x) = 'C';\n\n% Cplex - sense of the optimization\n    sense = 'minimize';\n\n% Cplex - Introduce all data in a Cplex structure\n    cplex = Cplex('MCS');\n    Model = struct();\n    [Model.A, Model.rhs, Model.lhs, Model.ub, Model.lb, Model.obj, Model.ctype, Model.sense] = deal(A, rhs, lhs, ub, lb, obj, ctype, sense);\n    cplex.Model = Model;\n\n% Cplex Indicators\n    % z = 1  -->  v >= alpha\n    for ivar = 1:length(var_group.z)\n        a = zeros(var.x(end), 1);\n        a(var_group.v(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 0, a, 'G', alpha);\n    end\n\n% Cplex Indicators\n    % z = 0  -->  v <= 0\n    for ivar = 1:length(var_group.z)\n        a = zeros(var.x(end), 1);\n        a(var_group.v(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 1, a, 'L', 0);\n    end\n\n% Cplex Indicators\n    % z = 1  -->  epsilon <= 0\n    for ivar = 1:length(var_group.z)\n        a = zeros(var.x(end), 1);\n        a(var_group.eps(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 0, a, 'L', 0);\n    end\n\n% Cplex Indicators\n    % z = 0  -->  epsilon <= M\n    for ivar = 1:length(var_group.z)\n        a = zeros(var.x(end), 1);\n        a(var_group.eps(ivar)) = 1;\n        cplex.addIndicators(var_group.z(ivar), 1, a, 'L', M);\n    end\n\n% Cplex Parameters\n    sP = struct();\n    [sP.mip.tolerances.integrality, sP.mip.strategy.heuristicfreq, sP.mip.strategy.rinsheur] = deal(integrality_tolerance, 1000, 50);\n    [sP.emphasis.mip, sP.output.clonelog, sP.timelimit, sP.threads] = deal(4, -1, max(10, timelimit), numWorkers);\n    [sP.preprocessing.aggregator, sP.preprocessing.boundstrength, ...\n        sP.preprocessing.coeffreduce, sP.preprocessing.dependency, ...\n        sP.preprocessing.dual, sP.preprocessing.fill,...\n        sP.preprocessing.linear, sP.preprocessing.numpass, ...\n        sP.preprocessing.presolve, sP.preprocessing.reduce,..., ...\n        sP.preprocessing.relax, sP.preprocessing.symmetry] = deal(50, 1, 2, 1, 1, 50, 1, 50, 1, 3, 1, 1);\n    cplex = setCplexParam(cplex, sP);\n    if printLevel == 0\n        cplex.DisplayFunc = [];\n    end\n\n% Calculation of MCSs\n    mcs_time{1, 1} = '------ TIMING ------';\n    mcs_time{1, 2} = '--- MCSs ---';\n    i = 0;\n    k = 0;\n    n_time = size(mcs_time, 1);\n    mcs_time{n_time+1, 1} = 'Preparation';\n    mcs_time{n_time+1, 2} = toc(time_aa);\n    mcs = [];\n    largest_mcs = 0;\n    while largest_mcs <= max_len_mcs && k < n_mcs && cplex.Model.rhs(cons.forceLength) <= max_len_mcs\n        ini_mcs_time = toc(time_aa);\n        cplex.Param.mip.limits.populate.Cur = 40;\n        cplex.Param.mip.pool.relgap.Cur = 0.1;\n        cplex.populate();\n        n_pool = size(cplex.Solution.pool.solution, 1);\n        if n_pool ~= 0\n            solution = cplex.Solution.pool.solution;\n            for j = 1:n_pool\n                k = k+1;\n                mcs{k, 1} = K_ind((solution(j).x(var.zp))>0.9);\n                n_cons = n_cons+1;\n                sol = solution(j).x(var.zp)>0.9;\n                cplex.Model.A(n_cons, var.zp) = sparse(double(sol));\n                cplex.Model.rhs(n_cons) = sum(sol)-1;\n                cplex.Model.lhs(n_cons) = 0;\n            end\n            i = i+1;\n            mcsi_time = toc(time_aa)-ini_mcs_time;\n            n_time = size(mcs_time, 1);\n            mcs_time{n_time+1, 1} = ['POPULATE_ORDER_' num2str(cplex.Model.rhs(cons.forceLength))];\n            mcs_time{n_time+1, 2} = mcsi_time;\n        else\n            mcsi_time = toc(time_aa)-ini_mcs_time;\n            n_time = size(mcs_time, 1);\n            mcs_time{n_time+1, 1} = ['POPULATE_ORDER_' num2str(cplex.Model.rhs(cons.forceLength)) 'NF'];\n            mcs_time{n_time+1, 2} = mcsi_time;\n            if forceLength == 1\n                cplex.Model.rhs(cons.forceLength) = cplex.Model.rhs(cons.forceLength)+1;\n                cplex.Model.lhs(cons.forceLength) = cplex.Model.lhs(cons.forceLength)+1;\n            else\n                n_time = size(mcs_time, 1);\n                mcs_time{n_time+1, 1} = 'TOTAL MCSs';\n                mcs_time{n_time+1, 2} = toc(time_aa);\n                return;\n            end\n        end\n        try save('tmp.mat', 'mcs', 'mcs_time'); end\n        try largest_mcs = max(cellfun(@length, mcs)); end\n    end\nend\nn_time = size(mcs_time, 1);\nmcs_time{n_time+1, 1} = 'TOTAL MCSs';\nmcs_time{n_time+1, 2} = toc(time_aa);\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/gMCS/calculateMCS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.23616630801078886}}
{"text": "function [x,y,ind] = spm_MDP_VB_ERP(MDP,FACTOR,T)\n% auxiliary routine for hierarchical electrophysiological responses\n% FORMAT [x,y] = spm_MDP_VB_ERP(MDP,FACTOR,T)\n%\n% MDP    - structure (see spm_MDP_VB)\n% FACTOR - hidden factors (at high and low level) to plot\n% T      - flag to return cell of expectations (at time T; usually 1)\n%\n% x      - simulated ERPs (high-level) (full lines)\n% y      - simulated ERPs (low level)  (dotted lines)\n% ind    - indices or bins at the end of each (synchronised) epoch\n%\n% This routine combines first and second level hidden expectations by\n% synchronising them; such that first level updating is followed by an\n% epoch of second level updating - during which updating is suspended\n% (and expectations are held constant). The ensuing spike rates can be\n% regarded as showing delay period activity. In this routine, simulated\n% local field potentials are band pass filtered spike rates (between eight\n% and 32 Hz).\n%\n% Graphics are provided for first and second levels, in terms of simulated\n% spike rates (posterior expectations), which are then combined to show\n% simulated local field potentials for both levels (superimposed).\n%\n% At the lower level, only expectations about hidden states in the first\n% epoch are returned (because the number of epochs can differ from trial\n% to trial).\n%\n% see also: spm_MDP_VB_LFP (for single level belief updating)\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP_VB_ERP.m 7656 2019-08-26 14:00:36Z karl $\n\n\n% defaults: assume the first factor is of interest\n%==========================================================================\ntry, f1 = FACTOR(1); catch, f1 = 1; end\ntry, f2 = FACTOR(2); catch, f2 = 1; end\n\n% and T = 1\n%--------------------------------------------------------------------------\nif nargin < 3, T = 1; end\n\nfor m = 1:numel(MDP)\n\n    % dimensions\n    %----------------------------------------------------------------------\n    xn  = MDP(m).xn{f1};      % neuronal responses\n    Nb  = size(xn,1);         % number of time bins per epochs\n    Nx  = size(xn,2);         % number of states\n    Ne  = size(xn,3);         % number of epochs\n    \n    \n    % expected hidden states\n    %======================================================================\n    x     = cell(Ne,Nx);\n    y     = cell(Ne);\n    for k = 1:Ne\n        for j = 1:Nx\n            x{k,j} = xn(:,j,T,k);\n        end\n        if isfield(MDP,'mdp')\n            y{k}   = spm_MDP_VB_ERP(MDP(m).mdp(k),f2,1);\n        else\n            y{k}   = [];\n        end\n    end\n    \n    if nargin > 2, return, end\n    \n    % synchronise responses\n    %----------------------------------------------------------------------\n    u   = {};\n    v   = {};\n    uu  = spm_cat(x(1,:));\n    for k = 1:Ne\n        \n        % low-level\n        %------------------------------------------------------------------\n        v{end + 1,1} = spm_cat(y{k});\n        if k > 1\n            u{end + 1,1} = ones(size(v{end,:},1),1)*u{end,1}(end,:);\n        else\n            u{end + 1,1} = ones(size(v{end,:},1),1)*uu(1,:);\n        end\n        \n        % time bin indices\n        %------------------------------------------------------------------\n        ind(k) = size(u{end},1);\n        \n        % high-level\n        %------------------------------------------------------------------\n        u{end + 1,1} = spm_cat(x(k,:));\n        v{end + 1,1} = ones(size(u{end,:},1),1)*v{end,1}(end,:);\n        \n        % time bin indices\n        %------------------------------------------------------------------\n        ind(k) = ind(k) + size(u{end},1);\n\n    end\n    \n    % accumulate over trials\n    %----------------------------------------------------------------------\n    U{m,1} = u;\n    V{m,1} = v;\n    \nend\n\n% time bin (seconds)\n%--------------------------------------------------------------------------\nu  = spm_cat(U);\nv  = spm_cat(V);\ndt = 1/64;\nt  = (1:size(u,1))*dt;\n\n% bandpass filter between 8 and 32 Hz\n%--------------------------------------------------------------------------\nc  = 1/32;\nx  = log(u + c);\ny  = log(v + c);\nx  = spm_conv(x,2,0) - spm_conv(x,16,0);\ny  = spm_conv(y,2,0) - spm_conv(y,16,0);\n\nif nargout > 2, return, end\n\n% simulated firing rates and the local field potentials\n%==========================================================================\n\n% higher-level unit responses\n%--------------------------------------------------------------------------\nfactor = MDP(1).label.factor{f1};\nname   = MDP(1).label.name{f1};\n\nsubplot(4,1,1), image(t,1:(size(u,2)),64*(1 - u')), ylabel('Unit')\ntitle(sprintf('Unit reponses : %s',factor),'FontSize',16)\nif numel(name) < 16\n    grid on, set(gca,'YTick',1:numel(name))\n    set(gca,'YTickLabel',name)\nend\n\n% lower-level unit responses\n%--------------------------------------------------------------------------\nfactor = MDP(1).MDP(1).label.factor{f2};\nname   = MDP(1).MDP(1).label.name{f2};\n\nsubplot(4,1,2), image(t,1:(size(v,2)),64*(1 - v')), ylabel('Unit')\ntitle(sprintf('Unit reponses : %s',factor),'FontSize',16)\nif numel(factor) < 16\n    grid on, set(gca,'YTick',1:numel(name))\n    set(gca,'YTickLabel',name)\nend\n\n% event related responses at both levels\n%--------------------------------------------------------------------------\nsubplot(4,1,3), plot(t,x',t,y','-.')\ntitle('Local field potentials','FontSize',16)\nylabel('Depolarisation'),spm_axis tight\ngrid on, xlabel('time (seconds)')\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_MDP_VB_ERP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2361488674846436}}
{"text": "function [sr_img] = superresolve_ebsr(slidingWindows, magFactor)\n%\n% LMSSR_GENERATESRUSINGEBSR Performs a Single Image Super-Resolution (SISR) approach according to \"Example-based Learning for Single-Image \n%                      Super-resolution\". Supports GS/Y and RGB.\n%    [sr_img] = LMSSR_GENERATESRUSINGEBSR(lr_img, upscaling)\n%\n% Parameters: lr_img          -   LR RGB or GS/Y image to be superresolved (height,width,dye)\n%             upscaling       -   Scalar value containing the upscaling factor for both Y- and X-coordinates\n%\n% Important note: YUV images are also supported but yield bad results!\n%\n% Author: Michel B\u00e4tz (LMS)\n%\n% See also: lmsSR_framework\n%\n\nlr_img    = slidingWindows.referenceFrame;\nupscaling = magFactor;\n\n\n%Low = lr_ref_img;\n%Low(:,:,2) = Low(:,:,1);\n%Low(:,:,3) = Low(:,:,1);\n%Low = im2uint8(Low);\n\nif size(lr_img,3) == 3, % Color image case\n    lr_img = lmsSR_convertYUV2RGB(lr_img);\nend\n\nsr_img = SuperresCode(lr_img,upscaling); % EXTERNAL CODE\nsr_img = uint8(sr_img); % Required as output contains uint8 values\n\nsr_img = im2double(sr_img);\n\nif size(lr_img,3) == 3, % Color image case\n    sr_img = lmsSR_convertRGB2YUV(sr_img);\nend\n\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/superresolve_ebsr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23612743191873423}}
{"text": "%kvaddm 'Add Image1 to Image2 Pixel by Pixel'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vaddm.pane file\n%\n% Parameters: \n% InputFile: i1 'Input Image #1', required: 'first input image'\n% OutputFile: o 'Output Image ', required: 'resulting output image'\n% InputFile: i2 'Input Image #2', optional: 'second input image'\n% Integer: c 'Constant Image', default: 0: 'add constant'\n%\n% Example: o = kvaddm({i1, i2}, {'i1','';'o','';'i2','';'c',0})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% vaddm - Add Image1 to Image2 Pixel by Pixel\n%\n%  DESCRIPTION\n% .I vaddm\n% Adds the first input image to the second input image (result = image1 + image2), with an optional operation gating image. The second input image can be entered as a constant, optionally.\n% If the sum of two pixel values is more than the maximum value of the image data type, the resultant pixel value will be set to this maximum value.\n% \n% The two input images must be of the same size and have the same\n% number of data bands.  The input\n% images may be of the same or different data types.  If the input\n% images are of different data types, then all input images will be\n% upcast to the highest input image data type.  The output\n% image data type will be the same as that of the highest data type\n% of the input images.\n%\n%  \n%\n%  EXAMPLES\n% vaddm -i1 input.image1 -i2 input.image2 -o output.image \n% \n% This subtracts input.image2 from input.image1 stores the results in output.image.\n%\n%  \"SEE ALSO\"\n% vcast1(1)\n%\n%  RESTRICTIONS \n% .I vaddm\n% can be defined for all data types supported by Khoros, but at the moment it has been implemented just for the bit and unsigned char types.\n% The structuring elements are subsets of the 3x3 matrix and the origin is always at the center of this matrix.\n%\n%  REFERENCES \n%\n%  COPYRIGHT\n% Copyright (C) 1993-1997 Junior Barrera, Roberto Lotufo.  All rights reserved.\n% \n\n\nfunction varargout = kvaddm(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kvaddm(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i1', '__input';'o', '__output';'i2', '__input';'c', 0};\nmaxval={0,0,1,255};\nminval={0,0,1,0};\nistoggle=[0,0,1,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','OutputFile','InputFile','Integer'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'vaddm\"  '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kvaddm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23608253366545204}}
{"text": "%FBA\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last Updated: 3/24/2011\nclassdef FBA\n    %printing\n    methods (Static)\n        function run(sim, fileName)\n            import edu.stanford.covert.cell.sim.analysis.FBA;\n            import edu.stanford.covert.cell.sim.util.PlotUtil;\n            import edu.stanford.covert.cell.sim.util.PrintUtil;\n            \n            %excel file\n            [content, colLabels, indentation] = FBA.printNetworkReduction(sim);\n            if nargin == 1\n                PrintUtil.printToStdIO(content, colLabels, struct('indentation', indentation));\n            else\n                PrintUtil.printToFile(content, colLabels, [fileName '.xls'], 'NetworkReduction', struct('indentation', indentation));\n            end\n            \n            %plots\n            if nargin == 1\n                FBA.plotNetworkReduction(sim, PlotUtil.newAxesHandle());\n            else\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                \n                cla(axesHandle);\n                FBA.plotNetworkReduction(sim, axesHandle);\n                saveas(figHandle, [fileName '-NetworkReduction.pdf']);\n                \n                close(figHandle);\n            end\n        end\n        \n        function [content, colLabels, indentation] = printNetworkReduction(sim)\n            p = sim.process('Metabolism');\n            \n            [subCmpRemoved, rxnRemoved] = p.formulateFBA([], [], true);\n            \n            content = cell(0, 6);\n            colLabels = {'ID', 'Compartment', 'Reason', 'Iteration-1', 'Iteration-2'};\n            reasons = {\n                'Disconnected'\n                'Substrate cannot be balanced: only appears in single reaction'\n                'Substrate cannot be balanced: move in same direction in all reactions in which it appears'\n                'Reaction has zero flux in all solutions of S*v = 0: reaction has no non-zero component in null space of S';\n                };\n            \n            subIDs = p.substrateWholeCellModelIDs;\n            cmpIDs = p.compartment.wholeCellModelIDs(p.substrateMetaboliteCompartmentIndexs(1, :));\n            content = [content;{\n                0 'Substrates' [] [] [] []}];\n            for i = 1:size(subCmpRemoved, 1)\n                if subCmpRemoved(i, 1) == 0\n                    continue;\n                end\n                [sIdx, cIdx] = ind2sub([size(p.reactionStoichiometryMatrix, 1) size(p.reactionStoichiometryMatrix, 3)], i);\n                content = [content;{\n                    1 subIDs{sIdx} cmpIDs{cIdx} reasons{subCmpRemoved(i, 3)} subCmpRemoved(i, 1) subCmpRemoved(i, 2)}]; %#ok<AGROW>\n            end\n            \n            rxnIDs = p.reactionWholeCellModelIDs;\n            content = [content;{\n                0 'Reactions' [] [] [] []}];\n            for i = 1:size(rxnRemoved, 1)\n                if rxnRemoved(i, 3) == 0\n                    continue;\n                end\n                content = [content;{\n                    1 rxnIDs{i} [] reasons{rxnRemoved(i, 3)} rxnRemoved(i, 1) rxnRemoved(i, 2)}]; %#ok<AGROW>\n            end\n            \n            %format output\n            indentation = cell2mat(content(:, 1));\n            content = content(:, 2:end);\n        end\n        \n        function plotNetworkReduction(sim, axesHandle)\n            p = sim.process('Metabolism');\n            \n            [subCmpRemoved, rxnRemoved] = p.formulateFBA([], [], true);\n            subCmpRemoved(subCmpRemoved(:, 1) == 0, 1) = max(subCmpRemoved(:, 1)) + 1;\n            rxnRemoved(rxnRemoved(:, 1) == 0, 1) = max(rxnRemoved(:, 1)) + 1;\n            \n            levels = sortrows(unique([subCmpRemoved; rxnRemoved], 'rows'), [1 2 3]);\n            \n            [~, subCmpIdxs] = sortrows(subCmpRemoved, 1:3);\n            [~, rxnIdxs] = sortrows(rxnRemoved, 1:3);\n            \n            [~, subCmpLevels] = ismember(subCmpRemoved, levels, 'rows');\n            [~, rxnLevels] = ismember(rxnRemoved, levels, 'rows');\n            \n            hold on;\n            \n            x = [\n                0.5\n                numel(rxnIdxs)+0.5\n                numel(rxnIdxs)+0.5\n                0.5\n                ];\n            y = [\n                0.5\n                0.5\n                numel(subCmpIdxs)+0.5\n                numel(subCmpIdxs)+0.5\n                ];\n            patch(x, y, 1, 'FaceColor', [1 1 1], 'Parent', axesHandle, 'FaceAlpha', 1);\n            patch(x, y, 1, 'CDataMapping', 'direct', 'Parent', axesHandle, 'FaceAlpha', 0.25, 'EdgeAlpha', 1);\n            for i = 2:size(levels, 1)\n                j = find(subCmpLevels(subCmpIdxs) < i, 1, 'last');\n                k = find(rxnLevels(rxnIdxs) < i, 1, 'last');\n                if isempty(j), j = 0; end;\n                if isempty(k), k = 0; end;\n                \n                x = [\n                    k+0.5\n                    numel(rxnIdxs)+0.5\n                    numel(rxnIdxs)+0.5\n                    k+0.5\n                    ];\n                y = [\n                    j+0.5\n                    j+0.5\n                    numel(subCmpIdxs)+0.5\n                    numel(subCmpIdxs)+0.5\n                    ];\n                patch(x, y, 1, 'FaceColor', [1 1 1], 'Parent', axesHandle, 'FaceAlpha', 1);                \n                patch(x, y, i, 'CDataMapping', 'direct', 'Parent', axesHandle, 'FaceAlpha', 0.25, 'EdgeAlpha', 1);\n            end\n            \n            rxnSMat = reshape(permute(p.reactionStoichiometryMatrix, [2 1 3]), ...\n                size(p.reactionStoichiometryMatrix, 2), [])';\n            \n            [y, x] = find(...\n                ((rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))) & ...\n                ~((rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))));\n            h1 = plot(axesHandle, x, y, 'r.', 'MarkerSize', 6);\n            \n            [y, x] = find(...\n                ~((rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))) &  ...\n                ((rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))));\n            h2 = plot(axesHandle, x, y, 'g.', 'MarkerSize', 6);\n            \n            [y, x] = find(...\n                ((rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))) &  ...\n                ((rxnSMat(subCmpIdxs, rxnIdxs) > 0 & repmat(p.reactionBounds(rxnIdxs, 2)' > 0, numel(subCmpIdxs), 1)) | ...\n                (rxnSMat(subCmpIdxs, rxnIdxs) < 0 & repmat(p.reactionBounds(rxnIdxs, 1)' < 0, numel(subCmpIdxs), 1))));\n            h3 = plot(axesHandle, x, y, 'b.', 'MarkerSize', 6);\n            \n            legend([h1 h2 h3], {'Drained'; 'Produced'; 'Bidirectional'}, 'Location', 'NorthEastOutside');\n            \n            colormap(jet);\n            \n            xlim([0.5 numel(rxnIdxs)+0.5])\n            ylim([0.5 numel(subCmpIdxs)+0.5]);\n            \n            box('on');\n            xlabel('Reactions', 'FontSize', 12);\n            ylabel('Substrates', 'FontSize', 12);\n            set(axesHandle, 'YDir', 'reverse');\n            set(axesHandle, 'XAxisLocation', 'top');\n            axis('square')\n        end\n    end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+analysis/FBA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23597951964532393}}
{"text": "% adjustlocs() - read neuroscan polar location file (.asc)\n%\n% Usage:\n%   >> chanlocs = adjustlocs( chanlocs );\n%   >> chanlocs = adjustlocs( chanlocs, 'key1', val1, 'key2', val2, ...);\n%\n% Inputs:\n%   chanlocs       - EEGLAB channel location data structure. See\n%                    help readlocs()\n%\n% Optional inputs:\n%   'center'       - [cell array] one or several electrode names to compute\n%                    center location (if several electrodes are provided, the\n%                    function use their iso-barycenter). Ex: { 'cz' } or \n%                    { 'fz' 'pz' }.\n%   'autocenter'   - ['on'|'off']  attempt to automatically detect all symetrical\n%                    electrode in the 10-20 system to compute the center. \n%                    Default: 'on'.\n%   'rotate'       - [cell array] name and planar angle of landmark electrodes\n%                    to use as template planar rotation. Ex: { 'c3', 90 }.\n%   'autorotate'   - ['on'|'off'] attempt to automatically detect \n%                    electrode in the 10-20 system to compute the average\n%                    planar rotation. Default 'on'.\n%   'scale'        - [cell array] name and phi angle of electrodes along\n%                    horizontal central line. Ex: { 'c3' 44 }. Scale uniformly\n%                    all direction. Use 'hscale' and 'vscale' for scaling x and\n%                    y axis independently.\n%   'hscale'       - [cell array] name and phi angle of electrodes along\n%                    honrizontal central line. Ex: { 'c3' 44 }.\n%   'vscale'       - [cell array] name and phi angle of one electrodes along\n%                    central vertical axis. Ex: { 'fz' 44 }.\n%   'autoscale'    - ['on'|'off'] automatic scaling with 10-20 system used as\n%                    reference. Default is 'on'.\n%   'uniform'      - ['on'|'off'] force the scaling to be uniform along the X\n%                    and the Y axis. Default is 'on'.\n%   'coordinates'  - ['pol'|'sph'|'cart'] use polar coordinates ('pol'), sperical\n%                    coordinates ('sph') or cartesian ('cart'). Default is 'sph'.\n%                    (Note that using polar and spherical coordinates have the \n%                    same effect, except that units are different). \n%                    Default is 'sph'.\n%\n% Outputs:\n%   chanlocs       - EEGLAB channel location data structure. See\n%                    help readlocs()\n%\n% Note: operations are performed in the following order, first re-centering\n%       then planar rotation and finally sperical re-scaling.\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 1 Dec 2003\n%\n% See also: readlocs()\n\n% Copyright (C) 2003 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction chanlocs = adjustlocs( chanlocs, varargin)\n    \n    if nargin < 1\n        help adjustlocs;\n        return;\n    end;\n    \n    % check input parameters\n    % ----------------------\n    g = finputcheck( varargin, { 'hscale'     'cell'  []   {};\n                                 'vscale'     'cell'  []   {};\n                                 'scale'      'cell'  []   {};\n                                 'center'     'cell'  []   {};\n                                 'rotate'     'cell'  []   {};\n                                 'autoscale'  'string'  { 'on' 'off' }    'off';\n                                 'autocenter' 'string'  { 'on' 'off' }    'on';\n                                 'autorotate' 'string'  { 'on' 'off' }    'on';\n                                 'uniform'    'string'  { 'on' 'off' }    'on';\n                                 'coordinates' 'string'  { 'pol' 'sph' 'cart' } 'sph' });\n    if ischar(g), error(g); end;\n    \n    names = { chanlocs.labels };\n    \n    % auto center\n    % -----------\n    if strcmpi(g.autocenter, 'on') & isempty(g.center)\n        disp('Reading template 10-20 file');\n        locs1020 = readlocs('eeglab1020.ced');\n        \n        % scan electrodes for horiz pos\n        % -----------------------------\n        tmpnames      = lower(names);\n        tmpnames1020  = lower({ locs1020.labels });\n        [tmp indelec] = intersect(tmpnames1020, tmpnames);\n\n        % remove non-symetrical electrodes\n        % --------------------------------\n        if ~isempty(indelec)\n            if find(indelec == 79), indelec(end+1) = 80; end; % for Cz\n            ind2remove = [];\n            for index = 1:length(indelec)\n                if mod(indelec(index),2)\n                    if ~ismember(indelec(index)+1, indelec)\n                        ind2remove = [ ind2remove index ];\n                    end;\n                else\n                    if ~ismember(indelec(index)-1, indelec)\n                        ind2remove = [ ind2remove index ];\n                    end;\n                end;\n            end;\n            indelec(ind2remove) = [];\n            if find(indelec == 80), indelec(end) = []; end; % for Cz\n        \n            g.center = tmpnames1020(indelec);\n        end;\n        if isempty(g.center)\n            disp('No electrodes found for auto-centering')\n        else\n            disp([ num2str(length(g.center)) ' landmark electrodes found for position auto-centering' ])\n        end;\n    end;\n\n    % auto rotate\n    % -----------\n    if strcmpi(g.autorotate, 'on') & isempty(g.rotate)\n        if exist('locs1020') ~= 1\n            disp('Reading template 10-20 file');\n            locs1020 = readlocs('eeglab1020.ced');\n        end;\n                \n        % scan electrodes for horiz pos\n        % -----------------------------\n        tmpnames      = lower(names);\n        tmpnames1020  = lower({ locs1020.labels });\n        tmptheta1020 = { locs1020.theta };\n        [tmp indelec] = intersect(tmpnames1020(1:end-1), tmpnames); % do not use cz\n\n        g.rotate(1:2:2*length(indelec))   = tmpnames1020 (indelec);\n        g.rotate(2:2:2*length(indelec)+1) = tmptheta1020(indelec);\n        \n        if isempty(g.rotate)\n            disp('No electrodes found for auto planar rotation')\n        else\n            disp([ num2str(length(g.rotate)/2) ' landmark electrodes found for auto planar rotation' ])\n        end;\n    end;\n\n    % auto scale\n    % ----------\n    if strcmpi(g.autoscale, 'on') & isempty(g.hscale) & isempty(g.vscale)\n        if exist('locs1020') ~= 1\n            disp('Reading template 10-20 file');\n            locs1020 = readlocs('eeglab1020.ced');\n        end;\n        \n        if strcmpi(g.uniform, 'off')\n            % remove all vertical electrodes for horizontal scaling\n            % -----------------------------------------------------\n            theta  = [ locs1020.theta ];\n            indxh  = find(abs(theta) == 90);\n            indxv  = union(find(theta == 0) , find(theta == 180));\n            locs1020horiz = locs1020(indxh);\n            locs1020vert  = locs1020(indxv);\n            \n            % scan electrodes for horiz pos\n            % -----------------------------\n            tmpnames      = lower(names);\n            tmpnames1020  = lower({ locs1020horiz.labels });\n            tmpradius1020 = { locs1020horiz.radius };\n            [tmp indelec] = intersect(tmpnames1020, tmpnames);\n            \n            if isempty(indelec)\n                disp('No electrodes found for horiz. position spherical re-scaling')\n            else\n                disp([ num2str(length(indelec)) ' landmark electrodes found for horiz. position spherical re-scaling' ]);\n                if strcmpi(g.coordinates, 'cart')\n                    g.hscale(2:2:2*length(indelec)+1) = [ locs1020horiz.Y ];\n                else\n                    g.hscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);\n                end;\n            end;\n            \n            % scan electrodes for vert. pos\n            % -----------------------------\n            tmpnames1020  = lower({ locs1020vert.labels });\n            tmpradius1020 = { locs1020vert.radius };\n            [tmp indelec] = intersect(tmpnames1020, tmpnames);\n            \n            if isempty(indelec)\n                disp('No electrodes found for vertical position spherical re-scaling')\n            else\n                disp([ num2str(length(indelec)) ' landmark electrodes found for vertical spherical re-scaling' ]);\n                g.vscale(1:2:2*length(indelec))   = tmpnames1020 (indelec);\n                if strcmpi(g.coordinates, 'cart')\n                    g.vscale(2:2:2*length(indelec)+1) = [ locs1020vert.X ];\n                else\n                    g.vscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);\n                end;\n            end;    \n        else\n            % uniform scaling\n            % ---------------\n            tmpnames      = lower(names);\n            tmpnames1020  = lower({ locs1020.labels });\n            tmpradius1020 = { locs1020.radius };\n            [tmp indelec] = intersect(tmpnames1020, tmpnames);\n            \n            if isempty(indelec)\n                disp('No electrodes found for uniform spherical re-scaling')\n            else\n                disp([ num2str(length(indelec)) ' landmark electrodes found for uniform spherical re-scaling' ]);\n                g.scale(1:2:2*length(indelec))   = tmpnames1020 (indelec);\n                if strcmpi(g.coordinates, 'cart')\n                    tmpabsxyz = mattocell(abs([ locs1020.X ]+j*[ locs1020.Y ]));\n                    g.scale(2:2:2*length(indelec)+1) = tmpabsxyz(indelec);\n                else\n                    g.scale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);\n                end;\n            end;\n        end;\n        if strcmpi(g.coordinates, 'sph')\n            g.coordinates = 'pol'; % use polar coordinates for scaling\n        end;\n    end;\n    \n    % get X and Y coordinates\n    % -----------------------\n    if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol')\n        [X Y] = pol2cart( [ chanlocs.theta ]/180*pi, [ chanlocs.radius ]); Z = 1;\n        if strcmpi(g.coordinates, 'sph')\n            X = X/0.25*46;\n            Y = Y/0.25*46;\n        end;\n    else\n        X = [ chanlocs.X ];\n        Y = [ chanlocs.Y ];\n        Z = [ chanlocs.Z ];\n    end;\n    \n    % recenter\n    % --------\n    if ~isempty(g.center)\n        for index = 1:length(g.center)\n            tmpindex = strmatch( lower(g.center{index}), lower(names), 'exact' );\n            if isempty(tmpindex)\n                error(['Electrode ''' g.center{index} ''' not found for re-centering']);\n            end;\n            indexelec(index) = tmpindex;\n        end;\n        showmsg('Using electrode', 'for re-centering', g.center);\n        centerx = mean(X(indexelec));\n        centery = mean(Y(indexelec));\n        X = X - centerx;\n        Y = Y - centery;\n    end;\n\n    % planar rotation\n    % ---------------    \n    if ~isempty(g.rotate)\n        % find electrodes\n        % ---------------\n        clear elec;\n        for index = 1:2:length(g.rotate)\n            tmpindex = strmatch( lower(g.rotate{index}), lower(names), 'exact' );\n            if isempty(tmpindex)\n                error(['Electrode ''' g.rotate{index} ''' not found for left-right scaling']);\n            end;\n            elec((index+1)/2) = tmpindex;\n        end;\n        vals = [ g.rotate{2:2:end} ];\n        \n        % compute average scaling factor\n        % ------------------------------\n        [ allangles tmp ] = cart2pol(X(elec), Y(elec));\n        allangles = allangles/pi*180;\n        diffangle = allangles - vals;\n        %diffangle2 = allangles + vals;\n        %if abs(diffangle1) > abs(diffangle2), diffangle = diffangle2;\n        %else                                  diffangle = diffangle1;\n        %end;\n        tmpind    = find(diffangle >  180); diffangle(tmpind) = diffangle(tmpind)-360;\n        tmpind    = find(diffangle < -180); diffangle(tmpind) = diffangle(tmpind)+360;\n        anglerot  = mean(diffangle);\n        tmpcplx = (X+j*Y)*exp(-j*anglerot/180*pi);\n        X = real(tmpcplx);\n        Y = imag(tmpcplx);\n        showmsg('Using electrode', ['for planar rotation (' num2str(anglerot,2) ' degrees)'], g.rotate(1:2:end));\n    end;\n    \n    % computing scaling factors\n    % -------------------------\n    if ~isempty(g.scale)\n        % find electrodes\n        % ---------------\n        clear elec;\n        for index = 1:2:length(g.scale)\n            tmpindex = strmatch( lower(g.scale{index}), lower(names), 'exact' );\n            if isempty(tmpindex)\n                error(['Electrode ''' g.scale{index} ''' not found for left-right scaling']);\n            end;\n            elec((index+1)/2) = tmpindex;\n        end;\n        vals = [ g.scale{2:2:end} ];\n        \n        % compute average scaling factor\n        % ------------------------------\n        nonzero = find(vals > 0);\n        hscalefact = mean(abs(Y(elec(nonzero))+j*X(elec(nonzero)))./vals(nonzero)); % *46/0.25; %/44/0.25;\n        vscalefact = hscalefact;\n        showmsg('Using electrode', ['for uniform spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.scale(1:2:end));\n    else\n        if ~isempty(g.hscale)\n            % find electrodes\n            % ---------------\n            clear elec;\n            for index = 1:2:length(g.hscale)\n                tmpindex = strmatch( lower(g.hscale{index}), lower(names), 'exact' );\n                if isempty(tmpindex)\n                    error(['Electrode ''' g.hscale{index} ''' not found for left-right scaling']);\n                end;\n                elec((index+1)/2) = tmpindex;\n            end;\n            vals = [ g.hscale{2:2:end} ];\n            showmsg('Using electrode', [ 'for left-right spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.hscale(1:2:end));\n            \n            % compute average scaling factor\n            % ------------------------------\n            hscalefact = mean(abs(Y(elec))./vals); % *46/0.25; %/44/0.25;\n            if isempty(g.vscale)\n                vscalefact =  hscalefact;\n            end;\n        end;\n        if ~isempty(g.vscale)\n            % find electrodes\n            % ---------------\n            clear elec;\n            for index = 1:2:length(g.vscale)\n                tmpindex = strmatch( lower(g.vscale{index}), lower(names), 'exact' );\n                if isempty(tmpindex)\n                    error(['Electrode ''' g.vscale{index} ''' not found for rear-front scaling']);\n                end;\n                elec((index+1)/2) = tmpindex;\n            end;\n            vals = [ g.vscale{2:2:end} ];\n            showmsg('Using electrode', ['for rear-front spherical re-scaling (x' num2str(1/vscalefact,4) ')'], g.vscale(1:2:end));\n            \n            % compute average scaling factor\n            % ------------------------------\n            vscalefact = mean(abs(X(elec))./vals); % *46/0.25; %/44/0.25;\n            if isempty(g.vscale)\n                hscalefact =  vscalefact;\n            end;\n        end;\n    end;\n    \n    % uniform?\n    % --------\n    if strcmpi(g.uniform, 'on') & ( ~isempty(g.vscale) | ~isempty(g.hscale))\n        disp('uniform scaling: averaging left-right and rear-front scaling factor');\n        hscalefact = mean([hscalefact vscalefact]);\n        vscalefact = hscalefact;\n    end;\n    \n    % scaling data\n    % ------------\n    if ~isempty(g.vscale) | ~isempty(g.hscale) | ~isempty(g.scale)\n        Y = Y/hscalefact;\n        X = X/vscalefact;\n        Z = Z/((hscalefact+vscalefact)/2);\n    end;\n    \n    % updating structure\n    % ------------------\n    if strcmpi(g.coordinates, 'sph') |  strcmpi(g.coordinates, 'pol') \n        [phi,theta] = cart2pol(Y, X);\n        phi = phi/pi*180;\n        if strcmpi(g.coordinates, 'pol')\n            theta = theta/0.25*46;\n        end;\n        \n        % convert to other types of coordinates\n        % -------------------------------------\n        labels = names';\n        chanlocs = struct('labels', names, 'sph_theta_besa', mattocell(theta), ...\n                'sph_phi_besa', mattocell(phi), 'sph_radius', { chanlocs.sph_radius });\n        chanlocs = convertlocs( chanlocs, 'sphbesa2all');\n    else\n        for index = 1:length(chanlocs)\n            chanlocs(index).X = X(index);\n            chanlocs(index).Y = Y(index);\n            chanlocs(index).Z = Z(index);\n        end;\n        chanlocs = convertlocs(chanlocs, 'cart2all');\n    end;\n    \nfunction showmsg(begmsg, endmsg, struct);\n    if length(struct) <= 1\n        disp([ begmsg ' ''' struct{1} ''' ' endmsg]);\n    elseif length(struct) <= 2\n        disp([ begmsg ' ''' struct{1} ''' and ''' struct{2}  ''' ' endmsg]);\n    elseif length(struct) <= 3\n        disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''' and ''' struct{3}  ''' ' endmsg]);\n    else\n        disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''', ''' struct{3}  ''' ... ' endmsg]);\n    end;\n    \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/adjustlocs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2359795196453239}}
{"text": "%% RRT for 3 DOF Mobile Robot\n% \n% <html><body><table style=\"border: 2px solid orange;\"><tr>\n% <td style=\"font-size:12pt;\">Do not change anything in rrt.m,\n% rrt_star.m and rrt_star_fn.m\n% </td></tr></table></body></html>\n% \n\n%% Getting started\n% Create *main_3dof_mobile_rrt.m* file. You can create m-file with any other name, that is\n% perfectly okay, this will not affect to the solution of a path/motion\n% planning problem. All the sources could be found in examples/ directory\n% of the distribution.\n%\n\n%% Step 1: Choosing the map \n% Firstly, we should define what map to use. It is done by defining map\n% structure the sample code is goes after.\n%\n%   map = struct('name', 'bench_june1.mat', 'start_point', [-14.5 -7.5], 'goal_point', [10 -0.65]);\n%\n\n%%\n%\n% * *name field* defines the file name in maps/ directory\n% * *start_point* defines the initial point of the problem\n% * *goal_point* defines the goal point on the map\n%\n\n%% Step 2: Setting maximum number of iterations\n%\n%   max_iter = 20e3;\n%\n% * *max_iter* variable defines how much iteration should be done to solve\n% the path planning problem.\n\n%% Step 3: Do we have to benchmark \n%\n%   is_benchmark = false;\n%\n% * *is_benchmark* enables benchmarking. For more details please read the\n% sources of rrt.m, rrt_star.m and rrt_star_fn.m\n\n%% Step 4: Setting random seed\n%\n%   rand_seed = 40;\n%\n% * *rand_seed* variable is a random seed for random number generator, it\n% is used for sampling nodes. It is usually used for benchmarking. We set\n% the same map, however the random seed is different for the same map. You\n% can use *now* if you don't care about random seed.\n%\n%   rand_seed = now;\n%\n\n%% Step 5: Choosing the class (model) we want \n% \n%   variant = 'FNSimple3D';\n%\n% * *variant* defines from what class we should instantiate the object. In\n% other words it defines what model we choose for application of RRT.\n%\n% *FNSimple3D* is a name of a class which contains all necessary methods\n% and fields in order to represent simple 3 DOF Mobile Robot model.\n\n%% Step 6: Rapidly-Exploring Random Tree (RRT)\n%\n%   rrt(map, max_iter, is_benchmark, rand_seed, variant);\n%\n% Line above runs RRT with given parameters. In addition, *rrt* function\n% returns the class object with a certain solution.\n\n%% Sources of *main_3dof_mobile_rrt.m*\n% Press \n% <matlab:edit('examples/main_3dof_mobile_rrt.m') here>\n% to play with example code.\n%\n%   % 3 DOF mobile robot example.\n%   % by Almaskhan Baimyshev\n%   % 08/28/2013\n%   \n%   map = struct('name', 'bench_june1.mat', 'start_point', [-14.5 -7.5], 'goal_point', [10 -0.65]);\n%   max_iter = 20e3;\n%   is_benchmark = false;\n%   rand_seed = 40;\n%   variant = 'FNSimple3D';\n%   result = rrt(map, max_iter, is_benchmark, rand_seed, variant);\n%\n", "meta": {"author": "olzhas", "repo": "rrt_toolbox", "sha": "b07e72cebe7053661083f4c4d1843aae88e1ad3c", "save_path": "github-repos/MATLAB/olzhas-rrt_toolbox", "path": "github-repos/MATLAB/olzhas-rrt_toolbox/rrt_toolbox-b07e72cebe7053661083f4c4d1843aae88e1ad3c/doc/threedof_rrt_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2359099478872609}}
{"text": "function byteStream = mrMeshTcpSerializeParams(params)\n%\n%    byteStream = mrMeshTcpSerializeParams(params)\n%\n% Turns the Matlab structure params into a byte-stream suitable for\n% TCP transmission using the mrMesh protocol.  That protocol uses pnet.\n%\n% See also:  mrMesh, pnet_WriteMsg and pnet_ReadMsg\n%\n% HISTORY\n% 2007.04.12 RFD wrote it.\n\n\nif(~isstruct(params))\n    byteStream=params;\n    return;\nend\n\nbyteStream = [];\nif(~isempty(params))\n    % the termination char is a new-line\n    termSeq = uint8(sprintf('\\n'));\n    eq = uint8(' = ');\n    % arrays (non-scalars) are sent in raw for and are enclodes in\n    % single-quotes. Scalars are sent in text (sprintf) form.\n    sq = uint8('''');\n    fnStr = fieldnames(params);\n    \n    for(ii=1:length(fnStr))\n        data = getfield(params,fnStr{ii});\n        sz = size(data);\n        data = data(:)';\n        fn = uint8(fnStr{ii});\n        if(ischar(data))\n            fn = uint8(fnStr{ii});\n            byteStream = [byteStream fn eq sq data sq termSeq];\n            \n        elseif(length(data)>1)\n            % *** FIX ME ***\n            % The current mrMesh server expects all numeric arrays to be\n            % sent as doubles. This sends 8x more data than necessary when\n            % sending uint8's! We should fix the server so that it can\n            % accept various data types.\n            dimStr = sprintf('%d,',sz);\n            fn = uint8(sprintf('%s[%s]',fnStr{ii},dimStr(1:end-1)));\n            byteStream = [byteStream fn eq sq typecast(double(data),'uint8') sq termSeq];\n        else\n            fn = uint8(fnStr{ii});\n            if(isinteger(data))\n                byteStream = [byteStream fn eq uint8(sprintf('%d',data)) termSeq];\n            else\n                byteStream = [byteStream fn eq uint8(sprintf('%f',data)) termSeq];\n            end\n        end\n    end\nend\n\nbyteStream(end+1) = 0;\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrMesh/meshserver/mrMeshTcpSerializeParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23590994102134782}}
{"text": "function []=panel2fdisp(N,n,T,Units,endo,Ymat,stringdates2,decimaldates2,Fstartlocation,Fendlocation,forecast_estimates,pref)\n\n\n\n\n\n\n\n\n% preliminary task: gather in a cell the values to be plotted\n% initiate the cell\nplotdata={};\n% because forecasts have to be computed for each unit, loop over units\nfor ii=1:N\n% each cell entry is a matrix of actual and forecast values\n% this matrix comprises 4 rows: the first row is actual data, while the three other rows are the estimates (point estimates and confidence bands) for the forecasts\n% also, this matrix has a number of rows equal to the dimension of decimaldates2, which comprises the total period sample+forecasts\n   % loop over variables\n   for jj=1:n\n      plotdata{jj,1,ii}=nan(4,size(decimaldates2,1));\n      % record actual sample values\n      plotdata{jj,1,ii}(1,1:T)=Ymat(:,jj,ii)';\n      % copy the last point of the actual sample for the forecast part of the matrix (required to have a clean plot)\n      plotdata{jj,1,ii}(:,Fstartlocation-1)=repmat(Ymat(Fstartlocation-1,jj,ii),4,1);\n      % record forecast, lower bound\n      plotdata{jj,1,ii}(2,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(1,:);\n      % record forecast, point estimate\n      plotdata{jj,1,ii}(3,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(2,:);\n      % record forecast, upper bound\n      plotdata{jj,1,ii}(4,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(3,:);\n   end\nend\n% then plot the figure\nif pref.plot\nforecast=figure('Tag','BEARresults');\nset(forecast,'Color',[0.9 0.9 0.9]);\nset(forecast,'name','unconditional forecasts');\n% initiate the count\ncount=0;\n% loop over units\nfor ii=1:N\n   % loop over endogenous variables\n   for jj=1:n\n   % increment count\n   count=count+1;\n   % then plot\n   subplot(N,n,count)\n   hold on\n   Xpatch=[decimaldates2(Fstartlocation-1:Fendlocation,1)' fliplr((decimaldates2(Fstartlocation-1:Fendlocation,1))')];\n   Ypatch=[plotdata{jj,1,ii}(2,Fstartlocation-1:Fendlocation) fliplr(plotdata{jj,1,ii}(4,Fstartlocation-1:Fendlocation))];\n   Fpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);\n   set(Fpatch,'facealpha',0.6);\n   set(Fpatch,'edgecolor','none');\n   plot(decimaldates2,plotdata{jj,1,ii}(3,:),'Color',[0.4 0.4 1],'LineWidth',2);\n   plot(decimaldates2,plotdata{jj,1,ii}(1,:),'Color',[0 0 0],'LineWidth',2);\n   hold off\n   set(gca,'XLim',[decimaldates2(1,1) decimaldates2(end,1)],'FontName','Times New Roman');\n   set(gca,'XGrid','on');\n   set(gca,'YGrid','on');\n      % top labels\n      if count<=n\n      title(endo{count,1},'FontWeight','normal');\n      end\n      % side labels\n      if jj==1\n      ylabel(Units{ii,1},'FontWeight','normal');\n      end\n   end\nend\nend\n\n\n\n% save on Excel\n% create the cell that will be saved on excel\nforecastcell={};\n% build preliminary elements: space between the tables\nvertspace=repmat({''},size(stringdates2,1)+3,1);\nhorzspace=repmat({''},3,6*n);\n% loop over units\nfor ii=1:N\n% initiate the cell of results\nunitcell={};\n   % loop over endogenous variables (horizontal dimension)\n   for jj=1:n\n   % create a header\n   header=[{[Units{ii,1} ': ' endo{jj,1}]} {''} {''} {''} {''};{''} {''} {''} {''} {''};{''} {'actual'} {'lower bound'} {'median'} {'upper bound'}];\n   % complete the cell\n   endocell=[[header;stringdates2 num2cell((plotdata{jj,1,ii})')] vertspace];\n   % concatenate to the previous parts of unitcell\n   unitcell=[unitcell endocell];\n   end\n% concatenate to the previous parts of afcell\nforecastcell=[forecastcell;horzspace;unitcell];\nend\n% trim\nforecastcell=forecastcell(4:end,1:end-1);\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),forecastcell,'forecasts','B2');\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/panel2fdisp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23590994102134782}}
{"text": "function vbrfa2010_testbed_experiment(D, common_nu, common_tau, maxiter)\n\ntestbed_experiment_vbrfa(D, common_nu, common_tau, maxiter, 'robustness', ...\n                         'independent-t'); \ntestbed_experiment_vbrfa(D, common_nu, common_tau, maxiter, 'robustness', ...\n                         'multivariate-t');\ntestbed_experiment_vbrfa(D, common_nu, common_tau, maxiter, 'robustness', ...\n                         'none');\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/vbrfa2010/vbrfa2010_testbed_experiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2359099410213478}}
{"text": "function dat = read_spmeeg_data(filename, varargin)\n\n% read_spmeeg_data() - import SPM5 and SPM8 meeg datasets\n%\n% Usage:\n%   >> header = read_spmeeg_data(filename, varargin);\n%\n% Inputs:\n%   filename - [string] file name\n%\n% Optional inputs:\n%   'begsample'      first sample to read\n%   'endsample'      last sample to read\n%   'chanindx'  -    list with channel indices to read\n%   'header'    - FILEIO structure header\n%\n% Outputs:\n%   dat    - data over the specified range\n% _______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n% Vladimir Litvak\n\nif nargin < 1\n    help read_spmeeg_data;\n    return;\nend;\n\ntypenames = {'uint8','int16','int32','float32','float64','int8','uint16','uint32'};\ntypesizes   = [1  2  4  4 8 1 2 4];\n\nheader    = ft_getopt(varargin, 'header');\nbegsample = ft_getopt(varargin, 'begsample');\nendsample = ft_getopt(varargin, 'endsample');\nchanindx  = ft_getopt(varargin, 'chanindx');\n\nif isempty(header)\n    header = read_spmeeg_header([filename(1:(end-3)) 'mat']);\nend\n\nif isempty(begsample), begsample = 1; end;\nif isempty(endsample), endsample = header.nSamples; end;\n\ndatatype = 'float32-le';\nscale = [];\nif isfield(header, 'orig')\n    if isfield(header.orig, 'data') && isnumeric(header.orig.data) ...\n            && ~isempty(header.orig.data)\n        try\n            dat = reshape(header.orig.data(chanindx, :, :), length(chanindx), []);\n            dat = dat(:, begsample:endsample);\n            return;\n        end\n    end\n\n    if isfield(header.orig, 'datatype')\n        datatype = header.orig.datatype;\n    elseif isfield(header.orig.data, 'datatype')\n        datatype = header.orig.data.datatype;\n    end\n    if isfield(header.orig, 'scale')\n        if isnumeric(header.orig.scale)\n            scale = header.orig.scale;\n        else\n            scale = header.orig.scale.values;\n        end\n    elseif isfield(header.orig.data, 'scale')\n        scale = header.orig.data.scale;\n    end\nend\n\nstepsize = typesizes(strmatch(strtok(datatype, '-'), typenames));\n\nfilename = [filename(1:(end-3)) 'dat'];\n\nfid = fopen_or_error(filename, 'r');\nfseek(fid, stepsize*header.nChans*(begsample-1), 'bof');\n[dat, siz] = fread(fid, [header.nChans, (endsample-begsample+1)], strtok(datatype, '-'));\nfclose(fid);\n\nif ~isempty(chanindx)\n    % select the desired channels\n    dat = dat(chanindx,:);\nend\n\nif ~isempty(scale) && ~ismember(strtok(datatype, '-'), {'float32', 'float64'})\n    \n    % This is a somewhat complicated mechanism to figure out which scaling\n    % coefficients go with which data points in a generic way\n    \n    trlind = floor(((begsample:endsample)-1)/header.nSamples)+1;\n\n    utrlind = unique(trlind);\n\n    for i = 1:length(utrlind)\n        dat(:, trlind == utrlind(i)) = dat(:, trlind == utrlind(i)).* ...\n            repmat(squeeze(scale(chanindx,utrlind(i))), 1, sum(trlind == utrlind(i)));\n    end\n\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/fileio/private/read_spmeeg_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2359099410213478}}
{"text": "% This M file creates the \"LossSpec_IGBT_Library.mat \" file \n% containing loss and thermal IGBT models provided in the\n% \"LossModelib.mdl' libray.\n% IGBT specifications are saved in the \"LossSpec_IGBT\" structure. \n%\n% Data provided below for three different commercial \n% IGBT/Diode half-bridge packs are extracted from manufacturer data sheets \n% (see pdf files provided in the same directory).\n%\n% How to to add your own IGBT specifications\n% ------------------------------------------\n%   1)  Open the \"LossModelib.mdl' library\n%   2)  Duplicate a cell containing specifications of one existing IGBT \n%       and insert it at the end of this file \n%       (see \"Add your own specifications here\" cell)\n%   3)  Modify this new set of data according to your specifications\n%   4)  Run this script file in order to update the \"LossSpec_IGBT_Library.mat \" file\n%   5)  In the \"LossModelib.mdl' library\n%            - select the IGBT or half-bridge model to update\n%            - open the Mask Editor \n%            - select \"IGBT_Type\" parameter\n%            - In the \"Popups\" window, enter a new description \n%              after existing IGBT descriptions \n%   6) Save the \"LossModelib.mdl' library.\n% Note: Future release of SPS will provide an easy-to-use GUI to add or\n% edit device characteristics.\n\n% Pierre Giroux, Hydro-Quebec (IREQ), March 2012\n\n% Ic=  Collector current\n% Vce= Collector-emitter voltage\n% Eon= Turn-on switching energy (mJ)\n% Eoff= Turn-off switching energy (mJ)\n% Tj= Junction temperature (degrees Celsius)\n% Vcc= Supply voltage (V)\n% Note1: IGBT switching energies are function of Vcc, Ic and Tj\n% Note2: IGBT on-state losses = Vce (function of Ic and Tj) * Ic\n%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nclear all\n\n%% Fuji Electric IGBT Module, 2 in one-package, 600V, 150A\nType='IGBT';\nManufacturer= 'Fuji Electric';\nPartNo= '2MBI150U2A 060';\nDescription= 'IGBT Module, 2 in one-package, 600V, 150A';\n%\n% Typical turn-on (Eon)switching energies vs Ic\nVcc_Eon= 300;\nTj_Eon=  [  25 125 ]; \nIc_Eon=  [  0  25    50    75    100   125   150   175   200   225  ]; \nEon=     [  0  0.85  1.62  2.40  3.18  4.02  4.87  5.83  6.81  7.84\n            0  1.12  2.15  3.20  4.27  5.49  6.67  8.18  9.85  11.6 ]; \n% Typical turn-off (Eoff)switching energies vs Ic\nVcc_Eoff= 300;\nTj_Eoff=  [ 25 125 ]; \nIc_Eoff=  [ 0  25    50    75    100   125   150   175   200   225  ]; \nEoff=     [ 0  0.66  1.33  2.13  3.18  4.37  5.46  6.90  8.34  9.92 \n            0  0.87  1.97  2.99  4.27  5.49  6.90  8.43  10.1  11.8 ];        \n% Typical on-state characteristics\nTj_OnState=  [ 25 125 ];      \nIc_OnState = [ 0   1      5     10    15    33    50    75    100   150   200   300 ]; \nVce_OnState= [ 0   0.64   0.74  0.80  0.87  1.08  1.19  1.37  1.51  1.77  2.03  2.48\n               0   0.48   0.66  0.75  0.87  1.08  1.26  1.50  1.68  2.02  2.35  3.01 ];\n%-------------------------------------------------------------------------\n%\n% Thermal Impedance:\n%\nRth_jc=0.25;    % Junction-to-Case thermal resistance(K/W)\n% Based on transient thermal impedance vs. time curve\nCth_j=0.27;   % Junction thermal capacitance (Joule/Kelvin)\n%\n%-------------------------------------------------------------------------\nLossSpec_IGBT(1)= struct('Type',Type, 'Manufacturer',Manufacturer, 'PartNo',PartNo, ...\n    'Description',Description, 'Vcc_Eon',Vcc_Eon, ...\n    'Tj_Eon',Tj_Eon, 'Ic_Eon',Ic_Eon, 'Eon',Eon, 'Vcc_Eoff',Vcc_Eoff, ...\n    'Tj_Eoff',Tj_Eoff, 'Ic_Eoff',Ic_Eoff, 'Eoff',Eoff, ...\n    'Tj_OnState',Tj_OnState, 'Ic_OnState',Ic_OnState, 'Vce_OnState',Vce_OnState, ...\n    'Rth_jc',Rth_jc, 'Cth_j',Cth_j);\nclear Vcc_Eon Tj_Eon Ic_Eon Eon Vcc_Eoff Tj_Eoff Ic_Eoff Eoff Tj_OnState ...\n      Ic_OnState Vce_OnState Manufacturer PartNo Description Type ...\n      Rth_jc Cth_j \n%=========================end of specifications===========================\n\n%% ABB IGBT Module, ABB HiPak, 1700V, 800A\n\nType='IGBT';\nManufacturer= 'ABB';\nPartNo= '5SNE 0800M170100';\nDescription= 'IGBT Module, ABB HiPak, 1700V, 800A';\n\n% For Tj=25 deg. C, manufacturer specifications provide Eon and Eoff at only one current (800 A).\n% The Eon and and Eoff values @ Tj=25 and 125 deg. C, 800 A specified below\n% are used to deduce the Eon(Ic) and Eoff(Ic) curves @ Tj=25 deg. C,\n% from the Eon(Ic) and Eoff(Ic) curves @ Tj=125 deg. C\n% assuming that Eon and Eoff stay proportionnal to their values @ Tj= 125 deg. C\n\nTj_800A=   [ 25   125 ];  % Junction temperature (degrees Celsius)\nEon_800A=  [ 160  250 ];  % Turn-on energy at Tj_800A (mJ) for Ic=800A\nEoff_800A= [ 220  300 ];  % Turn-off energy at Tj_800A (mJ) for Ic=800A\n%\n% Typical turn-on (Eon)switching energies vs Ic\nVcc_Eon= 900;  \nTj_Eon=  [ 25 125 ];    \nIc_Eon=    [ 0 198  399 501 686 800 900 999 1100 1200 1300 1440 1550 1620 ];\n% Eon @ 125 C (per data sheet curves)\nEon(2,:)=  [ 0 73.4 108 136 202 250 300 350 413  480  551  652  750  810  ];\n% Eon @ 25 C (calculated using data sheet spec at 25 C)\nEon(1,:)=Eon_800A(1)/Eon_800A(2) * Eon(2,:);\n%\n% Typical turn-off (Eoff)switching energies vs Ic\nVcc_Eoff= 900;  \nTj_Eoff=  [ 25 125 ];    \nIc_Eoff=    [ 0 198  399 501 686 800 900 999 1100 1200 1300 1440 1550 1620 ];\n% Eon @ 125 C (per data sheet curves)\nEoff(2,:)=  [ 0 99.7 161 192 255 300 335 372 413  451  497  558  608  640  ]; \n% Eon @ 25 C (calculated using data sheet spec at 25 C)\nEoff(1,:)=Eoff_800A(1)/Eoff_800A(2) * Eoff(2,:);\n%\n% IGBT - Typical on-state characteristics\nTj_OnState=  [ 25 125 ];      % (C)\nIc_OnState = [ 0  0.01  46   102  194  299  399  498  601  700  797  999  1200 1500 ];\nVce_OnState= [ 0  0.70  0.99 1.19 1.38 1.57 1.72 1.86 2.00 2.13 2.25 2.50 2.74 3.11\n               0  0.70  0.87 1.12 1.38 1.65 1.85 2.04 2.23 2.41 2.58 2.93 3.28 3.82 ]; \n%-------------------------------------------------------------------------\n% Thermal properties:\n%\nRth_jc=0.021;   % Junction-to-Case thermal resistance(K/W)\n%\n% Based on transient thermal impedance vs. time curve\nCth_j=6.5095;     % Junction thermal capacitance (Joule/Kelvin)\n%\n%-------------------------------------------------------------------------\n%-------------------------------------------------------------------------\nLossSpec_IGBT(2)= struct('Type',Type, 'Manufacturer',Manufacturer, 'PartNo',PartNo, ...\n    'Description',Description, 'Vcc_Eon',Vcc_Eon, ...\n    'Tj_Eon',Tj_Eon, 'Ic_Eon',Ic_Eon, 'Eon',Eon, 'Vcc_Eoff',Vcc_Eoff, ...\n    'Tj_Eoff',Tj_Eoff, 'Ic_Eoff',Ic_Eoff, 'Eoff',Eoff, ...\n    'Tj_OnState',Tj_OnState, 'Ic_OnState',Ic_OnState, 'Vce_OnState',Vce_OnState, ...\n    'Rth_jc',Rth_jc, 'Cth_j',Cth_j);\n%\nclear Vcc_Eon Tj_Eon Ic_Eon Eon Vcc_Eoff Tj_Eoff Ic_Eoff Eoff Tj_OnState ...\n      Ic_OnState Vce_OnState Manufacturer PartNo Description Type ...\n      Rth_jc Cth_j Tj_800A Eon_800A Eoff_800A\n%=========================end of specifications============================\n\n\n%% ABB  Half-bridge IGBT Module, 3300V, 250A\nType='IGBT';\nManufacturer= 'ABB';\nPartNo= '5SNG 0250P330300';\nDescription= 'Half-bridge IGBT Module, 3300V, 250A';\n\n% For Tj=25 deg. C, manufacturer specifications provide Eon and Eoff at only one current (250 A).\n% The Eon and and Eoff values @ Tj=25 and 125 deg. C, 250 A specified below\n% are used to deduce the Eon(Ic) and Eoff(Ic) curves @ Tj=25 deg. C,\n% from the Eon(Ic) and Eoff(Ic) curves @ Tj=125 deg. C\n% assuming that Eon and Eoff stay proportionnal to their values @ Tj= 125 deg. C\n\n\nTj_250A=   [ 25    125 ];  % Junction temperature (degrees Celsius)\nEon_250A=  [ 330   425 ];  % Turn-on energy at Tj_250A (mJ) for Ic=250A\nEoff_250A= [ 330   450 ];  % Turn-off energy at Tj_250A (mJ) for Ic=250A\n%\n% Typical turn-on (Eon)switching energies vs Ic\nVcc_Eon= 1800;  \nTj_Eon=  [ 25 125 ];    \nIc_Eon=   [ 0 37.8  99   199  250  300  349  400  451  499  ];\n% Eon @ 125 C (per data sheet curves)\nEon(2,:)= [ 0 83.6  160  318  425  522  643  775  919  1070 ];\n% Eon @ 25 C (calculated using data sheet spec at 25 C)\nEon(1,:)=Eon_250A(1)/Eon_250A(2) * Eon(2,:);\n%\n% Typical turn-off (Eoff)switching energies vs Ic\nVcc_Eoff= 1800;  \nTj_Eoff=  [ 25 125 ];    \nIc_Eoff=    [ 0 37.8  99   199  250  300  349  400  451  499  ];\n% Eon @ 125 C (per data sheet curves)\nEoff(2,:)=  [ 0 118   218  381  450  543  622  699  782  861  ]; \n% Eon @ 25 C (calculated using data sheet spec at 25 C)\nEoff(1,:)=Eoff_250A(1)/Eoff_250A(2) * Eoff(2,:);\n%\n% IGBT - Typical on-state characteristics\nTj_OnState=  [ 25 125 ];      % (C)\nIc_OnState=  [ 0   1      16    77    131   174   276   375   500  ];\nVce_OnState= [ 0   0.51   1.00  1.50  1.81  2.04  2.49  2.88  3.37 \n               0   0.50   1.00  1.71  2.18  2.50  3.11  3.77  4.52 ]; \n%-------------------------------------------------------------------------\n% Thermal properties:\n%\nRth_jc=0.051;   % Junction-to-Case thermal resistance(K/W)\n%\n% Based on transient thermal impedance vs. time curve\nCth_j=2.6804;     % Junction thermal capacitance (Joule/Kelvin)\n%\n%-------------------------------------------------------------------------\nLossSpec_IGBT(3)= struct('Type',Type, 'Manufacturer',Manufacturer, 'PartNo',PartNo, ...\n    'Description',Description, 'Vcc_Eon',Vcc_Eon, ...\n    'Tj_Eon',Tj_Eon, 'Ic_Eon',Ic_Eon, 'Eon',Eon, 'Vcc_Eoff',Vcc_Eoff, ...\n    'Tj_Eoff',Tj_Eoff, 'Ic_Eoff',Ic_Eoff, 'Eoff',Eoff, ...\n    'Tj_OnState',Tj_OnState, 'Ic_OnState',Ic_OnState, 'Vce_OnState',Vce_OnState, ...\n    'Rth_jc',Rth_jc, 'Cth_j',Cth_j);\n%\nclear Vcc_Eon Tj_Eon Ic_Eon Eon Vcc_Eoff Tj_Eoff Ic_Eoff Eoff Tj_OnState ...\n      Ic_OnState Vce_OnState Manufacturer PartNo Description Type ...\n      Rth_jc Cth_j Tj_250A Eon_250A Eoff_250A\n%=========================end of specifications===========================\n\n%% Add your own specifications here\n% Type='IGBT';\n% Manufacturer= 'My Manufacturer';\n% PartNo= 'XXX';\n% Description= 'My IGBT Module, YYY V, ZZZ A;\n% ....\n\n%% Save IBGT thermal data structure \"LossSpec_IGBT\" in \"LossSpec_IGBT_Library.mat\" file\nsave LossSpec_IGBT_Library LossSpec_IGBT\n%----------------------------END OF SCRIPT FILE--------------------------------;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35980-loss-calculation-in-a-buck-converter-using-simpowersystems-and-simscape/LossCalculationBuckConverter/LossSpec_IGBT_LibCreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.23589573663843538}}
{"text": "classdef FixedInCoordSysSensorSteeringModel < AbstractSensorSteeringModel\n    %FixedInCoordSysSensorSteeringModel Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        rhtAsc(1,1) double\n        dec(1,1) double\n        roll(1,1) double\n        coordSys AbstractGeometricCoordSystem\n        \n        lvdData LvdData\n    end\n    \n    methods\n        function obj = FixedInCoordSysSensorSteeringModel(rhtAsc, dec, roll, coordSys, lvdData)\n            obj.rhtAsc = rhtAsc;\n            obj.dec = dec;\n            obj.roll = roll;\n            obj.coordSys = coordSys;\n            \n            obj.lvdData = lvdData;\n        end\n        \n        function [boreDir] = getBoresightVector(obj, time, vehElemSet, ~, inFrame)\n            rotMat = obj.coordSys.getCoordSysAtTime(time, vehElemSet, inFrame);\n            \n            [x,y,z] = sph2cart(obj.rhtAsc, obj.dec, 1);\n            v = [x;y;z];\n            \n            boreDir = rotMat * v;\n        end\n        \n        function rollAngle = getBoresightRollAngle(obj)\n            rollAngle = obj.roll;\n        end\n        \n        function parentDcm = getSensorParentDcmToInertial(obj, time, vehElemSet, dcm, inFrame)\n            parentDcm = obj.coordSys.getCoordSysAtTime(time, vehElemSet, inFrame);\n        end\n        \n        %body to inertial\n        function sensorDcm = getSensorDcmToInertial(obj, time, vehElemSet, dcm, inFrame)\n%             sensorToParentDcm = eul2rotmARH([obj.rhtAsc,obj.dec,obj.roll],'zyx');\n%             parentToInertialDcm = obj.getSensorParentDcmToInertial(time, vehElemSet, dcm, inFrame);\n%             \n%             sensorDcm = parentToInertialDcm * sensorToParentDcm;\n\n            boreDir = obj.getBoresightVector(time, vehElemSet, dcm, inFrame);\n            M1 = vrrotvec2mat(vrrotvec([1;0;0], boreDir));\n            M2 = rotx(rad2deg(obj.getBoresightRollAngle()));\n            \n            sensorDcm = M2 * M1;\n        end\n        \n        function tf = isVehDependent(obj)\n            tf = obj.coordSys.isVehDependent();\n        end\n        \n        function useTf = openEditDialog(obj)\n            output = AppDesignerGUIOutput({false});\n            lvd_EditFixedInCoordSysSensorSteeringModelGUI_App(obj, obj.lvdData, output);\n            useTf = output.output{1};\n        end\n        \n        function enum = getEnum(obj)\n            enum = SensorSteeringModelEnum.FixedInCoordSys;\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Sensors/SensorModels/SensorSteeringModels/@FixedInCoordSysSensorSteeringModel/FixedInCoordSysSensorSteeringModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.235891203199595}}
{"text": "%io_loadspec_data.m\n%Jamie Near, McGill University 2014.\n%\n% USAGE:\n% [out,out_w]=io_loadspec_data(filename,sw,Larmor,subspecs,te,tr);\n% \n% DESCRIPTION:\n% Reads in philips MRS data (.data and .list files) using code adapted from \n% PhilipsRead_data.m, provided as part of the Gannet software package by \n% Richard Edden (gabamrs.blogspot.com).\n% \n% op_loadspec_data outputs the data in structure format, with fields \n% corresponding to time scale, fids, frequency scale, spectra, and header \n% fields containing information about the acquisition.  The resulting \n% matlab structure can be operated on by the other functions in this MRS \n% toolbox.  NOTE:  Since the Gannet code is geared towards edited GABA MRS \n% data, this code may not be general enough to handle all types of MRS data.  \n% Suggestions are most welcome.\n% \n% INPUTS:\n% filename   = filename of Philips .data file to be loaded.\n% sw         = spectral width (Hz) \n% Larmor     = Larmor frequency (Hz/ppm, ie.  127 for 3T)\n% subspecs   = number of subspectra in the data (from spectral editing, ISIS, etc.)\n% te         = echo time (ms).  Optional, default is [].\n% tr         = repetition time (ms).  Optional, default is [].\n%\n% OUTPUTS:\n% out        = Input water suppressed dataset in FID-A structure format.\n% out_w      = Input water reference dataset in FID-A structure format. \n\n\nfunction [out,out_w]=io_loadspec_data(filename,sw,Larmor,subspecs,te,tr);\n\nif nargin<6\n    if nargin<5\n        te=[];\n    end\n    tr=[];\nend\n\n\n%read in the data using the philipsDataLoad.m (adapted from PhilipsRead_data.m)\n[FullData,WaterData]=philipsDataLoad(filename);\n\n%As far as I can tell, the data that comes out of the philipsDataLoad\n%function is normally a N x Navgs matrix.  The coils have already been \n%combined. The Navgs dimension contains all the subspectra, so we will \n%split them now.  Note, that in the data-list format that I have seen, the\n%edit-OFF subspectra appear in elements [1 2 5 6 9 10 13 14...] and the\n%edit-ON subspectra appear in the elements [3 4 7 8 11 12 15 16...].  Other sequences\n%may result in a different subspecs order, but for now we will separate the \n%subspectra in this way.\n%If the data has multiple subspectra \nif subspecs>1\n    %First make an vector that holds the indices of the ON subspectra:\n    totalAvgs=size(FullData,2);\n    OFFindices=[1:2:totalAvgs]-mod([0:(totalAvgs/2)-1],2);\n    ONindices=[2:2:totalAvgs]+mod([1:totalAvgs/2],2);\n    %Now split the subspectra out of the \"averages\" dimension:\n    data(:,:,1)=FullData(:,OFFindices);\n    data(:,:,2)=FullData(:,ONindices);\nelse\n    data=FullData;\nend\n\nfids=squeeze(data);\nfids_w=squeeze(WaterData)';\n\nsz=size(fids);\nsz_w=size(fids_w);\n\n%Find the magnetic field strength:\nBo=Larmor/42.577;\n\n%Find the number of averages:\nNaverages=size(fids,2)*size(fids,3);\nNaverages_w=size(fids_w,2)*size(fids_w,3);\n\n%In Philips data/list format, coil channels have already been combined:\nNcoils=1;\nNcoils_w=1;\n\n%Now create a record of the dimensions of the data array.  \ndims.t=1;\ndims.coils=0;\ndims.averages=2;\nif subspecs>1\n    dims.subSpecs=3;\nelse\n    dims.subSpecs=0;\nend\n\ndims_w.t=1;\ndims_w.coils=0;\ndims_w.averages=2;\ndims_w.subSpecs=0;\n\n\nspecs=fftshift(ifft(fids,[],dims.t),dims.t);\nspecs_w=fftshift(ifft(fids_w,[],dims_w.t),dims_w.t);\n\n\n%Now get relevant scan parameters:*****************************\n\n%Get Spectral width and Dwell Time\nspectralwidth=sw;\ndwelltime=1/spectralwidth;\n    \n%Get TxFrq\ntxfrq=Larmor*1e6;\n\n%Leave date blank\ndate='';\n\n%Find the number of averages.  'averages' will specify the current number\n%of averages in the dataset as it is processed, which may be subject to\n%change.  'rawAverages' will specify the original number of acquired \n%averages in the dataset, which is unchangeable.\n%FOR WATER SUPPRESSED DATA:\nif dims.subSpecs ~=0\n    if dims.averages~=0\n        averages=sz(dims.averages)*sz(dims.subSpecs);\n        rawAverages=averages;\n    else\n        averages=sz(dims.subSpecs);\n        rawAverages=1;\n    end\nelse\n    if dims.averages~=0\n        averages=sz(dims.averages);\n        rawAverages=averages;\n    else\n        averages=1;\n        rawAverages=1;\n    end\nend\n\n%FOR WATER UNSUPPRESSED DATA:\nif dims_w.subSpecs ~=0\n    if dims_w.averages~=0\n        averages_w=sz(dims_w.averages)*sz(dims_w.subSpecs);\n        rawAverages_w=averages_w;\n    else\n        averages_w=sz(dims_w.subSpecs);\n        rawAverages_w=1;\n    end\nelse\n    if dims_w.averages~=0\n        averages_w=sz(dims_w.averages);\n        rawAverages_w=averages_w;\n    else\n        averages_w=1;\n        rawAverages_w=1;\n    end\nend\n\n\n%Find the number of subspecs.  'subspecs' will specify the current number\n%of subspectra in the dataset as it is processed, which may be subject to\n%change.  'rawSubspecs' will specify the original number of acquired \n%subspectra in the dataset, which is unchangeable.\n%FOR WATER SUPPRESSED DATA:\nif dims.subSpecs ~=0\n    subspecs=sz(dims.subSpecs);\n    rawSubspecs=subspecs;\nelse\n    subspecs=1;\n    rawSubspecs=subspecs;\nend\n\n%FOR WATER UNSUPPRESSED DATA:\nif dims_w.subSpecs ~=0\n    subspecs_w=sz(dims.subSpecs);\n    rawSubspecs_w=subspecs_w;\nelse\n    subspecs_w=1;\n    rawSubspecs_w=subspecs_w;\nend\n\n%****************************************************************\n\n\n%Calculate t and ppm arrays using the calculated parameters:\nf=[(-spectralwidth/2)+(spectralwidth/(2*sz(1))):spectralwidth/(sz(1)):(spectralwidth/2)-(spectralwidth/(2*sz(1)))];\nppm=f/(Bo*42.577);\nppm=ppm+4.65;\n\nt=[0:dwelltime:(sz(1)-1)*dwelltime];\n\n\n%FOR WATER SUPPRESSED DATA\n%FILLING IN DATA STRUCTURE\nout.fids=fids;\nout.specs=specs;\nout.sz=sz;\nout.ppm=ppm;  \nout.t=t;    \nout.spectralwidth=spectralwidth;\nout.dwelltime=dwelltime;\nout.txfrq=txfrq;\nout.date=date;\nout.dims=dims;\nout.Bo=Bo;\nout.averages=averages;\nout.rawAverages=rawAverages;\nout.subspecs=subspecs;\nout.rawSubspecs=rawSubspecs;\nout.seq='';\nout.te=te;\nout.tr=tr;\nout.pointsToLeftshift=0;\n\n\n%FILLING IN THE FLAGS\nout.flags.writtentostruct=1;\nout.flags.gotparams=1;\nout.flags.leftshifted=0;\nout.flags.filtered=0;\nout.flags.zeropadded=0;\nout.flags.freqcorrected=0;\nout.flags.phasecorrected=0;\nout.flags.averaged=0;\nout.flags.addedrcvrs=0;\nout.flags.subtracted=0;\nout.flags.writtentotext=0;\nout.flags.downsampled=0;\nif out.dims.subSpecs==0\n    out.flags.isFourSteps=0;\nelse\n    out.flags.isFourSteps=(out.sz(out.dims.subSpecs)==4);\nend\n\n\n%FOR WATER UNSUPPRESSED DATA\n%FILLING IN DATA STRUCTURE\nout_w.fids=fids_w;\nout_w.specs=specs_w;\nout_w.sz=sz_w;\nout_w.ppm=ppm;  \nout_w.t=t;    \nout_w.spectralwidth=spectralwidth;\nout_w.dwelltime=dwelltime;\nout_w.txfrq=txfrq;\nout_w.date=date;\nout_w.dims=dims_w;\nout_w.Bo=Bo;\nout_w.averages=averages_w;\nout_w.rawAverages=rawAverages_w;\nout_w.subspecs=subspecs_w;\nout_w.rawSubspecs=rawSubspecs_w;\nout_w.seq='';\nout_w.te=te;\nout_w.tr=tr;\nout_w.pointsToLeftshift=0;\n\n\n%FILLING IN THE FLAGS\nout_w.flags.writtentostruct=1;\nout_w.flags.gotparams=1;\nout_w.flags.leftshifted=0;\nout_w.flags.filtered=0;\nout_w.flags.zeropadded=0;\nout_w.flags.freqcorrected=0;\nout_w.flags.phasecorrected=0;\nout_w.flags.averaged=0;\nout_w.flags.addedrcvrs=0;\nout_w.flags.subtracted=0;\nout_w.flags.writtentotext=0;\nout_w.flags.downsampled=0;\nif out_w.dims.subSpecs==0\n    out_w.flags.isFourSteps=0;\nelse\n    out_w.flags.isFourSteps=(out.sz(out.dims.subSpecs)==4);\nend\n\n\n\n%DONE\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/inputOutput/io_loadspec_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.235891203199595}}
{"text": "function y = subsasgn(X,I,Y)\n%SUBASGN (overloaded)\n\ntry\n    if strcmp('()',I.type)\n        X_is_spdvar = isa(X,'sdpvar') |  isa(X,'ndsdpvar');\n        Y_is_spdvar = isa(Y,'sdpvar') |  isa(Y,'ndsdpvar');\n        if islogical(I.subs{1})\n            I.subs{1} = double(find(I.subs{1}));\n        end\n        if any(I.subs{1} <=0)\n            error('Index into matrix is negative or zero.');\n        end \n        \n        if length(I.subs)>2 && X_is_spdvar\n            y = subsasgn(ndsdpvar(X),I,Y);\n            return\n        end\n\n        switch 2*X_is_spdvar+Y_is_spdvar\n            case 1 \n                % This code does not work properly\n                % Only work if b is undefined!!?!!\n                % generally ugly code...\n                y = Y;\n                [n_y,m_y] = size(Y);\n                y_lmi_variables = y.lmi_variables;\n                try\n                    X0 = subsasgn(full(X),I,full(reshape(Y.basis(:,1),n_y,m_y)));\n                    dim = size(X0);\n                    y.basis = reshape(X0,prod(dim),1);\n                    X = full(X)*0;\n                    for i = 1:length(y_lmi_variables)\n                        X0 = subsasgn(X,I,full(reshape(Y.basis(:,i+1),n_y,m_y)));\n                        y.basis(:,i+1) = reshape(X0,prod(dim),1);\n                    end\n                    y.dim = dim;\n                    % Reset info about conic terms\n                    y.conicinfo = [0 0];\n                    y.basis = sparse(y.basis);\n                    if length(dim)>2\n                        y = ndsdpvar(y);\n                    end                    \n                catch\n                    error(lasterr)\n                end\n            case 2\n                if ~isempty(Y)     \n                    if isa(Y,'uint8') || isa(Y,'uint16') || isa(Y,'uint32') || isa(Y,'uint64')\n                        Y = sparse(double(Y));\n                    elseif isnumeric(Y)\n                        Y = sparse(Y);\n                    else\n                        Y = sparse(double(Y));\n                    end\n                end\n                y = X;\n                \n                % Special code for speed\n                % elements in vector replaced with constants\n                if min(X.dim(1),X.dim(2))==1 & (length(I.subs)==1)\n                     y = X;\n                     if isempty(Y)\n                         y.basis(I.subs{1},:) = [];\n                         if X.dim(1) == 1\n                             y.dim(2) = y.dim(2) - length(unique(I.subs{1}));\n                         else\n                             y.dim(1) = y.dim(1) - length(unique(I.subs{1}));\n                         end\n                     else\n                         y.basis(I.subs{1},1) = Y;\n                         y.basis(I.subs{1},2:end) = 0;                         \n                     end\n                     if prod(y.dim)~=size(y.basis,1)\n                         % Ah bugger, the dimension of the object was changed)\n                         aux = X.basis(:,1);\n                         aux = reshape(aux,X.dim);\n                         aux(I.subs{1})=Y;\n                         y.dim = size(aux);\n                     end\n                     y = clean(y);\n                     % Reset info about conic terms\n                     if isa(y,'sdpvar')\n                         y.conicinfo = [0 0];                         \n                     end\n                     return;\n                end\n                    \n                \n                x_lmi_variables = X.lmi_variables;\n                lmi_variables = [];\n                           \n                n = y.dim(1);\n                m = y.dim(2);\n                subX = sparse(subsasgn(full(reshape(X.basis(:,1),n,m)),I,Y));\n                y.basis = subX(:);\n                if isa(I.subs{1},'char')\n                    I.subs{1} = 1:n;\n                end\n                if length(I.subs)>1\n                    if isa(I.subs{2},'char')\n                        I.subs{2} = 1:m;\n                    end\n                end\n                if length(I.subs)>1\n                    if length(I.subs{1})==1 & length(I.subs{2})~=1\n                        I.subs{1} = repmat(I.subs{1},size(I.subs{2},1),size(I.subs{2},2));\n                    elseif length(I.subs{2})==1 & length(I.subs{1})~=1\n                        I.subs{2} = repmat(I.subs{2},size(I.subs{1},1),size(I.subs{1},2));\n                    end\n                end\n                \n                if length(I.subs)>1                  \n                    ii = kron(I.subs{1}(:),ones(length(I.subs{2}),1));\n                    jj = kron(ones(length(I.subs{1}),1),I.subs{2}(:));\n                    LinearIndex = sub2ind([n m],ii,jj);\n                else\n                    LinearIndex = I.subs{1};\n                end\n                \n                if isempty(Y)\n                    X.basis = X.basis(:,2:end);\n                    X.basis(LinearIndex,:) = [];\n                    y.basis = [y.basis(:,1) X.basis];\n                else\n                    X.basis(LinearIndex,2:end)=sparse(0);                \n                    y.basis = [y.basis(:,1) X.basis(:,2:end)];\n                end\n                         \n                y.dim(1) = size(subX,1);\n                y.dim(2) = size(subX,2);\n                if ~isempty(x_lmi_variables)\n                    y = clean(y);\n                end\n                if isa(y,'sdpvar')\n                    % Reset info about conic terms\n                    y.conicinfo = [0 0];                    \n                end\n                \n            case 3\n                z = X;\n                \n                x_lmi_variables = X.lmi_variables;\n                y_lmi_variables = Y.lmi_variables;\n                \n                                \n                % In a first run, we fix the constant term and null terms in the X basis\n                lmi_variables = [];\n                nx = X.dim(1);\n                mx = X.dim(2);\n                ny = Y.dim(1);\n                my = Y.dim(2);\n                \n                if (mx==1) & (my == 1) & isempty(setdiff(y_lmi_variables,x_lmi_variables)) & (max(I.subs{1}) < nx) & length(I.subs)==1 & length(unique(I.subs{1}))==length(I.subs{1}) ;\n                    % Fast specialized code for Didier\n                     y = specialcode(X,Y,I);\n                     return\n                end                \n               \n                subX = subsasgn(reshape(X.basis(:,1),nx,mx),I,reshape(Y.basis(:,1),ny,my));\n                [newnx, newmx] = size(subX);\n                                              \n                j = 1;\n                \n                yz = reshape(1:ny*my,ny,my);\n                subX2 = subsasgn(reshape(zeros(nx*mx,1),nx,mx),I,yz);\n                subX2 = subX2(:);\n                [ix,jx,sx] = find(subX2);\n                yz = 0*reshape(Y.basis(:,1),ny,my);                               \n                lmi_variables = zeros(1,length(x_lmi_variables));\n                \n                A = reshape(1:nx*mx,nx,mx);\n                B = reshape(1:newnx*newmx,newnx,newmx);\n                \n                rm = B(1:nx,1:mx);rm = rm(:);\n                [iix,jjx,ssx] = find(X.basis(:,2:end));\n                z.basis = [subX(:) sparse(rm(iix),jjx,ssx,newnx*newmx,size(X.basis,2)-1)];\n                z.basis(ix,2:end) = 0;\n                                               \n                keep = find(any(z.basis(:,2:end),1));\n                z.basis = z.basis(:,[1 1+keep]);\n                lmi_variables2 = x_lmi_variables(keep);\n\n                z.lmi_variables = lmi_variables2;\n                lmi_variables = lmi_variables2;\n                \n                all_lmi_variables = union(lmi_variables,y_lmi_variables);\n                in_z = ismembcYALMIP(all_lmi_variables,lmi_variables);\n                in_y = ismembcYALMIP(all_lmi_variables,y_lmi_variables);\n                z_ind = 2;\n                y_ind = 2;\n                basis = spalloc(size(z.basis,1),1+length(all_lmi_variables),0);\n                basis(:,1) = z.basis(:,1);\n                nz = size(subX,1);\n                mz = size(subX,2);\n                template = full(0*reshape(X.basis(:,1),nx,mx));\n                in_yin_z = 2*in_y + in_z;\n                if all(in_yin_z<3)\n                    case1 = find(in_yin_z==1);\n                    if ~isempty(case1)\n                        basis(:,case1+1) = z.basis(:,2:1+length(case1));                        \n                        in_yin_z(case1) = 0;\n                    end\n                end\n                    % Let's identify the indices at which we need to intervene\n                    case1 = find(in_yin_z==1);\n                    checkI = union(find(in_yin_z >= 2), setdiff(case1,case1+1));\n                    if size(checkI,1) > size(checkI,2)\n                        % Sometimes the in_yin_z vector is vertical (not\n                        % always though), so we make sure that checkI, on\n                        % which we'll iterate, is horizontal.\n                        checkI = checkI';\n                    end\n                    for i = checkI\n                        switch in_yin_z(i)\n                            case 1\n                                % We look for the end of the block of ones\n                                % starting at i\n                                iend = i + find([in_yin_z(i+1:end) 0] ~= 1, 1, 'first')-1;\n                                basis(:,i+1:iend+1) = z.basis(:,z_ind:z_ind+(iend-i));z_ind = z_ind+(iend-i)+1;\n                        case 2                          \n                            temp = sparse(subsasgn(template,I,full(reshape(Y.basis(:,y_ind),ny,my))));\n                            basis(:,i+1) = temp(:);\n                            y_ind = y_ind+1;\n                        case 3\n                            Z1 = z.basis(:,z_ind);\n                            Z4 = Y.basis(:,y_ind);\n                            Z3 = reshape(Z4,ny,my);\n                            Z2 = sparse(subsasgn(0*reshape(full(X.basis(:,1)),nx,mx),I,Z3));\n                            temp = reshape(Z1,nz,mz)+Z2;                            \n                            basis(:,i+1) = temp(:);\n                            z_ind = z_ind+1;\n                            y_ind = y_ind+1;\n                        otherwise\n                    end \n                end;\n                z.dim(1) = nz;\n                z.dim(2) = mz;\n                z.basis = basis;\n                z.lmi_variables = all_lmi_variables(:)';\n                y = z;\t                \n                % Reset info about conic terms\n                y.conicinfo = [0 0];                                 \n            otherwise\n        end\n    else\n        error('Reference type not supported');\n    end\n    \ncatch\n    error(lasterr)\nend\n\n\nfunction y = specialcode(X,Y,I)\n\ny = X;\nX_basis = X.basis;\nY_basis = Y.basis;\nind = I.subs{1};ind = ind(:);\nyvar_in_xvar = zeros(length(Y.lmi_variables),1);\nfor i = 1:length(Y.lmi_variables);\n    yvar_in_xvar(i) = find(X.lmi_variables==Y.lmi_variables(i));\nend\ny.basis(ind,:) = 0;\nmapper = [1 1+yvar_in_xvar(:)'];mapper = mapper(:);\n[i,j,k] = find(y.basis);\n[ib,jb,kb] = find(Y_basis);\ni = [i(:);ind(ib(:))];\nj = [j(:);mapper(jb(:))];\nk = [k(:);kb(:)];\ny.basis = sparse(i,j,k,size(y.basis,1),size(y.basis,2));\ny = clean(y);\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/subsasgn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2358454287475271}}
{"text": "function feature_map = extract_features(image, pos, scales, features, gparams, extract_info)\n\n% Sample image patches at given position and scales. Then extract features\n% from these patches.\n% Requires that cell size and image sample size is set for each feature.\n\nif ~iscell(features)\n    error('Wrong input');\nend;\n\nnum_features = length(features);\nnum_scales = length(scales);\nnum_sizes = length(extract_info.img_sample_sizes);\n\n% Extract image patches\nimg_samples = cell(2,1);\nfor sz_ind = 1:num_sizes\n    img_sample_sz = extract_info.img_sample_sizes{sz_ind};\n    img_input_sz = extract_info.img_input_sizes{sz_ind};\n    img_samples{sz_ind} = zeros(img_input_sz(1), img_input_sz(2), size(image,3), num_scales, 'uint8');\n    for scale_ind = 1:num_scales\n        img_samples{sz_ind}(:,:,:,scale_ind) = sample_patch(image, pos, round(img_sample_sz*scales(scale_ind)), img_input_sz, gparams);\n    end\nend\n\n% Find the number of feature blocks and total dimensionality\nnum_feature_blocks = 0;\ntotal_dim = 0;\nfor feat_ind = 1:num_features\n    num_feature_blocks = num_feature_blocks + length(features{feat_ind}.fparams.nDim);\n    total_dim = total_dim + sum(features{feat_ind}.fparams.nDim);\nend\n\nfeature_map = cell(1, 1, num_feature_blocks);\n\n% Extract feature maps for each feature in the list\nind = 1;\nfor feat_ind = 1:num_features\n    feat = features{feat_ind};\n    gparams.cell_size = feat.fparams.cell_size;\n    \n    % get the image patch index\n    img_sample_ind = cellfun(@(sz) isequal(feat.img_sample_sz, sz), extract_info.img_sample_sizes);\n    \n    % do feature computation\n    if feat.is_cell\n        num_blocks = length(feat.fparams.nDim);\n        feature_map(ind:ind+num_blocks-1) = feat.getFeature(img_samples{img_sample_ind}, feat.fparams, gparams);\n    else\n        num_blocks = 1;\n        feature_map{ind} = feat.getFeature(img_samples{img_sample_ind}, feat.fparams, gparams);\n    end\n    \n    ind = ind + num_blocks;\nend\n              \n% Do feature normalization\nif ~isempty(gparams.normalize_power) && gparams.normalize_power > 0\n    if gparams.normalize_power == 2\n        feature_map = cellfun(@(x) bsxfun(@times, x, ...\n            sqrt((size(x,1)*size(x,2))^gparams.normalize_size * size(x,3)^gparams.normalize_dim ./ ...\n            (sum(reshape(x, [], 1, 1, size(x,4)).^2, 1) + eps))), ...\n            feature_map, 'uniformoutput', false);\n    else\n        feature_map = cellfun(@(x) bsxfun(@times, x, ...\n            ((size(x,1)*size(x,2))^gparams.normalize_size * size(x,3)^gparams.normalize_dim ./ ...\n            (sum(abs(reshape(x, [], 1, 1, size(x,4))).^gparams.normalize_power, 1) + eps)).^(1/gparams.normalize_power)), ...\n            feature_map, 'uniformoutput', false);\n    end\nend\nif gparams.square_root_normalization\n    feature_map = cellfun(@(x) sign(x) .* sqrt(abs(x)), feature_map, 'uniformoutput', false);\nend\nend", "meta": {"author": "he010103", "repo": "CFWCR", "sha": "c6a30234dd6448cef954b8b38f518fa8047c4850", "save_path": "github-repos/MATLAB/he010103-CFWCR", "path": "github-repos/MATLAB/he010103-CFWCR/CFWCR-c6a30234dd6448cef954b8b38f518fa8047c4850/feature_extraction/extract_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23559259640015456}}
{"text": "fid = fopen('pairs.txt');\nCC = fscanf(fid,'%d %d');\nn_set = CC(1);n_num=CC(2);\n\nsame_pair = cell(n_set*n_num,2);\ndiff_pair = cell(n_set*n_num,2);\nlfw_label = zeros(n_set*n_num * 2,2);\n\nfor i=1:n_set\n    for j = 1 : n_num\n        CC = textscan(fid, '%s %d %d\\n');\n        p = CC{1};id1=CC{2};id2=CC{3};\n        same_pair((i-1)*n_num + j,1) = {sprintf('%s/%s/%s_%04d.jpg',pwd,p{1},p{1},id1)};\n        same_pair((i-1)*n_num + j,2) = {sprintf('%s/%s/%s_%04d.jpg',pwd,p{1},p{1},id2)};\n        if exist('list','var')\n            lfw_label((i-1)*n_num + j,1) = find(strcmp(list, sprintf('%s_%04d.jpg',p{1},id1)));\n            lfw_label((i-1)*n_num + j,2) = find(strcmp(list, sprintf('%s_%04d.jpg',p{1},id2)));\n        end;\n    end;\n    for j = 1 : n_num\n         CC = textscan(fid, '%s %d %s %d\\n');\n         p1 = CC{1};id1=CC{2};p2=CC{3};id2=CC{4};\n        diff_pair((i-1)*n_num + j,1) = {sprintf('%s/%s/%s_%04d.jpg',pwd,p1{1},p1{1},id1)};\n        diff_pair((i-1)*n_num + j,2) = {sprintf('%s/%s/%s_%04d.jpg',pwd,p2{1},p2{1},id2)};\n        if exist('list','var')\n            lfw_label(n_set*n_num + (i-1)*n_num + j,1) = find(strcmp(list, sprintf('%s_%04d.jpg',p1{1},id1)));\n            lfw_label(n_set*n_num + (i-1)*n_num + j,2) = find(strcmp(list, sprintf('%s_%04d.jpg',p2{1},id2)));\n        end;\n    end;\nend;\nfclose(fid);\n\nif exist('feature','var')\n    AllFeature1 = feature(:,lfw_label(:,1));\n    AllFeature2 = feature(:,lfw_label(:,2));\nend;\n", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/dataset/LFW/getlfwPairs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23547919447140203}}
{"text": "classdef LaunchVehicleSensorReport < matlab.mixin.SetGet\n    %LaunchVehicleSensorReport Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        sensor AbstractSensor\n        lvdData LvdData\n    end\n    \n    methods\n        function obj = LaunchVehicleSensorReport(sensor, lvdData)\n            obj.sensor = sensor;\n            obj.lvdData = lvdData;\n        end\n        \n        function [filepath, coverageT, azT, elT, rngT, angleToBoresightT] = generateReport(obj, targets, progressBar, busyStatusLabel, sensorNum, totalSensorNum, reportFolder)\n            arguments\n                obj(1,1) LaunchVehicleSensorReport\n                targets(1,:) AbstractSensorTarget\n                progressBar(1,1) wt.ProgressBar\n                busyStatusLabel(1,1) matlab.ui.control.Label\n                sensorNum(1,1) double\n                totalSensorNum(1,1) double\n                reportFolder(1,1) string\n            end\n            \n            progressBar.Indeterminate = false;\n            progressBar.startProgress('');\n            busyStatusLabel.Text = sprintf('Generating Data for Sensor \"%s\" [%u of %u]', obj.sensor.getListboxStr(), sensorNum, totalSensorNum);\n            \n            bodyInfos = obj.lvdData.celBodyData.getAllBodyInfo();\n            stateLog = obj.lvdData.stateLog;\n            \n            entries = stateLog.getAllEntries();\n            times = [entries.time]';\n            coverages = cell(1,numel(targets));\n            sensorAzs = cell(1,numel(targets));\n            sensorEls = cell(1,numel(targets));\n            sensorRngs = cell(1,numel(targets));\n            sensorAnglesToBoresight = cell(1,numel(targets));\n            for(i=1:length(entries))\n                entry = entries(i);\n                \n                sensorState = entry.getSensorStateForSensor(obj.sensor);\n                scElem = entry.getCartesianElementSetRepresentation(false);\n                dcm = entry.attitude.dcm;\n                frame = entry.centralBody.getBodyCenteredInertialFrame();\n                \n                results = obj.sensor.evaluateSensorTargets(sensorState, targets, scElem, dcm, bodyInfos, frame); \n                \n                for(j=1:length(results))\n                    result = results(j);\n                    \n                    coverages{j} = vertcat(coverages{j}, result.resultsBool(:)');\n                    \n                    [az, el, rng, angle] = result.getBoresightRelativeAngles(sensorState, scElem, dcm); \n                    \n                    sensorAzs{j} = vertcat(sensorAzs{j}, az);\n                    sensorEls{j} = vertcat(sensorEls{j}, el);\n                    sensorRngs{j} = vertcat(sensorRngs{j}, rng);\n                    sensorAnglesToBoresight{j} = vertcat(sensorAnglesToBoresight{j}, angle);\n                end\n                \n                progressBar.setProgress(i/length(entries), sprintf('%0.3f %%', 100*i/length(entries)));\n            end\n            \n            progressBar.Indeterminate = true;\n            busyStatusLabel.Text = sprintf('Writing Report File for Sensor \"%s\" [%u of %u]', obj.sensor.getListboxStr(), sensorNum, totalSensorNum);\n            progressBar.setProgress(1, '');\n            drawnow;\n            \n            coverageT = {};\n            filename = sprintf('SensorReport_%s_%s.xls', obj.sensor.getListboxStr(),datestr(now, 'YYYYmmDD_HHMMss'));\n            filepath = fullfile(reportFolder, filename);\n            for(i=1:length(coverages))\n                coverage = coverages{i};\n                \n                %compute instant and cumulative coverage\n                instantCoverage = NaN(height(coverage), 1);\n                cumCoverage = NaN(height(coverage), 1);\n                for(j=1:height(coverage))\n                    subCoverage = coverage(j,:);\n                    instantCoverage(j) = sum(subCoverage) / numel(subCoverage);\n                    \n                    subCoverage = coverage(1:j,:);\n                    sumSubCoverage = sum(subCoverage,1);\n                    sumSubCoverage(sumSubCoverage >= 1) = 1;\n                    cumCoverage(j) = sum(sumSubCoverage) / numel(sumSubCoverage);\n                end\n\n                target = targets(i);\n                labelStrs = target.getTargetPtLabelStrs();\n                \n                %Info worksheet\n                sensorNums = sensorNum * ones(numel(targets),1);\n                sensorNames = repmat(string(obj.sensor.getListboxStr()), numel(targets), 1);\n                targetNums = [1:numel(targets)]'; %#ok<NBRAK>\n                for(j=1:length(targets))\n                    targetNames(j,1) = string(targets(j).getListboxStr()); %#ok<AGROW>\n                end\n                \n                varNames = {'Sensor Number', 'Sensor Name', 'Target Number', 'Target Name'};\n                data = table(sensorNums, sensorNames, targetNums, targetNames, 'VariableNames',varNames);\n                writetable(data, filepath, 'FileType','spreadsheet', 'Sheet','Information'); \n                \n                %Sensor Coverage\n                worksheetName = sprintf('Coverage, Sensor %u Target %u', sensorNum, i);\n                \n                header = horzcat('Time [UT sec]', labelStrs, \"Instantaneous Coverage Fraction\", \"Cumulative Coverage Fraction\");\n                data = horzcat(times, coverage, instantCoverage, cumCoverage);\n                \n                coverageT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>\n                \n                %Sensor to Target Az\n                worksheetName = sprintf('Azimuth, Sensor %u Target %u', sensorNum, i);\n                \n                header = horzcat('Time [UT sec]', labelStrs);\n                data = horzcat(times, rad2deg(sensorAzs{i}));\n                \n                azT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>\n                \n                %Sensor to Target El\n                worksheetName = sprintf('Elevation, Sensor %u Target %u', sensorNum, i);\n                \n                header = horzcat('Time [UT sec]', labelStrs);\n                data = horzcat(times, rad2deg(sensorEls{i}));\n                \n                elT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>\n                \n                %Sensor to Target Range\n                worksheetName = sprintf('Range, Sensor %u Target %u', sensorNum, i);\n                \n                header = horzcat('Time [UT sec]', labelStrs);\n                data = horzcat(times, sensorRngs{i});\n                \n                rngT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>\n                \n                %Sensor to Target Range\n                worksheetName = sprintf('Angle, Sensor %u Target %u', sensorNum, i);\n                \n                header = horzcat('Time [UT sec]', labelStrs);\n                data = horzcat(times, rad2deg(sensorAnglesToBoresight{i}));\n                \n                angleToBoresightT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>\n            end\n        end\n    end\nend\n\nfunction T = writeDataTableToXLSFile(data, header, filename, worksheetName)\n    T = array2table(data);\n    T.Properties.VariableNames = header;\n\n    userdata.WorksheetName = worksheetName;\n    T.Properties.UserData = userdata;\n\n    writetable(T, filename, 'FileType','spreadsheet', 'Sheet',worksheetName);    \nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Sensors/Reports/@LaunchVehicleSensorReport/LaunchVehicleSensorReport.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.235479194471402}}
{"text": "%  Copyright (c) 2014, Karen Simonyan\n%  All rights reserved.\n%  This code is made available under the terms of the BSD license (see COPYING file).\n\nfunction [res, extra] = eval(config, scores, gt)\n    \n    % predicted labels\n    class = 2 * (scores >= config.threshold) - 1;\n    \n    % class-n accuracy\n    res = mean(class == gt) * 100;\n    \n    extra = [];\nend\n", "meta": {"author": "AlfredXiangWu", "repo": "face_verification_experiment", "sha": "9e5031c9ee45dd2cd9a54c91c099abb34bfbdb56", "save_path": "github-repos/MATLAB/AlfredXiangWu-face_verification_experiment", "path": "github-repos/MATLAB/AlfredXiangWu-face_verification_experiment/face_verification_experiment-9e5031c9ee45dd2cd9a54c91c099abb34bfbdb56/code/+evaluation/+accuracy/eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544473535548385}}
{"text": "function [X, varX, model, grChek] = svargplvmOptimisePoint(model, vardistx, y, display, iters, varargin)\n\n% SVARGPLVMOPTIMISEPOINT Optimise the postion of one or more latent points\n% given observations from 1 or more modalities\n% FORMAT\n% DESC optimises the location of a group of points in latent space\n% given an initialisation and the corresponding observed data point.\n% ARG model : the MRD model for which the point will be optimised.\n% ARG vardistx : the initialisation of the points in the latent space.\n% ARG y : the observed data points for which the latent points are to\n% be optimised.\n% ARG display : whether or not to display the iterations of the\n% optimisation (default: true)\n% ARG iters : maximum number of iterations for the optimisation\n% (default 2000).\n% RETURN x : the optimised means in the latent space.\n% RETURN varx : the optimised variances in the latent space.\n% RETURN model: the model which is augmented to also include the new test\n% points and the quantities that change because of these, as there is\n% coupling in the dynamics case.\n\n%\n% COPYRIGHT :  Andreas Damianou, 2013\n%\n% SEEALSO : vargplvmOptimisePoint\n\n% VARGPLVM\n\ngrChek = [];\n\nif nargin < 5 || isempty(iters), iters = 2000; end\nif nargin < 4 || isempty(display), display = true; end\n\noptions = optOptions;\nif display\n    options(1) = 1;\n    % options(9) = 1; % gradchek\nend\noptions(14) = iters;\n\n\nif isfield(model, 'optimiser')\n    optim = str2func(model.optimiser);\nelse\n    optim = str2func('scg');\nend\n\n\nif isfield(model, 'dynamics') && ~isempty(model.dynamics)\n    % TODO\n    error('Not implemented for dynamical case')\nelse\n    x = vardistExtractParam(vardistx);\nend\n\nif ~(isfield(model, 'dynamics') && ~isempty(model.dynamics))\n    model.DgtN_test = true;\n    for i = model.testModalities\n        % Perform precomputations which will result in faster execution. This\n        % happens in two stages:\n        % a) Precomputing constants only once here, instead in every call of\n        % the objective and grad\n        % b) Replace model.m with a reduced rank representation, since it only\n        % appears in the expression model.m * model.m'. This is the same tricks\n        % used in vargplvmCreate for DgtN flag.\n        % TODO: Do the same for dynamics case\n        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN\n            mOrig{i} = model.comp{i}.m;\n        end\n        model.comp{i}.testPrecomp.indexMissing = find(isnan(y{i}(1,:)));\n        indexPresent = setdiff(1:model.comp{i}.d, model.comp{i}.testPrecomp.indexMissing );\n        y{i} = y{i}(:,indexPresent);\n        P = model.comp{i}.P1 * (model.comp{i}.Psi1' * model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing));\n        model.comp{i}.testPrecomp.TrPP = sum(sum(P .* P));\n        model.comp{i}.testPrecomp.TrYY = sum(sum(model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing) .* model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing)));\n        y{i} = y{i} - repmat(model.comp{i}.bias(indexPresent),size(y{i},1),1);\n        y{i} = y{i}./repmat(model.comp{i}.scale(indexPresent),size(y{i},1),1);\n        mPres = model.comp{i}.m(:, indexPresent);\n        mPres = [mPres; y{i}];\n        YYT = mPres * mPres'; % NxN\n        [U S V]=svd(YYT);\n        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN\n            model.comp{i}.testPrecomp.mReduced=U*sqrt(abs(S));\n        end\n        model.comp{i}.testPrecomp.TrYY2 = sum(diag(YYT)); % scalar\n        \n        % For grads\n        mPresGrad = [y{i}; model.comp{i}.m(:, indexPresent)];\n        YYT = mPresGrad * mPresGrad'; % NxN\n        [U S V]=svd(YYT);\n        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN\n            model.comp{i}.testPrecomp.mReducedGrad=U*sqrt(abs(S));\n        end\n        model.comp{i}.testPrecomp.mY = mPresGrad*y{i}';\n        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN\n            model.comp{i}.m = []; % Less overhead in passing arguments (pass by value)\n        end\n    end\nelse\n    model.comp.DgtN_test = false;\nend\n\n\n\nif length(varargin) == 2\n    if strcmp(varargin{1}, 'gradcheck')\n        assert(islogical(varargin{2}));\n        %options(9) = varargin{2};\n        doGradchek = varargin{2};\n        if doGradchek\n            [gradient, delta] = feval('gradchek', vardistExtractParam(vardistx), @svargplvmPointObjective, @svargplvmPointGradient, model, y);\n            deltaf = gradient - delta;\n            d=norm(deltaf - gradient)/norm(gradient + deltaf); %%\n            d1=norm(deltaf - gradient,1)/norm(gradient + deltaf,1); %%\n            grRatio = sum(abs(gradient ./ deltaf)) / length(deltaf);\n            fprintf(1,' Norm1 difference: %d\\n Norm2 difference: %d\\n Ratio: %d\\n',d1,d, grRatio);\n            grChek = {delta, gradient, deltaf, d, d1};\n        else\n            grChek = [];\n        end\n    end\nend\n\n\nif iters > 0\n    if strcmp(func2str(optim), 'optimiMinimize')\n        % Carl Rasmussen's minimize function\n        x = optim('vargplvmPointObjectiveGradient', x, options, model, y);\n    else\n        % NETLAB style optimization.\n        x = optim('svargplvmPointObjective', x,  options, ...\n            'svargplvmPointGradient', model, y);\n    end\nend\n\nif isfield(model, 'dynamics') && ~isempty(model.dynamics)\n    if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise   %%% RE-OPT-CODE-NEW\n        % Expand and update the model.                                      %%% RE-OPT-CODE-NEW\n        % In this case, x is [mu_bar lambda theta_t X_u]                    %%% RE-OPT-CODE-NEW\n        [vardistx, model] = vargplvmPartExpand(model, x, 1);                %%% RE-OPT-CODE-NEW\n    else %%% RE-OPT-CODE-NEW\n        % now separate the variational disribution into the training part and the\n        % testing part and update the original training model (only with the new training\n        % variational distribution) and the test variational distribution\n        % this is doing the expand\n        x = reshape(x, vardist.numData, model.dynamics.q*2);\n        xtrain = x(1:model.N,:);\n        xtest = x(model.N+1:end,:);\n        model.dynamics.vardist = vardistExpandParam(model.dynamics.vardist, xtrain);\n        vardistx = vardistExpandParam(model.vardistx, xtest);\n    end %%% RE-OPT-CODE-NEW\nelse\n    vardistx = vardistExpandParam(vardistx,x);\nend\n\nX = vardistx.means;\nvarX = vardistx.covars;\n\nif ~(isfield(model, 'dynamics') && ~isempty(model.dynamics))\n    model = rmfield(model, 'DgtN_test');\n    for i=model.testModalities\n        model.comp{i} = rmfield(model.comp{i}, 'testPrecomp');\n        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN\n            model.comp{i}.m = mOrig{i};\n        end\n    end\nend\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/svargplvmOptimisePoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544472958611862}}
{"text": "function im1 = cropImage(im,center,scale)\n\nw = 200*scale;\nh = w;\nx = center(1) - w/2;\ny = center(2) - h/2;\nbbox = [x,y,w,h];\npadsize = round(bbox(3:4));\nim = padarray(im,padsize,0);\nim1 = imcrop(im,[bbox(1:2)+padsize,bbox(3:4)]);\nim1 = imresize(im1,[200,200]);\n", "meta": {"author": "geopavlakos", "repo": "object3d", "sha": "44033b2b4fe15d41a411cba0bbff906c23e8a802", "save_path": "github-repos/MATLAB/geopavlakos-object3d", "path": "github-repos/MATLAB/geopavlakos-object3d/object3d-44033b2b4fe15d41a411cba0bbff906c23e8a802/code/utils/cropImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23538156343327818}}
{"text": "function view = setBrightness(view,val);\n%\n% view = setBrightness(view,[val]);\n%\n% Set the brightness of a view, by\n% changing the color maps in each \n% view mode. Only those parts which\n% are used for the anatomical underlay\n% image (the first 1:numGrays entries)\n% are brightened -- the overlays are \n% unchanged.\n%\n% Val can range from 0 to 1. If omitted,\n% it is read off of the view's brightness\n% slider (so hopefully, in these circumstances,\n% it has one).\n%\n%\n% ras 01/05.\nif notDefined('val')\n    val = get(view.ui.brightness.sliderHandle,'Value');\nend\n\nsetSlider(view,view.ui.brightness,val);\n\nnumGrays = view.ui.mapMode.numGrays;\ncmap = gray(numGrays);\n\ndelta = 2*val - 1;\nif delta ~= 0\n    cmap = brighten(cmap,delta);\nend\n\nview.ui.anatMode.cmap = cmap;\nview.ui.ampMode.cmap(1:numGrays,:) = cmap;\nview.ui.phMode.cmap(1:numGrays,:) = cmap;\nview.ui.coMode.cmap(1:numGrays,:) = cmap;\nview.ui.mapMode.cmap(1:numGrays,:) = cmap;\n\nview = refreshScreen(view, 1);\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/UI/Thresholds/setBrightness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23538156343327815}}
{"text": "function [net, info] = cnn_plate()\nglobal datadir;\nstartup;\nif exist(opts.imdbPath,'file')\n    imdb=load(opts.imdbPath);\nelse\n    imdb=cnn_plate_setup_data(datadir);\n    mkdir(opts.expDir) ;\n    save(opts.imdbPath, '-struct', 'imdb') ;\nend\nnet=cnn_plate_init();\nnet.meta.normalization.averageImage =imdb.images.data_mean ;\nopts.train.gpus=1;\n[net, info] = cnn_train(net, imdb, getBatch(opts), ...\n  'expDir', opts.expDir, ...\n  net.meta.trainOpts, ...\n  opts.train, ...\n  'val', find(imdb.images.set == 3)) ;\n\n\nfunction fn = getBatch(opts)\n% --------------------------------------------------------------------\n    fn = @(x,y) getSimpleNNBatch(x,y) ;\nend\nfunction [images, labels]  = getSimpleNNBatch(imdb, batch)\n    images = imdb.images.data(:,:,:,batch) ;\n    labels = imdb.images.labels(1,batch) ;\n    if opts.train.gpus > 0\n        images = gpuArray(images) ;\n    end\nend\nend\n", "meta": {"author": "imistyrain", "repo": "MatConvNet-oneclick", "sha": "1fa9f76d745ac4733129aca0dbd5b356f54c0885", "save_path": "github-repos/MATLAB/imistyrain-MatConvNet-oneclick", "path": "github-repos/MATLAB/imistyrain-MatConvNet-oneclick/MatConvNet-oneclick-1fa9f76d745ac4733129aca0dbd5b356f54c0885/cnn_plate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23538156343327815}}
{"text": "function obj = addpoints(obj, xyz, varargin)\n% Plots points on fmridisplay objects (e.g., montages of slices)\n%\n% :Usage:\n% ::\n%\n%     newax = addpoints(obj, xyz, varargin)\n%\n% Registers handles with the object (referred to as obj)\n%\n% - enter xyz as n x 3 list of coordinates in mm to plot (world space)\n% - Points or text labels or both\n% - Flexible slice spacing, colors, marker sizes/styles, axis layout (one row/standard square)\n% - axial, saggital, or coronal orientation handled automatically\n% - Multiple different sets of points can be plotted in different colors/text labels\n%\n% :Optional Inputs:\n% \n% Takes all inputs of plot_points_on_slice.  See help for additional\n% documentation of options.  \n%\n%   **{'text', 'textcodes'}:**\n%        cell array of text values corresponding to points\n%\n%   **{'condf' 'colorcond'}:**\n%        vector of integers to define color conditions\n%\n%   **'close_enough':**\n%        mm within which to plot; defined automatically based on slice distance if not entered\n%\n%   **'color':**\n%        string, 'b', or vector, [1 0 0], to define colors; cell if condf is used, e.g., {'b' 'g'}\n%\n%   **{'marker', 'MarkerStyle'}:**\n%        e.g., 'o', 'v', 's'\n%\n%   **{'MarkerSize', 'markersize'}:**\n%\n%   **{'MarkerFaceColor', 'markerfacecolor'}:**\n%        see color above\n%\n% :Examples:\n%\n% Plot points (i.e., coordinate locations) for xyz coords:\n% ::\n%\n%    o2 = addpoints(o2, DB.xyz, 'MarkerFaceColor', 'b', 'Marker', 'o', 'MarkerSize', 4);\n%    o2 = addpoints(o2, DB.xyz, 'text', DB.textcodes, 'condf', DB.condf, 'color', {'b' 'g'});\n%    o2 = removepoints(o2);\n\nwh_montage = 1:length(obj.montage); % select which montages; default = all\n\nwhm = strcmp(varargin, 'wh_montages') | strcmp(varargin, 'wh_montage') | strcmp(varargin, 'which_montages') | strcmp(varargin, 'which montages');\nif any(whm)\n    whm = find(whm);\n    wh_montage = varargin{whm(1) + 1};\nend\n\n% Montages\n% -------------------------------------------------------------------------\n\nfor i = wh_montage\n    \n    if ~isfield(obj.montage{i}, 'plotted_point_handles') || isempty(obj.montage{i}.plotted_point_handles)\n        \n        obj.montage{i}.plotted_point_handles = [];\n        \n    end\n    \n    % Plot it\n    pointhan = plotpoints(xyz, obj.montage{i}, varargin{:});\n    \n    obj.montage{i}.plotted_point_handles = [obj.montage{i}.plotted_point_handles pointhan];\n    \nend\n\n\n\nend  % main function\n\n\n\n\n\nfunction pointhan = plotpoints(xyz, montagestruct, varargin)\n\n\n% fixed fields\n\nmyview = montagestruct.orientation;\nslicemm = montagestruct.slice_mm_coords;\naxhan = montagestruct.axis_handles;\n\n% optional inputs\n\ntextcodes = [];\ntexthandles = [];\ncondf = [];\n\nclose_enough = min(diff(slicemm)) ./ 2;\nif isempty(close_enough), close_enough = 8; end\n    \ncolor = 'k';\nmarker = 'o';\nmarkersize = 12;\nmarkerfacecolor = 'k';\n\n% ------------------------------------------------------\n% parse inputs\n% ------------------------------------------------------\n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n            % reserved keywords\n            \n            case {'text', 'textcodes'} % do not pass on to slice plot...\n                textcodes = varargin{i + 1};\n                varargin{i+1} = [];\n                varargin{i} = [];\n                \n            case {'condf' 'colorcond'}, condf = varargin{i + 1};\n                \n            case 'close_enough', close_enough = varargin{i + 1};\n                \n            case {'Color','color'} % do not pass on...\n                color = varargin{i+1};\n                varargin{i+1} = [];\n                varargin{i} = [];\n                \n            case {'marker', 'Marker', 'MarkerStyle'}, marker = varargin{i+1}; varargin{i+1} = [];\n                \n            case {'MarkerSize', 'markersize'}, markersize = varargin{i+1}; varargin{i+1} = [];\n                \n            case {'MarkerFaceColor', 'markerfacecolor'}, markerfacecolor = varargin{i+1}; varargin{i+1} = [];\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n\n% SETUP\n% -----------------------------------------------\n\nfprintf('Plotting points within %3.2f mm of slices\\n', close_enough);\n\nif isempty(condf)\n    condf = ones(size(xyz, 1), 1);\n    \n    if iscell(color)\n        error('Color should not be a cell array.');\n    end\n    color = {color};\n    \nelse\n    if ~iscell(color)\n        error('When entering condf, enter colors cell with same number of entries.');\n    end\nend\n\nu = unique(condf);\nn = length(u);\n\n% Do the work for each slice\n% -----------------------------------------------\n\npointhan = [];\n\nfor i = 1:length(axhan)\n    axes(axhan(i));\n    \n    for j = 1:n % For each color code\n        \n        % Select coordinates (2D) for plot\n        slicexyz = xyz;\n        \n        switch myview\n            case 'axial'\n                whcol = 3;\n                \n            case {'sagg', 'sagittal', 'saggital'}\n                \n                whcol = 1;\n                \n            case {'cor', 'coronal'}\n                \n                whcol = 2;\n                \n            otherwise\n                error('Unknown slice orientation.')\n        end\n        \n        \n        \n        wh_to_plot = condf == u(j) & abs(slicexyz(:, whcol) - slicemm(i)) <= close_enough;\n        \n        slicexyz = slicexyz(wh_to_plot, :);\n        \n        slicexyz(:, whcol) = [];\n        \n        if ~isempty(slicexyz)\n            \n            if isempty(textcodes)\n                \n                pointhan(end + 1) = plot(slicexyz(:, 1), slicexyz(:, 2), '.', 'color', color{j}, 'Marker', marker, 'MarkerSize', markersize, 'MarkerFaceColor', markerfacecolor);\n                \n            else\n                my_text = textcodes(wh_to_plot);\n                \n                pointhan = [pointhan plottext(slicexyz(:, 1), slicexyz(:, 2), my_text, color{j}, myview)];\n                \n            end\n            \n        end\n        \n        \n        \n    end % condition color codes\n    \nend % slices\n\nend % function\n\n\n\n\n\n\n\nfunction texthandles = plottext(x, y, textcodes, color, orientation)\n\n% adjust for font placement\nswitch orientation\n    case 'sagittal'\n        xshift = 6;\n    case 'axial'\n        xshift = -6;\n        \nend\n\n\ntexthandles = [];\nfor j = 1:length(textcodes)\n    % text labels\n    \n    \n    if ischar(color)\n        \n        texthandles(j) = text(x(j) + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');\n        \n    else\n        texthandles(j) = text(x(j)  + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');\n        \n    end\n    \nend\n\nend % plottext\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@fmridisplay/addpoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23538155729068688}}
{"text": "function varargout = spectral_mva(varargin)\n% SPECTRAL_MVA M-file for spectral_mva.fig\n%      SPECTRAL_MVA is a GUI for running Multivariate analysis of spectroscopic data\n%      \n%      Initially designed for analysis of X-ray Photoelectron spectra, can\n%      analys any type of datatables, containing spectra or any other data\n%\n%      Opens MAT files with or without a variable X\n%      Opens VMS files (XPS spectra) either from original vision software or CASAXPS software\n%       \n%      Preprocessing options of SMOOTHING, NORMALIZING, DERIVATIZING and SHIFTING spectra   \n%\n%      Three MVA methods - PCA, SIMPLISMA and MCR\n%      PLS_TOOLBOX from Eigenvector is a must \n%\n%       created by K.Artyushkova\n%      kartyush@unm.edu\n%      last update -06/21/2007\n% Begin initialization code - DO NOT EDIT\n\ngui_Singleton = 1;\ngui_State = struct('gui_Name',       mfilename, ...\n                   'gui_Singleton',  gui_Singleton, ...\n                   'gui_OpeningFcn', @spectral_mva_OpeningFcn, ...\n                   'gui_OutputFcn',  @spectral_mva_OutputFcn, ...\n                   'gui_LayoutFcn',  [] , ...\n                   'gui_Callback',   []);\nif nargin & isstr(varargin{1})\n    gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n    gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spectral_mva is made visible.\nfunction spectral_mva_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject    handle to figure\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n% varargin   command line arguments to spectral_mva (see VARARGIN)\n\n% Choose default command line output for spectral_mva\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\nplotgui\n\n% UIWAIT makes spectral_mva wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spectral_mva_OutputFcn(hObject, eventdata, handles)\n% varargout  cell array for returning output args (see VARARGOUT);\n% hObject    handle to figure\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n% --------------------------------------------------------------------\nfunction open_vms_Callback(hObject, eventdata, handles)\n% hObject    handle to open_vms (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n[filename, pathname]=uigetfiles('*.vms','Open vms files');\ncd(pathname)\n[N,M]=size(filename);\nif M==1;\n    [BE,data]=vms_sp_read(char(filename(:,1)),0);\nelse\n    [BE, data(:,M)]=vms_sp_read(char(filename(:,1)),0);\n     for i=2:M\n    [BE, data(:,i-1)]=vms_sp_read(char(filename(:,i)),0);\nend\nend\n\nhandles.or_sp=data;\nhandles.data=data;\nhandles.BE=BE;\nhandles.BE_or=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n% --------------------------------------------------------------------\nfunction open_mat_Callback(hObject, eventdata, handles)\n% hObject    handle to open_mat (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndata=lddlgpls('*','load spectra');\nBE=lddlgpls('*','load BE - click cancel if no BE to load')\na=isempty(BE);\n    if a==1\n    h= warndlg('The Binding energy range is absent and will be generated automaticaly','Opening MAT file');\n    pause(3)\n    [n,m]=size(data);\n    BE=[n:-1:1]';\n    axes(handles.axes1)\nreverplot(BE,data)\n    else\n        \n    BE=BE;\n    axes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nend\n    handles.or_sp=data;\n    handles.BE_or=BE;\n    handles.data=data;\n    handles.BE=BE;\nguidata(hObject,handles)\n\n% --------------------------------------------------------------------\nfunction save_spectra_Callback(hObject, eventdata, handles)\n% hObject    handle to save_spectra (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndatapath = uigetdir;\ncd(datapath)\nspectra=handles.data;\nBE=handles.BE;\n[filename, pathname] = uiputfile('*.mat', 'Save images as');\nsave(filename)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction spectrum_selection_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to spectrum_selection (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background, change\n%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.\nusewhitebg = 1;\nif usewhitebg\n    set(hObject,'BackgroundColor',[.9 .9 .9]);\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on slider movement.\nfunction spectrum_selection_Callback(hObject, eventdata, handles)\n% hObject    handle to spectrum_selection (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider\n\n\ndata=handles.data;\nBE=handles.BE;\n[n,m]=size(data);\n\nset(handles.Min,'string',1);\nset(handles.Max,'string',m);\n\nstep=1/m;\nslider_step(1)=step;\nslider_step(2)=step;\nif step==1;\n    set(handles.spectrum_selection, 'SliderStep', slider_step, 'Max', 2, 'Min',0,'Value',1)\n    i=1;\nelse\n    set(handles.spectrum_selection, 'SliderStep', slider_step, 'Max', m, 'Min',0)\n    i=get(hObject,'Value');\n    i=round(i);\n    if i==0\n        i=1;\n    elseif i>=m\n        i=m;\n    else i=i;\n    end\nend\nset(handles.current,'string',i);\naxes(handles.axes1)\nplot(BE,data(:,i))\nset(gca,'Xdir','reverse')\nhandles.N=i;\n%guidata(hObject,handles)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Number_comps_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to Number_comps (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n%       See ISPC and COMPUTER.\nif ispc\n    set(hObject,'BackgroundColor','white');\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\nfunction Number_comps_Callback(hObject, eventdata, handles)\n% hObject    handle to Number_comps (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of Number_comps as text\n%        str2double(get(hObject,'String')) returns contents of Number_comps as a double\n\nNpca=str2double(get(hObject,'String')) ;\nhandles.Npca=Npca;\nguidata(hObject,handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction scal_pca_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to scal_pca (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n%       See ISPC and COMPUTER.\nif ispc\n    set(hObject,'BackgroundColor','white');\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\n% --- Executes on button press in pca_button.\nfunction pca_button_Callback(hObject, eventdata, handles)\n% hObject    handle to pca_button (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\nNpca=handles.Npca;\ndata=handles.data;\ns=preprocess;\noptions.preprocessing=s;\noptions.display='off';\noptions.plots='final';\nmodel=pca(data, Npca,options);\nhandles.model=model;\nguidata(hObject,handles)\n\n\n\n% --- Executes on button press in display_loads.\nfunction display_loads_Callback(hObject, eventdata, handles)\n% hObject    handle to display_loads (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodel=handles.model;\nplotloads(model)\n\n\n% --- Executes on button press in disp_score_pca.\nfunction disp_score_pca_Callback(hObject, eventdata, handles)\n% hObject    handle to disp_score_pca (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodel=handles.model;\nplotscores(model)\n\n\n% --------------------------------------------------------------------\nfunction save_pca_Callback(hObject, eventdata, handles)\n% hObject    handle to save_pca (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodel=handles.model;\nBE=handles.BE;\nscores=model.loads{1};\nloads=model.loads{2};\ndatapath = uigetdir;\ncd(datapath)\n[filename, pathname] = uiputfile('*.mat', 'Save results as');\nsave(filename)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_1_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_1 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_3_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_3 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction normalize_Callback(hObject, eventdata, handles)\n% hObject    handle to normalize (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndata=handles.data;\nBE=handles.BE;\n[m,n]=size(data);\naxes(handles.axes1)\nplot(data)\n[x,y] = gselect('x');\nfor i=1:n\n        K(i)=data(x,i)/100;\n        data_n(:,i)=data(:,i)/K(i);    \nend\n   \ndata=data_n;\nhandles.data_n=data;\nhandles.data=data_n;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n% --------------------------------------------------------------------\nfunction derivatize_Callback(hObject, eventdata, handles)\n% hObject    handle to derivatize (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndata=handles.data;\nBE=handles.BE;\n[m,n]=size(data);\ntype=questdlg('Which derivative you wnat to apply?','Derivatization','1st', '2nd', '1st');\nN=inputdlg('Enter the width of smoothing window');  \nN=str2double(N);    \nif type=='1st'\n    for i=1:n\n     data_d(i,:) = savgol(data(:,i)',N, 2 ,1);\n end\nelse\n    for i=1:n\n     data_d(i,:) = savgol(data(:,i)',N, 2 ,2);\n end\nend\ndata=data_d';\nhandles.data_d=data;\nhandles.data=data;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n% --------------------------------------------------------------------\nfunction Undo_normalization_Callback(hObject, eventdata, handles)\n% hObject    handle to Undo_normalization (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndata=handles.or_sp;\nBE=handles.BE_or;\nhandles.data=data;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n% --------------------------------------------------------------------\nfunction undo_deriv_Callback(hObject, eventdata, handles)\n% hObject    handle to undo_deriv (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.or_sp;\nBE=handles.BE_or;\nhandles.data=data;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n% --------------------------------------------------------------------\nfunction Untitled_2_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_2 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction smooth_Callback(hObject, eventdata, handles)\n% hObject    handle to smooth (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\ndata=handles.data;\nBE=handles.BE;\n[m,n]=size(data);\nN=inputdlg('Enter the odd width of smoothing window > 3 - larger window causes more smoothing');  \nN=str2double(N);    \nfor i=1:n\n     data_s(i,:) = savgol(data(:,i)',N, 2 ,0);\nend\ndata=data_s';\nhandles.data_s=data;\nhandles.data=data;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n% --------------------------------------------------------------------\nfunction opencasavms_Callback(hObject, eventdata, handles)\n% hObject    handle to opencasavms (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n[filename, pathname]=uigetfiles('*.vms','Open vms files');\ncd(pathname)\n[N,M]=size(filename);\nif M==1;\n    [BE,data]=vms_sp_read_casa(char(filename(:,1)),0);\nelse\n    [BE, data(:,M)]=vms_sp_read_casa(char(filename(:,1)),0);\n     for i=2:M\n    [BE, data(:,i-1)]=vms_sp_read_casa(char(filename(:,i)),0);\nend\nend\n\nhandles.or_sp=data;\nhandles.data=data;\nhandles.BE=BE;\nhandles.BE_or=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n\n% --- Executes on button press in Plot_gui.\nfunction Plot_gui_Callback(hObject, eventdata, handles)\n% hObject    handle to Plot_gui (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata(:,1)=handles.BE;\ntemp=handles.data;\n[n,m]=size(temp);\ndata(:,2:m+1)=handles.data;\nH.Position=[262 118 560 335];\nfigure(H)\nplotgui(data);\nset(gca,'Xdir','reverse')\nhandles.H=H;\nguidata(hObject,handles)\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Nsimp_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to Nsimp (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n%       See ISPC and COMPUTER.\nif ispc\n    set(hObject,'BackgroundColor','white');\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction Nsimp_Callback(hObject, eventdata, handles)\n% hObject    handle to Nsimp (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of Nsimp as text\n%        str2double(get(hObject,'String')) returns contents of Nsimp as a double\nNsimp=str2double(get(hObject,'String'));\nhandles.der=0;\nhandles.Nsimp=Nsimp;\nguidata(hObject,handles)\n\n\n% --- Executes on button press in simplisma_main.\nfunction simplisma_main_Callback(hObject, eventdata, handles)\n% hObject    handle to simplisma_main (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\noffset=handles.offset;\nNsimp=handles.Nsimp;\nder=handles.der;\ndata=handles.data;\nBE=handles.BE;\nif der==0\n    [purspec,purint,purity_spec]=simplisma(data',BE, offset,Nsimp);\nelse\n   data2=invder(data');\n   [purspec,purint,purity_spec]=simplisma(data',BE, offset,Nsimp,data2);\nend\n\nmodel=handles.model;\nmodelsimp=model;\nmodelsimp.loads{1}=purspec';\nmodelsimp.loads{2}=purint;\nhandles.modelsimp=modelsimp;\nguidata(hObject,handles)\n\n\n% --- Executes on button press in simp_disp_spectr.\nfunction simp_disp_spectr_Callback(hObject, eventdata, handles)\n% hObject    handle to simp_disp_spectr (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodelsimp=handles.modelsimp;\nplotscores(modelsimp)\n\n% --- Executes on button press in simp_disp_int.\nfunction simp_disp_int_Callback(hObject, eventdata, handles)\n% hObject    handle to simp_disp_int (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodelsimp=handles.modelsimp;\nplotloads(modelsimp)\n\n% --- Executes during object creation, after setting all properties.\nfunction simp_offset_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to simp_offset (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n%       See ISPC and COMPUTER.\nif ispc\n    set(hObject,'BackgroundColor','white');\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction simp_offset_Callback(hObject, eventdata, handles)\n% hObject    handle to simp_offset (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of simp_offset as text\n%        str2double(get(hObject,'String')) returns contents of simp_offset as a double\n\noffset=str2double(get(hObject,'String')) ;\nhandles.offset=offset;\nguidata(hObject,handles)\n\n\n% --- Executes on button press in simpl_2nd.\nfunction simpl_2nd_Callback(hObject, eventdata, handles)\n% hObject    handle to simpl_2nd (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of simpl_2nd\n\n\nder=get(hObject,'Value');\nhandles.der=der;\nguidata(hObject,handles)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit8_CreateFcn(hObject, eventdata, handles)\n% hObject    handle to edit8 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n%       See ISPC and COMPUTER.\nif ispc\n    set(hObject,'BackgroundColor','white');\nelse\n    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit8_Callback(hObject, eventdata, handles)\n% hObject    handle to edit8 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit8 as text\n%        str2double(get(hObject,'String')) returns contents of edit8 as a double\n\n\n% --- Executes on button press in mcr_main.\nfunction mcr_main_Callback(hObject, eventdata, handles)\n% hObject    handle to mcr_main (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.data;\n[n,m]=size(data);\nopt=questdlg('Which intialization you want to use?','MCR','Random   ', 'PCA      ', 'Simplisma', 'Random   ');\nif opt=='Random   ';\n    N=inputdlg('Enter the number of components');  \n    Nmcr=str2double(N);\n    c0=rand(Nmcr,n);\nelseif opt=='PCA      '    \n    model=handles.model;\n    c0=model.loads{1}';\nelse\n    model=handles.modelsimp;\n    c0=model.loads{1}';\nend\n\nopt=questdlg('Do you want to apply nonnegativity to Concentrations?','MCR','Yes', 'No ', 'Yes');\nif opt=='Yes'\n   options.ccon='nonneg';\nelse\n   options.ccon='none';\nend\n\nopt=questdlg('Do you want to apply nonnegativity to Spectra?','MCR','Yes', 'No ', 'Yes');\nif opt=='Yes'\n   options.scon='nonneg';\nelse\n   options.scon='none';\nend\noptions.display='off';\noptions.plots='final';\nmodelmcr = mcr(data',c0,options);\nhandles.modelmcr=modelmcr;\nguidata(hObject,handles)\n\n% --- Executes on button press in mcr_disp_sp.\nfunction mcr_disp_sp_Callback(hObject, eventdata, handles)\n% hObject    handle to mcr_disp_sp (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodelmcr=handles.modelmcr;\nplotscores(modelmcr)\n\n\n% --- Executes on button press in mcr_disp_int.\nfunction mcr_disp_int_Callback(hObject, eventdata, handles)\n% hObject    handle to mcr_disp_int (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodelmcr=handles.modelmcr;\nplotloads(modelmcr)\n\n\n% --------------------------------------------------------------------\nfunction save_simpl_Callback(hObject, eventdata, handles)\n% hObject    handle to save_simpl (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmodelsimp=handles.modelsimp;\nBE=handles.BE;\nscores=modelsimp.loads{1};\nloads=modelsimp.loads{2};\ndatapath = uigetdir;\ncd(datapath)\n[filename, pathname] = uiputfile('*.mat', 'Save results as');\nsave(filename)\n\n\n% --------------------------------------------------------------------\nfunction save_mcr_Callback(hObject, eventdata, handles)\n% hObject    handle to save_mcr (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\nmodelmcr=handles.modelmcr;\nBE=handles.BE;\nscores=modelmcr.loads{1};\nloads=modelmcr.loads{2};\ndatapath = uigetdir;\ncd(datapath)\n[filename, pathname] = uiputfile('*.mat', 'Save results as');\nsave(filename)\n\n\n\n% --------------------------------------------------------------------\nfunction save_Callback(hObject, eventdata, handles)\n% hObject    handle to save (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\nmodelpca=handle.model;\nmodelsimp=handles.modelsimp;\nmodelmcr=handles.modelmcr;\ndata=handles.data\nBE=handles.BE;\ndatapath = uigetdir;\ncd(datapath)\n[filename, pathname] = uiputfile('*.mat', 'Save results as');\nsave(filename)\n\n\n% --------------------------------------------------------------------\nfunction open_casa_Callback(hObject, eventdata, handles)\n% hObject    handle to open_casa (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\nM = inputdlg('how many txt files to open?');\nM=str2double(M);\nif M==1;\n    [datafile,datapath] = uigetfile('*.*','Choose a vms file');\n    cd(datapath)\n    [n,BE,data,d]=textread(datafile,'%f%f%f%f','headerlines',4);\n    \nelse\n    prompt={'BE1:','BE2:'};\n     def={'295','282'};\n     dlgTitle='Enter the starting and enegind BE for the spectra';\n     lineNo=1;\n     answer=inputdlg(prompt,dlgTitle,lineNo,def);\n     N=str2double(answer);\n    for i=1:M\n      [datafile,datapath] = uigetfile('*.*','Choose a vms file');\n      cd(datapath)\n     [n,BE,temp,d]=textread(datafile,'%f%f%f%f','headerlines',4);\n     [i1,y]=find(BE==N(1));\n     [i2,y]=find(BE==N(2));\n     data(:,i)=temp(i1:i2);\n end\n BE=BE(i1:i2);\nend\n\nhandles.or_sp=data;\nhandles.data=data;\nhandles.BE=BE;\nhandles.BE_or=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n% --- Executes on button press in reverse.\nfunction reverse_Callback(hObject, eventdata, handles)\n% hObject    handle to reverse (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\nH=handles.H;\nfigure(1)\nset(gca,'Xdir','reverse')\n\n\n% --- Executes when figure1 window is resized.\nfunction figure1_ResizeFcn(hObject, eventdata, handles)\n% hObject    handle to figure1 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Calibrate_Callback(hObject, eventdata, handles)\n% hObject    handle to Calibrate (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.data;\nBE=handles.BE_or;\nhandles.BE_or_un=BE;\nhandles.or_sp_un=data;\nC=inputdlg('Which binding energy to use for calibration? Example: 285 or 284.8');  \nC=str2double(C);\n[x_sh, y_sh]=shift_spectra(data, BE,C);\ndata=y_sh;\nBE=x_sh;\nhandles.or_sp=data;\nhandles.BE_or=BE;\nhandles.data=data;\nhandles.BE=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n\n% --------------------------------------------------------------------\nfunction Undo_calibrate_Callback(hObject, eventdata, handles)\n% hObject    handle to Undo_calibrate (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.or_sp_un;\nhandles.or_sp=data;\nBE=handles.BE_or_un;\nhandles.data=data;\nhandles.BE_or=BE;\nhandles.BE=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n\n\n% --------------------------------------------------------------------\nfunction open_vms2_Callback(hObject, eventdata, handles)\n% hObject    handle to open_vms2 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n[filename, pathname]=uigetfiles('*.vms','Open vms files');\ncd(pathname)\n[N,M]=size(filename);\nif M==1;\n    [BE,data]=vms_sp_read2(char(filename(:,1)),0);\nelse\n    [BE, data(:,1)]=vms_sp_read2(char(filename(:,1)),0);\n    [BE, data(:,M)]=vms_sp_read2(char(filename(:,1)),0);\n   for i=2:M\n    [BE, data(:,i-1)]=vms_sp_read2(char(filename(:,i)),0);\nend\nend\n\nhandles.or_sp=data;\nhandles.data=data;\nhandles.BE=BE;\nhandles.BE_or=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_4_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_4 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.data;\nBE=handles.BE_or;\nhandles.BE_or_un=BE;\nhandles.or_sp_un=data;\nC=inputdlg('Which binding energy to use for calibration? Example: 285 or 284.8');  \nC=str2double(C);\n[x_sh, y_sh]=shift_spectra_or(data, BE,C);\ndata=y_sh;\nBE=x_sh;\nhandles.or_sp=data;\nhandles.BE_or=BE;\nhandles.data=data;\nhandles.BE=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction Untitled_5_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_5 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n[filename, pathname]=uigetfiles('*.vms','Open vms files');\ncd(pathname)\n[N,M]=size(filename);\nif M==1;\n    [BE,data]=vms_sp_read_casa2(char(filename(:,1)),0);\nelse\n    [BE, data(:,M)]=vms_sp_read_casa2(char(filename(:,1)),0);\n     for i=2:M\n    [BE, data(:,i-1)]=vms_sp_read_casa2(char(filename(:,i)),0);\nend\nend\n\nhandles.or_sp=data;\nhandles.data=data;\nhandles.BE=BE;\nhandles.BE_or=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n\n\n\n% --------------------------------------------------------------------\nfunction Untitled_6_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_6 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\ndata=handles.data;\nBE=handles.BE_or;\nhandles.BE_or_un=BE;\nhandles.or_sp_un=data;\n[y_sh, x_sh]=shift_spectra_diff(data, BE);\nBE=y_sh;\ndata=x_sh;\nhandles.or_sp=data;\nhandles.BE_or=BE;\nhandles.data=data;\nhandles.BE=BE;\naxes(handles.axes1)\nplot(BE,data)\nset(gca,'Xdir','reverse')\nguidata(hObject,handles)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15391-multivariate-analysis-and-preprocessing-of-spectral-data/spectral_mva.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23523315061190284}}
{"text": "function out = convert_caffe2mat( out )\n    assert(length(size(out)) <= 4, 'Only support at most 4-D data for convert.');\n    out = single(permute(out, [2 1 3 4]));\nend\n\n", "meta": {"author": "liuyuisanai", "repo": "RSA-for-object-detection", "sha": "626ad81172b260ecf8257a80731e5236fe41cb63", "save_path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection", "path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection/RSA-for-object-detection-626ad81172b260ecf8257a80731e5236fe41cb63/predict/utils/convert_caffe2mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23522124954095844}}
{"text": "function modelRet = gpsimTest\n\n% GPSIMTEST Test the gradients of the GPSIM model.\n% FORMAT\n% DESC runs some tests on the code in the GPSIM toolbox to\n% test that it is working.\n% RETURN model : a cell array of models used for testing.\n%\n% SEEALSO : modelTest\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n\n\n% SHEFFIELDML\n\nnumGenes = 5;\nnumProteins = 1;\nnumData = 4;\ntimes = linspace(0, 5, numData)';\ny = randn(numData, numGenes);\nyVar = randn(numData, numGenes);\nyVar = yVar.*yVar;\n\nnumCandGenes = 3;\nnumCandData = 5;\ntimesCand = linspace(0, 5, numCandData)';\nyCand = randn(numCandData, numCandGenes);\nyCandVar = randn(numCandData, numCandGenes);\nyCandVar = yCandVar.*yCandVar;\n\noptions = gpsimOptions;\n\nmodel = gpsimCreate(numGenes, numProteins, times, y, yVar, options);\n\nfprintf('Standard Parameter test:\\n');\nmodelGradientCheck(model);\n\nmodel = gpsimAddCandidate(model, numCandGenes, timesCand, yCand, yCandVar, options);\n\nfprintf('Candidate Parameter test:\\n');\nmodel.type = 'gpsimCandidate';\nmodelGradientCheck(model);\nmodel.type = 'gpsim';\n\nmodelRet = model;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpsimTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23522124954095844}}
{"text": "function EEG = hlp_icaact(EEG)\n% Recompute ica activations\n% \n% Author: Tim Mullen 2010, SCCN/INC, UCSD. \n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\nEEG.icaact = EEG.icaweights(:,EEG.icachansind)*EEG.icasphere*EEG.data(EEG.icachansind,:);\nEEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);\n    ", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/hlp/hlp_icaact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2352212495409584}}
{"text": "function planC = copyStructsFromFilesToPlanC(scanFileNames, planC)\n% function planC = copyStructsFromFilesToPlanC(scanFileNames, planC)\n%\n% APA 07/17/2013\n\nif ~exist('planC','var')\n    global planC\nend\n\nindexS = planC{end};\n\n[xValsBase, yValsBase, zValsBase] = getScanXYZVals(planC{indexS.scan});\n\nfor scanFileIndex = length(scanFileNames)\n    scanBasePlanC = loadPlanC(scanFileNames{scanFileIndex},tempdir);\n    indexSbaseScan = scanBasePlanC{end};\n    annotROIIndV = strcmpi('Annotation ROI',{scanBasePlanC{indexSbaseScan.structures}.structureName});\n    annotStrV = find(annotROIIndV);\n    [xValsBase1, yValsBase1, zValsBase1] = getScanXYZVals(scanBasePlanC{indexSbaseScan.scan});\n    for structIndex = 1:length(annotStrV)\n        structNum = annotStrV(structIndex);\n        sliceNumsV = [];\n        clear pointsC\n        for sliceNum = 1:length(scanBasePlanC{indexSbaseScan.structures}(structNum).contour)\n            for segNum = 1:length(scanBasePlanC{indexSbaseScan.structures}(structNum).contour(sliceNum).segments)\n                points = scanBasePlanC{indexSbaseScan.structures}(structNum).contour(sliceNum).segments(segNum).points;\n                if ~isempty(points)\n                    zValue = points(1,3);\n                    newSliceNum = findnearest(zValsBase,zValue);\n                    sliceNumsV = [sliceNumsV newSliceNum];\n                    points(:,3) = zValsBase(newSliceNum);\n                    pointsC{newSliceNum} = points;\n                end\n            end\n        end\n        \n        [sliceNumsV, indUniq] = unique(sliceNumsV);\n        \n        % Create Structures segments on sacn slices\n        newStructS = newCERRStructure(1, planC);\n        for slcNum = 1:length(zValsBase)\n            if ismember(slcNum,sliceNumsV)\n                newStructS.contour(slcNum).segments(1).points = pointsC{slcNum};\n            else\n                newStructS.contour(slcNum).segments.points = [];\n            end\n        end\n        \n        newStructNum = length(planC{indexS.structures}) + 1;\n        newStructS.structureName = 'Annotation ROI';\n        \n        planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructS, newStructNum);\n        planC = getRasterSegs(planC, newStructNum);\n        planC = updateStructureMatrices(planC, newStructNum, sliceNumsV);\n    end\nend\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_Data_Extraction/longitudinalLesionTracking/copyStructsFromFilesToPlanC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23517796644690525}}
{"text": "function [G] = spm_lx_phase (P,M)\n% Observation function for phase-coupled oscillators\n% FORMAT [G] = spm_lx_phase (P,M)\n%\n% G     Observations y = Gx\n\nNr=length(P.L);\nG=eye(Nr);", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/dcm_meeg/spm_lx_phase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.23493508547998254}}
{"text": "function [ cost, grad, numTotal, pred_cell ] = drdae_discrim_joint_kl_obj_gpu( theta, eI, data_cell, targets_cell, mixture_spectrum, fprop_only, pred_out)\n% Copyright (c) 2014-present University of Illinois at Urbana-Champaign\n% All rights reserved.\n% \t\t\n% Developed by:     Po-Sen Huang, Paris Smaragdis\n%                   Department of Electrical and Computer Engineering\n%                   Department of Computer Science\n%\n% discrim. training + joint masking using MATLAB GPU Toolbox\n%\n%PRNN_OBJ MinFunc style objective for Deep Recurrent Denoising Autoencoder\n%   theta is the full parameter vector\n%   eI contains experiment / network architecture\n%   data_cell is a cell array of matrices. Each a distinct length is a cell\n%             entry. Each matrix has a time series example in each column\n%   targets_cell is parallel to data, but contains the labels for each time\n%   fprop_only is a flag that only computes the cost, no gradient\n%   numTotal is total number of frames evaluated\n%   pred_out is a binary flag for whether pred_cell is populated\n%            pred_cell only filled properly when utterances one per cell\n\nimport parallel.gpu.GPUArray\n\ngtheta = gpuArray(theta);\n\n%% Debug: Turns this into an identity-function for debugging rest of system\nif isfield(eI, 'objReturnsIdentity') && eI.objReturnsIdentity\n    cost = 0; grad = 0; numTotal = 0;\n    for l = 1:numel(data_cell)\n        numUtterances = size(data_cell{l}, 2);\n        original_vector = reshape(data_cell{l}, eI.winSize*eI.featDim, []);\n        midPnt = ceil(eI.winSize/2);\n        original_vector = original_vector((midPnt-1)*14+1 : midPnt*14, :);\n        pred_cell{l} = reshape(original_vector, [], numUtterances);\n    end\n    return;\nend\n\n%if isempty(return_activation),\n  return_activation = 0;\n%end\n\n%% Load data from globals if not passed in (happens when run on RPC slave)\nglobal g_data_cell;\nglobal g_targets_cell;\nisSlave = false;\nif isempty(data_cell)\n    data_cell = g_data_cell;\n    targets_cell = g_targets_cell;\n    isSlave = true;\nend;\npred_cell = cell(1,numel(data_cell));\nact_cell = cell(1,numel(data_cell));\n%% default short circuits to false\nif ~isfield(eI, 'shortCircuit')\n    eI.shortCircuit = 0;\nend;\n\n%% default dropout to false\nif ~isfield(eI, 'dropout')\n  eI.dropout = 0;\nend;\n\n%% setup weights and accumulators\n[stack, W_t] = rnn_params2stack(gtheta, eI);\ncost = 0; numTotal = 0;\noutputDim = eI.layerSizes(end);\n\n%% setup structures to aggregate gradients\nstackGrad = cell(1,numel(eI.layerSizes));\n% W_t_grad = zeros(size(W_t));\nif isfield(eI, 'fullRNN') && eI.fullRNN==1\n   W_t_grad = cell(1,numel(eI.layerSizes)-1);\n    for l = 1:numel(eI.layerSizes)-1\n        W_t_grad{l}.W = gpuArray(zeros(size(W_t{l}.W)));\n    end\nelse\n   W_t_grad = gpuArray(zeros(size(W_t)));\nend\n\nfor l = 1:numel(eI.layerSizes)\n    stackGrad{l}.W = gpuArray(zeros(size(stack{l}.W)));\n    stackGrad{l}.b = gpuArray(zeros(size(stack{l}.b)));\nend\nif eI.shortCircuit\n    stackGrad{end}.W_ss = gpuArray(zeros(size(stack{end}.W_ss)));\nend;\n%% check options\nif ~exist('fprop_only','var')\n    fprop_only = false;\nend;\nif ~exist('pred_out','var')\n    pred_out = false;\nend;\n\n% DROPOUT: vector of length of hidden layers with 0 or 1\n% (to drop or keep activation unit) with prob=0.5\nhActToDrop = cell(numel(eI.layerSizes-1),1);\nfor i=1:numel(eI.layerSizes)-1\n if eI.dropout\n   hActToDrop{i} = gpuArray(1/eI.dropout * binornd(1,eI.dropout, eI.layerSizes(i),1));\n   %hActToDrop{i} = gpuArray(round(rand(eI.layerSizes(i),1)));\n else\n   hActToDrop{i} = gpuArray(ones(eI.layerSizes(i),1));\n end\nend\n\n%% loop over each distinct length\nfor c = 1:numel(data_cell)\n\n    targets = {};\n    if ~isempty(targets_cell), targets = targets_cell{c}; end;\n\n    mbsz=min(size(data_cell{c},2), floor(200*1024^2/size(data_cell{c},1)/8)); % 200mb max\n    if mbsz==0, continue; end\n    nbat = floor(size(data_cell{c},2)/mbsz)+1;\n\n     % convert different mini-bats to GPUs\n    for bat=1:nbat\n\n    data = gpuArray(data_cell{c}(:,1+(bat-1)*mbsz: min(size(data_cell{c},2), bat*mbsz)));\n    targets = gpuArray(targets_cell{c}(:,1+(bat-1)*mbsz:  min(size(targets_cell{c},2), bat*mbsz)));\n    mixtures=gpuArray(mixture_spectrum{c}(:,1+(bat-1)*mbsz: min(size(mixture_spectrum{c},2), bat*mbsz)));\n\n    uttPred = [];\n    T =size(data,1) / eI.inputDim;\n    % store hidden unit activations at each time instant\n    hAct = cell(numel(eI.layerSizes)-1, T);\n    for t = 1:T\n        %% forward prop all hidden layers\n        for l = 1:numel(eI.layerSizes)-1\n            if l == 1\n                hAct{1,t} = stack{1}.W * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);\n            else\n                hAct{l,t} = stack{l}.W * hAct{l-1,t};\n            end;\n            hAct{l,t} = hAct{l,t}+ repmat(stack{l}.b, 1, size(hAct{l,t},2));\n            % temporal recurrence. limited to single layer for now\n            if t > 1\n                if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                    hAct{l,t} = hAct{l,t} + W_t{l}.W * hAct{l,t-1};\n                elseif l == eI.temporalLayer\n                    hAct{l,t} = hAct{l,t} + W_t * hAct{l,t-1};\n                end\n            end;\n\n            % nonlinearity\n            if strcmpi(eI.activationFn,'tanh')\n                hAct{l,t} = tanh(hAct{l,t});\n            elseif strcmpi(eI.activationFn,'logistic')\n                hAct{l,t} = 1./(1+exp(-hAct{l,t}));\n            elseif strcmpi(eI.activationFn,'RELU')\n%                  maxg([ GPUsingle(zeros(size(hAct{1,t}))), hAct{l,t}], hAct{l,t});\n%                 hAct{l,t} = maxg(0,hAct{l,t});\n                hAct{l,t} = max(0,hAct{l,t});\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n            %dropout (hActToDrop will be all ones if no dropout specified)\n            hAct{1,t} = bsxfun(@times, hAct{1,t}, hActToDrop{l});\n%              hAct{1,t} = hAct{1,t}.*hActToDrop{l};\n        end;\n        % forward prop top layer not done here to avoid caching it\n    end;\n    %% compute cost and backprop through time\n    if  eI.temporalLayer\n        if isfield(eI, 'fullRNN') && eI.fullRNN==1\n            delta_t = cell(1, numel(eI.layerSizes)-1);\n            for l = 1:numel(eI.layerSizes)-1\n                delta_t{l} = gpuArray(zeros(eI.layerSizes(l),size(data,2)));\n            end\n        else\n            delta_t = gpuArray(zeros(eI.layerSizes(eI.temporalLayer),size(data,2)));\n        end\n    end;\n\n    y1_dim= 1:outputDim/2;\n    y2_dim= outputDim/2+1:outputDim;\n\n    for t = T:-1:1\n        l = numel(eI.layerSizes);\n        %% forward prop output layer for this timestep\n        curPred = bsxfun(@plus, stack{l}.W * hAct{l-1,t}, stack{l}.b);\n\n        if eI.outputnonlinear==1,\n           if strcmpi(eI.activationFn,'tanh')\n                curPred = tanh(curPred);\n           elseif strcmpi(eI.activationFn,'logistic')\n                curPred = 1./(1+exp(-curPred));\n           elseif strcmpi(eI.activationFn,'RELU')\n                curPred = max(0,curPred);\n           else\n                error('unrecognized activation function: %s',eI.activationFn);\n           end\n        end\n\n        mixture=mixtures((t-1)*numel(y1_dim)+1:t*numel(y1_dim),:);\n        a1 = curPred(y1_dim,:); a2 = curPred(y2_dim,:);\n\n        const=eI.const;%1e-8 ;\n        const2=eI.const2;% 1e-3;\n\n        if strcmp(eI.opt,'softlinear'),\n            y1= (a1)./((a1)+(a2)+1e-10).* mixture;\n            y2= (a2)./((a1)+(a2)+1e-10).* mixture;\n        elseif strcmp(eI.opt,'softabs'),\n            abs_a1= abs(a1); abs_a2= abs(a2);\n            y1= abs_a1./(abs_a1+abs_a2+1e-10).* mixture;\n            y2= abs_a2./(abs_a1+abs_a2+1e-10).* mixture;\n        elseif strcmp(eI.opt,'softabs_const')|| strcmp(eI.opt,'softabs_kl_const'),\n            y1= abs(a1)./(abs(a1)+abs(a2)+const).* mixture;\n            y2= abs(a2)./(abs(a1)+abs(a2)+const).* mixture;\n        elseif strcmp(eI.opt, 'softquad')\n            y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;\n            y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;\n        else\n        end\n\n        weighted_curPred=[y1; y2];\n        % add short circuit to regression prediction if model has it\n        if eI.shortCircuit\n            weighted_curPred = weighted_curPred + stack{end}.W_ss ...\n                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);\n        end;\n        if pred_out, uttPred = [weighted_curPred; uttPred]; end;\n        % skip loss computation if no targets given\n        if isempty(targets), continue; end;\n\n        curTargets = targets((t-1)*outputDim+1:t*outputDim, :);\n        curTargets_neg = [curTargets(outputDim/2+1:outputDim,:); curTargets(1:outputDim/2,:)];\n\n        y_t = (1- eI.r) * weighted_curPred + eI.r * curTargets_neg - curTargets;\n\n        ya_ta= y_t(y1_dim,:);\n        yb_tb= y_t(y2_dim,:);\n\n        if strcmp(eI.opt,'softlinear'),\n            delta_y1 =  (ya_ta-yb_tb).* y2./(a1+a2+1e-10);\n            delta_y2 = (-ya_ta+yb_tb) .* y1./ (a1+a2+1e-10);\n        elseif strcmp(eI.opt,'softabs'),\n            delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+1e-10);\n            delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+1e-10);\n\n            delta_y1(a1<0) = -delta_y1(a1<0);\n            delta_y2(a2<0) = -delta_y2(a2<0);\n        elseif strcmp(eI.opt,'softabs_const'),\n             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;\n             delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1+ ya_ta.* const_div;\n             delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2+ yb_tb.* const_div;\n\n             delta_y1(a1<0) =  -delta_y1(a1<0);\n             delta_y2(a2<0) =  -delta_y2(a2<0);\n        elseif strcmp(eI.opt,'softabs_kl_const'),\n             y_target_a = curTargets(y1_dim, :);\n             y_target_b = curTargets(y2_dim, :);\n             y_target_neg_a = y_target_b;\n             y_target_neg_b = y_target_a;\n\n             y_pred_a = weighted_curPred(y1_dim, :);\n             y_pred_b = weighted_curPred(y2_dim, :);\n\n             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;\n\n             delta_y1 =  (-y_target_a./(y_pred_a+const2) + y_target_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1+  (-y_target_a./(y_pred_a+const2)+1).* const_div;\n\n             delta_y2 =  (y_target_a./(y_pred_a+const2) - y_target_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2+ (-y_target_b./(y_pred_b+const2)+1) .* const_div;\n\n             % discrim part\n             delta_y1 =  delta_y1- eI.r* (-y_target_neg_a./(y_pred_a+const2) + y_target_neg_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);\n             delta_y1 = delta_y1-   eI.r* (-y_target_neg_a./(y_pred_a+const2)+1).* const_div;\n\n             delta_y2 = delta_y2- eI.r*(y_target_neg_a./(y_pred_a+const2) - y_target_neg_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);\n             delta_y2= delta_y2-  eI.r*(-y_target_neg_b./(y_pred_b+const2)+1) .* const_div;\n\n             delta_y1(a1<0) =  -delta_y1(a1<0);\n             delta_y2(a2<0) =  -delta_y2(a2<0);\n\n        elseif strcmp(eI.opt, 'softquad')\n            delta_y1 =  (ya_ta-yb_tb).* (2*a1.*y2)./ (a1.^2+a2.^2+1e-10); %  y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;\n            delta_y2 =  (-ya_ta+yb_tb).* (2*a2.*y1)./ (a1.^2+a2.^2+1e-10);%         y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;\n        else\n        end\n\n        delta = [ delta_y1; delta_y2 ];\n        if strcmp(eI.opt,'softlinear') || strcmp(eI.opt,'softabs') || strcmp(eI.opt, 'softquad') || strcmp(eI.opt,'softabs_const'),\n             cost = cost + 0.5 * ( sum( sum((weighted_curPred - curTargets).*(weighted_curPred - curTargets))) ...\n                -  eI.r* sum( sum((weighted_curPred - curTargets_neg).*(weighted_curPred - curTargets_neg))));\n        elseif strcmp(eI.opt,'softabs_kl_const'),\n             cost = cost +...\n             sum(sum( curTargets.*log( curTargets./(weighted_curPred + const2) + const2 )-curTargets+ weighted_curPred +const2))...\n            -eI.r* sum(sum( curTargets_neg.*log( curTargets_neg./(weighted_curPred + const2) + const2 )-curTargets_neg+ weighted_curPred +const2));\n        else\n\n        end\n        if eI.outputnonlinear==1,\n             if strcmpi(eI.activationFn,'tanh')\n                delta = delta .* (1 -curPred.^2);\n            elseif strcmpi(eI.activationFn,'logistic')\n                delta = delta .* curPred .* (1 - curPred);\n            elseif strcmpi(eI.activationFn,'RELU')\n                delta = delta .* double(curPred>0);\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n        end\n\n        if fprop_only, continue; end;\n        %% regression layer gradient and delta\n        stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';\n        stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);\n        % short circuit layer\n        if eI.shortCircuit\n            stackGrad{end}.W_ss = stackGrad{end}.W_ss + delta ...\n                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';\n        end;\n        delta = stack{l}.W' * delta;\n        %% backprop through hidden layers\n        for l = numel(eI.layerSizes)-1:-1:1\n            % aggregate temporal delta term if this is the recurrent layer\n            if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                delta = delta + delta_t{l};\n            elseif l == eI.temporalLayer\n                delta = delta + delta_t;\n            else\n            end\n            % push delta through activation function for this layer\n            % tanh unit choice assumed\n            if strcmpi(eI.activationFn,'tanh')\n                delta = delta .* (1 - hAct{l,t}.^2);\n            elseif strcmpi(eI.activationFn,'logistic')\n                delta = delta .* hAct{l,t} .* (1 - hAct{l,t});\n            elseif strcmpi(eI.activationFn,'RELU')\n                delta = delta .* gpuArray(hAct{l,t}>0);\n            else\n                error('unrecognized activation function: %s',eI.activationFn);\n            end;\n\n            % gradient of bottom-up connection for this layer\n            if l > 1\n                stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';\n            else\n                stackGrad{l}.W = stackGrad{l}.W + delta * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';\n            end;\n            % gradient for bias\n            stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);\n\n            % compute derivative and delta for temporal connections\n            if t > 1\n                if isfield(eI, 'fullRNN') && eI.fullRNN==1\n                     W_t_grad{l}.W = W_t_grad{l}.W + delta * hAct{l,t-1}';\n                     % push delta through temporal weights\n                     delta_t{l} = W_t{l}.W' * delta;\n                elseif l == eI.temporalLayer\n                     W_t_grad = W_t_grad + delta * hAct{l,t-1}';\n                     % push delta through temporal weights\n                     delta_t = W_t' * delta;\n                end;\n            end\n            % push delta through bottom-up weights\n            if l > 1\n                delta = stack{l}.W' * delta;\n            end;\n        end\n    end\n    pred_cell{c}=double(gather(uttPred));\n\n    % Return the activations for this utterance.\n    if return_activation,\n      act_cell{c} = cell2mat(hAct);\n    end\n    % keep track of how many examples seen in total\n    numTotal = numTotal + T * size(targets,2);\n    end\nend\n\n%% stack gradients into single vector and compute weight cost\nwCost = numTotal * eI.lambda * sum(gtheta.^2);\ngrad = rnn_stack2params(stackGrad, eI, W_t_grad, true);\ngrad = grad + 2 * numTotal * eI.lambda * gtheta;\n\n%% clipping\nif isfield(eI,'clip') && eI.clip~=0, % if eI.clip==0, no clip\n  if eI.clip > 0 % method one -clip the whole\n      norm_grad = norm(grad);  \n      fprintf('norm_grad:%f\\n', norm_grad);\n      % avoid numerial problem\n      if norm_grad <0 || norm_grad > 1e15 || isnan(norm_grad) || isinf(norm_grad),\n          grad = zeros(size(grad));\n          fprintf('set gradient to zeros\\n');\n      end  \n      if norm_grad > eI.clip \n         grad = eI.clip * grad/ norm_grad;    \n      end  \n  else % method two - clip each entry\n      clip_value = -1*eI.clip;\n      grad(grad > clip_value)=clip_value;\n      grad(grad < -clip_value)=-clip_value;     \n  end\nend\n%%\ncost = gather((cost));\ngrad = gather((grad));\nwCost = gather((wCost));\n\navCost = cost/numTotal;\navWCost = wCost/numTotal;\ncost = cost + wCost;\n\n% print output\nif ~isSlave && ~isempty(targets_cell)\n    fprintf('loss:  %f  wCost:  %f \\t',avCost, avWCost);\n\n    if isfield(eI, 'fullRNN') && eI.fullRNN==1\n        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\\n',sum(stack{1}.W(:).^2),...\n            sum(W_t{1}.W(:).^2), sum(stack{end}.W(:).^2));\n    else\n        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\\n',sum(stack{1}.W(:).^2),...\n            sum(W_t(:).^2), sum(stack{end}.W(:).^2));\n    end\nend;\n", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/codes/drdae_discrim_joint_kl_obj_gpu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2348505291042797}}
{"text": "function [m] = esvm_mine_train_iteration(m, training_function)\n%% ONE ITERATION OF: Mine negatives until cache is full and update the current\n% classifier using training_function (do_svm, do_rank, ...). m must\n% contain the field m.train_set, which indicates the current\n% training set of negative images\n% Returns the updated model (where m.mining_queue is updated mining_queue)\n%\n% Copyright (C) 2011-12 by Tomasz Malisiewicz\n% All rights reserved.\n% \n% This file is part of the Exemplar-SVM library and is made\n% available under the terms of the MIT license (see COPYING file).\n% Project homepage: https://github.com/quantombone/exemplarsvm\n\n% Start wtrace (trace of learned classifier parameters across\n% iterations) with first round classifier, if not present already\nif ~isfield(m.model,'wtrace')\n  m.model.wtrace{1} = m.model.w;\n  m.model.btrace{1} = m.model.b;\nend\n\nif length(m.mining_queue) == 0\n  fprintf(1,' ---Null mining queue, not mining!\\n');\n  return;\nend\n\n%If the skip is enabled, we just update the model\nif m.mining_params.train_skip_mining == 0\n  [hn, m.mining_queue, mining_stats] = ...\n      esvm_mine_negatives({m}, m.mining_queue, m.train_set, ...\n                     m.mining_params);\n\n  m = add_new_detections(m, cat(2,hn.xs{1}{:}), cat(1,hn.bbs{1}{: ...\n                   }));\nelse\n  mining_stats.num_visited = 0;\n  fprintf(1,'WARNING: train_skip_mining==0, just updating model\\n');  \nend\n   \nm = update_the_model(m, mining_stats, training_function);\n\nif isfield(m,'dataset_params') && m.dataset_params.display == 1\n  dump_figures(m);\nend\n\nfunction [m] = update_the_model(m, mining_stats, training_function)\n%% UPDATE the current SVM, keep max number of svs, and show the results\n\nif ~isfield(m,'mining_stats')\n  m.mining_stats{1} = mining_stats;\nelse\n  m.mining_stats{end+1} = mining_stats;\nend\n\nm = training_function(m);\n\n% Append new w to trace\nm.model.wtrace{end+1} = m.model.w;\nm.model.btrace{end+1} = m.model.b;\n\n% if (m.mining_params.dfun == 1)\n%   r = m.model.w(:)'*bsxfun(@minus,m.model.svxs,m.model.x(:,1)).^2 - ...\n%       m.model.b;\n% else\n%   r = m.model.w(:)'*m.model.svxs - m.model.b;\n% end\n% m.model.svbbs(:,end) = r;\n\nfunction dump_figures(m)\n\n% figure(1)\n% clf\n% show_cool_os(m)\n\n% if (mining_params.dump_images == 1) || ...\n%       (mining_params.dump_last_image == 1 && ...\n%        m.iteration == mining_params.train_max_mine_iterations)\n%   set(gcf,'PaperPosition',[0 0 10 3]);\n%   print(gcf,sprintf('%s/%s.%d_iter=%05d.png', ...\n%                     mining_params.final_directory,m.curid,...\n%                     m.objectid,m.iteration),'-dpng'); \n% end\n\nfigure(2)\nclf\nIsv1 = esvm_show_det_stack(m,7);\n\nimagesc(Isv1)\naxis image\naxis off\niter = length(m.model.wtrace)-1;\ntitle(sprintf('Ex %s.%d.%s SVM-iter=%03d',m.curid,m.objectid,m.cls,iter))\ndrawnow\nsnapnow\n\nif (m.mining_params.dump_images == 1) || ...\n      (m.mining_params.dump_last_image == 1 && ...\n       m.iteration == m.mining_params.train_max_mine_iterations)\n\n  imwrite(Isv1,sprintf('%s/%s.%d_iter_I=%05d.png', ...\n                    m.mining_params.final_directory, m.curid,...\n                    m.objectid, m.iteration), 'png');\nend\n\nfunction m = add_new_detections(m, xs, bbs)\n% Add current detections (xs,bbs) to the model struct (m)\n% making sure we prune away duplicates, and then sort by score\n%\n% Tomasz Malisiewicz (tomasz@cmu.edu)\n\n%First iteration might not have support vector information stored\nif ~isfield(m.model, 'svxs') || isempty(m.model.svxs)\n  m.model.svxs = [];\n  m.model.svbbs = [];\nend\n\nm.model.svxs = cat(2,m.model.svxs,xs);\nm.model.svbbs = cat(1,m.model.svbbs,bbs);\n\n%Create a unique string identifier for each of the supports\nnames = cell(size(m.model.svbbs,1),1);\nfor i = 1:length(names)\n  bb = m.model.svbbs(i,:);\n  names{i} = sprintf('%d.%.3f.%d.%d.%d',bb(11),bb(8), ...\n                             bb(9),bb(10),bb(7));\nend\n  \n[unames,subset,j] = unique(names);\nm.model.svbbs = m.model.svbbs(subset,:);\nm.model.svxs = m.model.svxs(:,subset);\n\n[aa,bb] = sort(m.model.w(:)'*m.model.svxs,'descend');\nm.model.svbbs = m.model.svbbs(bb,:);\nm.model.svxs = m.model.svxs(:,bb);\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/internal/esvm_mine_train_iteration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2348404369524402}}
{"text": "% This is the testing demo of FFDNet for denoising noisy color images corrupted by\n% AWGN with clipping setting. The noisy input is 8-bit quantized.\n%\n% To run the code, you should install Matconvnet first. Alternatively, you can use the\n% function `vl_ffdnet_matlab` to perform denoising without Matconvnet.\n%\n% \"FFDNet: Toward a Fast and Flexible Solution for CNN based Image\n% Denoising\" 2018/03/23\n% If you have any question, please feel free to contact with me.\n% Kai Zhang (e-mail: cskaizhang@gmail.com)\n\n% clear; clc;\n\nformat compact;\nglobal sigmas; % input noise level or input noise level map\naddpath(fullfile('utilities'));\n\nfolderModel = 'models';\nfolderTest  = 'testsets';\nfolderResult= 'results';\nimageSets   = {'CBSD68','Kodak24','McMaster'}; % testing datasets\nsetTestCur  = imageSets{1};      % current testing dataset\n\nshowResult  = 1;\nuseGPU      = 1;\npauseTime   = 0;\n\nimageNoiseSigma = 25;  % image noise level, 25.5 is the default setting of imnoise( ,'gaussian')\ninputNoiseSigma = 25;  % input noise level\n\nfolderResultCur       =  fullfile(folderResult, [setTestCur,'_Clip_',num2str(imageNoiseSigma(1)),'_',num2str(inputNoiseSigma(1))]);\nif ~isdir(folderResultCur)\n    mkdir(folderResultCur)\nend\n\nload(fullfile('models','FFDNet_Clip_color.mat'));\nnet = vl_simplenn_tidy(net);\n\n% for i = 1:size(net.layers,2)\n%     net.layers{i}.precious = 1;\n% end\n\nif useGPU\n    net = vl_simplenn_move(net, 'gpu') ;\nend\n\n% read images\next         =  {'*.jpg','*.png','*.bmp','*.tif'};\nfilePaths   =  [];\nfor i = 1 : length(ext)\n    filePaths = cat(1,filePaths, dir(fullfile(folderTest,setTestCur,ext{i})));\nend\n\n% PSNR and SSIM\nPSNRs = zeros(1,length(filePaths));\nSSIMs = zeros(1,length(filePaths));\n\nfor i = 1:length(filePaths)\n    \n    % read images\n    label   = imread(fullfile(folderTest,setTestCur,filePaths(i).name));\n    [w,h,c] = size(label);\n    \n    if c == 3\n        [~,nameCur,extCur] = fileparts(filePaths(i).name);\n        label = im2single(label);\n        \n        % add noise\n        randn('seed',0);\n        %input = imnoise(label,'gaussian'); % corresponds to imageNoiseSigma = 25.5;\n        input = imnoise(label,'gaussian',0,(imageNoiseSigma/255)^2);\n        \n        if mod(w,2)==1\n            input = cat(1,input, input(end,:,:)) ;\n        end\n        if mod(h,2)==1\n            input = cat(2,input, input(:,end,:)) ;\n        end\n        \n        % tic;\n        if useGPU\n            input = gpuArray(input);\n        end\n        \n        % set noise level map\n        sigmas = inputNoiseSigma/255; % see \"vl_simplenn.m\".\n        \n        % perform denoising\n        res    = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test'); % matconvnet default\n        % res    = vl_ffdnet_concise(net, input);    % concise version of vl_simplenn for testing FFDNet\n        % res    = vl_ffdnet_matlab(net, input); % use this if you did  not install matconvnet; very slow\n        \n        % output = input -res(end).x; % for 'model_color.mat'\n        output = res(end).x;\n        \n        \n        if mod(w,2)==1\n            output = output(1:end-1,:,:);\n            input  = input(1:end-1,:,:);\n        end\n        if mod(h,2)==1\n            output = output(:,1:end-1,:);\n            input  = input(:,1:end-1,:);\n        end\n        \n        if useGPU\n            output = gather(output);\n            input  = gather(input);\n        end\n        %toc;\n        \n        % calculate PSNR, SSIM and save results\n        [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);\n        if showResult\n            imshow(cat(2,im2uint8(input),im2uint8(label),im2uint8(output)));\n            title([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])\n            %imwrite(im2uint8(output), fullfile(folderResultCur, [nameCur, '_' num2str(imageNoiseSigma(1),'%02d'),'_' num2str(inputNoiseSigma(1),'%02d'),'_PSNR_',num2str(PSNRCur*100,'%4.0f'), extCur] ));\n            drawnow;\n            pause()\n        end\n        disp([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])\n        PSNRs(i) = PSNRCur;\n        SSIMs(i) = SSIMCur;\n        \n    end\nend\n\ndisp([mean(PSNRs),mean(SSIMs)]);\n\n\n\n\n", "meta": {"author": "cszn", "repo": "FFDNet", "sha": "e787f46df2f374ff3591186706229cb9a0591fea", "save_path": "github-repos/MATLAB/cszn-FFDNet", "path": "github-repos/MATLAB/cszn-FFDNet/FFDNet-e787f46df2f374ff3591186706229cb9a0591fea/Demo_AWGN_Color_Clip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23473637915483503}}
{"text": "classdef CLFQP < Controller\n    % This class defines a class of Control Lyapunov Functions (CLFs) that\n    % use quadratic programming (QP)\n    %\n    % @todo implement the CLF-QP controller\n    % \n    % @author ayonga @date 2016-10-14\n    % \n    % Copyright (c) 2016, AMBER Lab\n    % All right reserved.\n    %\n    % Redistribution and use in source and binary forms, with or without\n    % modification, are permitted only in compliance with the BSD 3-Clause \n    % license, see\n    % http://www.opensource.org/licenses/bsd-license.php\n    \n    properties\n        \n        \n        \n    end\n    \n    methods\n        \n        function obj = CLFQP(name)\n            % The controller class constructor function\n            %\n            % Parameters:\n            % name: the controller name @type char\n            \n            % call superclass constructor\n            obj = obj@Controller(name);\n            warning('P matrix from the Ricatti equation not verified for relative degree one outputs and not efficiently computed');\n%             error('This class has not been completely defined yet.');\n            \n        end\n        \n        \n        function u = calcControl(obj, t, x, vfc, gfc, plant, params, logger)\n            % Computes the control Lyapunov function based control laws\n            % control law for virtual constraints\n            %\n            % Parameters:\n            % t: the time instant @type double\n            % x: the states @type colvec\n            % vfc: the vector field f(x) @type colvec\n            % gfc: the vector field g(x) @type colvec\n            % plant: the continuous domain @type DynamicalSystem\n            % params: the control parameters @type struct\n            % logger: the data logger object @type SimLogger\n            %\n            % Return values:\n            % u: the computed torque @type colvec\n            \n            nx = plant.numState;\n            if strcmp(plant.Type,'SecondOrder')\n                q = x(1:nx);\n                dq = x(nx+1:end);\n            else\n                q = x;\n                dq = []; % will not affect any computation\n            end\n            \n            \n            y = struct2array(plant.VirtualConstraints);\n            ny = length(y);\n            y_a = cell(ny,1);\n            y_d = cell(ny,1);\n            tau = cell(ny,1);\n            \n            % total dimension of the virtual constraints\n            dim_y = sum([y.Dimension]);\n            % total dimension of outputs (including relative degrees)\n            dim_eta = sum([y.Dimension.*y.RelativeDegree]);\n            % some constants required for CLF\n            F_mat = zeros(dim_eta);\n            G_mat = zeros(dim_eta,dim_y);\n            I_mat = eye(dim_eta);\n            % partial derivative of the highest order of derivative (y^n-1) w.r.t.\n            % the state variable 'x'\n            DLfy = zeros(dim_y,length(x));   % A = DLfy*gfc; Lf = DLfy*vfc;\n            ddy = zeros(dim_y,1);\n            mu = zeros(dim_y,1);    % The derivatives mu = k(1) y + k(2) y' + ... k(n) y^(n-1)\n            eta = zeros(dim_eta,1);\n            idx = 1; % indexing of outputs\n            etaidx = 1; % indexing of eta\n            for i=1:ny\n                y_i = y(i);\n                \n                % returns y, y', y'', y^(n-1), Jy^n-1\n                \n                % calculate the actual outputs\n                %         [y_a{i}{:}] = calcActual(y_i,q,dq);\n                offset_param = y_i.OffsetParamName;\n                if y_i.hasOffset\n                    offset = params.(offset_param);\n                    y_a{i} = calcActual(y_i, q, dq, offset);\n                else\n                    y_a{i} = calcActual(y_i, q, dq);\n                end\n                % extract the parameter values\n               \n                output_param = y_i.OutputParamName; % desired output parameters\n                phase_param  = y_i.PhaseParamName;  % phase variable parameters\n                \n                \n                if isfield(params,output_param)\n                    a = params.(output_param);\n                else\n                    error('The parameter %s has not been specified in the ''params'' argument.\\n', output_param);\n                end\n                \n                if ~isempty(phase_param)\n                    if isfield(params,phase_param)\n                        p = params.(phase_param);\n                    else\n                        error('The parameter %s has not been specified in the ''params'' argument.\\n', phase_param);\n                    end\n                else\n                    p = [];\n                end\n                % calculate the desired outputs\n                y_d{i} = calcDesired(y_i, t, q, dq, a, p);\n                % calculate the phase variable\n                tau{i} = calcPhaseVariable(y_i, t, q, dq, p);\n                \n                \n                \n                \n                % control gain (k0,k1,...kN-1) for the feedback term\n                if isfield(params, 'epsilon')\n                    ep = params.epsilon;\n                    K = ones(1, y_i.RelativeDegree);\n                    for l= 1:y_i.RelativeDegree\n                        K(l) = nchoosek(y_i.RelativeDegree,l-1)*ep^(y_i.RelativeDegree - l + 1);\n                    end\n                    \n                    \n                else\n                    error('The control gain %s has not been specified in the ''params'' argument.\\n', control_param);\n                end\n                \n                \n                % stack the partial derivatives of all outputs\n                y_indices = idx:idx+y_i.Dimension-1;\n                eta_indices = etaidx:etaidx+y_i.Dimension-1;\n                \n                G_mat(eta_indices+(y_i.RelativeDegree-1)*numel(eta_indices),y_indices) = eye(y_i.Dimension);\n                \n                if y_i.RelativeDegree > 1 % only modify the first degree outputs (0th derivative). not higher derivatives\n                    I_mat(eta_indices,eta_indices) = ep*eye(numel(eta_indices));\n                end\n                \n                if strcmp(y_i.PhaseType, 'TimeBased')\n                    DLfy(y_indices,:) = y_a{i}{end};\n                    ddy(y_indices) = y_d{i}{end};\n                else\n                    DLfy(y_indices,:) = y_a{i}{end} - y_d{i}{end};\n                end\n                for j=1:y_i.RelativeDegree\n                    mu(y_indices) = mu(y_indices) + K(j)*(y_a{i}{j}-y_d{i}{j});\n                    eta(eta_indices+(j-1)*numel(eta_indices)) = y_a{i}{j} - y_d{i}{j};\n                    \n                    if j < y_i.RelativeDegree\n                        F_mat(eta_indices+(j-1)*numel(eta_indices),eta_indices+j*numel(eta_indices)) = eye(numel(eta_indices));\n                    end\n                end\n                % update the starting index for the next output\n                idx = idx+y_i.Dimension;\n                etaidx = etaidx+y_i.Dimension*y_i.RelativeDegree;\n            end\n            \n            \n            \n            %% here is where the CLF based controller is designed \n            % decoupling matrix\n            A_mat  = DLfy*gfc;\n            % feedforward term\n            Lf_mat = DLfy*vfc;\n            \n            % Lyapunov function\n            P = care(F_mat,G_mat,eye(dim_eta));\n            Pep = I_mat' * P * I_mat;\n            Veta = eta' * Pep * eta;\n            \n%             % CLF V for mu\n%             LgVetamu = 2*eta'*Pep*G_mat;\n%             LfVetamu = eta'*(F_mat'*Pep + Pep*F_mat)*eta + 0.3660*ep*Veta; \n            \n            % CLF V for u\n            LgVetau = 2*eta'*Pep*G_mat*A_mat;\n            LfVetau = eta'*(F_mat'*Pep+Pep*F_mat)*eta+0.3660*ep*Veta+2*eta'*Pep*G_mat*Lf_mat-2*eta'*Pep*G_mat*ddy;\n            \n            Hmat = A_mat' * A_mat;\n            \n            % feedforward controller\n            if strcmp(y_i.PhaseType, 'TimeBased')\n                bmat = Lf_mat'*A_mat - ddy'*A_mat;\n%                 u_ff = - A_mat \\ (Lf_mat - ddy);\n            else\n                bmat = Lf_mat'*A_mat;\n%                 u_ff = - A_mat \\ Lf_mat;\n            end\n            \n            options = optimoptions('quadprog','Algorithm','interior-point-convex','display','off');\n            \n%             muqp = quadprog(eye(6),[],LgVetamu,-LfVetamu,[],[],[],[],[],options);\n%             disp(max(mu - muqp))\n%             mu = muqp;\n%             u_fb = A_mat \\ mu;\n%             u = u_ff + u_fb;\n            \n            u = quadprog(Hmat,bmat,LgVetau,-LfVetau,[],[],[],[],[],options);\n%             disp(max(u - uqp))\n            % feedback controller\n\n            \n            \n            if ~isempty(logger)\n                calc = logger.calc;\n                \n                calc.mu = mu;\n                \n                for i=1:ny\n                    y_i = y(i);\n                    output_name = y_i.Name;\n                    \n                    for j=1:y_i.RelativeDegree\n                        \n                        if j > 1\n                            ya_name = ['d' num2str(j-1) 'ya_' output_name];\n                            yd_name = ['d' num2str(j-1) 'yd_' output_name];\n                            tau_name = ['d' num2str(j-1) 'tau_' output_name];\n                        else\n                            ya_name = ['ya_' output_name];\n                            yd_name = ['yd_' output_name];\n                            tau_name = ['tau_' output_name];\n                        end\n                        calc.(ya_name) = y_a{i}{j};\n                        calc.(yd_name) = y_d{i}{j};\n                        calc.(tau_name) = tau{i}{j};\n                        \n                    end\n                \n                end\n%                 calc.u_ff = u_ff;\n%                 calc.u_fb = u_fb;\n                calc.u = u;\n\n                logger.calc = calc;\n            end\n            \n        end\n    end\n    \nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/matlab/control/CLFQP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23473637345567946}}
{"text": "hydro = struct();\n\nhydro = readNEMOH(hydro,'../Sphere/');\n% hydro = readWAMIT(hydro,'../../WAMIT/Sphere/sphere.out',[]);\n% hydro = combineBEM(hydro); % Compare to WAMIT\nhydro = radiationIRF(hydro,15,[],[],[],[]);\nhydro = radiationIRFSS(hydro,[],[]);\nhydro = excitationIRF(hydro,15,[],[],[],[]);\nwriteBEMIOH5(hydro)\nplotBEMIO(hydro)\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/examples/BEMIO/NEMOH/Sphere/bemio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23473580894336182}}
{"text": "% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos\n% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n\nfunction CstDefineEfieldMonitor(mws,Efieldname, frequency)\n\n%'@ define monitor: e-field (f=2.25)\n% Efieldname is a string\n\nMonitor = invoke(mws,'Monitor');\ninvoke(Monitor,'Reset');\ninvoke(Monitor,'Name',Efieldname);\ninvoke(Monitor,'Dimension','Volume');\ninvoke(Monitor,'Domain','Frequency');\ninvoke(Monitor,'FieldType','Efield');\ninvoke(Monitor,'Frequency',num2str(frequency));\ninvoke(Monitor,'UseSubvolume','False');\ninvoke(Monitor,'SetSubvolume','-53.310273111111', '53.310273111111', '-53.310273111111', '53.310273111111', '-33.310273111111', '71.310273111111');\ninvoke(Monitor,'Create');\n\n\nend\n\n", "meta": {"author": "simos421", "repo": "CST-MATLAB-API", "sha": "a6019ad6f33fa14ebfd459579b6e7151dd3d4ece", "save_path": "github-repos/MATLAB/simos421-CST-MATLAB-API", "path": "github-repos/MATLAB/simos421-CST-MATLAB-API/CST-MATLAB-API-a6019ad6f33fa14ebfd459579b6e7151dd3d4ece/Simulation/CstDefineEfieldMonitor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2347358089433618}}
{"text": "function [ obj ] = mh_invert( obj )\n% Metropolized Gibbs sampling on collapsed HUGE model.\n% \n% This is a protected method of the tapas_Huge class. It cannot be called\n% from outside the class.\n% \n% \n\nobj = obj.mh_init( );\n% number of iterations and burn-in\nnIt = obj.options.nvp.numberofiterations;\nif isempty(nIt)\n    nIt = 2e5;\nend\nnBi = obj.options.nvp.burnin;\nif isempty(nBi) || nBi >= nIt\n    nBi = fix(nIt/2);\nend\n\n% inverse chain temperature\ninvTemp = obj.options.nvp.inversetemperature;\n\n% reserve memory\nq_nk = zeros(obj.N, obj.K);\nobj.trace = struct();\nobj.trace.smp = repmat(obj.aux.sample, nIt, 1);\nobj.trace.lpr = repmat(obj.aux.lpr, nIt, 1);\npsrf = repmat(obj.aux.sample, fix(nIt/obj.const.nPsrf) + 1, 1);\n\n%% ===== MAIN LOOP =====\nfor iIt = 1:nIt\n    \n    % subject level\n    for iMhDcm = 1:obj.options.mh.nSteps.dcm\n        % sample DCM (parameters)\n        obj = mh_sample_dcm( obj, invTemp );\n        % sample lambda (hyperparameters)\n        obj = mh_sample_noise( obj, invTemp );  \n    end\n\n    % group level\n    if mod(iIt, obj.options.mh.nSteps.knKm) == 0\n        k = mod(iIt/obj.options.mh.nSteps.knKm - 1,obj.K) + 1;\n        obj = mh_sample_kmhop( obj, k );\n    else\n        % sample weights pi\n        if obj.K > 1\n            for iMh = 1:obj.options.mh.nSteps.weights\n                obj = mh_sample_weights( obj );\n            end\n        end\n        % sample cluster mu and Sigma\n        for iMh = 1:obj.options.mh.nSteps.clusters\n            obj = mh_sample_cluster( obj );\n        end\n    end\n    \n    % save sample\n    obj.trace.smp(iIt) = obj.aux.sample;\n    obj.trace.lpr(iIt) = obj.aux.lpr;\n\n    % adapt proposal step size\n    if (iIt <= nBi/3) && (mod(iIt, obj.const.mhAdapt(1)) == 0)\n        obj = mh_adapt(obj, iIt);\n    end\n    \n    % accumulate cluster assigment estimate\n    if iIt > nBi\n        tmp = bsxfun(@times, exp(obj.aux.rho), obj.aux.sample.pi);\n        q_nk = q_nk + bsxfun(@rdivide, tmp, sum(tmp, 2));\n    end\n    % convergence monitoring\n    if mod(iIt, obj.const.nPsrf) == 0\n        iPsrf = iIt/obj.const.nPsrf;\n        psrf(iPsrf) = mh_psrf(obj.trace.smp(1:iIt), 4);\n    end\n    if obj.options.nvp.verbose && mod(iIt, 100) == 1\n        fprintf('Iteration %u\\n', iIt);\n    end\n    \n% -------------------------------------\nend%         END MAIN LOOP\n% -------------------------------------\n%%          Post Processing\n% estimates for assignment probability\nq_nk = q_nk/(nIt - nBi);\n\n% acceptance ratio\nratio = struct();\nobj.aux.nProp.sp(1) = obj.aux.nProp.sp(1)*obj.N;\nfor parameter = {'pi', 'mu', 'kappa', 'theta', 'lambda', 'sp'}\n    ratio.(parameter{1}) = obj.aux.nAccept.(parameter{1})./...\n        obj.aux.nProp.(parameter{1});\nend\n% posterior mean and quantiles\npostMean    = struct();\npostVar     = struct();\npostQuant   = struct();\nfor parameter = {'pi', 'mu', 'kappa', 'theta_c', 'theta_h', 'lambda'}\n    tmp = reshape([obj.trace.smp(nBi+1:end).(parameter{1})], ...\n        [size(obj.aux.sample.(parameter{1})), nIt - nBi]);\n    postMean.(parameter{1})  = mean(tmp, 3);\n    postVar.(parameter{1})   = var(tmp, 0, 3);\n    postQuant.(parameter{1}) = quantile(tmp, obj.options.quantiles, 3);\nend\n% cumulative probability levels for quantiles\npostQuant.levels = obj.options.quantiles;\n\n% calculate PSRF post burn-in\npsrf(end) = mh_psrf(obj.trace.smp(nBi + 1:end), 4);\n\n% collect posterior summaries\nobj.posterior = struct('nIt', nIt, 'nBi', nBi, 'q_nk', q_nk, ...\n    'ratio', ratio, 'psrf', psrf, 'mean', postMean, 'variance', postVar, ...\n    'quantile', postQuant, 'lvarBold', obj.aux.lvarBold, ...\n    'nrv', exp(-postMean.lambda));\n\n% thin MC chain\nif ~isempty(obj.options.nTrace)\n    % keep only nTrace samples from post-burn-in phase\n    nTrace  = min(nIt - nBi, obj.options.nTrace);\n    nThin   = fix((nIt - nBi)/nTrace);\n    % select samples uniformly\n    obj.trace.smp = obj.trace.smp(end-nThin*(nTrace - 1):nThin:end);\n    obj.trace.lpr = obj.trace.lpr(end-nThin*(nTrace - 1):nThin:end);\nend\n\nend\n\n%---------------------------------\n%            SAMPLING\n%---------------------------------\n%% SAMPLING: weights (pi)\nfunction [ obj ] = mh_sample_weights( obj )\n\n% propose (in unconstrained space) \nprop_piu = obj.aux.sample.pi_u + ...\n    randn(1,obj.K-1)*obj.aux.step.pi;\n% transform to unit simplex\nprop_pis = 1./(1 + exp(log(obj.K-1:-1:1) - prop_piu));\nprop_pic = cumprod(1-prop_pis);\nprop_pi = [prop_pis(1),-diff(prop_pic),prop_pic(end)];\n\n% evaluate joint (in unconstrained space)\n% log-prior on pi\nprop_lpr = log(prop_pi)*(obj.prior.alpha_0 - 1) + ...\n   sum(log(prop_pis)) + sum(log(1-prop_pis)) + ...\n   sum(log(prop_pic(1:end-1)));\nprop_lpr = max(prop_lpr, -realmax);\n% log-conditional of theta_c given pi\nprop_lcd = log(exp(obj.aux.rho)*prop_pi') + obj.aux.rho_max;\n\n% accept/reject\nobj.aux.nProp.pi = obj.aux.nProp.pi + 1;\na = exp(prop_lpr - obj.aux.lpr.pi...\n        + sum(prop_lcd - obj.aux.lpr.theta_c));\n%         a = exp(prop_lpr - obj.aux.lpr.pi);\nif ~isnan(a) && ~isinf(a) && rand()<a\n    obj.aux.sample.pi_u = prop_piu;\n    obj.aux.sample.pi = prop_pi;\n    obj.aux.lpr.pi = prop_lpr;\n    obj.aux.lpr.theta_c = prop_lcd;\n    obj.aux.nAccept.pi = obj.aux.nAccept.pi + 1;\nend\n\nend\n\n\n%% SAMPLING: cluster parameters (mu, kappa = - log(sigma^2))\nfunction [ obj ] = mh_sample_cluster( obj )\n\nobj.aux.nProp.mu = obj.aux.nProp.mu + 1;\nobj.aux.nProp.kappa = obj.aux.nProp.mu;\n\nfor k = 1:obj.K\n\n    prop_kappa = obj.aux.sample.kappa(k,:);\n    % mean\n    tmp = randn(1,obj.idx.P_c)*obj.aux.step.mu(k);\n    prop_mu = obj.aux.sample.mu(k,:) + tmp*...\n        obj.aux.transform.mu(:,:,k);\n    dlq = 0; % delta log-proposal density\n\n    % evaluate log-conditional\n    % prior\n    prop_dmu_k = prop_mu - obj.prior.m_0;\n    prop_lpr_mu = -prop_dmu_k*obj.prior.T_0*prop_dmu_k'/2;\n\n    % log-conditional theta_c given mu and kappa\n    prop_dtheta_c = bsxfun(@minus, obj.aux.sample.theta_c, prop_mu);\n    tmp = obj.aux.l2pi - .5*prop_dtheta_c.^2*exp(prop_kappa') ...\n        + .5*sum(prop_kappa);\n    if obj.K > 1\n        prop_rho = bsxfun(@plus, obj.aux.rho, obj.aux.rho_max);\n        prop_rho(:,k) = tmp;\n        prop_rho_max = max(prop_rho, [], 2);\n        prop_rho = bsxfun(@minus, prop_rho, prop_rho_max);\n        prop_lcd = log(exp(prop_rho)*obj.aux.sample.pi') ...\n            + prop_rho_max; % log-sum-exp\n    else\n        prop_rho_max = tmp;\n        prop_lcd = prop_rho_max;\n        prop_rho = zeros(obj.N, 1);\n    end\n\n    % accept/reject\n    a = exp(sum(prop_lcd - obj.aux.lpr.theta_c) ...\n          + prop_lpr_mu - obj.aux.lpr.mu(k) + dlq);\n%             a = exp(prop_lpr_mu - obj.aux.lpr.mu(k));\n    if ~isnan(a) && ~isinf(a) && rand()<a\n        obj.aux.nAccept.mu(k) = obj.aux.nAccept.mu(k) + 1;\n        obj.aux.sample.mu(k,:) = prop_mu;\n        obj.aux.rho = prop_rho;\n        obj.aux.rho_max = prop_rho_max;\n        obj.aux.lpr.theta_c = prop_lcd;\n        obj.aux.lpr.mu(k) = prop_lpr_mu;\n    end\n\n    % precision\n    prop_kappa = prop_kappa + randn(1,obj.idx.P_c)*obj.aux.step.kappa(k);\n\n    % evaluate log-conditional\n    % prior\n    prop_dkappa = prop_kappa - obj.prior.s_0;\n    prop_lpr_kappa = -.5*prop_dkappa.^2*obj.prior.nu_0;\n    % log-conditional theta_c given mu and kappa\n    prop_dtheta_c = bsxfun(@minus, obj.aux.sample.theta_c, ...\n        obj.aux.sample.mu(k,:));\n    tmp = obj.aux.l2pi - .5*prop_dtheta_c.^2*exp(prop_kappa') ...\n        + .5*sum(prop_kappa);\n    if obj.K > 1\n        prop_rho = bsxfun(@plus, obj.aux.rho, obj.aux.rho_max);\n        prop_rho(:,k) = tmp;\n        prop_rho_max = max(prop_rho, [], 2);\n        prop_rho = bsxfun(@minus, prop_rho, prop_rho_max);\n        prop_lcd = log(exp(prop_rho)*obj.aux.sample.pi') ...\n            + prop_rho_max;\n    else\n        prop_rho_max = tmp;\n        prop_lcd = prop_rho_max;\n        prop_rho = zeros(obj.N, 1);\n    end\n\n    % accept/reject\n    a = exp(sum(prop_lcd - obj.aux.lpr.theta_c) ...\n          + prop_lpr_kappa - obj.aux.lpr.kappa(k));\n%             a = exp(prop_lpr_kappa - obj.aux.lpr.kappa(k));\n    if ~isnan(a) && ~isinf(a) && rand()<a\n        obj.aux.nAccept.kappa(k) = obj.aux.nAccept.kappa(k) + 1;\n        obj.aux.sample.kappa(k,:) = prop_kappa;\n        obj.aux.rho = prop_rho;\n        obj.aux.rho_max = prop_rho_max;\n        obj.aux.lpr.theta_c = prop_lcd;\n        obj.aux.lpr.kappa(k) = prop_lpr_kappa;\n    end\n\nend\n\nend\n\n\n%% SAMPLING: DCM parameter (theta)\nfunction [ obj ] = mh_sample_dcm( obj, invTemp )\nnProp = obj.aux.nProp.theta + obj.aux.nProp.sp(1) + 1;\nbGmm = mod(nProp, obj.options.mh.nSteps.knGmm) == 0;\nif bGmm\n    obj.aux.nProp.sp(1) = obj.aux.nProp.sp(1) + 1;\nelse\n    obj.aux.nProp.theta = obj.aux.nProp.theta + 1;\nend\nprec = -.5*exp(obj.aux.sample.kappa);\n\nfor n = 1:obj.N\n\n    % propose\n    if bGmm % sample from GMM        \n        k = randsample(obj.K, 1, true, obj.aux.sample.pi);\n        prop_theta_c = obj.aux.sample.mu(k,:) + ...\n            randn(1, obj.idx.P_c).*exp(-.5*obj.aux.sample.kappa(k,:));\n        prop_theta_h = obj.prior.mu_h + randn(1,obj.idx.P_h)./...\n            sqrt(diag(obj.prior.Pi_h))'; % assume diagonal precision\n    else % sample from Gaussian kernel\n%             prop_theta_c = obj.aux.sample.theta_c(n,:) + ...\n%                 randn(1, obj.idx.P_c).*obj.aux.step.theta_c(n,:);\n        tmp = (randn(1, obj.idx.P_c + obj.idx.P_h).*obj.aux.step.theta(n,:))* ...\n            obj.aux.transform.theta;\n        prop_theta_c = obj.aux.sample.theta_c(n,:) + tmp(1:obj.idx.P_c);\n        prop_theta_h = obj.aux.sample.theta_h(n,:) + tmp(obj.idx.P_c+1:end);\n    end\n\n    % evaluate joint\n    % log-prior\n    prop_dtheta_c = bsxfun(@minus, prop_theta_c, obj.aux.sample.mu);\n    prop_rho = obj.aux.l2pi + sum(prec.*prop_dtheta_c.^2, 2)' ...\n        + 0.5*sum(obj.aux.sample.kappa, 2)';\n    prop_rho_max = max(prop_rho);\n    prop_rho = prop_rho - prop_rho_max;\n    prop_lpr_c = log(exp(prop_rho)*obj.aux.sample.pi(:)) + prop_rho_max;            \n    prop_dtheta_h = prop_theta_h - obj.prior.mu_h;\n    prop_lpr_h = -.5*prop_dtheta_h*obj.prior.Pi_h*prop_dtheta_h';\n    % log-likelihood\n    if invTemp\n        prop_epsilon = obj.bold_gen( [prop_theta_c, prop_theta_h], ...\n            obj.data(n), obj.inputs(n), obj.options.hemo, obj.R, ...\n            obj.L, obj.idx );\n        tmp = obj.aux.sample.lambda(n,:) - obj.aux.lvarBold(n,:);\n        prop_llh = -.5*sum(prop_epsilon.^2*exp(tmp)') ...\n           +.5*obj.aux.q_r(n)*sum(tmp);\n    else % skip calculation of BOLD signal if inverse temp is zero\n        prop_llh = 0;\n        prop_epsilon = 0;\n    end\n\n    % accept/reject\n    a = exp(~bGmm*(prop_lpr_c - obj.aux.lpr.theta_c(n) ...\n        + prop_lpr_h - obj.aux.lpr.theta_h(n)) ...\n        + invTemp*(prop_llh - obj.aux.lpr.llh(n)));\n\n    if ~isnan(a) && ~isinf(a) && rand()<a\n        if bGmm\n            obj.aux.nAccept.sp(1) = obj.aux.nAccept.sp(1) + 1;\n        else\n            obj.aux.nAccept.theta(n) = obj.aux.nAccept.theta(n) + 1;\n        end\n        obj.aux.sample.theta_c(n,:) = prop_theta_c;\n        obj.aux.sample.theta_h(n,:) = prop_theta_h;\n        obj.aux.lpr.theta_c(n) = prop_lpr_c;\n        obj.aux.lpr.theta_h(n) = prop_lpr_h;\n        obj.aux.rho(n,:) = prop_rho;\n        obj.aux.rho_max(n) = prop_rho_max;\n        obj.aux.epsilon{n} = prop_epsilon;\n        obj.aux.lpr.llh(n) = prop_llh;\n    end\n\nend\nend\n\n\n%% SAMPLING: Signal-to-noise (lambda)\nfunction [ obj ] = mh_sample_noise( obj, invTemp )\n\nobj.aux.nProp.lambda = obj.aux.nProp.lambda + 1;\nfor n = 1:obj.N\n\n    % propose in unconstrained space\n    prop_lambda = obj.aux.sample.lambda(n,:) + ...\n        randn(1, obj.R).*obj.aux.step.lambda(n);\n\n    % evaluate log-conditional\n    % prior\n    prop_dlambda = prop_lambda - obj.prior.lambda_0;\n    prop_lpr = -.5*prop_dlambda.^2*obj.prior.omega_0;\n    % likelihood\n    tmp = prop_lambda - obj.aux.lvarBold(n,:);\n    prop_llh = -.5*sum(obj.aux.epsilon{n}.^2*exp(tmp)') ...            \n        +.5*obj.aux.q_r(n)*sum(tmp);\n\n    % accept/reject\n    a = exp(prop_lpr - obj.aux.lpr.lambda(n) ...\n            + invTemp*(prop_llh - obj.aux.lpr.llh(n)));\n\n    if ~isnan(a) && ~isinf(a) && rand()<a\n        obj.aux.nAccept.lambda(n) = obj.aux.nAccept.lambda(n) + 1;\n        obj.aux.sample.lambda(n,:) = prop_lambda;\n        obj.aux.lpr.lambda(n) = prop_lpr;\n        obj.aux.lpr.llh(n) = prop_llh;\n    end\nend\nend\n\n\n%% SAMPLING: k-means-based mode hopping\n% A special proposal for clustering part of HUGE model (pi, mu and kappa)\nfunction [ obj ] = mh_sample_kmhop(obj, k)\n% track acceptance rate\nobj.aux.nProp.sp(2) = obj.aux.nProp.sp(2) + 1;\n\n% --- do kmeans for k = 1,...,K, and define q(...|k) ---\n% set up prior\ntmpm = exp(obj.prior.s_0+1./2./obj.prior.nu_0');\ntmpv = (exp(1./obj.prior.nu_0')-1).*exp(2*obj.prior.s_0+1./obj.prior.nu_0');\nb0 = tmpm./tmpv;\na0 = tmpm.^2./tmpv;\n\n% get data\nX = obj.aux.sample.theta_c;\n\n% reserve memory\nqmm = repmat(obj.prior.m_0,obj.K,1,obj.K);\nqms = repmat(diag(obj.prior.T_0)',obj.K,1,obj.K);\nqkm = repmat(obj.prior.s_0,obj.K,1,obj.K);\nqks = repmat(obj.prior.nu_0',obj.K,1,obj.K);\nqpm = zeros(obj.K,obj.K);\nfor k1 = 1:obj.K\n    % do kmeans\n    idx = kmeans(X,k1,'Replicates',100);\n    % assemble parameters for q\n    for k2 = 1:obj.K\n        nk = nnz(idx(:)==k2);\n        if nk > 0\n            mk = mean(X(idx(:)==k2,:),1);\n            ak = a0 + (nk + 1)/2;\n            bk = b0 + 0.5.*sum(bsxfun(@minus,X(idx(:)==k2,:),mk).^2,1);\n            tmpm = ak./bk;\n            tmpv = ak./bk.^2;\n            % q(kappa)\n            qks(k2,:,k1) = 1./log(tmpv./tmpm.^2 + 1);\n            qkm(k2,:,k1) = log(tmpm) - 1./2./qks(k2,:,k1);\n            % q(mu)\n            qms(k2,:,k1) = diag(obj.prior.T_0)' + nk.*exp(obj.prior.s_0);\n            qmm(k2,:,k1) = (diag(obj.prior.T_0)'.*obj.prior.m_0 + ...\n                nk.*exp(obj.prior.s_0).*mk)./qms(k2,:,k1);\n        end\n        qpm(k1,k2) = nk + obj.prior.alpha_0(k2);\n    end\nend\n\n% --- generate proposal for k in 1,...,K, and eval p ---\nk1 = k;\n\nprop_lpr_mu = zeros(1,obj.K);\nprop_lpr_kappa = zeros(1,obj.K);\nprop_rho = obj.aux.rho;\n\nprop_pi = zeros(1,obj.K);\nprop_kappa = zeros(obj.K,obj.idx.P_c);\nprop_mu = zeros(obj.K,obj.idx.P_c);\nfor k2 = 1:obj.K\n    % draw kappa*\n    prop_kappa(k2,:) = qkm(k2,:,k1) + randn(1,obj.idx.P_c)./sqrt(qks(k2,:,k1));\n    % draw mu*\n    prop_mu(k2,:) = qmm(k2,:,k1) + randn(1,obj.idx.P_c)./sqrt(qms(k2,:,k1));\n    % draw pi*\n    prop_pi(1,k2) = gamrnd(qpm(k1,k2),1);\n    \n    % eval log p(mu*)\n    prop_dmu_k = prop_mu(k2,:) - obj.prior.m_0;\n    prop_lpr_mu(k2) = -prop_dmu_k*obj.prior.T_0*prop_dmu_k'/2;\n    % eval log p(kappa*)\n    prop_dkappa = prop_kappa(k2,:) - obj.prior.s_0;\n    prop_lpr_kappa(k2) = -.5*prop_dkappa.^2*obj.prior.nu_0;\n    \n    % log-conditional theta_c given mu and kappa\n    prop_dtheta_c = bsxfun(@minus, obj.aux.sample.theta_c, prop_mu(k2,:));\n    prop_rho(:,k2) = obj.aux.l2pi - .5*prop_dtheta_c.^2*exp(prop_kappa(k2,:)') ...\n        + .5*sum(prop_kappa(k2,:));\n\nend\nprop_pi = prop_pi./sum(prop_pi);\n\n% eval log p(pi*)\nprop_pis = [prop_pi(1),prop_pi(2:end-1)./(1 - cumsum(prop_pi(1:end-2)))];\nprop_pic = cumprod(1-prop_pis);\nprop_piu = tapas_huge_logit(prop_pis) - log(1./(obj.K-1:-1:1));\n% log-prior on pi\nprop_lpr_pi = log(prop_pi)*(obj.prior.alpha_0 - 1) + ...\n   sum(log(prop_pis)) + sum(log(1-prop_pis)) + ...\n   sum(log(prop_pic(1:end-1)));\nprop_lpr_pi = max(prop_lpr_pi, -realmax);\n\n% eval log p(theta|pi*,mu*,kappa*)\nprop_rho_max = max(prop_rho, [], 2);\nprop_rho = bsxfun(@minus, prop_rho, prop_rho_max);\nprop_lcd = log(exp(prop_rho)*prop_pi') + prop_rho_max; % log-sum-exp\n\n% --- iterate over all permutations and eval q ---\n% eval log q(pi*,kappa*,mu*)\n[prop_lq_pi,prop_lq_kappa,prop_lq_mu] = eval_lq_perm(prop_pi,...\n    prop_kappa,prop_mu,qpm,qkm,qks,qmm,qms,obj.K);\n\n% eval log q(pi,kappa,mu)\n[smp_lq_pi,smp_lq_kappa,smp_lq_mu] = eval_lq_perm(obj.aux.sample.pi,...\n    obj.aux.sample.kappa,obj.aux.sample.mu,qpm,qkm,qks,qmm,qms,obj.K);\n\nm_prop_lq_mu = logmeanexp(prop_lq_mu);\nm_prop_lq_kappa = logmeanexp(prop_lq_kappa);\nm_prop_lq_pi = logmeanexp(prop_lq_pi);\n\nm_smp_lq_mu = logmeanexp(smp_lq_mu);\nm_smp_lq_kappa = logmeanexp(smp_lq_kappa);\nm_smp_lq_pi = logmeanexp(smp_lq_pi);\n\n% --- eval MH acceptance ratio ---\na = [sum(prop_lcd - obj.aux.lpr.theta_c) ...\n    ;sum(prop_lpr_kappa - obj.aux.lpr.kappa) ...\n    ;sum(prop_lpr_mu - obj.aux.lpr.mu) ...\n    ;prop_lpr_pi - obj.aux.lpr.pi ...\n    ;sum(m_smp_lq_kappa - m_prop_lq_kappa) ...\n    ;sum(m_smp_lq_mu - m_prop_lq_mu) ...\n    ;m_smp_lq_pi - m_prop_lq_pi ...\n];\n% figure(1);clf;stem(a);\na = min(1,exp(sum(a)));\n\n% accept/reject\nif ~isnan(a) && ~isinf(a) && rand()<a\n    obj.aux.nAccept.sp(2) = obj.aux.nAccept.sp(2) + 1;\n    obj.aux.sample.pi_u = prop_piu;\n    obj.aux.sample.pi = prop_pi;\n    obj.aux.sample.mu = prop_mu;\n    obj.aux.sample.kappa = prop_kappa;\n    obj.aux.lpr.pi = prop_lpr_pi;\n    obj.aux.lpr.mu = prop_lpr_mu;\n    obj.aux.lpr.kappa = prop_lpr_kappa;\n    obj.aux.lpr.theta_c = prop_lcd;\n    obj.aux.rho = prop_rho;\n    obj.aux.rho_max = prop_rho_max;\nend\n\nend\n\n% evaluate log q(pi*,kappa*,mu*) for all permutations\nfunction [lq_pi,lq_kappa,lq_mu] = eval_lq_perm(p_pi,p_kappa,p_mu,qpm,qkm,qks,qmm,qms,K)\npidx = perms(1:K);\n\nlq_mu = zeros(size(pidx));\nlq_kappa = zeros(size(pidx));\nlq_pi = zeros(size(pidx));\n\nx = p_pi;\nz = [x(1),x(2:end-1)./(1 - cumsum(x(1:end-2)))];\nc = cumprod(1-z);\n\nfor k1 = 1:K\n    m_pi = zeros(K,K);\n    m_mu = zeros(size(m_pi));\n    m_kappa = zeros(size(m_pi));\n    % mesh log q(pi)\n    tmp = gammaln(sum(qpm(k1,:))) - sum(gammaln(qpm(k1,:))) + ... % const\n    sum(log(z)) + sum(log(1-z)) + ... % jacobian\n    sum(log(c(1:end-1))); % jacobian\n    m_pi(:,:) = (qpm(k1,:)' - 1)*log(x(:)') + tmp/K; % x\n\n    % mesh log q(mu,kappa)\n    for k2 = 1:K\n        for k3 = 1:K\n            % log p(mu*)\n            m_mu(k2,k3) = -.5*(p_mu(k3,:) - qmm(k2,:,k1)).^2*qms(k2,:,k1)' -.5*log(2*pi) +.5*sum(log(qms(k2,:,k1)));\n            % log p(kappa*)\n            m_kappa(k2,k3) = -.5*(p_kappa(k3,:) - qkm(k2,:,k1)).^2*qks(k2,:,k1)' -.5*log(2*pi) +.5*sum(log(qks(k2,:,k1)));\n        end\n    end\n    \n    linInd = sub2ind([K,K], repmat(1:K,size(pidx,1),1), pidx);\n    lq_mu(:,k1) = sum(m_mu(linInd),2);\n    lq_kappa(:,k1) = sum(m_kappa(linInd),2);\n    lq_pi(:,k1) = sum(m_pi(linInd),2);\n\nend\nend\n\n% log(mean(exp(log_probability)))\nfunction lmep = logmeanexp(lpr)\ntmp = max(lpr(:));\nlmep = log(mean(exp(lpr(:) - tmp))) + tmp;\nend\n\n\n%---------------------------------\n%              MISC\n%---------------------------------\n%% adapt proposal distribution\nfunction [ obj ] = mh_adapt(obj, iIt)\n\n% adapt step size for:\nfor parameter = {'pi', 'mu', 'kappa', 'theta', 'lambda'}\n    % current acceptance rate\n    ratio = obj.aux.nAccept.(parameter{1})./obj.aux.nProp.(parameter{1});\n    % correction factor\n    tmp = ratio - obj.const.mhRate;\n    tmp = exp(sign(tmp).*abs(tmp).^3.*obj.const.mhReg);\n    % adapt step size\n    obj.aux.step.(parameter{1}) = obj.aux.step.(parameter{1}).*tmp;\n    % reset counter\n    obj.aux.nProp.(parameter{1}) = 0;\n    obj.aux.nAccept.(parameter{1}) = ...\n        zeros(size(obj.aux.nAccept.(parameter{1})));\n\nend\n\nstep = fix(iIt/obj.const.mhTrans);\nidx = iIt:-step:1;\n\n% match proposal distribution to posterior covariance for ...\n% ... cluster means\nmu = reshape([obj.trace.smp(idx).mu], obj.K, obj.idx.P_c, []);\nfor k = 1:obj.K\n    % calculate SVD on empirical covariance of posterior samples\n    tmp = cov(permute(mu(k,:,:), [3 2 1]));\n    [rotation, scales] = svd(tmp);\n    scales = sqrt(diag(scales));\n    % limit smallest proposal step size to 5% of maximum step size\n    scales(scales < max(scales)*.05) = max(scales)*.05;\n    if max(scales) > 0\n        obj.aux.transform.mu(:,:,k) = bsxfun(@times, rotation, scales')';\n        tmp = sum(log(scales));\n        obj.aux.step.mu(k) = obj.aux.step.mu(k)*exp(...\n            (obj.aux.logdet.mu(k) - tmp)/obj.idx.P_c);\n        obj.aux.logdet.mu(k) = tmp;        \n    end\nend\n\n% ... subject means\ntheta = [reshape([obj.trace.smp(idx).theta_c], obj.N, obj.idx.P_c, []), ...\n         reshape([obj.trace.smp(idx).theta_h], obj.N, obj.idx.P_h, [])];\npooled = zeros(obj.N, size(theta, 3), obj.idx.P_c + obj.idx.P_h);\nfor n = 1:obj.N\n    tmp = permute(theta(n,:,:), [1 3 2]);\n    pooled(n, :, :) = bsxfun(@minus, tmp, mean(tmp, 2));\nend\npooled = reshape(pooled, [], obj.idx.P_c + obj.idx.P_h);\n% calculate SVD on empirical covariance of posterior samples\ntmp = cov(pooled);\n\n[rotation, scales] = svd(tmp);\nscales = sqrt(diag(scales));\n% limit smallest proposal step size to 5% of maximum step size\nscales(scales < max(scales)*.05) = max(scales)*.05;\nif max(scales) > 0\n    obj.aux.transform.theta = bsxfun(@times, rotation, scales')';\n    tmp = sum(log(scales));\n    tmp = exp((obj.aux.logdet.theta - tmp)/(obj.idx.P_c + obj.idx.P_h));\n    for n = 1:obj.N\n        obj.aux.step.theta(n) = obj.aux.step.theta(n)*tmp;\n    end \n    obj.aux.logdet.theta = sum(log(scales));  \nend\n\nend\n\n\n%% potential scale reduction factor\nfunction [ psrf ] = mh_psrf( trace, nChains )\n\nnIt = length(trace);\npsrf = struct();\nfor parameter = fieldnames(trace)'\n    smpSize = [size(trace(1).(parameter{1})), nIt];\n    try\n        tmp = permute(reshape([trace(:).(parameter{1})], smpSize), [3 1 2]);\n            \n        psrf.(parameter{1}) = tapas_huge_psrf( tmp, nChains );\n    catch\n        warning('TAPAS:HUGE:convergence', [ 'Potential scale reduction ' ...\n            'factor could not be calculated for %s.'], parameter{1});\n        psrf.(parameter{1}) = NaN(smpSize);\n    end\nend\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/huge/@tapas_Huge/mh_invert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2346988030280791}}
{"text": "function [class,siz]=ChemSiz(Sin)\n\n%% Give Labels and size for plotting chemical size distributions\n%% Label definintions: \n%% 1=OC, 2=ECOCIn, 3=ECOC, 4=InOC, 5=NoID\n%% RC Moffet, 2010\nsiz=Sin.Size;\nclass=zeros(1,length(Sin.PartLabel));\nfor i = 1:length(Sin.PartLabel)\n    NoIdidx=strmatch('NoID',Sin.PartLabel{i},'exact');\n    OCidx=strmatch('OC',Sin.PartLabel{i},'exact');\n    OCAidx=strmatch('OCsp2',Sin.PartLabel{i},'exact');\n    ECidx=findstr(Sin.PartLabel{i},'EC');\n    Inidx=findstr(Sin.PartLabel{i},'In');\n    Kidx=findstr(Sin.PartLabel{i},'K');\n    if ~isempty(OCidx) || ~isempty(OCAidx) %% OC\n        class(i)=1;\n    elseif ~isempty(ECidx) && (~isempty(Inidx) || ~isempty(Kidx)) %% ECOCIn\n        class(i)=2;\n    elseif ~isempty(ECidx) && (isempty(Inidx) || isempty(Kidx)) %% ECOC\n        class(i)=3;\n    elseif (~isempty(Inidx) || ~isempty(Kidx)) && isempty(ECidx) %% InOC\n        class(i)=4;\n    elseif ~isempty(NoIdidx)  %% NoID\n        class(i)=5;\n    end\n    clear OCidx ECidx Inidx NoIdidx;\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29085-stxm-spectromicroscopy-particle-analysis-routines/AnalyticalChemistryScripts/ChemSiz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23469879748742672}}
{"text": "function [cl,cu] = matRad_getConstraintBounds(optiProb,cst)\n% matRad IPOPT get constraint bounds wrapper function\n% \n% call\n%   [cl,cu] = matRad_getConstraintBounds(optiProb,cst)\n%\n% input\n%   cst:            matRad cst struct\n%\n% output\n%   cl: lower bounds on constraints\n%   cu: lower bounds on constraints\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2016 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nBPtype = class(optiProb.BP);\nisEffectBP = strcmp(BPtype,'matRad_EffectProjection');\n\n% Initialize bounds\ncl = [];\ncu = [];\n\n% compute objective function for every VOI.\nfor  i = 1:size(cst,1)\n\n    % Only take OAR or target VOI.\n    if ~isempty(cst{i,4}) && ( isequal(cst{i,3},'OAR') || isequal(cst{i,3},'TARGET') )\n\n        % loop over the number of constraints for the current VOI\n        for j = 1:numel(cst{i,6})\n            \n            optiFunc = cst{i,6}{j};\n            \n            % only perform computations for constraints\n            %if ~isempty(strfind(cst{i,6}{j}.type,'constraint'))\n            if isa(optiFunc,'DoseConstraints.matRad_DoseConstraint')\n                \n                \n                if isEffectBP\n                    doses = optiFunc.getDoseParameters();\n                \n                    effect = cst{i,5}.alphaX*doses + cst{i,5}.betaX*doses.^2;\n                    \n                    optiFunc = optiFunc.setDoseParameters(effect);\n                end\n\n                    \n                 cl = [cl;optiFunc.lowerBounds(numel(cst{i,4}{1}))];\n                 cu = [cu;optiFunc.upperBounds(numel(cst{i,4}{1}))];\n                    \n                %end\n            end\n\n        end % over all objectives of structure\n\n    end % if structure not empty and target or oar\n\nend % over all structures\n   \n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/@matRad_OptimizationProblem/matRad_getConstraintBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.23459465935797477}}
{"text": "function varargout = bounds(x,lower,upper,aux)\n%BOUNDS Adds implicit bounds on variables.\n%\n% BOUNDS IS OBSOLETE: Use standard constraints\n%\n% BOUNDS(x,Lower,Upper)   Adds bound constraints on variables.\n%                         These bounds are used when performing\n%                         big M formulations and similar things.\n\nvariables = getvariables(x);\nif nargin == 1\n    lb = yalmip('getbounds',variables);\n    lower = lb(:,1);\n    upper = lb(:,2);\nelse\n    lower = lower(:);\n    upper = upper(:);\n    if length(lower)==1\n        lower = repmat(lower,length(variables),1);\n    end\n    if length(upper)==1\n        upper = repmat(upper,length(variables),1);\n    end\n    % 0 - No problems\n    % 1 - Trying to bound nonlinear variable\n    % 2 - Trying to bound nonlinear operator     \n    fail = yalmip('setbounds',variables,lower,upper);\n    switch fail\n        case {1,2}\n            error('BOUNDS can only be applied to linear unitary SDPVAR variables.')\n        otherwise\n    end\nend\n\nif nargout>0\n    varargout{1} = lower;\n    varargout{2} = upper;\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/bounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2344835254892603}}
{"text": "function appendYALMIPvariables(lmi_variables,mt,variabletype,hashed_monoms,current_hash);\n\nif nargin == 1\n    [mt,variabletype,hashed_monoms,current_hash] = yalmip('monomtable');\nend\n\n% Update monomtable and pre-calculated variable type\nn_mt = size(mt,1);\nm_mt = size(mt,2);\nnewmt = [];\nif min(lmi_variables)>m_mt % New variables\n    if size(mt,1)~=size(mt,2)\n        mt(size(mt,1),size(mt,1))=0;\n    end\n    % This was faster before. However in recent versions of matlab, there\n    % is a compiled version of blkdiag available\n    % fill=spalloc(size(mt,1),length(lmi_variables),0);   \n    % mt=[mt fill;fill' speye(length(lmi_variables))]; \n    if isempty(mt)        \n        mt = speye(length(lmi_variables));\n        newmt = mt;\n    elseif length(lmi_variables)==1  \n        % Slightly faster than general case\n       newmt = sparse(1);\n       mt(end+1,end+1) = newmt;\n    else\n        newmt = speye(length(lmi_variables));       \n        mt=blkdiag(mt,newmt);      \n    end\nelse\n    mt(lmi_variables,lmi_variables) = speye(length(lmi_variables));\nend\nvariabletype(1,size(mt,1)) = 0;\nif ~isempty(newmt)\n    new_hash = 3*rand_hash(size(mt,2),size(newmt,2),1);\n    hashed_monoms = [hashed_monoms;full(newmt*new_hash)];\n    current_hash = [current_hash;new_hash];\n    yalmip('setmonomtable',mt,variabletype,hashed_monoms,current_hash);\nelse \n    yalmip('setmonomtable',mt,variabletype);\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/appendYALMIPvariables.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.23438815348981254}}
{"text": "%this script demos the usage of evaluation routines\n% the result file 'demo.val.pred.txt' on validation data is evaluated\n% against the ground truth\n\nfprintf('CLASSIFICATION WITH LOCALIZATION TASK\\n');\n\nmeta_file = '../data/meta_clsloc.mat';\n%pred_file='demo.val.pred.loc.txt';\n%pred_file='/data/vision/torralba/deeplearning/visualization/prediction_imagenetValSet_imagenetCNNaveSumDeep.txt'\npred_file='/data/vision/torralba/deeplearning/visualization/prediction_imagenetValSet_googlenet_imagenet.txt'\n\nground_truth_file='../data/ILSVRC2014_clsloc_validation_ground_truth.txt';\nblacklist_file='../data/ILSVRC2014_clsloc_validation_blacklist.txt';\nnum_predictions_per_image=5;\noptional_cache_file = 'cache_groundtruth.mat';\n\nfprintf('pred_file: %s\\n', pred_file);\nfprintf('ground_truth_file: %s\\n', ground_truth_file);\nfprintf('blacklist_file: %s\\n', blacklist_file);\n\nif isempty(optional_cache_file)\n    fprintf(['NOTE: you can specify a cache filename and the ground ' ...\n             'truth data will be automatically cached to save loading time ' ...\n             'in the future\\n']);\nend\n\n% num_val_files = -1;\n% while num_val_files ~= 50000\n%     if num_val_files ~= -1 \n%         fprintf('That does not seem to be the correct directory. Please try again\\n');\n%     end\n%     %ground_truth_dir=input('Please enter the path to the Validation bounding box annotations directory: ', 's');\n     ground_truth_dir='/data/vision/torralba/deeplearning/imagenet_toolkit/val_bbox';\n%     %fprintf('ground_truth_dir: %s\\n', ground_truth_dir);\n%     val_files = dir(sprintf('%s/*.xml',ground_truth_dir));\n%     num_val_files = numel(val_files);\n% end\n\nerror_cls = zeros(num_predictions_per_image,1);\nerror_loc = zeros(num_predictions_per_image,1);\n\nfor i=1:num_predictions_per_image\n    [error_cls(i) error_loc(i)] = eval_clsloc(pred_file,ground_truth_file,ground_truth_dir,...\n                                              meta_file,i, blacklist_file,optional_cache_file);\nend\n\ndisp('# guesses vs clsloc error vs cls-only error');\ndisp([(1:num_predictions_per_image)',error_loc,error_cls]);\n\n%% Result: alexFullConv network\n% # guesses vs clsloc error vs cls-only error\n%     1.0000    0.7461    0.5077\n%     2.0000    0.6859    0.3841\n%     3.0000    0.6569    0.3209\n%     4.0000    0.6401    0.2835\n%     5.0000    0.6270    0.2556\n\n%% Result: googleNet_imagenet\n% # guesses vs clsloc error vs cls-only error\n%     1.0000    0.6691    0.3450\n%     2.0000    0.6158    0.2294\n%     3.0000    0.5937    0.1786\n%     4.0000    0.5813    0.1503\n%     5.0000    0.5734    0.1314", "meta": {"author": "zhoubolei", "repo": "CAM", "sha": "c63f2850a7a3dadc21fa1b021875e2d4d053ece5", "save_path": "github-repos/MATLAB/zhoubolei-CAM", "path": "github-repos/MATLAB/zhoubolei-CAM/CAM-c63f2850a7a3dadc21fa1b021875e2d4d053ece5/evaluation/demo_eval_clsloc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23427865989988356}}
{"text": "function exportIVH(structNum,scanSet,Opt)\n% exportDVH\n% This function exports DVH in an EXCEL format. Opt give the option to\n% choose if you want Normalised or Absolute DVH \n% written DK\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n%\n% Usage\n% exportDVH(structNum,Opt)\n\n% for command line help document\nif ~exist('structNum')& ~exist('scanSet')& ~exist('Opt')\n    prompt = {'Enter the structure Number';'Enter the scan number'; 'Enter \"abs\" for absolute OR \"nor\" for normalized DVH'};\n            dlg_title = 'Export IVH';\n            num_lines = 1;\n            def = {'';'';''};\n            outPutQst = inputdlg(prompt,dlg_title,num_lines,def);\n            if isempty(outPutQst{1}) | isempty(outPutQst{2})| isempty(outPutQst{3})\n                warning('Need to enter all the inputs');\n                return\n            else\n                structNum = str2num(outPutQst{1});\n                scanSet = str2num(outPutQst{2});\n                Opt = outPutQst{3};\n            end\nend\n\npath = uigetdir( cd,'Select destination Directory for DVH export');\nglobal planC\nindexS = planC{end};\nstructureCell = planC{indexS.structures};\noptS = opts4Exe([getCERRPath,'CERROptions.json']);\n%loop over all the structures that need to be exported\nfor i = 1:length(structNum)\n    name = structureCell(structNum(i)).structureName;        \n    [scansV, volsV] = getIVH(structNum(i), scanSet(i), planC);\n    [scanBinsV, volsHistV] = doseHist(scansV, volsV, optS.DVHBinWidth);\n    cumVolsV = cumsum(volsHistV);    \n    cumVols2V  = cumVolsV(end) - cumVolsV;  %cumVolsV is the cumulative volume lt that corresponding scan\n    switch upper(Opt)\n        case 'ABS'\n%             if abs flag is set just export the values as it is\n            fVol = cumVols2V;\n        case 'NOR'\n            %Normalizing the volume \n            fVol = cumVols2V/cumVolsV(end);\n    end\n    M = [scanBinsV; fVol];\n    %Export only NumPts points (for Dr. Myerson)\n    NumPts = 200;\n    if size(M,2)>NumPts\n        indAll = round(linspace(1,size(M,2),NumPts));\n        M = M(:,indAll);\n    end\n    xlswrite(fullfile(path,name), M');\nend\nclear fVol scansV volsV cumVolsV cumVols2V scanBinsV volsHistV optS", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/IntensityVolumeHistograms/exportIVH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2342663413133585}}
{"text": "function signal = set_infer_markers(varargin)\n% Infers markers from an event channel, if possible.\n% Signal = set_infer_markers(Signal)\n%\n% If the data set has one (or more) channels with relatively few unique values, and relatively few\n% off-median values (or plateaus thereof), markers are being generated to encode whenever such a\n% channel changes its value. By default, the detected event channels are being removed from the\n% data. \n%\n% This funciton is automatically called by io_loadset if no markers are present in the given \n% set. io_loadset has a parameter ('markerchannel') which can be utilized to customize the settings \n% below (as a cell array of arguments to set_infer_markers).\n%\n% In:\n%   Signal                    : continuous EEGLAB data set from which an interval should be selected\n%\n%   MaxEvents                 : a channel is only considered for event generation if it would produce\n%                               at most this many distinct events (default: 25000)\n%\n%   MaxTypes                  : a channel is only considered for event generation if it would produce\n%                               at most this many distinct event types (default 300)\n%\n%   IncludeLabel              : when to include the channel label into the generated event types; \n%                               can be 'always', 'multiplechans', 'never' (default: 'multiplechans')\n%\n%   AllPositive               : whether all events must have positive offsets from the baseline \n%                               (median) value (default: true)\n%\n%   EncodePlateaus            : Whether the trigger channel may contain (non-baseline) plateaus, to \n%                               be encoded in event duration. (default: true)\n%\n%   StrictInteger             : only consider channels that would produce integer event types \n%                               (otherwise: round to integer) (default: true)\n%\n%   RelativeBaselineThreshold : Relative baseline threshold. If the event types would be larger than\n%                               this threshold, they will be re-coded to be relative to the smallest\n%                               event type in the channel. (default: 10000)\n%\n%   OmitBaselineThreshold     : Baseline omission threshold. If the baseline event takes up more than\n%                               this fraction of the data, it will not be encoded as events.\n%                               (default: 0.8)\n%\n%   RemoveEventChannels       : Whether to remove channels that have been identified as event\n%                               channels (default: true)\n%\n% Out:\n%   Signal    : data set restricted to the selected range\n%\n% Examples:\n%   % for a data set with one or more trigger channels, fill in contents of the .event field\n%   % and remove the trigger channel(s); do nothing if the data set does not contain trigger channels\n%   eeg = set_infer_markers(eeg)\n%\n%   % fill in contents of the .event field from trigger channels, and do not remove these channels\n%   eeg = set_infer_markers('Signal',eeg,'RemoveEventChannels',false)\n%\n%   % if an event channel is not being detected because it produces more than the default MaxEvents \n%   % number of events, use a larger cutoff value\n%   eeg = set_infer_markers('Signal',eeg,'MaxEvents',30000)\n%   \n%   % if an event channel is not being detected because it produces more than the default MaxTypes\n%   % number of distinct event types, use a larger cutoff value\n%   eeg = set_infer_markers('Signal',eeg,'MaxTypes',1000)\n%\n%   % for event channels that have values that far from zero (say, 30000+), the values are by default\n%   % made relative to to the baseline value (most frequent or smallest value, depending on the \n%   % EncodePlateaus setting) -- if this is not intended, override the cutoff with a larger value\n%   eeg = set_infer_markers('Signal',eeg,'RelativeBaselineThreshold',Inf)\n%\n%   % if a trigger channel contains many subsequent events of the same type (i.e. plateaus), by \n%   % default only one event is generated with the appropriate duration; if instead an event should \n%   % be generated for each sample, override that default (and possibly increase MaxEvents)\n%   eeg = set_infer_markers('Signal',eeg,'EncodePlateaus',false,'MaxEvents',Inf)\n%   \n% See also:\n%   io_loadset\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2010-01-26\n\ndeclare_properties('independent_channels',false,'independent_trials',false);\n\narg_define(varargin, ...\n    arg_norep({'signal','Signal'}), ...\n    arg({'force_processing','ForceProcessing'},false,[], 'Force marker processing. Scan for marker channels even if a data set already has events.'), ...\n    arg({'max_events','MaxEvents'},30000,uint32([0 1000000000]), 'Number of events allowed. If a channel would produce more than this many events, it is not considered an event channel.'), ...\n    arg({'max_event_fraction','MaxEventFraction'},0.3,[0 1], 'Maximum fraction of events. If a channel would produce more events than this fraction of its total number of samples, the channel is not considered an event channel.'), ...\n    arg({'max_types','MaxTypes'},300,uint32([0 1000000000]), 'Number of eventtypes allowed. If a channel would produce more than this many event types, it is not considered an event channel.'), ...\n    arg({'include_label','IncludeLabel'},'multiplechans',{'always','multiplechans','never'},'Integrate channel labels. When to integrate channel labels into the event types - by default. only when there are multiple event channels.'), ...\n    arg({'all_positive','AllPositive'},true,[],'Events must be positive. Only if all event types produced by a channel would correspond to positive numbers, the channel is considered an event channel.'), ...\n    arg({'encode_plateaus','EncodePlateaus'},true,[],'Plateaus encoded. The trigger channel may contain (non-baseline) plateaus, to be encoded in event duration.'), ...\n    arg({'strict_integer','StrictInteger'},true,[],'Strictly integer. Only allow channels that have integer event types (otherwise: round to integers).'), ...\n    arg({'relative_baseline_thresh','RelativeBaselineThreshold'},10000,[],'Relative baseline threshold. If the event types would be larger than this threshold, they will be re-coded to be relative to the smallest event type in the channel.'), ...\n    arg({'omit_baseline_thresh','OmitBaselineThreshold'},0.8,[0 1],'Baseline omission threshold. If the baseline event takes up more than this fraction of the data, it will not be encoded as events.'), ...\n    arg({'remove_eventchns','RemoveEventChannels'},true,[],'Remove event channels. Whether to remove those channels that have been identified as event channels.'));\n\n% obtain the chanlocs\nif isfield(signal,{'head','parts'})\n    signal = exp_eval(signal); end\nutl_check_fields(signal,{'data','chanlocs'},'signal','signal');\n\n% figure out which are the event channels\nfprintf('Scanning potential marker channel ');\nfor k=1:size(signal.data,1) %#ok<*NODEF>\n    fprintf('%i ',k);\n    X = signal.data(k,:);\n    X(isnan(X)) = 0;\n    % do a few vectorized computations for speed...\n    numtypes(k) = length(unique(X));\n    if numtypes(k) <= max_types\n        if encode_plateaus\n            % in the plateaus case, the baseline is 0 or the smallest value\n            baseline(k) = min(X);\n            if baseline(k) < relative_baseline_thresh && baseline(k) > 0\n                baseline(k) = 0; end\n            % whether baseline periods are encoded as events depends on the fraction of time in the\n            % data set\n            omit_baseline(k) = mean(X == baseline(k)) > omit_baseline_thresh;\n            eventmask = ([1; diff(X(:))] ~= 0);\n            if omit_baseline(k)\n                eventmask = eventmask & (X(:) ~= baseline(k)); end\n            numevents(k) = nnz(eventmask);\n        else\n            % without plateaus, the baseline type is the mode\n            baseline(k) = mode(X);\n            numevents(k) = nnz(X - baseline(k));\n            omit_baseline(k) = true;\n        end\n    else\n        % channel will not be considered\n        baseline(k) = 0;\n        omit_baseline(k) = true;\n        numevents(k) = 0;\n    end\n    allpositive(k) = all(X >= baseline(k));\n    allinteger(k) = all(abs(X-round(X)) <= eps(X));\nend\nfprintf('\\n');\n\n% find the mask of event channels\neventchans = (numtypes <= max_types) & (numevents <= max_events) & (numevents <= size(signal.data,2)*max_event_fraction) & (~all_positive | allpositive) & (~strict_integer | allinteger);\n    \n% determine whether to include labels\ninclude_label = hlp_rewrite(include_label,'always',true,'never',false,'multiplechans',nnz(eventchans) > 1);\n\n% initialize events\nif ~isfield(signal,'event') || isempty(signal.event)\n    signal.event = struct('latency',{},'duration',{},'type',{}); end\n\n% generate events\nfor k = find(eventchans)\n    try\n        % find event codes per sample\n        X = round(signal.data(k,:) - baseline(k));\n        X(isnan(X)) = 0;\n        % do a run-length encode into events\n        lat = find([1; diff(X(:))] ~= 0);\n        % optionally mask out baseline events\n        if omit_baseline(k)\n            mask = X(lat) ~= 0;\n        else\n            mask = true(1,length(lat));\n        end\n        % get values, duration, and latency as cell arrays\n        dur = num2cell(diff([lat; numel(X)+1]));\n        val = cellfun(@num2str,num2cell(X(lat(mask)),1),'UniformOutput',false);\n        if include_label\n            val = cellfun(@(n) [signal.chanlocs(k).labels '_' n],val,'UniformOutput',false); end\n        lat = num2cell(lat(mask));\n        dur = dur(mask);\n        if ~isempty(lat)\n            % make space\n            signal.event(end+length(lat)).latency = [];\n            % insert new content\n            [signal.event(end-length(lat)+1:end).latency] = lat{:};\n            [signal.event(end-length(lat)+1:end).duration] = dur{:};\n            [signal.event(end-length(lat)+1:end).type] = val{:};\n        else\n            % the channel is not actually an event channel (but a flatline)\n            eventchans(k) = false;\n        end\n    catch e\n        disp(['Could not process channel ' num2str(k)]);\n        env_handleerror(e);\n    end\nend\n\n% sort events\nsignal.event = signal.event(hlp_getresult(2,@sort,[signal.event.latency]));\n\n% remove event channels\nsignal.data = signal.data(~eventchans,:,:,:,:,:,:,:);\nsignal.chanlocs = signal.chanlocs(~eventchans);\nsignal.nbchan = size(signal.data,1);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/dataset_editing/set_infer_markers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2340026900120585}}
{"text": "% STD_ERPIMAGE - Compute ERP images and save them on disk.\n%\n% Usage:\n%   >> std_erpimage( EEG, 'key', 'val', ...);\n%\n% Inputs:\n%   EEG          - a loaded epoched EEG dataset structure. May be an array\n%                  of such structure containing several datasets.\n%\n% Optional inputs:\n%   'components' - [numeric vector] components of the EEG structure for which \n%                  the measure will be computed {default|[] -> all}\n%   'channels'   - [cell array] channels of the EEG structure for which \n%                  activation ERPs will be computed {default|[] -> none}\n%   'trialindices' - [cell array] indices of trials for each dataset.\n%                  Default is all trials.\n%   'recompute'  - ['on'|'off'] force recomputing data file even if it is \n%                  already on disk.\n%   'rmcomps'    - [integer array] remove artifactual components (this entry\n%                  is ignored when plotting components). This entry contains \n%                  the indices of the components to be removed. Default is none.\n%   'interp'     - [struct] channel location structure containing electrode\n%                  to interpolate ((this entry is ignored when plotting \n%                  components). Default is no interpolation.\n%   'fileout'    - [string] name of the file to save on disk. The default\n%                  is the same name (with a different extension) as the \n%                  dataset given as input.\n%\n% ERPimage options:\n%   'concatenate' - ['on'|'off'] concatenate single trial of different\n%                  subjects for plotting ERPimages ('on'). The default\n%                  ('off') computes an ERPimage for each subject and then\n%                  averages these ERPimages. This allows to perform\n%                  statistics (the 'on' options does not allow statistics).\n%   'smoothing'  - Smootmeter (number of trials). {Default: 10}\n%                  ERPIMAGE equivalent: 'avewidth'\n%   'nlines'     - Number of lines for ERPimage. ERPIMAGE equivalent is \n%                  'decimate'. Note that this parameter must be larger than\n%                  the minimum number of trials in each design cell \n%                  {Default: 10}\n%   'sorttype'   - Sorting event type(s) ([int vector]; []=all). See Notes below.\n%                  Either a string or an integer.\n%   'sortwin'    - Sorting event window [start, end] in milliseconds ([]=whole epoch)\n%   'sortfield'  - Sorting field name. {default: latency}.\n%   'erpimageopt'  - ERPIMAGE options, separated by commas (Ex: 'erp', 'cbar').\n%                  {Default: none}. For further details see >> erpimage help\n% Outputs:\n%   erpimagestruct - structure containing ERPimage information that is\n%                    been saved on disk.\n%\n%   Files are saved on disk.\n%    [dataset_file].icaerpim     % component ERPimage file\n% OR\n%    [dataset_file].daterpim     % channel ERPimage file\n%\n% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2011-\n\n% Copyright (C) 2011 Arnaud Delorme\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction allerpimage = std_erpimage( EEG, varargin)\n\nif nargin < 1\n    help std_erpimage;\n    return;\nend\n\nallerpimage = [];\n[opt, moreopts] = finputcheck( varargin, { ...\n    'components'    'integer'     []                    [];\n    'channels'      { 'cell','integer' }  { [] [] }     {};\n    'trialindices' { 'integer','cell' }   []            [];\n    'recompute'     'string'      { 'on','off' }        'off';\n    'savefile'      'string'      { 'on','off' }        'on';\n    'fileout'       'string'      []                    '';\n    'rmcomps'       'cell'        []                    cell(1,length(EEG));\n    'interp'        'struct'      { }                   struct([]);\n    'nlines'        ''            []                    10;\n    'smoothing'     ''            []                    10;\n    'sorttype'       ''           {}                    '';\n    'sortwin'        ''           {}                    [];\n    'sortfield'      ''           {}                    'latency';\n    'concatenate'   'string'      { 'on'  }             'on';\n    'trialinfo'     'struct'      []                    struct([]);\n    'savetrials'    'string'      { 'on','off' }        'on'; % obsolete (never used)\n    'erpimageopt'   'cell'        {}                    {}}, ...\n    'std_erpimage', 'ignore');\nif ischar(opt), error(opt); end\nif length(EEG) == 1 && isempty(opt.trialindices), opt.trialindices = { [1:EEG.trials] }; end\nif isempty(opt.trialindices), opt.trialindices = cell(length(EEG)); end\nif ~iscell(opt.trialindices), opt.trialindices = { opt.trialindices }; end\nif isempty(opt.channels)\n    if isfield(EEG,'icaweights')\n        numc = size(EEG(1).icaweights,1);\n    else\n        error('EEG.icaweights not found');\n    end\n    if isempty(opt.components)\n        opt.components = 1:numc;\n    end\nend\n\n% filename\n% --------\nif isempty(opt.fileout), opt.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end\nif ~isempty(opt.channels)\n    filenameshort = [ opt.fileout '.daterpim'];\n    prefix = 'chan';\n    if iscell(opt.channels)\n        if ~isempty(opt.interp)\n            opt.indices = eeg_chaninds(opt.interp, opt.channels, 0);\n        else\n            opt.indices = eeg_chaninds(EEG(1), opt.channels, 0);\n            for ind = 2:length(EEG)\n                if ~isequal(eeg_chaninds(EEG(ind), opt.channels, 0), opt.indices)\n                    error([ 'Channel information must be consistent when ' 10 'several datasets are merged for a specific design' ]);\n                end\n            end\n        end\n    else\n        opt.indices = opt.channels;\n    end\nelse\n    opt.indices = opt.components;\n    filenameshort = [ opt.fileout '.icaerpim'];\n    prefix = 'comp';\nend\nfilename = filenameshort;\n\n% ERP information found in datasets\n% ---------------------------------\nif exist(filename) && strcmpi(opt.recompute, 'off')\n    fprintf('Use existing file for ERSP: %s; check the ''recompute checkbox'' to force recomputing.\\n', filenameshort);\n    return;\nend\n\nallerpimage = [];\nif strcmpi(opt.concatenate, 'off')\n    % compute ERP images\n    % ------------------\n    if isempty(opt.channels)\n         X = eeg_getdatact(EEG, 'component', opt.indices, 'trialindices', opt.trialindices );\n    else X = eeg_getdatact(EEG, 'channel'  , opt.indices, 'trialindices', opt.trialindices, 'rmcomps', opt.rmcomps, 'interp', opt.interp);\n    end\n    if ~isempty(opt.sorttype)\n         events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices);\n    else events = [];\n    end\n        \n    % reverse engeeneering the number of lines for ERPimage\n    finallines = opt.nlines;\n    if ~isempty(events)\n         if all(isnan(events))\n             error('Cannot sort trials for one of the dataset');\n         end\n         lastx  = sum(~isnan(events));\n    else lastx  = size(X,3);\n    end\n    if lastx < finallines + floor((opt.smoothing-1)/2) + 3\n        error('The default number of ERPimage lines is too large for one of the dataset');\n    end\n    firstx = 1;\n    xwidth = opt.smoothing;\n    %xadv   = lastx/finallines;\n    nout   = finallines; %floor(((lastx-firstx+xadv+1)-xwidth)/xadv);\n    nlines = (lastx-xwidth)/(nout-0.5)*i; % make it imaginary\n    %nlines = ceil(lastx/((lastx-firstx+1-xwidth)/(nout-1)));\n\n    if 0\n        % testing conversion back and forth\n        % ---------------------------------\n        for lastx = 20:300\n            for xwidth = 1:19\n                for nlines = (xwidth+1):100\n                    \n                    nout = floor(((lastx+nlines)-xwidth)/nlines);\n                    realnlines = (lastx-xwidth)/(nout-0.5);\n                    noutreal = floor(((lastx+realnlines)-xwidth)/realnlines);\n                    \n                    if nout ~= noutreal\n                        error('Wrong conversion 2');\n                    end\n                    \n                end\n            end\n        end\n    end\n    \n    clear tmperpimage eventvals;\n    for index = 1:size(X,1)\n        [tmpX, tmpevents] = erpimage(squeeze(X(index,:,:)), events, EEG(1).times, '', opt.smoothing, nlines, 'noplot', 'on', opt.erpimageopt{:}, moreopts{:});\n        if isempty(events), tmpevents = []; end\n        eventvals{index}   = tmpevents;\n        tmperpimage{index} = tmpX';\n    end\n    allerpimage.events = eventvals{1};\n    for index = 1:size(X,1)\n        allerpimage.([ prefix int2str(opt.indices(index)) ]) = tmperpimage{index};\n    end\nelse\n    % generate dynamic loading commands\n    % ---------------------------------\n    for dat = 1:length(EEG)\n        filenames{dat} = fullfile(EEG(dat).filepath, EEG(dat).filename);\n    end\n    allerpimage.times = EEG(1).times;\n    for index = 1:length(opt.indices)\n        if ~isempty(opt.channels)\n             com = sprintf('squeeze(eeg_getdatact(%s, ''interp'', chanlocsforinterp));', vararg2str( { filenames 'channel'  , opt.indices(index), 'rmcomps', opt.rmcomps, 'trialindices', opt.trialindices } ));\n        else com = sprintf('squeeze(eeg_getdatact(%s));', vararg2str( { filenames 'component', opt.indices(index), 'trialindices', opt.trialindices } ));\n        end\n        allerpimage = setfield(allerpimage, [ prefix int2str(opt.indices(index)) ], com);\n    end\n    if ~isempty(opt.channels)\n        com = sprintf('squeeze(eeg_getdatact(%s, ''interp'', chanlocsforinterp));', vararg2str( { filenames 'rmcomps', opt.rmcomps, 'trialindices', opt.trialindices } ));\n        allerpimage = setfield(allerpimage, [ prefix 'all' ], com);\n    end\n    allerpimage = setfield(allerpimage, 'chanlocsforinterp', opt.interp);\n    if ~isempty(opt.sorttype)\n         events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices);\n         %geteventcom = sprintf('eeg_getepochevent(%s);', vararg2str( { filenames 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield } ));\n    else events = [];\n    end\n    allerpimage = setfield(allerpimage, 'events', events);\nend\nallerpimage.times       = EEG(1).times;\nallerpimage.parameters  = varargin;\nallerpimage.datatype    = 'ERPIMAGE';\nallerpimage.datafiles   = computeFullFileName( { EEG.filepath }, { EEG.filename });\nallerpimage.datatrials  = opt.trialindices;\nallerpimage.trialinfo   = opt.trialinfo;\n\n% Save ERPimages in file (all components or channels)\n% ----------------------------------------------\nif strcmpi(opt.savefile, 'on')\n    if strcmpi(prefix, 'comp')\n        std_savedat(filename, allerpimage);\n    else\n        tmpchanlocs = EEG(1).chanlocs;\n        allerpimage.labels = opt.channels;\n        std_savedat(filename, allerpimage);\n    end\nend\n\n% compute full file names\n% -----------------------\nfunction res = computeFullFileName(filePaths, fileNames)\nfor index = 1:length(fileNames)\n    res{index} = fullfile(filePaths{index}, fileNames{index});\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_erpimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2340026900120585}}
{"text": "function [result, M] = warp_pnt(input, target, method);\n\n% WARP_PNT determine intermediate positions using warping (deformation)\n% the input cloud of points is warped to match the target.\n% The strategy is to start with simpelest linear warp, followed by a more\n% elaborate linear warp, which then is followed by the nonlinear warps up\n% to the desired order.\n%\n% [result, M] = warp_pnt(input, target, method)\n%     input          contains the Nx3 measured 3D positions\n%     target         contains the Nx3 template 3D positions\n%     method         should be empty or any of 'nonlin1', 'nonlin2' ... 'nonlin5'\n%\n% The default is a traditional linear warp with rescaling in each\n% dimension. Optionally you can select a nonlinear warp of the 1st (affine)\n% up to the 5th order.\n%\n% This function depends on the OPTIM and WARPING toolboxes.\n\n% Copyright (C) 2000-2005, Robert Oostenveld\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n% $Log: warp_optim.m,v $\n% Revision 1.1  2009/01/30 04:02:13  arno\n% *** empty log message ***\n%\n% Revision 1.7  2006/11/23 11:34:51  roboos\n% use optimization toolbox if possible, othewise use the standard fminsearch function\n%\n% Revision 1.6  2006/09/13 09:55:58  roboos\n% fixed bug (typo) in rigidbody\n%\n% Revision 1.5  2006/04/13 12:55:45  roboos\n% added a str2func to solve a problem with feval and private\n%\n% Revision 1.4  2006/04/13 10:50:34  roboos\n% renamed calls to warp3d into warp_apply\n%\n% Revision 1.3  2006/04/13 10:47:39  roboos\n% renamed all calls to warpfun into warp_error\n%\n% Revision 1.2  2006/04/13 10:38:24  roboos\n% fixed a problem due to find/strmatch\n%\n% Revision 1.1  2005/08/15 08:12:40  roboos\n% Renamed warp_pnt into warp_optim for consistency with other functions.\n% Also changed the code, the subsequent ordering of the simple to\n% more complex warps is handled more clean.\n%\n% Revision 1.4  2005/03/21 15:43:42  roboos\n% fixed bug in output for nonlinear warping\n% added support for rigidbody or globalrescale warp\n%\n% Revision 1.3  2004/05/19 09:57:08  roberto\n% added GPL copyright statement, added CVS log item\n%\n\nglobal fb;\n\nif nargin<3\n  method='traditional';\nend\n\npos1 = input;\npos2 = target;\n\n% The warp_error function might be located in the private subdirectory fo\n% fieldtrip, i.e. only available to functions in the fieldtrip toolbox.\n% The following line ensures that the function can also be found by the\n% feval that is executed by the optimalization toolbox.\nwarp_error = str2func('warp_error');\n\n% set the options for the minimalisation routine\nif exist('fminunc')\n  % use the optimization toolbox\n  optimfun = @fminunc;\n  options  = optimset('fminunc');\n  options  = optimset(options, 'Display', 'off');\n  options  = optimset(options, 'MaxIter', 1500);\n  % options  = optimset(options, 'MaxFunEvals', '1000*numberOfVariables');\n  options  = optimset(options, 'TolFun', 1e-4);\n  options  = optimset(options, 'LargeScale', 'off');\nelse\n  % use a standard matlab function, this function converges slower\n  optimfun = @fminsearch;\n  options  = optimset('fminsearch');\n  options  = optimset(options, 'Display', 'off');\n  options  = optimset(options, 'MaxIter', 4500);\nend\n\nif fb; fprintf('distance = %f\\n', warp_error([0 0 0 0 0 0], pos1, pos2, 'rigidbody')); end\n\n% the warp is done in steps, starting simple and progressively getting more complex\nlevel = find(strcmp(method, {\n  'rigidbody'          % 1\n  'globalrescale'     % 2\n  'traditional'       % 3\n  'nonlin1'           % 4\n  'nonlin2'           % 5\n  'nonlin3'           % 6\n  'nonlin4'           % 7\n  'nonlin5'           % 8\n  }));\n\nif isempty(method)\n  error('incorrect warping method specified');\nend\n\nif level>=1\n  % do a rigid-body transformation (6 parameters)\n  if fb; disp('rigidbody...'); end\n  ri = [0 0 0 0 0 0];\n  rf = optimfun(warp_error, ri, options, pos1, pos2, 'rigidbody');\n  if fb; fprintf('distance = %f\\n', warp_error(rf, pos1, pos2, 'rigidbody')); end\nend\n\nif level>=2\n  % do a rigid-body + global rescaling transformation (7 parameters)\n  if fb; disp('rigidbody + global rescaling...'); end\n  gi = [rf 1];\n  gf = optimfun(warp_error, gi, options, pos1, pos2, 'globalrescale');\n  if fb; fprintf('distance = %f\\n', warp_error(gf, pos1, pos2, 'globalrescale')); end\nend\n\nif level>=3\n  % do a rigid-body + individual rescaling transformation (9 parameters)\n  if fb; disp('rigidbody + individual rescaling...'); end\n  ti = [gf gf(7) gf(7)];\n  tf = optimfun(warp_error, ti, options, pos1, pos2, 'traditional');\n  if fb; fprintf('distance = %f\\n', warp_error(tf, pos1, pos2, 'traditional')); end\nend\n\nif level>=4\n  % do a first order nonlinear transformation,\n  if fb; disp('1st order nonlinear...'); end\n  e1i = traditional(tf);\n  e1i = [e1i(1:3,4) e1i(1:3,1:3)];\t% reshuffle from homogenous into nonlinear\n  e1f = optimfun(warp_error, e1i, options, pos1, pos2);\n  if fb; fprintf('distance = %f\\n', warp_error(e1f, pos1, pos2, 'nonlinear')); end\nend\n\nif level>=5\n  % do a second order nonlinear transformation,\n  if fb; disp('2nd order nonlinear...'); end\n  e2i = [e1f zeros(3,6)];\n  e2f = optimfun(warp_error, e2i, options, pos1, pos2);\n  if fb; fprintf('distance = %f\\n', warp_error(e2f, pos1, pos2, 'nonlinear')); end\nend\n\nif level>=6\n  % do a third order nonlinear transformation,\n  if fb; disp('3rd order nonlinear...'); end\n  e3i = [e2f zeros(3,10)];\n  e3f = optimfun(warp_error, e3i, options, pos1, pos2);\n  if fb; fprintf('distance = %f\\n', warp_error(e3f, pos1, pos2, 'nonlinear')); end\nend\n\nif level>=7\n  % do a fourth order nonlinear transformation,\n  if fb; disp('4th order nonlinear...'); end\n  e4i = [e3f zeros(3,10)];\n  e4f = optimfun(warp_error, e4i, options, pos1, pos2);\n  if fb; fprintf('distance = %f\\n', warp_error(e4f, pos1, pos2, 'nonlinear')); end\nend\n\nif level>=8\n  % do a fifth order nonlinear transformation,\n  if fb; disp('5th order nonlinear...'); end\n  e5i = [e4f zeros(3,10)];\n  e5f = optimfun(warp_error, e5i, options, pos1, pos2);\n  if fb; fprintf('distance = %f\\n', warp_error(e5f, pos1, pos2, 'nonlinear')); end\nend\n\n% return the estimated parameters of the highest level warp\n% and compute the warped points\nswitch level\n  case 1\n    M = rf;\n  case 2\n    M = gf;\n  case 3\n    M = tf;\n  case 4\n    M = e1f;\n  case 5\n    M = e2f;\n  case 6\n    M = e3f;\n  case 7\n    M = e4f;\n  case 8\n    M = e5f;\nend\nresult = warp_apply(M, input, method);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/private/warp_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2340026900120585}}
{"text": "function a = gt( x, y )\n\n%Disciplined convex programming information for GT (>):\n%   The right-hand side of a less-than constraint must be convex. The\n%   left-hand side must be concave. Of course, real constant and affine\n%   expressions are both convex and concave and can be used on either\n%   side as well.\n%\n%Disciplined geometric programming information for GT (>):\n%   The right-hand side of a less-than constraint must be log-convex---\n%   including positive constants, monomials, posynomials, generalized\n%   posynomials, and products thereof. The left-hand side must be log-\n%   concave---including positive constants, monomials, reciprocals of\n%   log-convex expressions, and products thereof.\n%\n%Note that CVX does not distinguish between strict greater-than (>) and\n%greater-than-or-equal (>=) constraints; they are treated identically. \n%Feasible interior-point solvers tend to return points which satisfy\n%strict inequality, but not all solvers do.\n\nwarning( 'CVX:StrictInequalities', cvx_error( 'The use of strict inequalities in CVX is strongly discouraged, because solvers treat them as non-strict inequalities. Please consider using \">=\" instead.', [66,75], false, '' ) );\nb = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '>' );\nif nargout, a = b; end\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/gt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23400268438325034}}
{"text": "function clout = reparse_continguous(cl)\n% Re-define regions in region object based on contiguous blobs\n%\n% :Usage:\n% ::\n%\n%    clout = reparse_continguous(cl)\n%\n% ..\n%    NEEDS SOME ADDITIONAL WORK/CHECKING\n% ..\n\nivec = region2imagevec(cl);\n\nclout = region(ivec, 'contiguous_regions', 'noverbose');\n\n% ----------------------------------------------\n% Add other fields\n% ----------------------------------------------\n\nclindx = ivec.volInfo.cluster;  % wh are in new clusters\nnvox = length(clindx);\n\ndat = cat(2, cl.all_data);\n\nif size(dat, 2) == nvox\n    \n    % matching field; get dat for new clout\n    for j = 1:length(clout)\n        clout(j).all_data = dat(:, clindx == j);\n        \n        clout(j).dat = nanmean(clout(j).all_data', 1)';\n    end\n    \nelseif isempty(dat)\n    % do nothing\nelse\n    disp('Warning!  all_dat field is wrong size.');\n    \nend\n\nend\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@region/reparse_continguous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23392444862057513}}
{"text": "function opts = SRSolverParams(varargin)\n%SRSOLVERPARAMS Parameters for numerical optizimation.\n%   SRSOLVERPARAMS returns a parameter structure used for numerical\n%   optimization and computations in different super-resolution algorithms.\n%\n%   The parameter structure consist of the following parameters:\n%       - maxFunEvals:  Maximum number of objective function evaluations.\n%       - maxIter:      Maximum number of iterations for non-linear\n%                       optimization.\n%       - maxIrlsIter:  Maximum number of iterations for iteratively\n%                       re-weighted least squares algorithms.\n%       - tolX:         Measure of the absolute precision required for the\n%                       super-resolved pixel values (termination\n%                       tolerance).\n%       - tolF:         Measure of the absolute precision required for\n%                       objective functions in non-linear optimization\n%                       (termination tolerance).\n%       - gradCheck:    Set to 1 to check the analytic derived gradients\n%                       for debug purposes.\n%       - verbose:      Level for debug messages. Set to -1 for no\n%                       messages, to 0 for only warning messages and 1 for \n%                       error messages.\n    \n    % Set default value to parameter structure\n    opts = struct('maxFunEvals',         50, ...    % Maximim number of function evals\n                  'maxIter',             50, ...    % Maximum number of iterations\n                  'maxIrlsIter',         15, ...    % Maximum number of iteration for iteratively re-weighted least squares\n                  'tolX',                1e-3, ...  % Tolerance criterion for image pixels\n                  'tolF',                1e-3, ...  % Tolerance criterion for objective function value\n                  'verbose',             false, ... % Use debug outputs\n                  'gradCheck',           false);    % Check objective function gradient\n    \n    % Update with user-defined parameters\n    for k = 1:2:(nargin - 1)\n        \n        param = varargin{k};\n        value = varargin{k+1};\n        if isfield(opts, param)\n            opts = setfield(opts, param, value);\n        else\n            error( sprintf('Invalid parameter %s', param) );\n        end\n       \n    end", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/SRToolbox/common/SRSolverParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23392444862057513}}
{"text": "classdef TestStructuredEdgeDetection\n    %TestStructuredEdgeDetection\n\n    properties (Constant)\n        im = fullfile(mexopencv.root(),'test','balloon.jpg');\n    end\n\n    methods (Static)\n        function test_1\n            img = imread(TestStructuredEdgeDetection.im);\n            img = single(img) / 255.0;\n\n            modelFilename = get_model_file();\n            pDollar = cv.StructuredEdgeDetection(modelFilename);\n\n            E = pDollar.detectEdges(img);\n            validateattributes(E, {'single'}, ...\n                {'size',[size(img,1) size(img,2)], '>=',0, '<=',1});\n\n            O = pDollar.computeOrientation(E);\n            validateattributes(O, {'single'}, ...\n                {'size',[size(img,1) size(img,2)]});\n\n            E_nms = pDollar.edgesNms(E, O);\n            validateattributes(E_nms, {'single'}, ...\n                {'size',[size(img,1) size(img,2)], '>=',0, '<=',1});\n        end\n\n        function test_custom_feat_extract\n            % skip test if external M-file is not found on the path\n            if ~exist('myRFFeatureGetter.m', 'file')\n                error('mexopencv:testskip', 'undefined function');\n            end\n\n            img = imread(TestStructuredEdgeDetection.im);\n            img = single(img) / 255.0;\n\n            modelFilename = get_model_file();\n            pDollar = cv.StructuredEdgeDetection(modelFilename, ...\n                'myRFFeatureGetter');\n            E = pDollar.detectEdges(img);\n        end\n\n        function test_get_features\n            img = imread(TestStructuredEdgeDetection.im);\n            img = single(img) / 255.0;\n\n            opts = struct();\n            opts.normRad = 4;\n            opts.grdSmooth = 0;\n            opts.shrink = 2;\n            opts.nChns = 13;\n            opts.nOrients = 4;\n\n            features = cv.StructuredEdgeDetection.getFeatures(img, opts);\n            validateattributes(features, {'numeric'}, {'real', 'ndims',3});\n            sz = size(features);\n            %assert(sz(1) * opts.shrink == size(img,1));\n            %assert(sz(2) * opts.shrink == size(img,2));\n            assert(sz(3) == opts.nChns);\n        end\n    end\n\nend\n\nfunction features = myRFFeatureGetter(src, opts)\n    if false\n        nsize = fix([size(src,1) size(src,2)] ./ opts.shrink);\n        features = zeros([nsize opts.nChns], 'single');\n        %TODO: ... compute features\n    else\n        % call opencv's implementation\n        features = cv.StructuredEdgeDetection.getFeatures(src, opts);\n    end\nend\n\nfunction fname = get_model_file()\n    fname = fullfile(mexopencv.root(),'test','model.yml.gz');\n    if exist(fname, 'file') ~= 2\n        % download model from GitHub\n        url = 'https://cdn.rawgit.com/opencv/opencv_extra/3.2.0/testdata/cv/ximgproc/model.yml.gz';\n        urlwrite(url, fname);\n    end\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/test/unit_tests/TestStructuredEdgeDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23392444862057513}}
{"text": "function [contact, fric_coef, geometry] = RightToe(robot)\n  \n    param = sys.GetExtraParams();\n    \n    \n    r_foot_frame = robot.Joints(getJointIndices(robot, 'r_leg_akx'));\n    contact = CoordinateFrame(...\n        'Name','RightToe',...\n        'Reference',r_foot_frame,...\n        'Offset',[param.lt, 0, param.hf],...\n        'R',[0,0,0]... % z-axis is the normal axis, so no rotation required\n        );\n    \n    fric_coef.mu = param.mu;\n    fric_coef.gamma = param.gamma;\n\n\n    geometry.la = param.wf/2;\n    geometry.lb = param.wf/2;\n    geometry.La = 0;\n    geometry.Lb = param.lh+ param.lt;\n    \nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/atlas/+sys/+frames/RightToe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.23390872761876402}}
{"text": "function YLim= visutil_selectYLim(h, varargin)\n\nprops = {'Policy',          'auto'          '!CHAR(auto tightest tight)';\n         'TightenBorder'     0.03        \t'DOUBLE';\n         'Symmetrize'       0               '!BOOL';\n         'SetLim'           1               '!BOOL';\n         };\n\nif nargin==0,\n  YLim= props; return\nend\n\nopt= opt_proplistToStruct(varargin{:});\n[opt, isdefault]= opt_setDefaults(opt, props);\nopt_checkProplist(opt, props);\nmisc_checkType(h,'!GRAPHICS');\n\nswitch(opt.Policy),\n case 'auto',\n  YLim= get(h, 'YLim');\n case 'tightest',\n  visutil_backaxes(h);\n  axis('tight');\n  YLim= get(h, 'YLim');\n case 'tight',\n  visutil_backaxes(h);\n  axis('tight');\n  yl= get(h, 'YLim');\n  % add border not to make it too tight:\n  yl= yl + [-1 1]*opt.TightenBorder*diff(yl);\n  % determine nicer limits\n  dig= floor(log10(diff(yl)));\n  if diff(yl)>1,\n    dig= max(1, dig);\n  end\n  YLim= [util_trunc(yl(1),-dig+1,'floor') util_trunc(yl(2),-dig+1,'ceil')];\nend\n\nif opt.Symmetrize,\n  ma= max(abs(YLim));\n  YLim= [-ma ma];\nend\n\nif opt.SetLim,\n  set(h, 'YLim',YLim);\nend\n\nif nargout==0,\n  clear YLim;\nend", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_RobotArm/dylee/visutil_selectYLim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.23390872761876402}}
{"text": "function z = GetVolt()\n%\n%\nw = 0 + 4*randn(1,1);\nz = 14.4 + w;", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/1.AvgFilter/GetVolt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.2338338795164836}}
{"text": "function planC = divideStructureAntPostLeftRight(structNum, planC)\n% function divideStructureAntPostLeftRight(structNum, planC)\n%\n% APA, 08/23/2012\n\nif ~exist('planC','var')\n    global planC\nend\n\nglobal stateS\n\nindexS = planC{end};\n\nscanNum = getStructureAssociatedScan(structNum,planC);\n\nnewStructNumT = length(planC{indexS.structures}) + 1;\nnewStructNumL = length(planC{indexS.structures}) + 2;\nnewStructNumB = length(planC{indexS.structures}) + 3;\nnewStructNumR = length(planC{indexS.structures}) + 4;\n\nnewStructTS = newCERRStructure(scanNum, planC, newStructNumT);\nnewStructLS = newCERRStructure(scanNum, planC, newStructNumL);\nnewStructBS = newCERRStructure(scanNum, planC, newStructNumB);\nnewStructRS = newCERRStructure(scanNum, planC, newStructNumR);\n\nfor slcNum = 1:length(planC{indexS.scan}(scanNum).scanInfo)\n    \n    % Calculate centroid for this slice\n    [rasterSegments, planC, isError]    = getRasterSegments(structNum,planC);\n    rasterIndices = find(rasterSegments(:,6) == slcNum);\n    \n    zValue = planC{indexS.scan}(scanNum).scanInfo(slcNum).zValue;\n    \n    if ~isempty(rasterIndices)\n        \n        maskM = rasterToMask(rasterSegments(rasterIndices,:), scanNum, planC);\n        \n        %Get r,c,s list of all points in mask.\n        [rV,cV] = find(maskM);\n        \n        %Take the mean of all points... unweighted as this is a mask.\n        rowCOM = mean(rV);\n        colCOM = mean(cV);\n        slcCOM = 1; % dummy value\n        \n        %Convert from rcs, to xyz coordinates.\n        [xc,yc] = mtoxyz(rowCOM, colCOM, slcCOM, scanNum, planC, 'uniform');\n        \n        for segNum = 1:length(planC{indexS.structures}(structNum).contour(slcNum).segments)\n            xV = planC{indexS.structures}(structNum).contour(slcNum).segments(segNum).points(:,1);\n            yV = planC{indexS.structures}(structNum).contour(slcNum).segments(segNum).points(:,2);\n            [xyTV,xyLV,xyBV,xyRV] = dividePolygon(xV,yV,xc,yc);\n            newStructTS.contour(slcNum).segments(segNum).points = [xyTV xyTV(:,1).^0*zValue];\n            newStructLS.contour(slcNum).segments(segNum).points = [xyLV  xyLV(:,1).^0*zValue];\n            newStructBS.contour(slcNum).segments(segNum).points = [xyBV  xyBV(:,1).^0*zValue];\n            newStructRS.contour(slcNum).segments(segNum).points = [xyRV  xyRV(:,1).^0*zValue];\n        end\n        \n    else\n        newStructTS.contour(slcNum).segments(1).points = [];\n        newStructLS.contour(slcNum).segments(1).points = [];\n        newStructBS.contour(slcNum).segments(1).points = [];\n        newStructRS.contour(slcNum).segments(1).points = [];\n    end\n    \nend\n\n\nstateS.structsChanged = 1;\n\nnewStructLS.structureName = [planC{indexS.structures}(structNum).structureName '_RIGHT'];\nnewStructRS.structureName = [planC{indexS.structures}(structNum).structureName '_LEFT'];\npatientPosition = planC{indexS.scan}.scanInfo(1).DICOMHeaders.PatientPosition;\nif isequal(patientPosition,'HFP') || isequal(patientPosition,'FFP')\n    newStructTS.structureName = [planC{indexS.structures}(structNum).structureName '_POSTERIOR'];\n    newStructBS.structureName = [planC{indexS.structures}(structNum).structureName '_ANTERIOR'];\nelse\n    newStructTS.structureName = [planC{indexS.structures}(structNum).structureName '_ANTERIOR'];\n    newStructBS.structureName = [planC{indexS.structures}(structNum).structureName '_POSTERIOR'];    \nend\nplanC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructTS, newStructNumT);\nplanC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructLS, newStructNumL);\nplanC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructBS, newStructNumB);\nplanC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructRS, newStructNumR);\n\nplanC = getRasterSegs(planC, [newStructNumT newStructNumL newStructNumB newStructNumR]);\nplanC = updateStructureMatrices(planC, newStructNumT);\nplanC = updateStructureMatrices(planC, newStructNumL);\nplanC = updateStructureMatrices(planC, newStructNumB);\nplanC = updateStructureMatrices(planC, newStructNumR);\n\n% Refresh View\nif ~isempty(stateS) && isfield(stateS,'handle') && isfield(stateS.handle,'CERRSliceViewer') && isnumeric(stateS.handle.CERRSliceViewer)    \n    stateS.structsChanged = 1;\n    CERRRefresh\nend\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/divideStructureAntPostLeftRight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23376978693807124}}
{"text": "function t_opf_dc_ipopt(quiet)\n%T_OPF_DC_MIPS  Tests for DC optimal power flow using MIPS solver.\n\n%   MATPOWER\n%   Copyright (c) 2004-2021, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\nif nargin < 1\n    quiet = 0;\nend\n\nnum_tests = 43;\n\nt_begin(num_tests, quiet);\n\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n\ncasefile = 't_case9_opf';\nif quiet\n    verbose = 0;\nelse\n    verbose = 0;\nend\nif have_feature('octave')\n    if have_feature('octave', 'vnum') >= 4\n        file_in_path_warn_id = 'Octave:data-file-in-path';\n    else\n        file_in_path_warn_id = 'Octave:load-file-in-path';\n    end\n    s1 = warning('query', file_in_path_warn_id);\n    warning('off', file_in_path_warn_id);\nend\n\nt0 = 'DC OPF (IPOPT): ';\nmpopt = mpoption('out.all', 0, 'verbose', verbose);\nmpopt = mpoption(mpopt, 'opf.dc.solver', 'IPOPT');\n\nif have_feature('ipopt')\n    %% set up indices\n    ib_data     = [1:BUS_AREA BASE_KV:VMIN];\n    ib_voltage  = [VM VA];\n    ib_lam      = [LAM_P LAM_Q];\n    ib_mu       = [MU_VMAX MU_VMIN];\n    ig_data     = [GEN_BUS QMAX QMIN MBASE:APF];\n    ig_disp     = [PG QG VG];\n    ig_mu       = (MU_PMAX:MU_QMIN);\n    ibr_data    = (1:ANGMAX);\n    ibr_flow    = (PF:QT);\n    ibr_mu      = [MU_SF MU_ST];\n    ibr_angmu   = [MU_ANGMIN MU_ANGMAX];\n\n    %% get solved DC power flow case from MAT-file\n    load soln9_dcopf;       %% defines bus_soln, gen_soln, branch_soln, f_soln\n\n    %% run OPF\n    t = t0;\n    [baseMVA, bus, gen, gencost, branch, f, success, et] = rundcopf(casefile, mpopt);\n    t_ok(success, [t 'success']);\n    t_is(f, f_soln, 3, [t 'f']);\n    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);\n    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);\n    t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);\n    t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);\n    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);\n    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);\n    t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);\n    t_is(branch(:,ibr_data  ), branch_soln(:,ibr_data  ), 10, [t 'branch data']);\n    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);\n    t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);\n\n    %%-----  test OPF with angle difference limits  -----\n    t = [t0 'w/angle diff lims : '];\n    mpc = loadcase(casefile);\n    mpc.branch(4, ANGMAX) = 3;\n    mpc.branch(7, ANGMIN) = -4.5;\n    r = rundcopf(mpc, mpopt);\n    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);\n    t_ok(success, [t 'success']);\n    t_is(   f, 6456.7213, 3, [t 'f']);\n    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);\n    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);\n    t_is(   gen(:,PG        ),    [99.98497;89.35133;125.66371], 4, [t 'gen dispatch']);\n    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);\n    e = zeros(size(branch, 1), 1);\n    e(4) = 297.83776;\n    e(7) = -26.94788;\n    t_is(branch(:,MU_ANGMAX )-branch(:,MU_ANGMIN ), e, 4, [t 'branch ang diff mu']);\n\n    t = [t0 'w/ignored angle diff lims : '];\n    mpopt1 = mpoption(mpopt, 'opf.ignore_angle_lim', 1);\n    r = rundcopf(mpc, mpopt1);\n    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);\n    t_ok(success, [t 'success']);\n    t_is(f, f_soln, 3, [t 'f']);\n    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);\n    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);\n    t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);\n    t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);\n    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);\n    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);\n    t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);\n    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);\n    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);\n    t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);\n\n    %%-----  run OPF with extra linear user constraints & costs  -----\n    %% two new z variables\n    %%      0 <= z1, P3 - P1 <= z1\n    %%      0 <= z2, P3 - P2 <= z2\n    %% with A and N sized for DC opf\n    mpc = loadcase(casefile);\n    mpc.A = sparse([1;1;1;2;2;2],[10;12;13;12;11;14],[-1;1;-1;1;-1;-1],2,14);\n    mpc.u = [0; 0];\n    mpc.l = [-Inf; -Inf];\n    mpc.zl = [0; 0];\n\n    mpc.N = sparse([1;2], [13;14], [1;1], 2, 14);   %% new z variables only\n    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z\n    mpc.H = sparse(2,2);                            %% no quadratic term\n    mpc.Cw = [1000;1];\n\n    t = [t0 'w/extra constraints & costs 1 : '];\n    [r, success] = rundcopf(mpc, mpopt);\n    t_ok(success, [t 'success']);\n    t_is(r.gen(1, PG), 116.15974, 4, [t 'Pg1 = 116.15974']);\n    t_is(r.gen(3, PG), 116.15974, 4, [t 'Pg3 = 116.15974']);\n    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);\n    t_is(r.cost.usr, 0.3348, 3, [t 'user costs']);\n\n    %% with A and N sized for AC opf\n    mpc = loadcase(casefile);\n    mpc.A = sparse([1;1;1;2;2;2],[19;21;25;21;20;26],[-1;1;-1;1;-1;-1],2,26);\n    mpc.u = [0; 0];\n    mpc.l = [-Inf; -Inf];\n    mpc.zl = [0; 0];\n\n    mpc.N = sparse([1;2], [25;26], [1;1], 2, 26);   %% new z variables only\n    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z\n    mpc.H = sparse(2,2);                            %% no quadratic term\n    mpc.Cw = [1000;1];\n\n    t = [t0 'w/extra constraints & costs 2 : '];\n    [r, success] = rundcopf(mpc, mpopt);\n    t_ok(success, [t 'success']);\n    t_is(r.gen(1, PG), 116.15974, 4, [t 'Pg1 = 116.15974']);\n    t_is(r.gen(3, PG), 116.15974, 4, [t 'Pg3 = 116.15974']);\n    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);\n    t_is(r.cost.usr, 0.3348, 3, [t 'user costs']);\n\n    t = [t0 'infeasible : '];\n    %% with A and N sized for DC opf\n    mpc = loadcase(casefile);\n    mpc.A = sparse([1;1], [10;11], [1;1], 1, 14);   %% Pg1 + Pg2\n    mpc.u = Inf;\n    mpc.l = 600;\n    [r, success] = rundcopf(mpc, mpopt);\n    t_ok(~success, [t 'no success']);\n\n    %% OPF with all buses isolated\n    t = [t0 'all buses isolated : '];\n    mpc = loadcase(casefile);\n    mpc.bus(:, BUS_TYPE) = NONE;\n    try\n        r = rundcopf(mpc, mpopt);\n        t_is(r.success, 0, 12, [t 'success = 0']);\n    catch\n        t_ok(0, [t 'unexpected fatal error']);\n    end\nelse\n    t_skip(num_tests, 'IPOPT not available');\nend\n\nif have_feature('octave')\n    warning(s1.state, file_in_path_warn_id);\nend\n\nt_end;\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/t/t_opf_dc_ipopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23371084262168798}}
{"text": "function test_suite=test_meeg_chan_neighborhood()\n% tests for cosmo_meeg_chan_neighborhood\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n    try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n        test_functions=localfunctions();\n    catch % no problem; early Matlab versions can use initTestSuite fine\n    end\n    initTestSuite;\n\nfunction test_neighbors()\n    % note: this tests assumes that meeg_chan_neighbors works properly\n    if cosmo_skip_test_if_no_external('fieldtrip')\n        return;\n    end\n\n    % only test every test_step-th channel\n    test_step=10;\n\n    ds=cosmo_synthetic_dataset('type','meeg','size','big');\n    msk=ds.fa.chan<10 | mod(ds.fa.chan,5)==0 | ds.fa.chan>250;\n    imsk=find(msk);\n    rp=randperm(numel(imsk));\n    ds=cosmo_slice(ds,imsk(rp),2);\n    ds=cosmo_dim_prune(ds);\n    n=numel(ds.a.fdim.values{1});\n    ds.a.fdim.values{1}=ds.a.fdim.values{1}(randperm(n));\n\n    nbrs=cosmo_meeg_chan_neighbors(ds,'chantype','meg_planar','radius',0);\n    nh=cosmo_meeg_chan_neighborhood(ds,nbrs);\n\n    assertEqual(nh.a.fdim.values,{{nbrs.label}});\n    assertEqual(nh.a.fdim.labels,{'chan'});\n\n    n=numel(nh.neighbors);\n    for k=1:test_step:n\n        idx=nh.neighbors{k};\n        chan_label=ds.a.fdim.values{1}(ds.fa.chan(idx));\n        assert(all(cosmo_match(chan_label,nh.a.fdim.values{1}{k})));\n    end\n\n    % test correspondence with neighbors\n    args={'chantype','all','delaunay',true};\n    nbrs=cosmo_meeg_chan_neighbors(ds,args{:});\n    nh=cosmo_meeg_chan_neighborhood(ds,args{:});\n    nh2=cosmo_meeg_chan_neighborhood(ds,nbrs);\n    assertEqual(nh,nh2);\n\n    ds_label=ds.a.fdim.values{1};\n\n    n=numel(nh.neighbors);\n    for k=1:test_step:n\n        idx=nh.neighbors{k};\n\n        chan_label=ds.a.fdim.values{1}(ds.fa.chan(idx));\n\n        % ensure both arguments for intersect are column vectors,\n        % because Octave behaves differently than Matlab\n        assertEqual(intersect(ds_label(:),nbrs(k).neighblabel(:)),...\n                        unique(chan_label'));\n\n    end\n\n\n    % try with dataset labels\n    args={'chantype','all','count',5,'label','dataset'};\n    nbrs=cosmo_meeg_chan_neighbors(ds,args{:});\n    nh=cosmo_meeg_chan_neighborhood(ds,nbrs);\n    n=numel(nh.neighbors);\n    assertEqual(n, numel(ds.a.fdim.values{1}));\n    assertEqual(1:n, nh.fa.chan);\n    ds_label=ds.a.fdim.values{1};\n    nh_label=nh.a.fdim.values{1};\n\n    for k=1:test_step:n\n        i=find(cosmo_match(nh_label,ds_label{k}));\n        assertEqual(nbrs(i).label,ds_label{k});\n\n        overlap=cosmo_overlap({ds_label(ds.fa.chan(nh.neighbors{i}))},...\n                                {nbrs(i).neighblabel});\n        assertEqual(overlap,1);\n    end\n\n    % test for number of channels\n    nbrs=cosmo_meeg_chan_neighbors(ds,'count',5,...\n                        'chantype','meg_combined_from_planar');\n    nh=cosmo_meeg_chan_neighborhood(ds,nbrs);\n    assertEqual(numel(nh.neighbors),102);\n    h=cellfun(@numel,nh.neighbors)/7;\n    assert(all(h>=5 & h<=10));\n    mh=mean(h);\n    assert(mh>6 && mh<9);\n\n    nbrs=cosmo_meeg_chan_neighbors(ds,'count',5,'chantype','meg_planar');\n    nh=cosmo_meeg_chan_neighborhood(ds,nbrs);\n    assertEqual(numel(nh.neighbors),204);\n    h=cellfun(@numel,nh.neighbors)/7;\n    assert(all(h==5));\n\n\n    % test tiny dataset\n    ds=cosmo_synthetic_dataset('type','meeg');\n    opt=struct();\n    opt.delaunay=true;\n    opt.label='dataset';\n    opt.chantype='meg_axial';\n\n    nh=cosmo_meeg_chan_neighborhood(ds,opt);\n    assertEqual(nh.neighbors,{[1 4]});\n\n    opt.chantype='meg_planar';\n    nh=cosmo_meeg_chan_neighborhood(ds,opt);\n    assertEqual(nh.neighbors,{[2 5 3 6]; [2 5 3 6]});\n\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_meeg_chan_neighborhood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2337108358741517}}
{"text": "function output = callvsdp(interfacedata)\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc       = interfacedata.c;\nK       = interfacedata.K;\nx0      = interfacedata.x0;\nub      = interfacedata.ub;\nlb      = interfacedata.lb;\n\n% Bounded variables converted to constraints\nif ~isempty(ub)\n    [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\n% Convert from internal (sedumi-like) format to VSDPs sdpt3-like format\n[blk,A,C,b]=sedumi2vsdp(F_struc(:,1),F_struc(:,2:end),c,K);\n\nif options.savedebug\n    ops = options.sdpt3;\n    save sdpt3debug blk A C b ops -v6\nend\n\n% Solver to be used in VSDP\noptions.vsdp.model = interfacedata;\n\nsolvertime = tic;     \n[objt,Xt,yt,Zt,info] = mysdps_yalmip(blk,A',C,b,options);\n\n% Compute rigorous lower bound (default behaviour)\nif options.vsdp.verifiedlower\n    [fL, Y, dL] = vsdplow_yalmip(blk,A',C,b,Xt,yt,Zt,[],options);\n    if isnan(Y)\n        info(1) = 11;\n    end\n    %[fL, Y, dL] = vsdplow(blk,A,C,b,Xt,yt,Zt)    \nelse\n    Y = [];\n    fL = [];\n    dL = [];\nend\n\n% Compute rigorous lower bound\nif options.vsdp.verifiedupper\n    %[fL, Y, dL] = vsdplow_yalmip(blk,A,C,b,[],[],[],[],options)    \n    % Now compute rigorous lower bound\n    [fU, X, lb] = vsdpup_yalmip(blk,A',C,b,Xt,yt,Zt,[],options);\n    %[fU, X, lb] = vsdpup(blk,A,C,b,Xt,yt,Zt);    \nelse\n    fU = [];\n    X = [];\n    lb = [];\nend\n\nsolvertime = toc(solvertime);\n\nDual = [];\nSlack = [];\ntop = 1; \nif K.f>0\n    Dual = [Dual;Xt{top}(:)];\n    Slack = [Slack;Zt{top}(:)];\n    top = top+1;\nend\nif K.l>0\n    Dual = [Dual;[Xt{1:K.l}]'];\n    Slack = [Slack;[Zt{1:K.l}]'];\n    top = top + K.l;\nend\nif any(K.q)\n    Dual = [Dual;Xt{top}(:)];\n    Slack = [Slack;Zt{top}(:)];\n    top = top + 1;\nend\nif any(K.s)     \n    for i = 1:length(K.s)\n        Dual = [Dual;Xt{top+i-1}(:)];     \n        Slack = [Slack;Zt{top+i-1}(:)];     \n    end\nend\n\nif ~isempty(Y) & ~isnan(Y)\n    Primal = Y;  % Primal variable in YALMIP\nelse\n    Primal = yt;  % Primal variable in YALMIP\nend\n\n% Convert error code\nswitch info(1)\n    case 0\n        problem = 0; % No problems detected\n    case {-1,-5} \n        problem = 5; % Lack of progress\n    case {-2,-3,-4,-7}\n        problem = 4; % Numerical problems\n    case -6\n        problem = 3; % Maximum iterations exceeded\n    case -10\n        problem = 7; % YALMIP sent incorrect input to solver\n    case 1\n        problem = 2; % Dual feasibility\n    case 2\n        problem = 1; % Primal infeasibility \n    case 11\n        problem = 11;\n    otherwise\n        problem = -1; % Unknown error\nend\n\n% always save output\nif options.savesolveroutput\n    solveroutput.objt = objt;\n    solveroutput.Xt = Xt;\n    solveroutput.yt = yt;\n    solveroutput.Zt = Zt;\n    solveroutput.fL = fL;\n    solveroutput.Y  = Y;\n    solveroutput.dL  = dL;    \n    solveroutput.fU = fU;\n    solveroutput.X  = X;\n    solveroutput.lb  = lb;\n    solveroutput.info = info;\n else\n    solveroutput = [];\nend\n\nif options.savesolverinput\n    solverinput.blk = blk;\n    solverinput.A   = A;\n    solverinput.C   = C;\n    solverinput.b   = b; \n    solverinput.options   = options.sdpt3;\nelse\n    solverinput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(Primal,Dual,Slack,problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);\n\n\nfunction [blk,A,C,b]=sedumi2vsdp(Cin,Ain,c,K);\n\nC = {};\nA = {};\nb  = -c;\nblk = {};\ntop = 1;\nk = 1;\n\nif any(K.f)\n    C{k,1} = Cin(top:top+K.f-1);\n%    A{k} = -Ain(top:top+K.f-1,:);\n    for j = 1:length(c)\n        A{j,k} = -Ain(top:top+K.f-1,j);\n    end\n    blk{k,1} = 'u';\n    blk{k,2} = K.f;\n    top = top + K.f;\n    k = k + 1;\nend\n\nif any(K.l)\n    K.s = [repmat(1,1,K.l) K.s];\n    K.s(K.s == 0) = [];\n%     C{k,1} = Cin(top:top+K.l-1);\n% %    A{k} = -Ain(top:top+K.l-1,:);\n%     for j = 1:length(c)\n%         A{j,k} = -Ain(top:top+K.l-1,j);\n%     end\n%     blk{k,1} = 'l';\n%     blk{k,2} = K.l;\n%     top = top + K.l;\n%     k = k + 1;\nend\n\nif any(K.s)\n    for i = 1:length(K.s)\n        C{k,1} = reshape(Cin(top:top+K.s(i)^2-1),K.s(i),K.s(i));\n        for j = 1:length(c)\n            A{j,k} = reshape(-Ain(top:top+K.s(i)^2-1,j),K.s(i),K.s(i));\n        end\n        blk{k,1} = 's';\n        blk{k,2} = K.s(i);\n        k = k + 1;\n        top = top + K.s(i)^2;\n    end\nend\n\nA = A';", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callvsdp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23351120190125874}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright 2014 National Renewable Energy Laboratory and National \n% Technology & Engineering Solutions of Sandia, LLC (NTESS). \n% Under the terms of Contract DE-NA0003525 with NTESS, \n% the U.S. Government retains certain rights in this software.\n% \n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n% \n% http://www.apache.org/licenses/LICENSE-2.0\n% \n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef constraintClass<handle\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % The ``constraintClass`` creates a ``constraint`` object saved to the MATLAB\n    % workspace. The ``constraintClass`` includes properties and methods used\n    % to define constraints between the body motion relative to the global reference \n    % frame or relative to other bodies. \n    %\n    %.. autoattribute:: objects.constraintClass.constraintClass            \n    %     \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \n    properties (SetAccess = 'public', GetAccess = 'public') %input file \n        hardStops                   = struct(...                    % (`structure`) Defines the constraint hardstop\n          'upperLimitSpecify',          'off',...                   % (`string`) Initialize upper stroke limit. ``  'on' or 'off' `` Default = ``off``. \n          'upperLimitBound',            1, ...                      % (`float`) Define upper stroke limit in m or deg. Only active if `lowerLimitSpecify` is `on` `` Default = ``1``. \n          'upperLimitStiffness',        1e6, ...                    % (`float`) Define upper limit spring stiffness, N/m or N-m/deg. `` Default = ``1e6``. \n          'upperLimitDamping',          1e3, ...                    % (`float`) Define upper limit damping, N/m/s or N-m/deg/s.  `` Default = ``1e3``.\n          'upperLimitTransitionRegionWidth', 1e-4, ...              % (`float`) Define upper limit transition region, over which spring and damping values ramp up to full values. Increase for stability. m or deg. ``Default = 1e-4``\n          'lowerLimitSpecify',          'off',...                   % Initialize lower stroke limit. ``  `on` or `off` `` Default = ``off``. \n          'lowerLimitBound',            -1, ...                     % (`float`) Define lower stroke limit in m or deg. Only active if `lowerLimitSpecify` is `on` ``   `` Default = ``-1``. \n          'lowerLimitStiffness',        1e6, ...                    % (`float`) Define lower limit spring stiffness, N/m or N-m/deg.  `` Default = ``1e6``.\n          'lowerLimitDamping',          1e3, ...                    % (`float`) Define lower limit damping, N/m/s or N-m/deg/s.  `` Default = ``1e3``.\n          'lowerLimitTransitionRegionWidth', 1e-4)                  % (`float`) Define lower limit transition region, over which spring and damping values ramp up to full values. Increase for stability. m or deg. ``Default = 1e-4``                                                                                    \n        initial                     = struct(...                    % \n            'displacement',             [0 0 0])                    % (`structure`) Defines the initial displacement of the constraint. ``displacement`` (`3x1 float vector`) is defined as the initial displacement of the constraint [m] in the following format [x y z], Default = [``0 0 0``].\n        name                        = 'NOT DEFINED'                 % (`string`) Specifies the constraint name. For constraints this is defined by the user, Default = ``NOT DEFINED``.\n        location                    = [999 999 999]                 % (`3x1 float vector`) Constraint location [m]. Defined in the following format [x y z]. Default = ``[999 999 999]``.        \n        orientation                 = struct(...                    % (`structure`) Defines the orientation axis of the constraint.\n            'z',                        [0, 0, 1], ...              % \n            'y',                        [0, 1, 0], ...              % \n            'x',                        [], ...                     % \n            'rotationMatrix',           [])                         % (`structure`) Defines the orientation axis of the constraint. ``z`` (`3x1 float vector`) defines the direciton of the Z-coordinate of the constraint, Default = [``0 0 1``]. ``y`` (`3x1 float vector`) defines the direciton of the Y-coordinate of the constraint, Default = [``0 1 0``]. ``x`` (`3x1 float vector`) internally calculated vector defining the direction of the X-coordinate for the constraint, Default = ``[]``. ``rotationMatrix`` (`3x3 float matrix`) internally calculated rotation matrix to go from standard coordinate orientation to the constraint coordinate orientation, Default = ``[]``.\n    end                             \n    \n    properties (SetAccess = 'private', GetAccess = 'public') %internal\n        number                      = []                            % Constraint number\n    end\n    \n    methods (Access = 'public')                                        \n        function obj = constraintClass(name)\n            % This method initilizes the ``constraintClass`` and creates a\n            % ``constraint`` object.          \n            %\n            % Parameters\n            % ------------\n            %     filename : string\n            %         String specifying the name of the constraint\n            %\n            % Returns\n            % ------------\n            %     constraint : obj\n            %         contraintClass object         \n            %\n            if exist('name','var')\n                obj.name = name;\n            else\n                error('The constraint class number(s) in the wecSimInputFile must be specified in ascending order starting from 1. The constraintClass() function should be called first to initialize each constraint with a name.')\n            end\n        end\n        \n        function obj = checkLoc(obj,action)\n            % This method checks WEC-Sim user inputs and generate an error message if the constraint location is not defined in constraintClass.\n            \n            % Checks if location is set and outputs a warning or error. Used in mask Initialization.\n            switch action\n              case 'W'\n                if obj.location == 999 % Because \"Allow library block to modify its content\" is selected in block's mask initialization, this command runs twice, but warnings cannot be displayed during the first initialization. \n                    obj.location = [888 888 888];\n                elseif obj.location == 888\n                    obj.location = [0 0 0];\n                    s1= ['For ' obj.name ': constraint.location was changed from [9999 9999 9999] to [0 0 0]'];\n                    warning(s1)\n                end\n              case 'E'\n                try\n                    if obj.location == 999\n                      s1 = ['For ' obj.name ': constraint.location needs to be specified in the WEC-Sim input file.' ...\n                        ' constraint.location is the [x y z] location, in meters, for the pitch constraint.'];\n                      error(s1)\n                    end\n                catch exception\n                  throwAsCaller(exception)\n                end\n            end\n        end\n        \n        function obj = setOrientation(obj)\n            % This method calculates the constraint ``x`` vector and ``rotationMatrix`` matrix in the ``orientation`` structure based on user input.\n            obj.orientation.z = obj.orientation.z / norm(obj.orientation.z);\n            obj.orientation.y = obj.orientation.y / norm(obj.orientation.y);\n            z = obj.orientation.z;\n            y = obj.orientation.y;\n            if abs(dot(y,z))>0.001\n                error('The Y and Z vectors defining the constraint''s orientation must be orthogonal.')\n            end\n            x = cross(y,z)/norm(cross(y,z));\n            x = x(:)';\n            obj.orientation.x = x;\n            obj.orientation.rotationMatrix  = [x',y',z'];\n        end\n        \n        function setInitDisp(obj, relCoord, axisAngleList, addLinDisp)\n            % Function to set a constraints's initial displacement\n            % \n            % This function assumes that all rotations are about the same relative coordinate. \n            % If not, the user should input a relative coordinate of 0,0,0 and \n            % use the additional linear displacement parameter to set the cg or location\n            % correctly.\n            %\n            % Parameters\n            % ------------\n            %    relCoord : [1 3] float vector\n            %        Distance from x_rot to the body center of gravity or the constraint\n            %        or pto location as defined by: relCoord = cg - x_rot. [m]\n            %\n            %    axisAngleList : [nAngle 4] float vector\n            %        List of axes and angles of the rotations with the \n            %        format: [n_x n_y n_z angle] (angle in rad)\n            %        Rotations applied consecutively in order of dimension 1\n            %\n            %    addLinDisp : [1 3] float vector\n            %        Initial linear displacement (in addition to the \n            %        displacement caused by rotation) [m]\n            % \n            \n            % initialize quantities before for loop\n            axisList = axisAngleList(:,1:3);\n            angleList = axisAngleList(:,4);\n            nAngle = size(axisList,1);\n            rotMat = eye(3);\n            \n            % Loop through all axes and angles.\n            for i=1:nAngle\n                rotMat = axisAngle2RotMat(axisList(i,:),angleList(i))*rotMat;\n            end\n\n            % calculate net axis-angle rotation\n%             [netAxis, netAngle] = rotMat2AxisAngle(rotMat);\n\n            % calculate net displacement due to rotation\n            rotatedRelCoord = relCoord*(rotMat');\n            linDisp = rotatedRelCoord - relCoord;\n\n            % apply rotation and displacement to object\n            obj.initial.displacement = linDisp + addLinDisp;\n            \n        end\n\n        function listInfo(obj)\n            % This method prints constraint information to the MATLAB Command Window.\n            fprintf('\\n\\t***** Constraint Name: %s *****\\n',obj.name)\n        end\n\n        function setNumber(obj,number)\n            % Method to set the private number property\n            obj.number = number;\n        end\n    end\nend", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/constraintClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23351120190125874}}
{"text": "%     NeuroSLAM System Copyright (C) 2018-2019 \n%     NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n%     Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n%     The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n%     The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n%     Reference:\n%     Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n%     \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n% Jan 2, 2019\ngroundTruthFile = 'C:\\NeuroSLAM_Datasets\\02_NeuroSLAM_Groudtruth\\02_SynPanData_GT.txt';\nexpMapFile = 'C:\\NeuroSLAM_Datasets\\03_NeuroSLAM_Experiments_Results\\SynPanData\\01_exp_map_ml.txt';\n% plot_3d_multilayer_experience_map(groundTruthFile, expMapFile, xExpMapScaling, yExpMapScaling, zExpMapScaling, xExpMapTrans, yExpMapTrans, zExpMapTrans, xGtScaling, yGtScaling, zGtScaling)\nplot_3d_multilayer_experience_map(groundTruthFile, expMapFile, 0.3, -0.35, 0.213, 0.5, 0, 0, 20,20,20);", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/08_draw_fig_for_paper/01_EM_OM/SynPanData/draw_3d_ml_em_synpandata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23346906221893005}}
{"text": "function [resRates] = ma_getResRates(massLoss)\n%getResRates Summary of this function goes here\n%   Detailed explanation goes here\n    maxNumRes = max(horzcat(massLoss.lossConvert.resLost, massLoss.lossConvert.resConvert));\n    resRates = zeros(1,maxNumRes);\n\n    for(i=1:length(massLoss.lossConvert)) %#ok<*NO4LP>\n        lossConvert = massLoss.lossConvert(i);\n        resRates(lossConvert.resLost) = resRates(lossConvert.resLost) - lossConvert.resLostRates(lossConvert.resLost);\n\n        sumRates = sum(lossConvert.resLostRates);\n        resRates(lossConvert.resConvert) = resRates(lossConvert.resConvert) + sumRates*lossConvert.resConvertPercent(lossConvert.resConvert);\n    end\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/ma_getResRates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23346905553266567}}
{"text": "function w = fix_data_length(w, maxlen)\n   %FIX_DATA_LENGTH adjust length of waveform data to allow batch processing\n   %   waveform = fix_data_length(waveform)\n   %       adjusts all waveforms to the length of the largest, while\n   %       zero-padding all shorter waveforms\n   %\n   %   waveform = fix_data_length(waveform, maxlength)\n   %       sets all waveform lengths to maxlength.  This use of the function\n   %       has been superceeded by set(waveform,'samplelength',maxlength);\n   %\n   %  examples\n   %       % let inWaves be a 1x2 waveform object\n   %       % 3000 samples in inWaves(1)\n   %       % 10025 samples in inWaves(2)\n   %\n   %       % set both waves' data to a length of to 10025 while padding the\n   %       % smaller of the two with zeroes.\n   %       outWaveforms = fix_data_length(inWaves)\n   %\n   %       % set both sample lengths to 500 truncating both of them...\n   %       outWaveform = fix_data_length(inWaves, 500)\n   %\n   %       %The above example is nearly the same as\n   %       outWaveform = set(inWaves,'sample_length',500)\n   %\n   %       Behaviorally, this differs from the set command because it\n   %       automatically determines the maximum desired length, when not\n   %       specified.\n   %\n   %\n   % See also WAVEFORM/EXTRACT, WAVEFORM/DOUBLE, WAVEFORM/SET -- Sample_Length\n   \n   % AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks\n   % $Date$\n   % $Revision$\n   \n   % Note: Glenn Thompson 2016 - this function could be simplified by using\n   % waveform/get_time_range and waveform/pad\n   Wcount = numel(w);\n   \n   if ~exist('maxlen','var')\n      m(Wcount) = 0;\n      for j = Wcount : -1 : 1\n         m(j) = numel(w(j).data);\n      end\n      maxlen = max(m);\n   end\n   \n   if length(maxlen) == 2\n      st = maxlen(1);\n      ed = maxlen(2);\n   else\n      st = 1;\n      ed = maxlen(end);\n   end\n   \n   for j = 1 : Wcount\n      D = w(j).data;\n      if ed > numel(D)\n         D(ed) = 0;\n      else\n         D = D(st:ed);\n      end\n      w(j) = set(w(j),'data',D);\n   end;\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@waveform/fix_data_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23346905553266564}}
{"text": "function varargout = pm_restore_ramp(varargin)\n% \n% Restores linear phase-ramps in the x-, y- and z-direction \n% that has previously been removed from pm by pm_estimate_ramp.\n% FORMAT: pm = pm_estimate_ramp(pm,mask,ramps)\n%\n% Input:\n% pm     : 2 or 3D phasemap that has been unwrapped and\n%          that has had its ramps removed by pm_remove_ramp \n% mask   : Mask that indicates which voxels are worth\n%          bothering with and which are not.\n% ramps  : 3x1 vector signifying the slope of the ramps in\n%          the x-, y- and z-directions. This SHOULD be the\n%          values returned by a previous call to pm_estimate_ramp.\n%\n% Output: \n% pm     : Same as pm in, but with linear ramps restored.\n%\n% This routine was written on the suggestion of Mark J, and will \n% potentially improve performance of subsequent phase-unwrapping.\n% I haven't actually found it particularly helpful, and it may\n% simply have been a sneaky fMRIB attempt to delay the SPM \n% phasemap toolbox.\n%__________________________________________________________________\n% Jesper Andersson 30/9-03\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Jesper Andersson \n% $Id: pm_restore_ramp.m 1317 2008-04-08 16:16:38Z chloe $\n\nerror('mex-function pm_restore_ramp.c not compiled');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/FieldMap/pm_restore_ramp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2332463813515838}}
{"text": "function getdepthRefined_structureIO(id)\n%cd /n/fs/sun3d/code/SiftFuv2StructureIO\n%/n/fs/vision/ionicNew/starter.sh getdepthRefined_structureIO 20000mb 120:00:00 1 300 1 /n/fs/modelnet/log/\n\nbasicSetup;\ninterval =20;\nOuputPath = '/n/fs/sun3d/data/SUNRGBDv2/';\nwebtemplate = 'https://sun3d.cs.princeton.edu/player/?name=SUNRGBDv2/%s/&box3D=true&write=true&annotation=annotation3Dfinal&width=640&height=480&R=true&&highlight=false&rect=only';\n%directory ='/net/pvd00/p/sunrgbd/mingrub/data_capture/11082015/single_image/2015-11-08T15.25.26.491/';\ndirectory ='/Users/shurans/Downloads/2015-11-08T15.25.26.491/';\nload(fullfile(directory,'metadata.mat'))\nframeIDtarget = metadata.main_Id;\nfilename = metadata.main_frame(1:end-4);\nfolder = [fullfile(OuputPath,filename) '/'];\n%% get web page link\nwebpagelink = sprintf(webtemplate,filename);\ndisplay(webpagelink)\n\nif ~metadata.bad\n    %% refine the depth\n    [depthRefined, image] = SiftFuv2warpFast(directory,frameIDtarget, interval);\n\n    %% put it into folder \n    mkdir([folder 'annotation/']);\n    mkdir([folder 'annotation3D/']);\n    system(sprintf('chmod -R 777 %sannotation/',folder));\n    system(sprintf('chmod -R 777 %sannotation3D/',folder));\n    mkdir([folder 'depth/']);\n    mkdir([folder 'extrinsics/']);\n    mkdir([folder 'image/']); \n    depth = uint16(depthRefined*1000);\n    depth = bitor(bitshift(depth,3), bitshift(depth,-13));\n    imwrite(depth,sprintf('%s/depth/%s.png',folder,filename));\n    imwrite(image,sprintf('%s/image/%s.jpg',folder,filename));\n    \n    data = loadStructureIOdata(directory,[]);\n    fid = fopen([folder 'intrinsics.txt'],'w');\n    K = data.K';\n    fprintf(fid,'%f %f %f\\n%f %f %f\\n%f %f %f\\n',K(1),K(2),K(3),K(4),K(5),K(6),K(7),K(8),K(9));\n    fclose(fid);\n    %% get extrinsics\n   \n    depth = depthRefined;\n    [x,y] = meshgrid(1:size(depth,2), 1:size(depth,1));\n    XYZcamera(:,:,1) = (x-data.K(1,3)).*depth/data.K(1,1);\n    XYZcamera(:,:,2) = (y-data.K(2,3)).*depth/data.K(2,2);\n    XYZcamera(:,:,3) = depth;\n    XYZcamera(repmat(depth==0,[1,1,3])) = NaN;\n    X = XYZcamera(:,:,1);Y = XYZcamera(:,:,3);Z = -XYZcamera(:,:,2);\n\n    [Rtilt,R] = rectify(cat(3,X,Y,Z));\n    cameraRt =[eye(3) zeros(3,1)];\n    cameraRt(1:3,1:3) =[1 0 0; 0 0 -1 ;0 1 0]*Rtilt*[1 0 0; 0 0 -1 ;0 1 0]';\n    timeStamp = clock;\n    timeStamp = sprintf('%.4d%.2d%.2d%.2d%.2d%.2d',timeStamp(1),timeStamp(2),timeStamp(3),timeStamp(4),timeStamp(5),round(timeStamp(6)));    \n    delete([folder '/extrinsics/*.txt'])\n    fp = fopen([folder '/extrinsics/' timeStamp '.txt'],'w');\n    for rowID=1:size(cameraRt,1)\n        fprintf(fp, '%f %f %f %f\\n',cameraRt(rowID,:));\n    end\n    \n    system(sprintf('chmod -R 775 %s',folder));\n    \n    \nend\n        \n%%\n%{\nif 0 \n    rgb = [reshape(image(:,:,1),[],1),reshape(image(:,:,2),[],1),reshape(image(:,:,3),[],1)];\n    figure,\n    XYZnew = Rtilt*[X(:),Y(:),Z(:)]';\n    vis_point_cloud(XYZnew',double(rgb),40,4000);\nend\npoints2ply('refined.ply', [X(:),Y(:),Z(:)], rgb)\n%}\nend", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/getdepthRefined_structureIO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23324401026916988}}
{"text": "function x=othertriangle(y);\n\nif y(1,1)==1;\n    warning('doesnt work for DIS matrices');\nend\n\nx=y*0;\nif ndims(y)==2;\n    x=y+rot90(flipud(triu(y)),3);\nend\n\nif ndims(y)==3;\n    for n=1:size(y,3);\n        y1=y(:,:,n);\n        x(:,:,n)=y1+rot90(flipud(triu(y1)),3);\n    end\nend\n\nif ndims(y)==4;\n    for n=1:size(y,3);\n        for n1=1:size(y,4);        \n            y1=y(:,:,n,n1);\n            x(:,:,n,n1)=y1+rot90(flipud(triu(y1)),3);\n        end\n    end\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Support_functions/othertriangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2331992246918513}}
{"text": "function acq = acqf_vbmc(Xs,vp,gp,optimState,fmu,fs2,fbar,vtot)\n%ACQF_VBMC Acquisition fcn. for prospective uncertainty search.\n\n% Xs is in *transformed* coordinates\n\n% Probability density of variational posterior at test points\np = max(vbmc_pdf(vp,Xs,0),realmin);\n\n% Prospective uncertainty search\nz = optimState.ymax;\nacq = -vtot .* exp(fbar-z) .* p;\n\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/acq/acqf_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.23313042545421303}}
{"text": "function [K, P] = biasVardistPsi1Compute(biaskern, vardist, Z)\n\n% BIASVARDISTPSI1COMPUTE one line description\n% FORMAT\n% DESC description\n% RETURN K : description\n% RETURN P : description\n% ARG biasKern : the kernel structure associated with the white kernel.\n% ARG vardist : description\n% ARG Z : description\n%\n%\n% SEEALSO : others\n%\n%\n% COPYRIGHT : Michalis K. Titsias, 2009\n%\n\n% VARGPLVM\n\nK = repmat(biaskern.variance,size(vardist.means,1),size(Z,1));\n\nP = [];", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/biasVardistPsi1Compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23308627966055245}}
{"text": "clear;\nclc;\n\ns = iio_sys_obj_matlab; % Constructor\ns.ip_address = '10.66.99.200';\ns.dev_name = 'ad9361';\ns.in_ch_no = 2;\ns.out_ch_no = 2;\ns.in_ch_size = 8192;\ns.out_ch_size = 8192;\n\ns = s.setupImpl();\n\ninput = cell(1, s.in_ch_no + length(s.iio_dev_cfg.cfg_ch));\nFs = 30.72e6;\nFc = 1e6;\nt = 1/Fs:1/Fs:s.in_ch_size/Fs;\nfor i=1:s.in_ch_no\n    input{i} = sin(2*pi*Fc*t+(i-1)*pi/2)*1024;\nend\ninput{s.getInChannel('RX_LO_FREQ')} = 2.4e9;\ninput{s.getInChannel('RX_SAMPLING_FREQ')} = 30.72e6;\ninput{s.getInChannel('RX_RF_BANDWIDTH')} = 18.0e6;\ninput{s.getInChannel('RX1_GAIN_MODE')} = 'slow_attack';\ninput{s.getInChannel('RX1_GAIN')} = 0;\ninput{s.getInChannel('RX2_GAIN_MODE')} = 'slow_attack';\ninput{s.getInChannel('RX2_GAIN')} = 0;\ninput{s.getInChannel('TX_LO_FREQ')} = 2.4e9;\ninput{s.getInChannel('TX_SAMPLING_FREQ')} = 30.72e6;\ninput{s.getInChannel('TX_RF_BANDWIDTH')} = 18.0e6;\n\noutput = cell(1, s.out_ch_no + length(s.iio_dev_cfg.mon_ch));\n\nfor i = 1:5\noutput = stepImpl(s, input);\nrssi1 = output{s.out_ch_no+1};\nrssi2 = output{s.out_ch_no+2};\nend\n\ns.releaseImpl();\n\nfigure % new figure\nax1 = subplot(2,1,1); % top subplot\nax2 = subplot(2,1,2); % bottom subplot\n\nplot(ax1,output{1});\ntitle(ax1,'I');\nxlabel('Sample');\nylabel('Amplitude');\n\nplot(ax2,output{2});\ntitle(ax2,'Q');\nxlabel('Sample');\nylabel('Amplitude');", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/hil_models/legacy/fmcomms2_3_data_stream/ad9361_matlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23308627966055237}}
{"text": "function res = spm_eeg_artefact_nans(S)\n% Plugin for spm_eeg_artefact doing NaN detection\n% S            - input structure\n% fields of S:\n%    S.D       - M/EEG object\n%    S.chanind - vector of indices of channels that this plugin will look at\n%\n%    Additional parameters can be defined specific for each plugin.\n%\n% Output:\n% res -\n%    If no input is provided the plugin returns a cfg branch for itself.\n%\n%    If input is provided the plugin returns a matrix of size D.nchannels x D.ntrials\n%    with zeros for clean channel/trials and ones for artefacts.\n%__________________________________________________________________________\n% Copyright (C) 2011-2017 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: spm_eeg_artefact_nans.m 7132 2017-07-10 16:22:58Z guillaume $\n\n\n%-This part if for creating a config branch that plugs into spm_cfg_eeg_artefact\n% Any parameters can be specified and they are then passed to the plugin\n% when it's called.\n%--------------------------------------------------------------------------\nif nargin == 0\n    nans      = cfg_branch;\n    nans.tag  = 'nans';\n    nans.name = 'Detect NaNs';\n    nans.val  = {};\n    nans.help = {''};\n    \n    res = nans;\n    \n    return\nend\n\nSVNrev = '$Rev: 7132 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('sFnBanner', mfilename, SVNrev);\nspm('FigName','M/EEG NaN detection');\n\nD = spm_eeg_load(S.D);\n\nchanind = S.chanind;\nres = zeros(D.nchannels, D.ntrials);\n\nif isequal(S.mode, 'reject')\n    res = zeros(D.nchannels, D.ntrials);\n    \n    %-Artefact detection\n    %----------------------------------------------------------------------\n    \n    spm_progress_bar('Init', D.ntrials, 'Trials checked');\n    if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials,100));\n    else Ibar = [1:D.ntrials]; end\n    \n    for i = 1:D.ntrials\n        for j = 1:length(chanind)\n            if any(isnan(squeeze(D(chanind(j), :, i))))\n                res(chanind(j), i) = 1;\n            end\n        end\n        if any(Ibar == i), spm_progress_bar('Set', i); end\n    end\n    \n    spm_progress_bar('Clear');\n    \nelseif isequal(S.mode, 'mark')\n    if isequal(D.type, 'continuous')\n        spm_progress_bar('Init', length(chanind), 'Channels checked');\n        if length(chanind) > 100, Ibar = floor(linspace(1, length(chanind),100));\n        else Ibar = [1:length(chanind)]; end\n    else\n        spm_progress_bar('Init', D.ntrials, 'Trials checked');\n        if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials,100));\n        else Ibar = [1:D.ntrials]; end\n    end\n    \n    for i = 1:D.ntrials\n        res = [];\n        for j = 1:length(chanind)\n            dat  = ~isnan(squeeze(D(chanind(j), :, i)));\n            if  sum(dat)/length(dat)<(1-S.badchanthresh)\n                res(end+1).type   = 'artefact_nan';\n                res(end).value    = char(D.chanlabels(chanind(j)));\n                res(end).time     = D.trialonset(i);\n                res(end).duration = D.time(end) - D.time(1) + 1;\n            else\n                tmp  = find(dat);\n                diffs = diff([0 tmp D.nsamples]);\n                onsets = find(diffs>1);\n                \n                onsetsamples = [];\n                if any(onsets == 1);\n                    onsetsamples = 1;\n                    onsets(1)    = [];\n                    onsetsamples = [onsetsamples tmp(onsets-1)+1];\n                    onsets       = [1 onsets];\n                else\n                    onsetsamples = [onsetsamples tmp(onsets-1)+1];\n                end\n                \n                k = 1;\n                m = 1;\n                while k<=length(onsets)\n                    if m <= length(onsets)\n                        ind1 = onsetsamples(k);\n                        ind2 = onsetsamples(m) + diffs(onsets(m))-2;\n                        if ind2 > length(dat)\n                            ind2 = length(dat);\n                        end\n                        if (sum(dat(ind1:ind2))/(ind2-ind1+1))<0.5\n                            m = m+1;\n                        else\n                            if m>k\n                                m = m-1;\n                            end\n                            \n                            res(end+1).type   = 'artefact_nan';\n                            res(end).value    = char(D.chanlabels(chanind(j)));\n                            res(end).time     = D.time(onsetsamples(k)+1) - D.time(1) + D.trialonset(i);\n                            res(end).duration = (onsetsamples(m) + diffs(onsets(m))-onsetsamples(k)-1)/D.fsample;\n                            \n                            k = m+1;\n                            m = k;\n                        end\n                    else\n                        ind1 = onsetsamples(k);\n                        ind2 = length(dat);\n                        if (sum(dat(ind1:ind2))/(ind2-ind1+1))<0.5\n                            res(end+1).type   = 'artefact_nan';\n                            res(end).value    = char(D.chanlabels(chanind(j)));\n                            res(end).time     = D.time(onsetsamples(k)+1) - D.time(1) + D.trialonset(i);\n                            res(end).duration = (length(dat)-onsetsamples(k)+2)/D.fsample;\n                        else\n                            m = m-1;\n                            \n                            res(end+1).type   = 'artefact_nan';\n                            res(end).value    = char(D.chanlabels(chanind(j)));\n                            res(end).time     = D.time(onsetsamples(k)+1) - D.time(1) + D.trialonset(i);\n                            res(end).duration = (onsetsamples(m) + diffs(onsets(m))-onsetsamples(k)-1)/D.fsample;\n                        end\n                        break;\n                    end\n                end\n            end\n            \n            if isequal(D.type, 'continuous')\n                if any(Ibar == j), spm_progress_bar('Set', j); end\n            end\n        end\n        if ~isempty(res)\n            ev = D.events(i);\n            if iscell(ev)\n                ev = ev{1};\n            end\n            \n            if ~S.append\n                ev(strmatch('artefact_nan', {ev.type})) = [];\n            end\n            \n            D = events(D, i, spm_cat_struct(ev, res));\n        end\n        \n        if ~isequal(D.type, 'continuous')\n            if any(Ibar == i), spm_progress_bar('Set', i); end\n        end\n    end\n    \n    spm_progress_bar('Clear');\n    \n    res = D;\nend\n\nspm('FigName','M/EEG NaN detection: done');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_artefact_nans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.233070776074746}}
{"text": "function [d,fp,dt,tc,t]=v_readhtk(file)\n%V_READHTK  read an HTK parameter file [D,FP,DT,TC,T]=(FILE)\n%\n% Input:\n%    FILE = name of HTX file\n% Outputs:\n%       D = data: column vector for waveforms, one row per frame for other types\n%      FP = frame period in seconds\n%      DT = data type (also includes Voicebox code for generating data)\n%             0  WAVEFORM     Acoustic waveform\n%             1  LPC          Linear prediction coefficients\n%             2  LPREFC       LPC Reflection coefficients:  -v_lpcar2rf([1 LPC]);LPREFC(1)=[];\n%             3  LPCEPSTRA    LPC Cepstral coefficients\n%             4  LPDELCEP     LPC cepstral+delta coefficients (obsolete)\n%             5  IREFC        LPC Reflection coefficients (16 bit fixed point)\n%             6  MFCC         Mel frequency cepstral coefficients\n%             7  FBANK        Log Fliter bank energies\n%             8  MELSPEC      linear Mel-scaled spectrum\n%             9  USER         User defined features\n%            10  DISCRETE     Vector quantised codebook\n%            11  PLP          Perceptual Linear prediction\n%            12  ANON\n%      TC = full type code = DT plus (optionally) one or more of the following modifiers\n%               64  _E  Includes energy terms\n%              128  _N  Suppress absolute energy\n%              256  _D  Include delta coefs\n%              512  _A  Include acceleration coefs\n%             1024  _C  Compressed\n%             2048  _Z  Zero mean static coefs\n%             4096  _K  CRC checksum (not implemented yet)\n%             8192  _0  Include 0'th cepstral coef\n%            16384  _V  Attach VQ index\n%            32768  _T  Attach delta-delta-delta index\n%       T = text version of type code e.g. LPC_C_K\n\n%   Thanks to Dan Ellis (ee.columbia.edu) for sorting out decompression.\n%   Thanks to Stuart Anderson (whispersys.com) for making it work on 64 bit machines.\n\n%      Copyright (C) Mike Brookes 2005\n%      Version: $Id: v_readhtk.m 10865 2018-09-21 17:22:45Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfid=fopen(file,'r','b');\nif fid < 0\n    error(sprintf('Cannot read from file %s',file));\nend\nnf=fread(fid,1,'int32');             % number of frames\nfp=fread(fid,1,'int32')*1.E-7;       % frame interval (converted to seconds)\nby=fread(fid,1,'int16');            % bytes per frame\ntc=fread(fid,1,'int16');            % type code (see comments above for interpretation)\ntc=tc+65536*(tc<0);\ncc='ENDACZK0VT';                    % list of suffix codes\nnhb=length(cc);                     % number of suffix codes\nndt=6;                              % number of bits for base type\nhb=floor(tc*pow2(-(ndt+nhb):-ndt));\nhd=hb(nhb+1:-1:2)-2*hb(nhb:-1:1);   % extract bits from type code\ndt=tc-pow2(hb(end),ndt);            % low six bits of tc represent data type\n\n% hd(7)=1 CRC check\n% hd(5)=1 compressed data\nif (dt==5)  % hack to fix error in IREFC files which are sometimes stored as compressed LPREFC\n    fseek(fid,0,'eof');\n    flen=ftell(fid);        % find length of file\n    fseek(fid,12,'bof');\n    if flen>14+by*nf        % if file is too long (including possible CRCC) then assume compression constants exist\n        dt=2;               % change type to LPREFC\n        hd(5)=1;            % set compressed flag\n        nf=nf+4;            % frame count doesn't include compression constants in this case\n    end\nend\n\nif any(dt==[0,5,10])        % 16 bit data for waveforms, IREFC and DISCRETE\n    d=fread(fid,[by/2,nf],'int16').';\n    if ( dt == 5),\n        d=d/32767;                    % scale IREFC\n    end\nelse\n    if hd(5)                            % compressed data - first read scales\n        nf = nf - 4;                    % frame count includes compression constants\n        ncol = by / 2;\n        scales = fread(fid, ncol, 'float');\n        biases = fread(fid, ncol, 'float');\n        d = ((fread(fid,[ncol, nf], 'int16')+repmat(biases,1,nf)).*repmat(1./scales,1,nf)).';\n    else                              % uncompressed data\n        d=fread(fid,[by/4,nf],'float').';\n    end\nend;\nfclose(fid);\nif nargout > 4\n    ns=sum(hd);                 % number of suffixes\n    kinds={'WAVEFORM' 'LPC' 'LPREFC' 'LPCEPSTRA' 'LPDELCEP' 'IREFC' 'MFCC' 'FBANK' 'MELSPEC' 'USER' 'DISCRETE' 'PLP' 'ANON' '???'};\n    t=[kinds{min(dt+1,length(kinds))} reshape(['_'*ones(1,ns);cc(hd>0)],1,2*ns)];\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_readhtk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2330707706760253}}
{"text": "function computeAllPredictionTime_HN(pathModels,pathResults,training,param,maxOrder,nBoot,seed)\n% -------------------------------------------------------------------------\n% function computeAllPrediction_HN(pathModels,pathResults,training,param,maxOrder,nBoot,imbalance,batchNum)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes prediction performance estimation for a given \n% feature set type, and for all model orders of all experiments with \n% different degrees of freedom. See ref. [1,2] for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n%     early prediction of different tumour outcomes in head and neck cancer.\n%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n%     doi:\n% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 2. pathModels: Full path to the Models folder of the corresponding experiment.\n%                --> Ex: '/myProject/WORKSPACE/COHORT-BASED-RESULTS/Experiment1/MODELS'\n% 2. pathResults: Full path to the Results folder of the corresponding experiment.\n%                --> Ex: '/myProject/WORKSPACE/COHORT-BASED-RESULTS/Experiment1/RESULTS'\n% 3. training: Structure defining all parameters for the given experiment \n%              to perform. See masterScript_HN.m for more details.\n% 4. param: Cell of two strings, defining 1) The feature set type/name; and\n%           2) the outcome to model\n% 5. maxOrder: Integer specifying the maximal model order to construct.\n%              --> Ex: 10\n% 6. nBoot: Number of bootstrap samples to use.\n%           --> Ex: 100\n% 7. imbalance: String specifying the type of imbalance-adjustement strategy\n%               employed. Either 'IABR' for imbalance-adjusted bootstrap\n%               resampling (see ref.[1]), or 'IALR' for imbalance-adjusted\n%               logistic regression (see ref.[2]).\n%               --> Ex: 'IALR'\n% 8. batchNum: (optional input). If present, integer that specifies the\n%              batch number for parallelization purposes.\n%              --> Ex: 6\n% -------------------------------------------------------------------------\n% OUTPUTS: Prediction performance results are saved in a folder named 'RESULTS' in the\n% corresponding folder of each experiment (e.g. 'Experiment1', 'Experiment2', etc.)\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: July 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\nwarning off\n\ncd(pathModels)\nfSetName = param{1};\noutcomeName = param{2};\noutcome = training.(outcomeName).timeToEvent;\ncensoring = 1 - training.(outcomeName).outcome;\nmodels = load(['MODELS_',fSetName,'_',outcomeName]); models = struct2cell(models); models = models{1};\n\ntic\nfprintf(['\\n --> COMPUTING PREDICTION PERFORMANCE (MODEL ORDERS OF 1 to % u) FOR  \"',fSetName,'\" FEATURE SET AND \"',outcomeName,'\" OUTCOME ... '],maxOrder)\nfor j = 1:maxOrder\n    orderName = ['Order',num2str(j)];\n    data = models.(orderName).Data;\n    [orderResults] = predictionPerformanceEstimationTime_HN(data,outcome,nBoot,censoring,seed);\n    results.(orderName) = orderResults;\n    results.(orderName).Data = models.(orderName).Data;\n    results.(orderName).Name = models.(orderName).Name;\nend\ncd(pathResults), save(['RESULTS_',fSetName,'_',outcomeName],'results')\nfprintf('DONE!\\n'), toc\n\ncd(startpath)\nend\n", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/computeAllPredictionTime_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23305799344395411}}
{"text": "function [] = anim8_DIC_image_3Dmeasure_points_2n(ImSet,DIC2DpairResults,DIC3DpairResults,faceMeasureString,varargin)\n%% function for plotting 2D-DIC results imported from Ncorr in step 2\n% called inside plotNcorrPairResults\n% plotting the images chosen for stereo DIC (2 views) with the\n% correlated points results plotted on top, colored as their correlation\n% coefficient.\n% on the left side the images from the reference camera (reference image and current images), and on the right side the\n% images from the deformed camera\n% requirements: GIBBON toolbox\n%\n%\n% INPUT:\n% * IMset - a 2nX1 cell array containing 2n grayscale images. The first n\n% images are from camera A (the \"reference\" camera), and the last n images\n% are from camera B (the \"deformed\" camera). The first image in the set is\n% considered as the reference image, on which the reference grid of points\n% is defined, and all the correlated points and consequent displacements\n% and strains, are relative to this image.\n% * DIC_2Dpair_results - containig the correlated points, correlation\n% coefficients, faces..\n% * optional: CorCoeffCutOff - - maximal correlation coefficient to plot\n% points\n% * optional: CorCoeffDispMax - maximal correlation coefficient in colorbar\n\n%%\nDIC2DpairResultsL=DIC2DpairResults{1};\nDIC2DpairResultsR=DIC2DpairResults{2};\nDIC3DpairResultsL=DIC3DpairResults{1};\nDIC3DpairResultsR=DIC3DpairResults{2};\n\nnImages=DIC2DpairResultsL.nImages;\nnCam=DIC2DpairResultsL.nCamDef;\n\nPointsL=DIC2DpairResultsL.Points(nImages+1:end);\nPointsR=DIC2DpairResultsR.Points(1:nImages);\nCorCoeffVecL=DIC2DpairResultsL.CorCoeffVec(nImages+1:end);\nCorCoeffVecR=DIC2DpairResultsR.CorCoeffVec(1:nImages);\n\nswitch nargin\n    case 4 % in case no results were entered\n        optStruct=struct;\n    case 5\n        optStruct=varargin{1};\n    otherwise\n        error('wrong number of input arguments');\nend\n\n%% cut out point with large correlation coefficient\nif ~isfield(optStruct,'CorCoeffCutOff')\n    CorCoeffCutOff=max([cell2mat(CorCoeffVecL); cell2mat(CorCoeffVecR)]);\nelse\n    CorCoeffCutOff=optStruct.CorCoeffCutOff;\nend\n\nfor ii=1:nImages\n    CorCoeffVecL{ii}(CorCoeffVecL{ii}>CorCoeffCutOff)=NaN;   \n    CorCoeffVecR{ii}(CorCoeffVecR{ii}>CorCoeffCutOff)=NaN;  \nend\n\n\n%%\nswitch faceMeasureString\n    case {'DispMgn'}\n        PCL=DIC3DpairResultsL.Disp.DispMgn;  \n        PCR=DIC3DpairResultsR.Disp.DispMgn;  \n        cMap='jet';\n     case {'DispX'}\n         for ii=1:nImages\n             PCL{ii,1}=DIC3DpairResultsL.Disp.DispVec{ii}(:,1);\n             PCR{ii,1}=DIC3DpairResultsR.Disp.DispVec{ii}(:,1);\n         end\n         cMap='jet';\n    case {'DispY'}\n        for ii=1:nImages\n            PCL{ii,1}=DIC3DpairResultsL.Disp.DispVec{ii}(:,2);\n            PCR{ii,1}=DIC3DpairResultsR.Disp.DispVec{ii}(:,2);\n        end\n        cMap='jet';\n    case {'DispZ'}\n        for ii=1:nImages\n            PCL{ii,1}=DIC3DpairResultsL.Disp.DispVec{ii}(:,3);\n            PCR{ii,1}=DIC3DpairResultsR.Disp.DispVec{ii}(:,3);\n        end\n        cMap='jet';\n    otherwise\n        error('unexpected face measure string. plots not created');\nend\n\n\n%%\n\nif ~isfield(optStruct,'PClimits')    \n    PCmin=0;\n    PCmax=0;\n    for ii=1:nImages\n        PCmin=min([min(PCL{ii}(~isnan(CorCoeffVecL{ii}))) min(PCL{ii}(~isnan(CorCoeffVecL{ii}))) PCmin]);\n        PCmax=max([max(PCR{ii}(~isnan(CorCoeffVecR{ii}))) max(PCR{ii}(~isnan(CorCoeffVecR{ii}))) PCmax]);\n    end\n    PClimits=[PCmin PCmax];\nelse\n    PClimits=optStruct.PClimits;\nend\n\n%%\nhf=figure; hold all;\nhf.Units='normalized'; hf.OuterPosition=[.05 .05 .9 .9]; hf.Units='pixels';\n\nii=1;\nhp1=imagesc(repmat(ImSet{ii},1,1,3)); hold on; axis ij\nPL=PointsL{ii}(~isnan(CorCoeffVecL{ii}),:);\nPR=PointsR{ii}(~isnan(CorCoeffVecR{ii}),:);\nhp2=scatter(PL(:,1),PL(:,2),6,PCL{ii}(~isnan(CorCoeffVecL{ii})),'+');\nhp3=scatter(PR(:,1),PR(:,2),6,PCR{ii}(~isnan(CorCoeffVecR{ii})),'+');\npbaspect([size(ImSet{ii},2) size(ImSet{ii},1) 1])\nhs1=title(['Cam ' num2str(nCam) ' frame ' num2str(1)]);\ncolormap(cMap);\nhc1=colorbar;\ncaxis(PClimits)\ntitle(hc1, faceMeasureString);\nhc1.FontSize=16;\naxis off\ndrawnow\n\n%Create the time vector\nanimStruct.Time=linspace(0,1,nImages);\n\nfor ii=1:nImages\n    xNowL=PointsL{ii}(~isnan(CorCoeffVecL{ii}),1);\n    yNowL=PointsL{ii}(~isnan(CorCoeffVecL{ii}),2);\n    xNowR=PointsR{ii}(~isnan(CorCoeffVecR{ii}),1);\n    yNowR=PointsR{ii}(~isnan(CorCoeffVecR{ii}),2);\n    \n    cNowL=PCL{ii};\n    cNowR=PCR{ii};\n    \n    TitleNow=['Cam ' num2str(nCam) ' frame ' num2str(ii)];\n    \n    %Set entries in animation structure\n    animStruct.Handles{ii}=[hp1,hp2,hp2,hp2,hp3,hp3,hp3,hs1]; %Handles of objects to animate\n    animStruct.Props{ii}={'CData','XData','YData','CData','XData','YData','CData','String'}; %Properties of objects to animate\n    animStruct.Set{ii}={repmat(ImSet{ii},1,1,3),xNowL,yNowL,cNowL,xNowR,yNowR,cNowR,TitleNow}; %Property values for to set in order to animate\n    \nend\n\nanim8(hf,animStruct);\n\nend\n\n%% \n% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation\n% \n% License: <https://github.com/MultiDIC/MultiDIC/blob/master/LICENSE.txt>\n% \n% Copyright (C) 2018  Dana Solav\n% \n% If you use the toolbox/function for your research, please cite our paper:\n% <https://engrxiv.org/fv47e>", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_MultiDIC/anim8_DIC_image_3Dmeasure_points_2n.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23290147381767423}}
{"text": "dtDirs = {'/biac3/wandell4/data/reading_longitude/dti_adults/ak090724/dti40trilin/'...\n    '/biac3/wandell4/data/reading_longitude/dti_adults/am090121/dti06trilinrt/'...\n    '/biac3/wandell4/data/reading_longitude/dti_adults/rfd080930/dti06trilinrt/'};\n\nBPFDirs = {'/biac3/wandell5/data/relaxometry/ak090721/trilin_ak_2mms'...\n    '/biac3/wandell5/data/relaxometry/am_090126/trilin2mml'...\n    '/biac3/wandell5/data/relaxometry/rb_090716/trilin_rb_2mms'};\n\nsub={'ak' 'am' 'rfd'}\n\nfor j=1:1%2 %1.5T or 3T anatomy\n    for i=2:2%length(sub),\n        name3T=sub{i};\n        name15T=[sub{i} '1_5'];\n        path3=['/biac3/wandell5/data/relaxometry/100405HLF3T/anal/' name3T 'lin_2mms1/'];\n        path15=['/biac3/wandell5/data/relaxometry/100405HLF3T/anal/' name15T 'lin_2mms'];%Nbs1\n\n        if j==1,\n            path=path15;\n        elseif j==2\n            path=path3;\n        end;\n        %%% load maps  %%%\n        hlf=niftiRead([path '/HLF_F.nii.gz']);\n        t1=niftiRead([path '/T1_LFit_F.nii.gz']);\n        T1hWf=niftiRead([path '/T1fh_F.nii.gz']);\n        wf=niftiRead([path '/Wf_F.nii.gz']);\n        dt = dtiLoadDt6(fullfile(dtDirs{i},'dt6'));\n        bpf=niftiRead(fullfile(BPFDirs{i},'f.nii.gz'));\n       Class=niftiRead([path15 '/T1_class2mm.nii.gz']);\n       \n%        t1=t1.data;\n%        hlf=hlf.data;\n%        wf=wf.data;\n%        T1hWf=T1hWf.data;\n%        bpf=bpf.data;\n%        \n      [eigVec,eigVal] = dtiEig(dt.dt6);\n    [fa,md,rd] = dtiComputeFA(eigVal);\n    [cl, cp, cs] = dtiComputeWestinShapes(eigVal);\n\n%       we will make wm masks for the maps\n\nmaskAnat=find(Class.data==3 | Class.data==4);\n\nif(~all(dt.xformToAcpc(:)==Class.qto_xyz(:)))\n    maskR= mrAnatResliceSpm(double(Class.data),inv(Class.qto_xyz),dt.bb,dt.mmPerVoxel,1);\n    maskDif=find(maskR==3 | maskR==4);\n    clear maskR;\n\nelse\n    maskDif=maskAnat;\nend;\n\n%compute means andsd's for each measure within white matter mask\nfa_std=std(fa(maskDif(~isnan(fa(maskDif)))));\nrd_std=std(rd(maskDif(~isnan(rd(maskDif)))));\nmd_std=std(md(maskDif(~isnan(md(maskDif)))));\ncl_std=std(cl(maskDif(~isnan(cl(maskDif)))));\n\nhlf_std=std(hlf.data(maskAnat(~isnan(hlf.data(maskAnat)))));\nwf_std=std(wf.data(maskAnat(~isnan(wf.data(maskAnat)))));\nt1_std=std(t1.data(maskAnat(~isnan(t1.data(maskAnat)))));\nT1hWf_std=std(T1hWf.data(maskAnat(~isnan(T1hWf.data(maskAnat)))));\nbpf_std=std(bpf.data(maskAnat(~isnan(bpf.data(maskAnat)))));\n\nfa_mean=mean(fa(maskDif(~isnan(fa(maskDif)))));\nrd_mean=mean(rd(maskDif(~isnan(rd(maskDif)))));\nmd_mean=mean(md(maskDif(~isnan(md(maskDif)))));\ncl_mean=mean(fa(maskDif(~isnan(cl(maskDif)))));\n\n\nhlf_mean=mean(hlf.data(maskAnat(~isnan(hlf.data(maskAnat)))));\nwf_mean=mean(wf.data(maskAnat(~isnan(wf.data(maskAnat)))));\nt1_mean=mean(t1.data(maskAnat(~isnan(t1.data(maskAnat)))));\nT1hWf_mean=mean(T1hWf.data(maskAnat(~isnan(T1hWf.data(maskAnat)))));\nbpf_mean=mean(bpf.data(maskAnat(~isnan(bpf.data(maskAnat)))));\n\n\n\n\n\n%load morigroups and rois\n%fg will contain all mori groups\nfbDir=[dtDirs{i} 'fibers/MoriGroups'];\n\nfg=dtiReadFibers(fbDir)\n\nroiDir=[dtDirs{i} 'ROIs'];\n\nfgName(3)={'Left Cortico-Spinal'};\nroi1{3}=dtiReadRoi(fullfile(roiDir,'CST_roi1_L'));\nroi2{3}=dtiReadRoi(fullfile(roiDir,'CST_roi2_L'));\nfgName(4)={'Right Cortico-Spinal'};\nroi1{4}=dtiReadRoi(fullfile(roiDir,'CST_roi1_R'));\nroi2{4}=dtiReadRoi(fullfile(roiDir,'CST_roi2_R'));\nfgName(11)={'Left Inferior Fronto-Occ'};\nroi1{11}=dtiReadRoi(fullfile(roiDir,'IFO_roi1_L'));\nroi2{11}=dtiReadRoi(fullfile(roiDir,'IFO_roi2_L'));\nfgName(12)={'Right Inferior Frontal-Occ'};\nroi1{12}=dtiReadRoi(fullfile(roiDir,'IFO_roi1_R'));\nroi2{12}=dtiReadRoi(fullfile(roiDir,'IFO_roi2_R'));\nfgName(13)={'Left Inferior Longitude'};\nroi1{13}=dtiReadRoi(fullfile(roiDir,'ILF_roi1_L'));\nroi2{13}=dtiReadRoi(fullfile(roiDir,'ILF_roi2_L'));\nfgName(14)={'Right Inferior Longitude'};\nroi1{14}=dtiReadRoi(fullfile(roiDir,'ILF_roi1_R'));\nroi2{14}=dtiReadRoi(fullfile(roiDir,'ILF_roi2_R'))\nfgName(19)={'Left Arcuate'};\nroi1{19}=dtiReadRoi(fullfile(roiDir,'SLF_roi1_L'));\nroi2{19}=dtiReadRoi(fullfile(roiDir,'SLFt_roi2_L'));\nfgName(20)={'Right Arcuate'};\nroi1{20}=dtiReadRoi(fullfile(roiDir,'SLF_roi1_R'));\nroi2{20}=dtiReadRoi(fullfile(roiDir,'SLFt_roi2_R'));\n%compute properties on tract trajectory for the specific fiber goups of\n%interest\n\ngroups=[3  11  13  19 4 12 14 20];\nfor ii=groups;\n    %compute fa and md along the trajectory of the fiber group as a\n    %weighted average of fa and md at each fiber\n    [fa_ md_ rd_ d cl_]=dtiComputeDiffusionPropertiesAlongFG(fg(ii), dt, roi1{ii}, roi2{ii}, 30);\n    %clip fiber group between 2 rois to obtain core segment\n    fgClipped = dtiClipFiberGroupToROIs(fg(ii),roi1{ii},roi2{ii});\n    %compute quantitative measures along trajectory of fiber group\n    [hlf_, SuperFiber, weightsNormalized] =dtiFiberGroupPropertyWeightedAverage(fgClipped, hlf, 30,'image');\n    [wf_, SuperFiber, weightsNormalized] =dtiFiberGroupPropertyWeightedAverage(fgClipped, wf, 30,'image');\n    [t1_, SuperFiber, weightsNormalized] =dtiFiberGroupPropertyWeightedAverage(fgClipped, t1, 30,'image');\n    [T1hWf_, SuperFiber, weightsNormalized] =dtiFiberGroupPropertyWeightedAverage(fgClipped, T1hWf, 30,'image');\n    [bpf_, SuperFiber, weightsNormalized] =dtiFiberGroupPropertyWeightedAverage(fgClipped, bpf, 30,'image');\n    \n\n   \n    %Standardize measures based on variance within white matter mask\n    faZ=((fa_-fa_mean)./fa_std);\n    rdZ=((rd_-rd_mean)./rd_std);\n    mdZ=((md_-md_mean)./md_std);\n    clZ=((cl_-cl_mean)./cl_std);\n\n\n    hlfZ=(hlf_-hlf_mean)./hlf_std;\n    T1hWfZ=(T1hWf_-T1hWf_mean)./T1hWf_std;\n    t1Z=(t1_-t1_mean)./t1_std;\n    wfZ=(wf_-wf_mean)./wf_std;\n    bpfZ=(bpf_-bpf_mean)./bpf_std;\n\n    %Make plot for fiber group ii\n    figure(ii);\n     subplot(2,4,find(groups==ii));\n    \n       subplot(2,1,1);\n   plot(horzcat(faZ,rdZ,mdZ,clZ),'LineWidth',2);axis([0 30 -2 2]);title([sub{i} 'Dif' fgName{ii}])\n         legend('fa', 'rd', 'md', 'cl');ylabel('Z Score');\n   subplot(2,1,2);\n    plot(horzcat(hlfZ,T1hWfZ,t1Z,wfZ,bpfZ),'LineWidth',2);axis([0 30 -2 2]);title([sub{i} 'Anat' fgName{ii}])\n   %if find(groups==ii)==1 | find(groups==ii)==5\n        legend( 'hlf', 'T1hWf', 't1', 'wf' ,'bpf'); ylabel('Z Score');\n   % end\n\nend\n\n\n\n\n\n\n    end\n    \n    \nend;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/stats/fiberStat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23290147381767423}}
{"text": "function opts = init_LapSRN_opts(scale, depth, gpu)\n% -------------------------------------------------------------------------\n%   Description:\n%       Generate model options for LapSRN\n%\n%   Input:\n%       - scale : SR upsampling scale\n%       - depth : number of conv layers in one pyramid level\n%       - gpu   : GPU ID, 0 for CPU mode\n%\n%   Output:\n%       - opts  : options for LapSRN\n%\n%   Citation: \n%       Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution\n%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang\n%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017\n%\n%   Contact:\n%       Wei-Sheng Lai\n%       wlai24@ucmerced.edu\n%       University of California, Merced\n% -------------------------------------------------------------------------\n\n    %% network options\n    opts.scale              = scale;\n    opts.depth              = depth;\n    opts.weight_decay       = 0.0001;\n    opts.init_sigma         = 0.001;\n    opts.conv_f             = 3;\n    opts.conv_n             = 64;\n    opts.loss               = 'L1';\n\n    %% training options\n    opts.gpu                = gpu;\n    opts.batch_size         = 64;\n    opts.num_train_batch    = 100;     % number of training batch in one epoch\n    opts.num_valid_batch    = 100;      % number of validation batch in one epoch\n    opts.lr                 = 1e-5;     % initial learning rate\n    opts.lr_step            = 50;       % number of epochs to drop learning rate\n    opts.lr_drop            = 0.5;      % learning rate drop ratio\n    opts.lr_min             = 1e-6;     % minimum learning rate\n    opts.patch_size         = 128;\n    opts.data_augmentation  = 1;\n    opts.scale_augmentation = 1;\n\n    %% dataset options\n    opts.train_dataset          = {};\n    opts.train_dataset{end+1}   = 'T91';\n    opts.train_dataset{end+1}   = 'BSDS200';\n    %opts.train_dataset{end+1}   = 'General100';\n    opts.valid_dataset          = {};\n    %opts.valid_dataset{end+1}   = 'Set5';\n    %opts.valid_dataset{end+1}   = 'Set14';\n    opts.valid_dataset{end+1}   = 'BSDS100';\n\n\n    %% setup model name\n    opts.data_name = 'train';\n    for i = 1:length(opts.train_dataset)\n        opts.data_name = sprintf('%s_%s', opts.data_name, opts.train_dataset{i});\n    end\n\n    opts.net_name = sprintf('LapSRN_x%d_depth%d_%s', ...\n                            opts.scale, opts.depth, opts.loss);\n\n    opts.model_name = sprintf('%s_%s_pw%d_lr%s_step%d_drop%s_min%s_bs%d', ...\n                            opts.net_name, ...\n                            opts.data_name, opts.patch_size, ...\n                            num2str(opts.lr), opts.lr_step, ...\n                            num2str(opts.lr_drop), num2str(opts.lr_min), ...\n                            opts.batch_size);\n\n\n    %% setup dagnn training parameters\n    if( opts.gpu == 0 )\n        opts.train.gpus     = [];\n    else\n        opts.train.gpus     = [opts.gpu];\n    end\n    opts.train.batchSize    = opts.batch_size;\n    opts.train.numEpochs    = 1000;\n    opts.train.continue     = true;\n    opts.train.learningRate = learning_rate_policy(opts.lr, opts.lr_step, opts.lr_drop, ...\n                                                   opts.lr_min, opts.train.numEpochs);\n\n    opts.train.expDir = fullfile('models', opts.model_name) ; % model output dir\n    if( ~exist(opts.train.expDir, 'dir') )\n        mkdir(opts.train.expDir);\n    end\n\n    opts.train.model_name       = opts.model_name;\n    opts.train.num_train_batch  = opts.num_train_batch;\n    opts.train.num_valid_batch  = opts.num_valid_batch;\n    \n    % setup loss\n    opts.level = ceil(log(opts.scale) / log(2));\n    opts.train.derOutputs = {};\n    for s = opts.level : -1 : 1\n        opts.train.derOutputs{end+1} = sprintf('level%d_%s_loss', s, opts.loss);\n        opts.train.derOutputs{end+1} = 1;\n    end\n\n\nend", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/init_LapSRN_opts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23290147381767423}}
{"text": "function lvPerfTable = getLVPerfTable(lvDef, liftoffUt)\n    lvPerfTable = [];\n    lvDefCumData = getStageData(lvDef);\n    startUt = liftoffUt;\n    for(i=1:size(lvDefCumData,1)) %#ok<*NO4LP>\n        row = lvDefCumData(i,:);\n        coastDur = row(8);\n        coastStart = startUt + row(1);\n        endUt = startUt + row(1) + coastDur;\n        thrust = row(2);\n        mdot = row(3);\n        massStart = row(4);\n        massEnd = row(5);\n        dryMassCum = row(6);\n        fuMassCum = row(7);\n        cDa = row(9);\n        \n        lvPerfTable(i,:) = [startUt, endUt, thrust, mdot, massStart, massEnd, dryMassCum, fuMassCum, coastStart, cDa]; %#ok<AGROW>\n        startUt = endUt;\n    end    \n    \n    lvPerfTable(end+1,:) = lvPerfTable(end,:);\n    lvPerfTable(end, 1) = lvPerfTable(end-1, 2);\n    lvPerfTable(end, 2) = Inf;\n    lvPerfTable(end, 3) = 0.0;\n    lvPerfTable(end, 4) = 0.0;    \n    lvPerfTable(end, 5) = lvPerfTable(end-1, 6);\n    lvPerfTable(end, 6) = lvPerfTable(end, 5);\n    lvPerfTable(end, 7) = lvPerfTable(end-1, 7);\n    lvPerfTable(end, 8) = 0.0;\n    lvPerfTable(end, 9) = Inf;\n    lvPerfTable(end, 10) = 0.0;", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/launch_traj/getLVPerfTable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23290147381767423}}
{"text": "function [f,model] = penlab_callback_f(x,model)\n\nglobal latest_x_f\nglobal latest_df\n\nx = x(:);\n[f,latest_df] = fmincon_fun(x,model);\nlatest_x_f = x;", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/penlab_callback_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.566018549837479, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2326963780252172}}
{"text": "function [rsamobjects, ah]=plotrsam(sta, chan, snum, enum, DATAPATH)\n% [rsamobjects, ah]=plotrsam_wrapper(sta, chan, snum, enum, DATAPATH)\n% \n%   Inputs:\n%       sta - station code\n%       chan - channel code\n%       snum - start datenum\n%       enum - end datenum\n%       DATAPATH - path to data, including pattern\n%\n%   Outputs:\n%       rsamobjects - vector of rsam objects\n%       ah - vector of axes handles\n%\n%   Examples:\n%       1. Data from the digital seismic network, Montserrat\n%           DP = fullfile('/raid','data','antelope','mvo','SSSS_CCC_YYYY.DAT');\n%           [rsamobjects, ah] = rsam.plotrsam('MBWH','SHZ',datenum(2001,2,24), datenum(2001,3,3), DP);\n%       2. Data from the analog seismic network, Montserrat\n%           DP = fullfile(DROPBOX, 'DOME', 'SEISMICDATA', 'RSAM_1', 'SSSSYYYY.DAT');\n%           [rsamobjects, ah] = rsam.plotrsam('MWHZ','',datenum(1996,7,1), datenum(1996,8,13), DP);\n%   Could use the following logic in a wrapper to decide DP:\n%       strfind(sta{i},'MB') & ~strcmp(sta{i},'MBET')\n\n    % validate\n    if nargin ~= 5\n        help rsam>plotrsam()\n        return\n    end\n\n    % initialise\n    if ~iscell(sta)\n        sta={sta};\n    end\n    if ~iscell(chan)\n        chan={chan};\n    end\n    numsta = length(sta);\n    numrsams = 0;\n    rsamobjects = [];\n    ah = [];\n\n    % load data\n    for i=1:numsta\n        s = rsam('file', DATAPATH, 'snum', snum, 'enum', enum, 'sta', sta{i},'chan',chan{i});\n        if ~isempty(s.data)\n            numrsams = numrsams + 1;\n            rsamobjects = [rsamobjects resample(s.despike(100))];\n            %ah(i)=subplot(numsta,1,i),plot(resample(s.despike(10)));\n        end\n    end\n\n    % plot data\n    if numrsams > 0\n        figure\n        for i=1:numrsams\n            ah(i) = subplot(numrsams, 1, i), plot(rsamobjects(i))\n        end\n        linkaxes(ah, 'x')\n        %datetick('x','keeplimits')\n    end\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@rsam/obsolete/plotrsam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.232634163901469}}
{"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n% This is a testing environment for the files in the folder kernel/numerics\n% 1. Based on data/contents, a list of required files is generated and it \n%    is verified, that all files are present; additional files are listed.\n% 2. All c-files are compiled.\n% 3. All files are executed.\n%==============================================================================\n\nFAIRcheckFiles(mfilename);\ntestEnd;\n\n%==============================================================================\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/numerics/testNumerics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.232634163901469}}
{"text": "function [c] = datasets_feature(dataset_names, train_lists, test_lists, feature, c)\n%\n% Copyright Aditya Khosla http://mit.edu/khosla\n%\n% Please cite this paper if you use this code in your publication:\n%   A. Khosla, J. Xiao, A. Torralba, A. Oliva\n%   Memorability of Image Regions\n%   Advances in Neural Information Processing Systems (NIPS) 2012\n%\n\nif(~exist('c', 'var'))\n  c = conf();\nend\n\nif (~exist('OCTAVE_VERSION','builtin'))\n    openPool(c.cores);\nend\n\nif(c.common_dictionary)\n    c.feature_config.(feature).dictionary = build_dictionary(train_lists, feature, c);\nend\ncache_folder = c.cache;\nidx = randperm(length(train_lists));\n\nfor j=1:length(train_lists)\n  i = idx(j);\n  vprintf(c.verbosity, 0, 'Dataset: %s\\n', dataset_names{i});\n  c.cache = [cache_folder '/' dataset_names{i} '/'];\n\n  if(~c.common_dictionary)\n      c.feature_config.(feature).dictionary = build_dictionary(train_lists{i}, feature, c);\n  end\n  \n  batch_feature(train_lists{i}, 'train', feature, c);\n  batch_feature(test_lists{i}, 'test', feature, c);\nend\n\nc.cache = cache_folder;\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/util/datasets_feature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23257594661276054}}
{"text": "%% Point Cloud Viewer (OpenCV)\n%\n% Display point cloud image using OpenCV.\n%\n% Copyright 2012 The MathWorks, Inc.\n\n\n%% Input Signals\n%\n% * Pause (boolean): Pause point cloud image (1: Pause / 0: Not pause).\n%\n% * Pos (int32): Start position of XYZ and Image input pixel data ([y x]).\n% Note that Pos is zero index based. \n%\n% * XYZ (double): XYZ data of points.\n%\n% * Image (uint8): RGB data of points.\n%\n% * View (double): View point ([x y z]). View input is available when \"Set view point by input\" block parameter was checked.\n%\n\n%% Output Signals\n%\n% * Image (uint8): RGB point cloud image. Image is available when \"Image output\" block parameter was checked.\n%\n\n%% Block Parameters\n%\n% * Window size: Size of Point Cloud Viewer window\n%\n% * Frame size: Size of XYZ and Image input data ([rows colums]).\n%\n% * Full frame size: Size of whole XYZ and Image data ([rows colums]).\n%\n% * Background color: Background color (R G B).\n%\n% * Look at point: Look at point of point cloud image ([x y z]).  \n%\n% * Set view point by Input: Configure view point is set by an input signal or keyboard input (ON: Input signal / OFF: Keyboard input).\n%\n% Note that when this parameter was OFF, view point can be changed by keyboard input while point cloud display window is active.\n%\n% Note that keyboard input is not case sensitive.  \n%\n% - Press R(r) : Initial view point\n%\n% - Press K(k) : +y\n%\n% - Press J(j) : -y\n%\n% - Press H(h) : +x\n%\n% - Press L(l) : -x\n%\n% - Press I(i)  : +z\n%\n% - Press M(m): -z\n%\n% * Initial view point: Initial view point when \"Set view point by Input\" parameter was OFF ([x y z]). \n%\n% * View point step: View point step for keyboard input. Step value has to be greater than zero.\n% \n% * Camera distortion coefficients: The input vector of camera distortion coefficients ([k1 k2 p1 p2 k3]) Zero value means no distortion.\n%\n% * Image output: Configure output of point cloud image (ON: Image output/OFF:No image output).\n%\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36803-simulink-for-pcv-point-cloud-viewer/slpcv/Lib/doc_en/slpcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23257594661276054}}
{"text": "clear all;\nclose all;\nclc;\nspx.cluster.ssc.util.bench_subspace_preservation(@ssc_nn_omp, 'ssc_nn_omp');\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/ssc_subspace_preservation_test/bench_ssc_nn_omp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257594661276051}}
{"text": "function camBV2Scheme(bval_filename,bvec_filename,scheme_filename)\n%Converts mrVIsta b-values and vectors to the camino scheme format\n%\n%   camBV2Scheme(bval_filename,bvec_filename,scheme_filename)\n%\n%\n% (c) Stanford Vista, Sherbondy, 2010\n\nbvec_opt = [' -bvecfile ' bvec_filename];\nbval_opt = [' -bvalfile ' bval_filename];\n\n% First, guess at what units the bvals are in as camino expects kg,s,m\n% units or specifically s/m^2 and we often get them in two other standard \n% forms, e.g., b=800 (s/mm^2) or b = 0.8 (ms/micron^2)\nb = dlmread(bval_filename);\nif any(b>100)\n    bscale = '1E6';\nelse\n    bscale = '1E9';\nend\n\nxform_opt = [' -bscale ' bscale ' -flipz -flipy -flipx '];\n\n% Has to be scheme2 format so lets strip any provided extension\n[pathstr, name, ext] = fileparts(scheme_filename);\nscheme_filename = fullfile(pathstr,[name '.scheme2']);\nscheme_opt = [' > ' scheme_filename];\n\ncmd = ['fsl2scheme' bvec_opt bval_opt xform_opt  scheme_opt];\n\ndisplay(cmd);\nsystem(cmd,'-echo');\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/camino/camBV2Scheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257594661276051}}
{"text": "load('test_data.mat')\niou_ = compute_dense_overlap(ofx,ofy,stx,sty,vsx,vsy,dx1,dy1,dx2,dy2,gx1,gy1,gx2,gy2,1,1);\nerr = abs(iou_ - iou);\nif all(err(:)) < 1e-12\n    fprintf('Test for compute_dense_overlap [passed]\\n');\nelse\n    fprintf('Test for compute_dense_overlap [failed]\\n');\nend\n    \n    \n", "meta": {"author": "peiyunh", "repo": "tiny", "sha": "37c44deacf53e0fbe23327ef3721b5fb5f22559f", "save_path": "github-repos/MATLAB/peiyunh-tiny", "path": "github-repos/MATLAB/peiyunh-tiny/tiny-37c44deacf53e0fbe23327ef3721b5fb5f22559f/utils/test_compute_dense_overlap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2325759466127605}}
{"text": "%% t_gifti_4\n%\n\n% Download from RDT\n%{\n rdt = RdtClient('vistasoft');\n rdt.crp('/vistadata/anatomy/anatomyNIFTI');\n\n leftMeshFile = rdt.readArtifact('leftMesh',...\n    'type','mat',...\n    'destinationFolder',fullFolderName);\n%}\n\n%%  Set the vista data path and change into the gifti data directory\n\nchdir(fullfile(vistaRootPath,'local'));\n%% Create a gifti structure from a mrMesh mesh\n\n% This loads a VISTASOFT msh structure\n% First the original mesh\nload(fullfile(vistaRootPath,'local','leftMesh.mat'));\ng = gifti;\ng.faces = int32(meshGet(msh,'triangles')' + 1);\n\n% Choose either the initial unsmoothed vertices, or the smoothed vertices\n% g.vertices = single(meshGet(msh,'initVertices')');\ng.vertices = single(meshGet(msh,'vertices')');\n\n% We don't know how this is used.\ng.mat = eye(4,4);  \n% g.mat = rand(4,4);\n% mrvNewGraphWin; h = plot(g);\n\n% we take the green channel and use a gray scale map.  Their algorithm\n% seems to normalize the color list and map it through the color map.\ncdata = meshGet(msh,'colors');\ncdata = cdata(2,:)';\ngg.cdata = single(cdata);\nmrvNewGraphWin; clf; colormap(gray); h = plot(g,gg);\n\n%% Change the color map - I had some time on my hands.\ncolormap(cool); pause(0.5)\ncolormap(jet); pause(0.5)\ncolormap(redGreenCmap); pause(0.5)\ncolormap(blueyellowCmap); pause(0.5)\n\n%% Change lighting and such\ndaspect([1,1,1]); view(45,30); axis tight\nlightangle(45,30);\nset(h,'SpecularColorReflectance',0,'SpecularExponent',50)\n[az,el] = view;\ng.mat = eye(4,4);  \n% g.mat = rand(4,4);\n% mrvNewGraphWin; h = plot(g);\n\ng.private.data{2}.metadata(1).name = 'AnatomicalStructurePrimary'; \ng.private.data{2}.metadata(1).value = 'CortexLeft';\n\n% Also, DTI-Query will use the AnatomicalStructureSecondary metadata field\n% to distinguish the surfaces that have been loaded.  While it's not\n% necessary, it may be helpful to set this field as well:  \n% g.private.data{2}.metadata(2).name = 'AnatomicalStructureSecondary'; \n% g.private.data{2}.metadata(2).value = 'Pial'; % (or whatever you would like to tag the structure as)\n\n% Then, \n% save(g,'dhTest.gii');\n\n% From Guillaume Flandin - storing metadata2\n% g = gifti('file.gii');\n% g.private.metadata(1).name  = 'AnatomicalStructurePrimary'; \n% g.private.metadata(1).value = 'CortexLeft'; \n\n%% Attach metadata to the gifti so Doug H. can read it. Name it as left.\n% Helped by Guillaume Flandin email: gflandin@fil.ion.ucl.ac.uk\n\n% First the left\nload(fullfile(mrvDataRootPath,'anatomy','T1andMesh','Left_Mesh_Unsmoothed.mat'));\ng = gifti;\ng.faces = int32(meshGet(msh,'triangles')' + 1);\n\n% Choose either the initial unsmoothed vertices, or the smoothed vertices\n% g.vertices = single(meshGet(msh,'initVertices')');\ng.vertices = single(meshGet(msh,'initVertices')');\n\n% Set the flag to indicate this is a left hemisphere\ng.private.data{2}.metadata(1).name = 'AnatomicalStructurePrimary'; \ng.private.data{2}.metadata(1).value = 'CortexLeft';\nsave(g,'left_gifti.gii');\n% mrvNewGraphWin; h = plot(g); axis on; grid on\n\n% Now the right\nload(fullfile(mrvDataRootPath,'anatomy','T1andMesh','Right_Mesh_Unsmoothed.mat'));\ng = gifti;\ng.faces = int32(meshGet(msh,'triangles')' + 1);\n\n% Choose either the initial unsmoothed vertices, or the smoothed vertices\n% g.vertices = single(meshGet(msh,'initVertices')');\ng.vertices = single(meshGet(msh,'initVertices')');\n\n% Set the flag to indicate this is a left hemisphere\ng.private.data{2}.metadata(1).name = 'AnatomicalStructurePrimary'; \ng.private.data{2}.metadata(1).value = 'CortexRight';\n\nsave(g,'right_gifti.gii');\n% mrvNewGraphWin; h = plot(g);  axis on; grid on\n\n% and actually, according to the specifications of the file format, you can\n% store metadata for the complete file as above or for a given DataArray: \n% g.private.data{2}.metadata(1).name = 'AnatomicalStructurePrimary'; \n% g.private.data{2}.metadata(1).value = 'CortexLeft';\n% \n% We need to figure out how to save these fields to work with dtiQuery.\n\n%% End\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/tutorials/fileFilters/gifti/t_gifti_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257594661276046}}
{"text": "function rgb = cortex\n\n% returns a predefined color as [red green blue] values\n%\n% skin_surface         = [255 213 119]/255;\n% outer_skull_surface  = [140  85  85]/255;\n% inner_skull_surface  = [202 100 100]/255;\n% cortex = [255 213 119]/255;\n% black  = [0   0   0  ]/255;\n% white  = [255 255 255]/255;\n% red    = [255 0   0  ]/255;\n% green  = [0   192 0  ]/255;\n% blue   = [0   0   255]/255;\n% yellow = [255 255 0  ]/255;\n% cortex_light = [199 194 169]/255;\n% cortex_dark  = [100 97 85]/255;\n\nrgb = [255 213 119]/255;\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/plotting/private/cortex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.23253107842941437}}
{"text": "function []= prepare_h5_data(data_folder, h5_save_folder,h5_save_list)\n% Generate the hdf5 file and a file list used to train the network\n% --------------------------------------------------------\n% Copyright (c) 2017, Lequan Yu\n% Licensed under The MIT License\n% --------------------------------------------------------\n\n    % re-sample the data into same resolution, default is False.\n    use_isotropic=0;\n    patchSize = 64;\n    if nargin<3\n        data_folder = '../data';\n        h5_save_folder = '../h5_data';\n        h5_save_list = '../train.list';\n\n    if ~exist(h5_save_folder,'dir')\n        mkdir(h5_save_folder);\n    end\n\n    addpath('./util');\n    fid = fopen(h5_save_list, 'w');\n\n    %% generate the hdf5 file\n    for id = 0:0\n        tic;\n        img_path = [data_folder, '/', 'training_axial_crop_pat', num2str(id), '.nii.gz'];\n        seg_path = [data_folder, '/', 'training_axial_crop_pat', num2str(id), '-label.nii.gz'];\n\n        img_nii = load_nii(img_path);\n        seg_nii = load_nii(seg_path); \n\n        %pre-process the images (intensity and resize)\n        [img,seg] = pre_process_isotropic(img_nii,seg_nii,use_isotropic,id); \n\n        % crop the heart patches (ROI) from whole image and randomly crop patches\n        [img,seg,rimgs,rsegs] = Create_ROIs(img, seg,patchSize);\n\n        %% Do data augmentation (permute & rotate & flip)\n        % We only do augmentation at axial plane\n        % You can do agumentation in all three planes by setting it_p = 1:3\n        pp= [1 2 3; 2 3 1; 3 1 2];\n        for it_p = 1:1\n            permute_img = permute(img,pp(it_p,:));\n            permute_seg = permute(seg,pp(it_p,:));\n            for it_r = 1:4\n                % rotate\n                rotate_img = rot90(permute_img, it_r - 1);\n                rotate_seg  = rot90(permute_seg, it_r - 1);\n                % flip\n                for it_f = 0:1\n                    if it_f == 0\n                        flip_img = rotate_img;\n                        flip_seg = rotate_seg;              \n                    else\n                        flip_img = flip(rotate_img, it_f);\n                        flip_seg = flip(rotate_seg, it_f);\n                    end\n\n                    % h5 file path\n                    h5_path    = [h5_save_folder, '/', num2str(id), '_p', num2str(it_p),...\n                        '_r', num2str(it_r), 'f', num2str(it_f), '.h5'];\n                    if exist(h5_path,'file')\n                        delete(h5_path);\n                    end\n\n                    [d1, d2, d3, d4, d5] = size(flip_img);\n                    data_dims = [d1, d2, d3, d4, d5];\n                    [d1, d2, d3, d4, d5] = size(flip_seg);\n                    seg_dims = [d1, d2, d3, d4, d5];\n\n                    % store as h5 format\n                    h5create(h5_path,'/data',data_dims,'Datatype','single','Deflate',0,'ChunkSize',data_dims);\n                    h5create(h5_path,'/label',seg_dims,'Datatype','uint8','Deflate',0,'ChunkSize',seg_dims);\n                    h5write(h5_path,'/data', single(flip_img));\n                    h5write(h5_path,'/label',uint8(flip_seg));\n                    fprintf(fid,'%s\\n', h5_path);\n                end\n            end\n        end\n\n        %% save randomly cropped patches.\n        % Default, we do not use them to train the model\n        for i= 1: 0 %size(random_img, 5)\n            h5_path  = [h5_save_folder, '/',num2str(id), '_random_', num2str(i), '.h5'];\n            if exist(h5_path,'file')\n                delete(h5_path);\n            end\n\n            write_img = rimgs{i};\n            write_seg  = rsegs{i};\n            [d1, d2, d3, d4, d5] = size(write_img);\n            data_dims = [d1, d2, d3, d4, d5];\n            [d1, d2, d3, d4, d5] = size(write_seg);\n            seg_dims = [d1, d2, d3, d4, d5];\n\n            % store as h5 format\n            h5create(h5_path,'/data',data_dims,'Datatype','single','Deflate',0,'ChunkSize',data_dims);\n            h5create(h5_path,'/label',seg_dims,'Datatype','uint8','Deflate',0,'ChunkSize',seg_dims);\n            h5write(h5_path,'/data', single(write_img));\n            h5write(h5_path,'/label',uint8(write_seg));\n            fprintf(fid,'%s\\n', h5_path);\n        end\n        toc;\n    end\n    fclose(fid);\nend\n", "meta": {"author": "yulequan", "repo": "HeartSeg", "sha": "b689b376d9cce9e02adf33606035892284c8814c", "save_path": "github-repos/MATLAB/yulequan-HeartSeg", "path": "github-repos/MATLAB/yulequan-HeartSeg/HeartSeg-b689b376d9cce9e02adf33606035892284c8814c/code/prepare_h5_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23246069724157295}}
{"text": "function view=analyze4d2mrLoadRet3TSeries(view,inFile,scan,volsToSkip,rotateInplanes,scaleFact,flipudFlag,rotateFlag,flipSliceOrder)\n% view=4danalyze2mrLoadRet3TSeries(view,inFile,scan,volsToSkip,rotateInplan\n% es,scaleFact,flipudFlag,fliplrFlag,flipSliceOrder)\n% Converts from 4d analyze functional image data to mrLoadRet TSeries\n% format.\n% Uses read_avw to read in 4d analyze files. Then saves out the block as\n% mlr TSeries while skipping over any initial 'junk frames';\n%\n% The doRotate param allows to you rotate the functional data by doRotate*90 degrees\n% Try to read the the first volume to see if it's there and get the\n% dimensions of all the rest\n% ARW 032703 : Now saves out data in mrLoadRet3.0 format (.mat as opposed to .dat files)\n\n% AAB 2003.07.08 After the temporal normalization bug, I reconverted the\n% Tuebingen data using the Brucker-2-analyze converter downloaded from the\n% website. The new time series do not need to be rotated or flipped\n% up/down, but do need to be flipped left/right. So, I changed flipFlag to\n% flipudFlag (for up/down) and added fliplrFlag (for left/right). I set\n% all three values to be off by default.\n% ARW : 120805 : This function based on analyze2mrLoadRet3TSeries. \n\n\nif (~exist('volsToSkip','var'))\n    volsToSkip=0;\nend\n\nif (~exist('scaleFact','var'))\n    scaleFact=[1 1]; % No interpolation. (Scaling=1)\nend\n\nif (length(scaleFact)~=2) % If we just get a scalar for the scale factor, assume that it applies in both dimensions\n    scaleFact=repmat(scaleFact(1),2);\nend\n\nif (~exist('rotateInplanes','var'))\n    rotateInplanes=0; % This is off by default. Rotates 1*90 degrees\nend\n\nif (~exist('flipudFlag','var'))\n    flipudFlag=0; % This is off by default. Flips up/down after rotation\nend\n\nif (~exist('fliplrFlag','var'))\n    fliplrFlag=0; % This is off by default. Flips left/right after rotation\nend\nif (~exist('flipSliceOrder','var'))\n    flipSliceOrder=0; % This is off by default. Flips left/right after rotation\nend\n\n\ndisp('Reading volume');\nfuncVol=read_avw(inFile);\ndisp('Done');\n\n% Now take care of flipping...\n\n% \n% if (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged\n%     funcVol=zeros(y,x,nSlices,nVols);\n% else\n%     funcVol=zeros(x,y,nSlices,nVols);\n% end\n% \n% fprintf('Rotating by %d x 90, flipupFlag=%d, fliplrFlag=%d',doRotate,flipudFlag,fliplrFlag);\n% \n% \n% for t=0:(nVols-1)\n%     thisImIndex=t+firstVolIndex;\n%     suffix=sprintf('%03d',thisImIndex);\n%     fileName=[inFileRoot,suffix];\n%     V=spm_vol(fileName);\n%     im=spm_read_vols(V);\n%     \n%     % Do the rotation and scaling\n%     \n%     if (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged\n%         im2=zeros(y,x,nSlices);\n%     else\n%         im2=zeros(x,y,nSlices);\n%     end\n%     fprintf('\\nVol=%d',thisImIndex);\n%    \n%     for thisSlice=1:nSlices\n%         imSlice=squeeze(im(:,:,thisSlice));\n% %         imSlice=imresize(imSlice,[scaleFact(1)*y,scaleFact(2)*x],'nearest');\n%         \n%         im2(:,:,thisSlice)=rot90(imSlice,doRotate);\n%         \n%         if (flipudFlag)\n%             im2(:,:,thisSlice)=flipud(im2(:,:,thisSlice));\n%         end\n%         \n%         if (fliplrFlag)\n%             im2(:,:,thisSlice)=fliplr(im2(:,:,thisSlice));\n%         end\n%         \n%     end % next imSlice\n%     \n%     \n%     if (flipSliceOrder) % We can make it so the slice order is reversed \n%         im2=im2(:,:,[thisSlice:-1:1]);\n%     end\n% \n%     funcVol(:,:,:,t+1)=im2;\n%     %fprintf('.');\n%     \n% end\n\n% Crop the skipped frames\nfuncVol=funcVol(:,:,:,(volsToSkip+1):end);\n\nif (rotateInplanes)\ndisp('Rotating');\n\n[y x nSlices nVols]=size(funcVol)\nfor thisVol=1:nVols\n    for thisSlice=1:nSlices\n        funcVol(:,:,thisSlice,thisVol)=rot90(squeeze(funcVol(:,:,thisSlice,thisVol)),rotateInplane);\n    end\nend\nend\n\n% Now write them out in a different format\nfprintf('\\nDone reading data: Writing now...\\n');\nfor t=1:nSlices\n\n    tSeries=squeeze(funcVol(:,:,t,:));\n    tSeries=reshape(tSeries,x*y,nVols);\n    tSeries=tSeries';\n    view=saveTSeries(tSeries,view,scan,t);\n    \n    fprintf('_');\nend\n\nfprintf('\\nDone\\n');\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Init/analyze4d2mrLoadRet3TSeries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2324117482377493}}
{"text": "function [net,stats, ders_iter] = cnn_train_dag_ridge(net, imdb, input, getBatch, varargin)\n%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper\n%    CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with\n%    the DagNN wrapper instead of the SimpleNN wrapper.\n\n% Copyright (C) 2014-16 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% if show test1, please assign true to is_show_test1\nis_show_test1 = true;%false;%\n\naddpath(fullfile(vl_rootnn, 'examples'));\n\nopts.expDir = fullfile('data','exp') ;\nopts.continue = true ;\nopts.batchSize = 256 ;\nopts.numSubBatches = 1 ;\nopts.train = [] ;\nopts.val = [] ;\nopts.gpus = [] ;\nopts.prefetch = false ;\nopts.numEpochs = 300 ;\nopts.learningRate = 0.001 ;\nopts.weightDecay = 0.0005 ;\n\nopts.solver = @solver.adam; % Empty array - optimised SGD solver\n[opts, varargin] = vl_argparse(opts, varargin);\nif isempty(opts.solver)\n  opts.solverOpts.momentum = 0.9;\nelse\n  assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...\n    'Invalid solver - a function handle with two outputs expected.');\n  % A call without any input arg - def opts\n  opts.solverOpts = opts.solver();\nend\n\nopts.saveSolverState = true ;\nopts.randomSeed = 0 ;\nopts.profile = false ;\nopts.parameterServer.method = 'mmap' ;\nopts.parameterServer.prefix = 'mcn' ;\n\nopts.derOutputs = {'objective_r', 1} ;\nopts.extractStatsFn = @extractStats ;\nopts.plotStatistics = false;\nopts = vl_argparse(opts, varargin) ;\n\n%if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\n% if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\n% if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\n% if isnan(opts.train), opts.train = [] ; end\n% if isnan(opts.val), opts.val = [] ; end\n\n% -------------------------------------------------------------------------\n%                                                            Initialization\n% -------------------------------------------------------------------------\n\nevaluateMode = isempty(opts.train) ;\nif ~evaluateMode\n  if isempty(opts.derOutputs)\n    error('DEROUTPUTS must be specified when training.\\n') ;\n  end\nend\n\n% -------------------------------------------------------------------------\n%                                                        Train and validate\n% -------------------------------------------------------------------------\n\nmodelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\nmodelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n\nstart = opts.continue * findLastCheckpoint(opts.expDir) ;\nif start >= 1\n  fprintf('%s: resuming by loading epoch %d\\n', mfilename, start) ;\n  [net, state, stats] = loadState(modelPath(start)) ;\nelse\n  state = [] ;\nend\n\nglobal out;\nout=false;\n\n% if is_show_test1\n%     act_num = zeros(512,1);%-test1\n%     epoch=0;\n    ders_iter = zeros(size(input{1},3),opts.numEpochs);\n% end\nfor epoch=start+1:opts.numEpochs\n\n    if out\n        break;\n    end\n        \n  % Set the random seed based on the epoch and opts.randomSeed.\n  % This is important for reproducibility, including when training\n  % is restarted from a checkpoint.\n\n  rng(epoch + opts.randomSeed) ;\n  %prepareGPUs(opts, epoch == start+1) ;\n\n  % Train for one epoch.\n  params = opts ;\n  params.epoch = epoch ;\n  params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n  params.train = opts.train(randperm(numel(opts.train))) ; % shuffle\n  params.val = opts.val(randperm(numel(opts.val))) ;\n  %params.imdb = imdb ;\n  params.getBatch = getBatch ;\n\n  if numel(opts.gpus) <= 1\n    [net, state, ders_iter(:,epoch)] = processEpoch(net, input, state, params, 'train') ;\n    [net, state] = processEpoch(net, input, state, params, 'val') ;\n    if ~evaluateMode\n      %saveState(modelPath(epoch), net, state) ;\n    end\n    lastStats = state.stats ;\n  else\n    spmd\n      [net, state, ders_iter(:,epoch)] = processEpoch(net, input, state, params, 'train') ;\n      [net, state] = processEpoch(net, input, state, params, 'val') ;\n      if labindex == 1 && ~evaluateMode\n        %saveState(modelPath(epoch), net, state) ;\n      end\n      lastStats = state.stats ;\n    end\n    lastStats = accumulateStats(lastStats) ;\n  end\n\n  stats.train(epoch) = lastStats.train ;\n  stats.val(epoch) = lastStats.val ;\n  clear lastStats ;\n  %saveStats(modelPath(epoch), stats) ;\n\n  if opts.plotStatistics\n    switchFigure(1) ; clf ;\n    plots = setdiff(...\n      cat(2,...\n      fieldnames(stats.train)', ...\n      fieldnames(stats.val)'), {'num', 'time'}) ;\n    for p = plots\n      p = char(p) ;\n      values = zeros(0, epoch) ;\n      leg = {} ;\n      for f = {'train', 'val'}\n        f = char(f) ;\n        if isfield(stats.(f), p)\n          tmp = [stats.(f).(p)] ;\n          values(end+1,:) = tmp(1,:)' ;\n          leg{end+1} = f ;\n        end\n      end\n      subplot(1,numel(plots),find(strcmp(p,plots))) ;\n      plot(1:epoch, values','o-') ;\n      xlabel('epoch') ;\n      title(p) ;\n      legend(leg{:}) ;\n      grid on ;\n    end\n    drawnow ;\n    print(1, modelFigPath, '-dpdf') ;\n  end\nend\n\n% if is_show_test1\n%     %-test1\n%     aa=zeros(epoch,1);\n%      for i=1:epoch\n%         aa(i) = sum(act_num>i-1 );\n%      end\n%      figure,plot(aa);\n%      xlabel('adjust times');\n%      ylabel('channel numbers');\n%      title('adjust times vs channel numbers');\n%     %-test1\n% end\n% With multiple GPUs, return one copy\nif isa(net, 'Composite'), net = net{1} ; end\n\n% -------------------------------------------------------------------------\nfunction [net, state, ders] = processEpoch(net, input, state, params, mode)\n% -------------------------------------------------------------------------\n% Note that net is not strictly needed as an output argument as net\n% is a handle class. However, this fixes some aliasing issue in the\n% spmd caller.\n\n% initialize with momentum 0\nif isempty(state) || isempty(state.solverState)\n  state.solverState = cell(1, numel(net.params)) ;\nend\n\n% move CNN  to GPU as needed\nnumGpus = numel(params.gpus) ;\nif numGpus >= 1\n  net.move('gpu') ;\n  %state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ;\nend\nif numGpus > 1\n  parserv = ParameterServer(params.parameterServer) ;\n  net.setParameterServer(parserv) ;\nelse\n  parserv = [] ;\nend\n\n% profile\nif params.profile\n  if numGpus <= 1\n    profile clear ;\n    profile on ;\n  else\n    mpiprofile reset ;\n    mpiprofile on ;\n  end\nend\n\nnum = 0 ;\nepoch = params.epoch ;\nsubset = params.(mode) ;\nadjustTime = 0 ;\n\nstats.num = 0 ; % return something even if subset = []\nstats.time = 0 ;\n\nstart = tic ;\nfor t=1:params.batchSize:numel(subset)\n%   fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...\n%           fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;\n  batchSize = min(params.batchSize, numel(subset) - t + 1) ;\n\n  for s=1:params.numSubBatches\n    % get this image batch and prefetch the next\n    batchStart = t + (labindex-1) + (s-1) * numlabs ;\n    batchEnd = min(t+params.batchSize-1, numel(subset)) ;\n    batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n    num = num + numel(batch) ;\n    if numel(batch) == 0, continue ; end\n\n    feats=input{1};\n    labels=input{2};\n    \n%lx     inputs ={'input1', gpuArray(ims),'input2', ...\n%          gpuArray(ims), 'label', gpuArray(labels)};\n    inputs ={'input', feats, 'label_gaussian', labels};\n\n\n    if params.prefetch\n      if s == params.numSubBatches\n        batchStart = t + (labindex-1) + params.batchSize ;\n        batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;\n      else\n        batchStart = batchStart + numlabs ;\n      end\n      nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n      %params.getBatch(params.imdb, nextBatch) ;\n    end\n\n    if strcmp(mode, 'train')\n      net.mode = 'normal' ;\n      net.accumulateParamDers = (s ~= 1) ;\n      net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;\n%         if is_show_test1      \n%               showing gradient value in each depth channel %-test1\n              ders = squeeze(gather(sum(sum(net.vars(1).der))));\n%                 ders = squeeze(gather(sum(sum(net.params(1).der))));\n%               figure(3);\n%               plot(a);\n%               xlabel('channel number'); ylabel('value');title('gradient weights');\n%               [val, ind] = sort(a,'descend');\n%               act_num(ind(1:64))= act_num(ind(1:64))+1;  %-test1\n%         end\n    else\n      net.mode = 'test' ;\n      net.eval(inputs) ;\n    end\n  end\n\n  % Accumulate gradient.\n  if strcmp(mode, 'train')\n    if ~isempty(parserv), parserv.sync() ; end\n    state = accumulateGradients(net, state, params, batchSize, parserv) ;\n  end\n\n  % Get statistics.\n  time = toc(start) + adjustTime ;\n  batchTime = time - stats.time ;\n  stats.num = num ;\n  stats.time = time ;\n  stats = params.extractStatsFn(stats,net) ;\n  currentSpeed = batchSize / batchTime ;\n  averageSpeed = (t + batchSize - 1) / time ;\n  if t == 3*params.batchSize + 1\n    % compensate for the first three iterations, which are outliers\n    adjustTime = 4*batchTime - time ;\n    stats.time = time + adjustTime ;\n  end\n\n%   fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;\n  for f = setdiff(fieldnames(stats)', {'num', 'time'})\n    f = char(f) ;\n    fprintf(' %s: %.8f', f, stats.(f)) ;\n          \n    if strcmp(f,'objective_r')&& stats.(f)<0.02  \n        global out;\n        out=true;\n    end  \n    break;\n  end\n  fprintf('\\n') ;\nend\n\n% Save back to state.\nstate.stats.(mode) = stats ;\nif params.profile\n  if numGpus <= 1\n    state.prof.(mode) = profile('info') ;\n    profile off ;\n  else\n    state.prof.(mode) = mpiprofile('info');\n    mpiprofile off ;\n  end\nend\nif ~params.saveSolverState\n  state.solverState = [] ;\nelse\n  state.solverState = cellfun(@gather, state.solverState, 'uniformoutput', false) ;\nend\n\nnet.reset() ;\n%net.move('cpu') ;\n\n% -------------------------------------------------------------------------\nfunction state = accumulateGradients(net, state, params, batchSize, parserv)\n% -------------------------------------------------------------------------\nnumGpus = numel(params.gpus) ;\notherGpus = setdiff(1:numGpus, labindex) ;\n\nfor p=1:numel(net.params)\n\n  if ~isempty(parserv)\n    parDer = parserv.pullWithIndex(p) ;\n  else\n    parDer = net.params(p).der ;\n  end\n\n  switch net.params(p).trainMethod\n\n    case 'average' % mainly for batch normalization\n      thisLR = net.params(p).learningRate ;\n      net.params(p).value = vl_taccum(...\n          1 - thisLR, net.params(p).value, ...\n          (thisLR/batchSize/net.params(p).fanout),  parDer) ;\n\n    case 'gradient'\n      thisDecay = params.weightDecay * net.params(p).weightDecay ;\n      thisLR = params.learningRate * net.params(p).learningRate ;\n      \n      if isempty(params.solver)\n        if isempty(state.solverState{p})\n          state.solverState{p} = zeros(size(parDer), 'like', parDer);\n        end\n        \n        state.solverState{p} = vl_taccum(...\n          params.solverOpts.momentum,  state.solverState{p}, ...\n          - (1 / batchSize), parDer) ;\n        net.params(p).value = vl_taccum(...\n          (1 - thisLR * thisDecay / (1 - params.solverOpts.momentum)),  ...\n          net.params(p).value, ...\n          thisLR, state.solverState{p}) ;\n      else\n        grad = (1 / batchSize) * parDer + thisDecay * net.params(p).value;\n        % call solver function to update weights\n        [net.params(p).value, state.solverState{p}] = ...\n          params.solver(net.params(p).value, state.solverState{p}, ...\n          grad, params.solverOpts, thisLR) ;\n      end\n\n    otherwise\n      error('Unknown training method ''%s'' for parameter ''%s''.', ...\n        net.params(p).trainMethod, ...\n        net.params(p).name) ;\n  end\nend\n\n% -------------------------------------------------------------------------\nfunction stats = accumulateStats(stats_)\n% -------------------------------------------------------------------------\n\nfor s = {'train', 'val'}\n  s = char(s) ;\n  total = 0 ;\n\n  % initialize stats stucture with same fields and same order as\n  % stats_{1}\n  stats__ = stats_{1} ;\n  names = fieldnames(stats__.(s))' ;\n  values = zeros(1, numel(names)) ;\n  fields = cat(1, names, num2cell(values)) ;\n  stats.(s) = struct(fields{:}) ;\n\n  for g = 1:numel(stats_)\n    stats__ = stats_{g} ;\n    num__ = stats__.(s).num ;\n    total = total + num__ ;\n\n    for f = setdiff(fieldnames(stats__.(s))', 'num')\n      f = char(f) ;\n      stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;\n\n      if g == numel(stats_)\n        stats.(s).(f) = stats.(s).(f) / total ;\n      end\n    end\n  end\n  stats.(s).num = total ;\nend\n\n% -------------------------------------------------------------------------\nfunction stats = extractStats(stats, net)\n% -------------------------------------------------------------------------\nsel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;\nfor i = 1:numel(sel)\n  stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;\nend\n\n% -------------------------------------------------------------------------\nfunction saveState(fileName, net_, state)\n% -------------------------------------------------------------------------\nnet = net_.saveobj() ;\nsave(fileName, 'net', 'state') ;\n\n% -------------------------------------------------------------------------\nfunction saveStats(fileName, stats)\n% -------------------------------------------------------------------------\nif exist(fileName)\n  save(fileName, 'stats', '-append') ;\nelse\n  save(fileName, 'stats') ;\nend\n\n% -------------------------------------------------------------------------\nfunction [net, state, stats] = loadState(fileName)\n% -------------------------------------------------------------------------\nload(fileName, 'net', 'state', 'stats') ;\nnet = dagnn.DagNN.loadobj(net) ;\nif isempty(whos('stats'))\n  error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...\n        fileName) ;\nend\n\n% -------------------------------------------------------------------------\nfunction epoch = findLastCheckpoint(modelDir)\n% -------------------------------------------------------------------------\nlist = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;\ntokens = regexp({list.name}, 'net-epoch-([\\d]+).mat', 'tokens') ;\nepoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;\nepoch = max([epoch 0]) ;\n\n% -------------------------------------------------------------------------\nfunction switchFigure(n)\n% -------------------------------------------------------------------------\nif get(0,'CurrentFigure') ~= n\n  try\n    set(0,'CurrentFigure',n) ;\n  catch\n    figure(n) ;\n  end\nend\n\n% -------------------------------------------------------------------------\nfunction clearMex()\n% -------------------------------------------------------------------------\nclear vl_tflow vl_imreadjpeg ;\n\n% -------------------------------------------------------------------------\nfunction prepareGPUs(opts, cold)\n% -------------------------------------------------------------------------\nnumGpus = numel(opts.gpus) ;\nif numGpus > 1\n  % check parallel pool integrity as it could have timed out\n  pool = gcp('nocreate') ;\n  if ~isempty(pool) && pool.NumWorkers ~= numGpus\n    delete(pool) ;\n  end\n  pool = gcp('nocreate') ;\n  if isempty(pool)\n    parpool('local', numGpus) ;\n    cold = true ;\n  end\n\nend\nif numGpus >= 1 && cold\n  fprintf('%s: resetting GPU\\n', mfilename)\n  clearMex() ;\n  if numGpus == 1\n    gpuDevice(opts.gpus)\n  else\n    spmd\n      clearMex() ;\n      gpuDevice(opts.gpus(labindex))\n    end\n  end\nend\n", "meta": {"author": "XinLi-zn", "repo": "TADT", "sha": "659e031a9c40624d53b7b1d4d25f16cd70795c3b", "save_path": "github-repos/MATLAB/XinLi-zn-TADT", "path": "github-repos/MATLAB/XinLi-zn-TADT/TADT-659e031a9c40624d53b7b1d4d25f16cd70795c3b/target_aware_features/losses/cnn_train_dag_ridge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23241174243761673}}
{"text": "classdef (ConstructOnLoad) ZmapCatalog < matlab.mixin.Copyable\n    % ZmapCatalog represents the basic utilities for an event catalog\n    %\n    % ZmapCatalog properties:\n    %   Name - name of this catalog\n    %   Date - date and time of event\n    %   XYZ - position of each event\n    %   Magnitude - magnitude of each event\n    %   MagnitudeType - Magnitude units, such as M, ML, MW, etc.\n    %\n    %   IsSortedBy - describes sort order\n    %   SortDirection - describes sorting direction\n    %\n    % ZmapCatalog read-only properties:\n    %   Count - number of events in catalog\n    %\n    %   X - read-only X position\n    %   Y - read-only Y position\n    %   Z - read-only Z position\n    %\n    %   DateSpan - time between first and last events in catalog (duration)\n    %   DayOfYear - dates represented as the day of year\n    %   DecimalYear - dates represented as a decimal year\n    %\n    %\n    % ZmapCatalog methods:\n    %\n    %  Catalog construction:\n    %   ZmapCatalog -\n    %   blank - return a blank catalog\n    %   cat - combines two catalogs\n    %   copy - copy catalog. otherwise handles likely point to same object\n    %\n    %\n    %  Output functions:\n    %   blurb - get simple statement about catalog\n    %   disp - Display array.\n    %   summary - return a summary of this catalog\n    %   table - write catalog as a table\n    %\n    %  Query methods:\n    %   isempty - true when there are no events in the catalog\n    %   relativeTimes - get times relative to first event or a specific time\n    %\n    %\n    %  Plotting functions:\n    %   scatter - Scatter/bubble plot\n    %   scatter3 - 3-D Scatter plot\n    %\n    %  Set membership functions:\n    %   setdiff - returns values that are in A but not in B with no repetitions. NO tolerance\n    %   setxor - return combination of values that are either in A or B, but not in both. no tolerance\n    %   intersect - return values common to both events, no repetitions. no tolerance\n    %\n    %  Sorting, Filtering, Subsetting methods:\n    %   removeDuplicates - removes events from catalog that are similar within tolerances\n    %   sort - sort this catalog by the specified field (IN PLACE)\n    %   subset - get a subset of this catalog.\n    %   subsetInPlace - modifies this catalog, not a copy of it.\n    %\n    %   sortedByDistanceTo - get a catalog that has been sorted by distance to a point\n    %\n    %  Spatial methods:\n    %   distanceTo - get distance to events in catalog from a point or set of points\n    %   epicentralDistanceTo - get distance from all events to a point (assuming Z is same for all)\n    %   hypocentralDistanceTo - get 3D distance from all events to a point\n    %   selectCircle - select events in a circle defined by distance, number of events, or both\n    %   selectClosestEvents - determine which N events are closest to a point\n    %   selectRadius - select subset catalog to a radius from a point\n    %\n    %  Misc. methods\n    %   validate - check validity of the catalog\n    \n    properties\n        Date            (:,1) datetime          % date and time of event\n        EventID         (:,1) string            % id of this event\n        Magnitude       (:,1) double            % Magnitude of each event\n        MagnitudeType   (:,1) categorical       % Magnitude units, such as M, ML, MW, etc.\n    end\n    \n    properties(SetObservable, AbortSet)\n        Name            (1,:) char      = ''    % name of this catalog\n        IsSortedBy      char            = ''    % describes sort order\n        SortDirection   char            = ''    % describes sorting direction\n        Filter          (:,1) logical           % logical filter for subsetting events\n        XYZ             (:,3) double            % position of each event\n        OtherFields     cell % of ZmapCatalogAddon  % TODO:  1st implementaion is MomentTensorAddon\n    end\n    \n    properties(Hidden)\n        XLabel          (1,:) char      = 'X'\n        YLabel          (1,:) char      = 'Y'\n        ZLabel          (1,:) char      = 'Z'\n        ZDir            (1,:) char      = 'normal'\n    end\n    \n    properties(Dependent)\n        DecimalYear % dates represented as a decimal year\n        DayOfYear   % dates represented as the day of year\n        Count       % the number of events in catalog\n        DateSpan    % the time between first and last events in catalog\n        X               double      % X position of each event\n        Y               double      % Y position of each event\n        Z               double      % Z position of each event\n        XLabelWithUnits\n        YLabelWithUnits\n        ZLabelWithUnits\n        Longitude       double     \t% Longitude (Deg) of each event\n        Latitude        double     \t% Latitude (Deg) of each event\n        Depth           double     \t% Depth of events\n        LengthUnit                 % units for X, Y, Z offsets\n    end\n    \n    properties(Dependent, Hidden)\n        FieldnamesForColorby\n        HorizontalUnit\n    end\n    \n    events\n        ValueChange\n    end\n    \n    properties(Constant)\n        DefaultRefEllipsoid = @()getappdata(groot, 'ZmapDefaultReferenceEllipsoid');\n    end\n    \n    properties(SetAccess=immutable)\n        Type        (1,:) char\n        RefEllipsoid referenceEllipsoid = ZmapCatalog.DefaultRefEllipsoid();\n    end\n    \n    properties(SetAccess=immutable, Hidden)\n        distanceFcn2d   function_handle     = @obj.cartesianEpicentralDistanceTo;\n        distanceFcn3d   function_handle     = @obj.cartesianHypocentralDistanceTo;\n    end\n    \n    \n    methods\n        % ordered as: Constructors, dependent property methods, alphabetical list of all others\n        function obj = ZmapCatalog(varargin)\n            obj.Type = 'zmapcatalog';\n            if ~isempty(varargin)\n                if nargin==1 && isa(varargin{1}, 'ZmapCatalog')\n                    obj = copy(varargin{1});\n                    return\n                end\n                p = inputParser;\n                p.addParameter('ReferenceEllipsoid', obj.RefEllipsoid);\n                p.addParameter('Name', obj.Name);\n                p.addParameter('LengthUnit', obj.RefEllipsoid.LengthUnit);\n                p.parse(varargin{:});\n                obj.RefEllipsoid = p.Results.ReferenceEllipsoid;\n                obj.RefEllipsoid.LengthUnit = p.Results.LengthUnit;\n                obj.Name = p.Results.Name;\n            end\n            \n            if ~iscartesian(obj.RefEllipsoid)\n                obj.XLabel = 'Longitude';\n                obj.YLabel = 'Latitude';\n                obj.ZLabel = 'Depth';\n                obj.ZDir   = 'reverse';\n                obj.distanceFcn2d   = @obj.geodeticEpicentralDistanceTo;\n                obj.distanceFcn3d   = @obj.geodeticHypocentralDistanceTo;\n            end\n        end\n        \n        % -----------------\n        function tf = hasAddon(obj, type)\n            tf =  any(cellfun(@(x)x.Type == string(type), obj.OtherFields));\n        end\n        \n        function list = getAddonTypes(obj)\n            list = cellfun(@(x)x.Type, obj.OtherFields, 'UniformOutput', false);\n        end\n        \n        function aoFnc = getAddon(obj, type)\n            idx = cellfun(@(x)x.Type == string(type), obj.OtherFields);\n            if any(idx)\n                aoFnc = obj.OtherFields{idx};\n            end\n        end\n        function setAddon(obj, other)\n            type = other.Type;\n            if obj.hasAddon(type)\n                idx = getAddonTypes == string(type);\n                obj.OtherFields(idx) = {other};\n            else\n                if ~iscell(obj.OtherFields)\n                    obj.OtherFields = {};\n                end\n                obj.OtherFields(end+1) = {other};\n            end\n        end\n        % -----------------\n            \n        function val = get.FieldnamesForColorby(obj)\n            val = obj.GetFieldnamesForColorby;\n        end\n        \n        function val = get.Count(obj)\n            if numel(obj) == 0\n                val = 0;\n            else\n                val = size(obj.XYZ, 1);\n            end\n        end\n        \n        function out = get.DateSpan(obj)\n            % dspan = obj.DateSpan  returns difference between min & max dates\n            out = range(obj.Date);\n            if days(out)>5\n                out.Format = 'd';\n            end\n        end\n        \n        function propval = get.DecimalYear(obj)\n            propval = decyear(obj.Date);\n        end\n        \n        function propval = get.DayOfYear(obj)\n            propval = fix(datenum(obj.Date)) - datenum(obj.Date.Year - 1, 12 , 31);\n        end\n        function propval = get.X(obj)\n            propval = obj.XYZ(:, 1);\n        end\n        function propval = get.Y(obj)\n            propval = obj.XYZ(:, 2);\n        end\n        function propval = get.Z(obj)\n            propval = obj.XYZ(:, 3);\n        end\n        \n        function lu = get.LengthUnit(obj)\n            lu = obj.RefEllipsoid.LengthUnit;\n        end\n        \n        function hu = get.HorizontalUnit(obj)\n            if iscartesian(obj.RefEllipsoid)\n                hu = obj.RefEllipsoid.LengthUnit;\n            else\n                hu = 'degree';\n            end\n        end\n        \n        function lb = get.XLabelWithUnits(obj)\n            lb = [obj.XLabel, ' [', obj.HorizontalUnit, ']'];\n        end\n        \n        function lb = get.YLabelWithUnits(obj)\n            lb = [obj.YLabel, ' [', obj.HorizontalUnit, ']'];\n        end\n        \n        function lb = get.ZLabelWithUnits(obj)\n            lb = [obj.ZLabel, ' [', obj.LengthUnit, ']'];\n        end\n        \n        function val = get.Depth(obj)\n            val = obj.XYZ(:, 3);\n        end\n        \n        function set.Depth(obj, val)\n            obj.XYZ(1:numel(val), 3)=val;\n        end\n        \n        function val = get.Latitude(obj)\n            val = obj.XYZ(:, 2);\n        end\n        \n        function set.Latitude(obj, val)\n            obj.XYZ(1:numel(val), 2)=val;\n        end\n        \n        function val = get.Longitude(obj)\n            val = obj.XYZ(:, 1);\n        end\n        \n        function set.Longitude(obj, val)\n            obj.XYZ(1:numel(val), 1)=val;\n        end\n        \n        function s = blurb(obj)\n            % BLURB get simple statement about catalog\n            if numel(obj)>1\n                s = sprintf('%s catalog matrix', strjoin(string(size(obj)), 'x'));\n            elseif numel(obj)==1 && obj.Count > 0\n                s = sprintf('%s \"%s\" with %d events\\n', class(obj), obj.Name, obj.Count);\n            else\n                s = sprintf('empty %s', class(obj));\n            end\n        end\n        \n        function obj = cat(objA, objB)\n            % CAT combines two catalogs\n            % combinedCatalog = cat(catalogA, catalogB)\n            % duplicates are not removed\n            obj = copy(objA);\n            \n            \n            the_fields = obj.fields_that_must_be_nevent_length();\n            for n = 1 : numel(the_fields)\n                f= the_fields{n};\n                obj.(f) = [objA.(f) ; objB.(f)];\n            end\n            \n            the_fields = obj.possibly_empty_fields();\n            for n = 1 : numel(the_fields)\n                fn = the_fields{n};\n                \n                if isempty(objA.(fn)) && isempty(objB.(fn))\n                    continue\n                end\n                \n                if istable(objA.(fn))\n                    cols=@(x) 1;\n                else\n                    cols=@(x)size(x, 2);\n                end\n                \n                if isempty(objA.(fn))\n                    obj.(fn) = [repmat(missing, objA.Count, cols(objB.(fn)))\t; objB.(fn)];\n                elseif isempty(objB.(fn))\n                    obj.(fn) = [objA.(fn)   ; repmat(missing, objB.Count, cols(objA.(fn)))];\n                else\n                    obj.(fn) = [objA.(fn);            objB.(fn)];\n                end\n                \n            end\n            \n            \n        end\n        \n        function disp(obj)\n            if numel(obj)>1\n                disp(obj.blurb);\n                return\n            end\n            disp(obj.blurb)\n            disp('with properties:');\n            \n            show_categorical = @(f) {numel(categories(obj.(f))), get_limited_categories(obj.(f))};\n            show_logical = @(f) {sum(obj.(f)), numel(obj.(f))};\n            show_cell    = @(f) {strjoin(num2str(size(obj.(f))), 'x')};\n            show_simple  = @(f) {obj.(f)};\n            show_range   = @(f) {min(obj.(f)), max(obj.(f))};\n            show_refellipse=@(f) {obj.(f).Name, obj.(f).LengthUnit};\n            \n            business = { ... classname , dispformat, dispfun\n                \"categorical\"   , '%d categories [ %s ]'        , show_categorical;...\n                \"logical\"       , '<logical> [%d of %d are true]' , show_logical;...\n                \"cell\"          , '<%s cell>'                   , show_cell;...\n                \"char\"          , '''%s'''                      , show_simple;...\n                \"string\"        , '''%s'''                      , show_simple;...\n                \"datetime\"      , {'%s', '[ %s  to  %s ]'}      , {show_simple, show_range};...\n                \"duration\"      , {'%s', '[ %s  to  %s ]'}      , {show_simple, show_range};...\n                \"referenceEllipsoid\" , '%s [Units:%s]'          , show_refellipse;...\n                \"\"              , {'%g', '[ %g  to  %g ]'}      , {show_simple, show_range}...\n                };\n            \n            p = obj.display_order();\n            for i = 1:numel(p)\n                pn = p{i};\n                logic = business(class(obj.(pn))==[business{:, 1}], :);\n                if isempty(logic)\n                    logic = business(end, :);\n                end\n                fn = logic{3};\n                fmtstr = logic{2};\n                if iscell(logic{2})\n                    if numel(obj.(pn)) > 1\n                        fmtstr = fmtstr{2};\n                        fn = fn{2};\n                    else\n                        fmtstr = fmtstr{1};\n                        fn = fn{1};\n                    end\n                end\n                \n                try\n                    values = fn(pn);\n                catch\n                    if isempty(obj.(pn))\n                        fmtstr = 'empty <%s>';\n                    else\n                        fmtstr = '<%s>';\n                    end\n                    values = class(obj.(pn));\n                end\n                fmtstr = \"\\t%20s : \" + fmtstr + \"\\n\";\n                \n                fprintf(fmtstr, pn, values{:});\n            end\n            if ~isempty(obj.OtherFields)\n                disp(\" With other fields:\")\n                for j = 1:numel(obj.OtherFields)\n                    disp(obj.OtherFields{j})\n                end\n            end\n            \n        end\n\n        function [dists, units] = distanceTo(obj, x, y, z)\n            % get distance to events in catalog from a point or set of points\n            if ~exist('z', 'var')||isempty(z)\n                [dists, units] = obj.distanceFcn2d(x, y);\n            else\n                [dists, units] = obj.distanceFcn3d(x, y, z);\n            end\n        end\n        \n        function [dists, units] = epicentralDistanceTo(obj, x, y)\n            [dists, units] = obj.distanceFcn2d(x, y);\n        end\n        \n        function [dists, units] = hypocentralDistanceTo(obj, x, y, z)\n            [dists, units] = obj.distanceFcn3d(x, y, z);\n        end\n        \n        \n        \n        function [C, IA, IB] = intersect(A, B)\n            % return values common to both events, no repetitions. no tolerance\n            % based solely on Date,  X, Y, Z, and Magnitude\n            dateFmt='uuuu-MM-dd''T''HH:mm:ss.SSSSSSSSS';\n            compstrA = string(A.Date, dateFmt)+join(string(A.XYZ))+\" \"+string(A.Magnitude);\n            compstrB = string(B.Date, dateFmt)+join(string(B.XYZ))+\" \"+string(B.Magnitude);\n            IA=ismember(compstrA, compstrB);\n            if nargout==3\n                IB=ismember(compstrB, compstrA);\n            end\n            C=A.subset(IA);\n        end\n        \n        function TF = isempty(obj)\n            % ISEMPTY is true when there are no events in the catalog\n            % tf = ISEMPTY(catalog)\n            TF = numel(obj)==0 || isempty(obj.XYZ);\n        end\n        \n        function rt = relativeTimes(obj, other)\n            % get times relative to first event or a specific time\n            % rt = catalog.RELATIVETIMES() get times relative to start\n            % rt = catalog.RELATIVETIMES(other) get times relative to another time\n            \n            if ~exist('other', 'var')\n                rt = obj.Date - min(obj.Date);\n                return\n            end\n            switch class(other)\n                case 'datetime'\n                    rt = obj.Date - datetime;\n                otherwise\n                    error('ZMAP:ZmapCatalog:relativeTimes:unknownComparison',...\n                        'do not know how to compare to a %s try giving a specific date',class(other));\n            end\n        end\n        \n        function [obj, sameidx] = removeDuplicates(obj, varargin)\n            % REMOVEDUPLICATES removes events from catalog that are similar within tolerances\n            %\n            % catalog = catalog.REMOVEDUPLICATES() removes the duplicates according to default\n            % tolerances. To specify tolerances, add them as NAME - VALUE pairs.\n            %\n            % Valid Tolerances names are:\n            %   'tolHoriz_m'  : Horizontal distance tolerance, in meters\n            %   'tolVert_m' : Z tolerance, in meters\n            %   'tolTime'    : Time tolerance (in seconds) OR a duration\n            %   'tolMag'     : Magnitude Tolerance\n            %\n            % For example:\n            %   c = mycat.removeDuplicates('tolVert_m', 20 , 'tolTime', milliseconds(50))\n            %\n            % this only compares events adjacent in the catalog (sorted by time).\n            %\n            % catalog is returned in DateOrder\n            \n            \n            obj.sort('Date');\n            orig_size = obj.Count;\n            p = inputParser();\n            non_neg_scalar = @(x) isscalar(x) && x>=0;      % used to verify inputs\n            p.addOptional('tolHoriz_m'  , 10            , non_neg_scalar );\n            p.addOptional('tolVert_m'   , 0.5           , non_neg_scalar );\n            p.addOptional('tolTime'     , seconds(0.01) , non_neg_scalar );\n            p.addOptional('tolMag'      , 0.001         , non_neg_scalar );\n            p.parse(varargin{:})\n            \n            tols = p.Results;\n            if ~isduration(tols.tolTime)\n                tols.tolTime = seconds(tols.tolTime);\n            end\n            msg.dbfprintf(['Removing duplicates\\n Using Tolerances:\\n'...\n                '     Time : %10s\\n Horiz Dist : %6g m\\n    Vert Dist : %6g m\\n      Mag : %6.3f\\n'],...\n                tols.tolTime, tols.tolHoriz_m, tols.tolVert_m, tols.tolMag);\n            % Dip, DipDirection, Rake, MomentTensor are not included in calculation\n            \n            [dist, units] = obj.subset((1:obj.Count-1)).distanceTo(obj.Y(2:end), obj.X(2:end));\n            \n            isSame = abs(diff(obj.Date)) <= tols.tolTime & ...\n                dist <= tols.tolHoriz_m * unitsratio('meter', units) & ...\n                abs(diff(obj.Z))     <= tols.tolVert_m * unitsratio('meters', units) & ...\n                abs(diff(obj.Magnitude)) <= tols.tolMag;\n            sameidx = [false; isSame];\n            obj = obj.subset(~sameidx);\n            msg.dbfprintf('Removed %d duplicates\\n', orig_size - obj.Count);\n            obj.sort('Date')\n        end\n        \n        function h = scatter(obj, varargin)\n            if ~isempty(varargin) && isa(varargin{1}, 'matlab.graphics.axis.Axes')\n                ax = varargin{1};\n            else\n                ax = gca;\n            end\n            h = scatter(ax, obj.XYZ(:, 1), obj.XYZ(:, 2), varargin{:});\n            ax.XLabel.String = obj.XLabel;\n            ax.YLabel.String = obj.YLabel;\n        end\n        \n        function h = scatter3(obj, varargin)\n            if ~isempty(varargin) && isa(varargin{1}, 'matlab.graphics.axis.Axes')\n                ax = varargin{1};\n            else\n                ax = gca;\n            end\n            h = scatter3(ax, obj.XYZ(:, 1), obj.XYZ(:, 2), obj.XYZ(:, 3), varargin{:});\n            ax.XLabel.String = obj.XLabel;\n            ax.YLabel.String = obj.YLabel;\n            ax.ZLabel.String = obj.ZLabel;\n            ax.ZDir = obj.ZDir;\n        end\n        \n        function [ minicat, max_km ] = selectCircle(obj, esp, x, y, z )\n            %selectCircle Select events in a circle defined by either distance or number of events or both\n            % [ minicat, maxd ] = catalog.SELECTCIRCLE( SELCRIT, x, y, z ) where selcrit is an\n            % EventSelectionParameters object. The comparison point is x, y, z, where\n            % x, y are in degrees, and z is in km or is empty [].\n            % returns a catalog containing selected events, along with the maximum distance of the\n            % catalog from the chosen point\n            %\n            % see also selectClosestEvents, selectRadius, EventSelectionParameters\n            if ~(esp.UseEventsInRadius || esp.UseNumClosestEvents)\n                error('ZMAP:ZmapCatalog:selectCircle:NoCriteriaChosen',...\n                    'Error: Neither selection criteria was chosen. Results would be one value (repeated)');\n            end\n            [dists, distunits] = obj.distanceTo(y, x, z);\n            \n            mask = esp.SelectionFromDistances(dists, distunits);\n            minicat = obj.subset(mask);\n            max_km = max(dists(mask));\n        end\n        \n        function [other, max_km] = selectClosestEvents(obj, x, y, z, n , flag)\n            % SELECTCLOSESTEVENTS determine which N events are closest to a point (x, y, z).\n            % [otherCat, max_km] = catalog.SELECTCLOSESTEVENTS(x, y, z, nEvents)\n            % for epicentral distance, leave Z empty.\n            %  ex.  selectClosestEvents(mycatalog, 82, -120, [], 20);\n            % the distance to the nth closest event\n            %\n            %  catalog.SELECTCLOSESTEVENTS(... 'DistanceOnly')\n            %  FLAG can be 'DistanceOnly', which means otherCat is never created.\n            %  Use this optionwhen calling with a tilde.  For example: \n            %   [~, xxx] = catalog.SELECTCLOSESTEVENTS(x, y, z, nEvents, 'DistOnly')\n            % \n            % sorting is unaffected\n            %\n            % see also selectCircle, selectRadius\n            \n            [dists, distunits] = obj.distanceTo(x, y, z);\n            [smallest_dists, I] = mink(dists, n);\n            evIdx=false(size(dists));\n            evIdx(I)=true;\n            max_km = smallest_dists(end) .* unitsratio('kilometer', distunits);\n            if exist('flag', 'var') && flag==\"DistanceOnly\"\n                other = obj.subset(evIdx);\n            else\n                other=[];\n            end\n        end\n        \n        function other = selectRadius(obj, x, y, z, radius, radius_units)\n            %SELECTRADIUS  select subset catalog to a radius from a point\n            % catalog = catalog.SELECTRADIUS(x , y, radius, radius_units) epicentral radius from a point. sortorder is preserved\n            % catalog = catalog.SELECTRADIUS(x, y, z, radius, radius_units) hypocentral radius from a point. sortorder is preserved\n            %\n            % see also selectClosestEvents, selectCircle\n            if isempty('z')\n                [dists, distunits] = obj.distanceTo(x, y);\n            else\n                [dists, distunits] = obj.distanceTo(x, y, z);\n            end\n            \n            mask = dists <= radius .* unitsratio(distunits, radius_units);\n            other = obj.subset(mask);\n        end\n        \n        function [C, IA] = setdiff(A, B)\n            % returns values that are in A but not in B with no repetitions. NO tolerance.\n            % based solely on Date, X, Y, Z, and Magnitude\n            dateFmt='uuuu-MM-dd''T''HH:mm:ss.SSSSSSSSS';\n            \n            compstrA = string(A.Date, dateFmt)+join(string(A.XYZ))+\" \"+string(A.Magnitude);\n            compstrB = string(B.Date, dateFmt)+join(string(B.XYZ))+\" \"+string(B.Magnitude);\n            IA=ismember(compstrA, compstrB);\n            C=A.subset(~IA);\n        end\n        \n        function E = setxor(A, B)\n            % return combination of values that are either in A or B, but not in both. no tolerance\n            % based solely on Date,  X, Y, Z, and Magnitude\n            C=setdiff(A, B); % in A, not in B\n            D=setdiff(B, A); % in B, not in A\n            E = C.cat(D);\n        end\n        \n        function sort(obj, field, direction)\n            % SORT this catalog by the specified field (IN PLACE)\n            % catalog.SORT(field), where field is a valid ZmapCatalog property\n            %\n            % catalog.SORT(field, direction), where direction is 'ascend' or 'descend'\n            % ex.\n            % catalog.sort('Date', 'ascend')\n            %\n            % NOTE: modifies original\n            %\n            % see also sortedByDistanceTo\n            \n            if ~isprop(obj, field)\n                error('ZMAP:ZmapCatalog:sort:invalidSortField',...\n                    '%s is not a valid property of a ZmapCatalog', field);\n            end\n            if ~exist('direction', 'var')\n                direction = 'ascend';\n            end\n            [~, idx] = sort(obj.(field), direction);\n            obj.subsetInPlace(idx);\n            obj.IsSortedBy      = field;\n            obj.SortDirection   = direction;\n        end\n        \n        function other = sortedByDistanceTo(obj, x, y, varargin)\n            % SORTEDBYDISTANCE returns a catalog that has been sorted by distance to a point\n            % ans=catalog.SORTEDBYDISTANCE(x, y) % epicentral sort\n            % ans=catalog.SORTEDBYDISTANCE(x, y, z) % hypocentral sort\n            %\n            % does NOT modify original\n            [~, idx]   = sort(obj.distanceTo(x, y, varargin{:}));\n            other     = obj.subset(idx);\n            other.IsSortedBy    = 'distance';\n            other.SortDirection = 'ascending';\n        end\n        \n        function newobj = subset(obj, range)\n            % SUBSET get a subset of this object\n            % newcatalog = catalog.SUBSET(mask) where mask is a t/f array matching obj.Count\n            %    will keep all \"true\" events\n            % newcatalog = catalog.SUBSET(range), where range evaluates to an integer array\n            %    will retrieve the specified events.\n            %    this option can be used to change the order of the catalog too\n            \n            newobj             = obj.blank();\n            newobj.Name        = obj.Name;\n            \n            if isempty(range) || ~any(range)\n                return\n            end\n            \n            if islogical(range)\n                cnt = obj.Count;\n                if numel(range) == 1 && range && cnt > 1\n                    range = true(cnt, 1);\n                end\n                if ~any(size(range) == cnt)\n                    error('ZMAP:ZmapCatalog:subset:invalidDimension','When using logical indexing, one dimension must be the length of the catalog')\n                end\n            elseif ~isvector(range)\n                error('ZMAP:ZmapCatalog:subset:tooManySubsets','multiple concurrent subsets not supported')\n            end\n            \n            the_fields = obj.fields_that_must_be_nevent_length();\n            for n = 1 : numel(the_fields)\n                fn = the_fields{n};\n                newobj.(fn) = obj.(fn)(range, :); % always copy rows\n            end\n            \n            the_fields = obj.possibly_empty_fields();\n            for n = 1 : numel(the_fields)\n                fn = the_fields{n};\n                if ~isempty(obj.(fn))\n                    newobj.(fn) = obj.(fn)(range, :); % always copy rows\n                end\n            end\n            for n = 1 : numel(obj.OtherFields)\n                newobj.OtherFields{n} = obj.OtherFields{n}.subset(range);\n            end\n        end\n        \n        function subsetInPlace(obj, range)\n            % SUBSET_IN_PLACE modifies this object, not a copy of it.\n            the_fields = obj.fields_that_must_be_nevent_length();\n            for n = 1 : numel(the_fields)\n                fn = the_fields{n};\n                obj.(fn) = obj.(fn)(range, :); % always copy rows\n            end\n            \n            the_fields = obj.possibly_empty_fields();\n            for n = 1 : numel(the_fields)\n                fn = the_fields{n};\n                if ~isempty(obj.(fn))\n                    obj.(fn) = obj.(fn)(range, :); % always copy rows\n                end\n            end\n            for n = 1 : numel(obj.OtherFields)\n                obj.OtherFields{n}.subsetInPlace(range);\n            end\n        end\n        \n        function s = summary(obj, verbosity)\n            % SUMMARY return a summary of this catalog\n            % valid verbosity values: 'simple', 'stats'\n            \n            tFmt = 'uuuu-MM-dd HH:mm:ss';\n            \n            % add additional ways to look at catalog if it makes sense\n            if ~exist('verbosity', 'var')\n                verbosity = '';\n            end\n            if numel(obj) > 1\n                s = sprintf('%d Catalogs', numel(obj));\n                return\n            end\n            \n            if isempty(obj) || obj.Count==0\n                s = sprintf('Empty Catalog, named \"%s\"', obj.Name);\n                return\n            end\n            leq = char(8804); %pretty version of <= , because a typed representation doesn't work across all platforms.\n            depUn = shortenLengthUnit(obj.LengthUnit);\n            \n            switch verbosity\n                case 'simple'\n                    trange = bounds2(obj.Date);\n                    mrange = bounds2(obj.Magnitude);\n                    drange = bounds2(obj.Z);\n                    mtypes  = cat2mtypestring();\n                    fmtstr  = [...\n                        'Catalog \"%s\" with %d events\\n',...\n                        'Start Date: %s\\n',...\n                        'End Date:   %s\\n',...\n                        obj.ZLabel, ':     %4.2f ', depUn, ' ', leq, ' Z ', leq, ' %4.2f', depUn, '\\n',...\n                        'Magnitudes: %2.1f ', leq, ' M ', leq, ' %2.1f\\n',...\n                        'MagnitudeTypes: %s'];\n                    s = sprintf(fmtstr, obj.Name, obj.Count, string(trange(:), tFmt), drange, mrange, mtypes);\n                case 'stats'\n                    trange = bounds2(obj.Date);\n                    mrange = bounds2(obj.Magnitude);\n                    drange = bounds2(obj.Z);\n                    \n                    fmtstr = [...\n                        'Catalog \"%s\"\\nNumber of events: %d\\n',...\n                        'Start Date: %s\\n',...\n                        'End Date:   %s\\n',...\n                        '  %s\\n',...\n                        obj.ZLabel, ':     %4.2f ', depUn, ' ', leq, ' Z ', leq, ' %4.2f ', depUn, '\\n',...\n                        '  %s\\n',...\n                        'Magnitudes: %2.1f ', leq, ' M ', leq, ' %2.1f\\n',...\n                        '  %s\\n',...\n                        'Magnitude Types: %s'];\n                    \n                    mean_int    = mean(diff(obj.Date));\n                    median_int  = median(diff(obj.Date));\n                    std_int     = std(diff(obj.Date));\n                    mean_int.Format     = 'd';\n                    median_int.Format   = 'd';\n                    std_int.Format      = 'd';\n                    if std_int < 10\n                        std_int.Format      = 'hh:mm:ss';\n                    end\n                    if mean_int < 10\n                        mean_int.Format     = 'hh:mm:ss';\n                    end\n                    if median_int < 10\n                        median_int.Format   = 'hh:mm:ss';\n                    end\n                    meanstdmedian = @(x) [mean(x), std(x) median(x)];\n                    s = sprintf(fmtstr, obj.Name, obj.Count, ...\n                        string(trange, tFmt),...\n                        sprintf('intervals: mean: %s \u00b1std %s , median: %s', mean_int, std_int, median_int),...\n                        drange, sprintf('mean: %.3f \u00b1std %.3f , median: %.3f', meanstdmedian(obj.Z)),...\n                        mrange, sprintf('mean: %.2f \u00b1std %.2f , median: %.2f', meanstdmedian(obj.Magnitude)),...\n                        cat2mtypestring());\n                case 'list'\n                    fprintf('Catalog \"%s\" with %d events\\n', obj.Name, obj.Count);\n                    fprintf('Date                      %3s       %3s   %3s(%s)    Mag  MagType\\n', obj.YLabel, obj.XLabel, obj.ZLabel, depUn);\n                    for n=1:obj.Count\n                        fmtstr  = '%s  %8.4f  %9.4f   %6.2f   %4.1f   %s\\n';\n                        mt      = obj.MagnitudeType(n);\n                        fprintf( fmtstr, string(obj.Date(n), tFmt),...\n                            obj.Y(n), obj.X(n), obj.Z(n), obj.Magnitude(n), mt);\n                    end\n                otherwise\n                    s = sprintf('Catalog \"%s\", containing %d events', obj.Name, obj.Count);\n            end\n            function mtypes = cat2mtypestring()\n                % CAT2MTYPESTRING returns a string representation of the catalog type\n                % mtypes = CAT2MTYPESTRING()\n                mtypes = strjoin(categories(unique(obj.MagnitudeType)), ', ');\n                if isempty(mtypes)\n                    mtypes = '-none-';\n                end\n            end\n        end\n        \n        function tbl = table(obj)\n            % TABLE write catalog as a table.\n            %\n            warnState=warning('off', 'MATLAB:structOnObject');\n            st       = struct(obj);\n            warning(warnState.state, warnState.identifier); %restore\n            \n            flds     = fieldnames(st);\n            % to  convert to a table, all fields must be of same length\n            % but some fields aren't individual to events.\n            todelete = structfun(@(x)numel(x)~=st.Count , st);\n            st       = rmfield(st, flds(todelete));\n            tbl      = struct2table(st);\n            tbl.Properties.Description = obj.Name;\n        end\n        \n        \n        function validate(obj)\n            % check validity of the catalog\n            data_len_fn = @(x)size(obj.(x), 1);\n            flds =  obj.fields_that_must_be_nevent_length();\n            data_lengths = unique(cellfun(data_len_fn, flds));\n            if numel(unique(data_lengths)) ~= 1\n                error( 'ZMAP:ZmapCatalog:validate:inconsistentFieldLengths', 'not all data fields are same length: %s', mat2str(data_lengths));\n            end\n            expected_len = data_lengths(1);\n            data_len_fn = @(x) isempty(obj.(x)) || numel(obj.(x)) == expected_len; % returns TF vector\n            \n            flds = obj.possibly_empty_fields();\n            data_len_ok = cellfun(data_len_fn, flds );\n            if ~all(data_lengths_ok)\n                error('ZMAP:ZmapCatalog:validate:incorrectFieldLengths','incorrect field lengths for: %s', strjoin(flds(~data_len_ok), ','));\n            end\n        end\n    end\n    \n    methods(Hidden)\n        % helper methods\n        function [dists, units] = cartesianEpicentralDistanceTo(obj, x, y)\n            % get distance from all events to a point (assuming Z is same for all)\n            dists = sqrt(sum((obj.XYZ(:, 1:2) - [x, y]).^ 2));\n            units = obj.HorizontalUnit;\n        end\n        \n        function [dists, units] = cartesianHypocentralDistanceTo(obj, x, y, z)\n            % get 3D distance from all events to a point\n            %\n            % [dists, units] = obj.hypocentralDistanceTo(x, y, z)\n            % [dists, units] = obj.hypocentralDistanceTo([x, y, z])\n            if nargin == 2 && ( isequal(size(x), [1 3]) || isequal(size(x), size(obj.XYZ)) )\n                dists = sqrt(sum((obj.XYZ - x) .^2));\n            else\n                dists = sqrt(sum((obj.XYZ - [x, y, z]) .^2));\n            end\n            units = obj.HorizontalUnit;\n        end\n        \n        function [dists, units] = geodeticEpicentralDistanceTo(obj, to_lat, to_lon)\n            % get epicentral (lat-lon) distance to another point\n            % [dists, units] = catalog.EPICENTRALDISTANCETO(to_lat, to_lon) returns the distance in the same\n            % units as the catalog's RefEllipsoid.\n            dists    = distance(obj.Latitude, obj.Longitude, to_lat, to_lon, obj.RefEllipsoid);\n            units = obj.RefEllipsoid.LengthUnit;\n        end\n        \n        function [dists, units] = geodeticHypocentralDistanceTo(obj, to_lat, to_lon, to_depth_km)\n            % get hypocentral distance (3-D distance) to another point\n            % [dists_km, units] = catalog.HYPOCENTRALDISTANCETO(to_lat, to_lon, to_depth_km)\n            if obj.RefEllipsoid.LengthUnit == \"kilometer\"\n            dists     = distance(obj.Latitude, obj.Longitude, to_lat, to_lon, obj.RefEllipsoid);\n            delta_dep = (obj.Depth - to_depth_km);\n            dists     = sqrt( dists .^ 2 + delta_dep .^ 2);\n            units     = obj.RefEllipsoid.LengthUnit;\n            else\n                error('ZMAP:ZmapCatalog:incompatibleLengthUnit','For geodetic hypocentral distance, the ref ellipsoid must be kilometer, not %s',...\n                    obj.RefEllipsoid.LengthUnit);\n            end\n        end\n    end\n    \n    methods(Static)\n        function obj = blank()  % To be implemented by every ZmapCatalog subclass\n            % return a blank catalog\n            obj = ZmapCatalog();\n        end\n        \n        function obj = from(other)\n            % create a zmap catalog from something else.\n            % if it is another zmap catalog, then it is copied\n            if isnumeric(other)\n                obj = ZmapCatalog.fromZmapArray(other);\n            elseif istable(other)\n                obj = ZmapCatalog.fromTable(other);\n            elseif isstruct(other)\n                obj = ZmapCatalog.fromStruct(other);\n            elseif isa(other, 'ZmapCatalog')\n                obj = copy(other);\n            else\n                error('ZMAP:ZmapCatalog:unableToConvertfrom',...\n                    'There is no known method to create a ZmapCatalog from a %s', class(other))\n            end\n        end\n        \n        function obj = fromTable(other)\n            % catalog = ZMAPCATALOG(table) create a catalog from a table\n            if ~istable(other)\n                error('ZMAP:ZmapCatalog:unableToConvertFrom',...\n                      'attempted to create a ZmapCatalog from a table, but was instead provided a %s',class(other));\n            end                          % ZMAPCATALOG(table)\n            \n            other = table2zmapcatalogtable(other);\n            obj=ZmapCatalog();\n            vn = other.Properties.VariableNames;\n            for i = 1:numel(vn)\n                fieldname = vn{i};\n                try\n                    obj.(fieldname) = other.(fieldname);\n                catch ME\n                    fprintf('Error interpreting field: %s\\n', fieldname);\n                    warning(ME.message);\n                end\n            end\n            \n            if ~any(vn == \"MagnitudeType\") || isempty(obj.MagnitudeType)\n                obj.MagnitudeType = repmat(categorical({''}), size(obj.Magnitude));\n            end\n            if ~any(vn == \"EventID\") || isempty(obj.EventID)\n                obj.EventID = generate_event_ids(obj.Date);\n            end\n            \n            obj.Name    = other.Properties.Description;\n            pu          = other.Properties.VariableUnits;\n            \n            % automatically convert depth units\n            if ~isempty(pu)\n                depthIdx = vn == \"Depth\";\n                if any(depthIdx)\n                    units       = validateLengthUnit(pu{depthIdx});\n                    obj.Depth   = unitsratio(obj.LengthUnit, units) * obj.Depth;\n                end\n            end\n        end\n        \n        function obj = fromZmapArray(other, refEllipse)\n            % catalog = ZMAPCATALOG(zmaparray) create a catalog from a ZmapArray with columns:\n            %   [longitude, latitude, decyear, month, day, magnitude, depth_km, hour, minute, second]\n            \n            \n            nCols = size(other, 2);\n            \n            validArray = isnumeric(other) && nCols >= 9 ...\n                && all(abs(other(:,1)) <= 180)  ... check longitude\n                && all(abs(other(:,2)) <= 90) ... check latitude\n                && all(other(:,4) > 0) && all(other(:,4) <= 12) ... check month\n                && all(other(:,8) >= 0) && all(other(:,8) <= 24) ... check hour\n                && all(other(:,9) >= 0) && all(other(:,9) <= 60); % check minute\n            \n            if validArray && nCols == 10\n                validArray = all(other(:, 10) >= 0) && all(other(:, 10) <= 60); % check seconds\n            end\n            \n            if ~validArray \n                error('ZMAP:ZmapCatalog:unableToConvertFrom', ['(older) Zmap Arrays are Expected to be 9 or 10 column numeric matrix, containing:\\n',...\n              '[ lon lat decyr month day mag dep hr min [sec] ]']')\n            end\n            \n            if ~any(other(:,3) > 100) && all(other(:,3)>=0)\n                error('ZMAP:ZmapCatalog:ambiguousDates', ['The catalog dates appear to have 2-digits years.',...\n                ' Change to 4-digit years before importing']);\n            end\n            \n            % import Catalog from Array\n            if nCols == 12\n                mta = MomentTensorAddon();\n                mta.Dip = other(:, 10);\n                mta.DipDirection = other(:, 11);\n                mta.Rake = other(:, 12);\n                nCols = 9;\n                % instead of seconds, it is dip, dip direction, and rake.\n            end\n            msg.dbfprintf(['importing from old catalog array with %d columns and %d events:\\n'...\n                '[ lon lat decyr month day mag dep hr min sec ]\\n'], nCols, size(other, 1));\n            \n            if ~exist('refEllipse', 'var')\n                refEllipse = referenceEllipsoid('earth', 'kilometer');\n            end\n            if iscartesian(ZmapCatalog.DefaultRefEllipsoid()),...\n                error('ZMAP:ZmapCatalog:incompatibleRefEllipsoid',...\n                'ZMAP arrays are in Lat-Lon, and is incompatible with this ZMAP session, which is in cartesian mode');\n            end   \n            obj = ZmapCatalog();\n            other(:, 7) = other(:, 7) .* unitsratio(obj.LengthUnit, refEllipse.LengthUnit);\n            obj.XYZ = other(:, [1, 2, 7]);\n            if nCols==9 % no column for SECONDS\n                other(:, 10)=0;\n            end\n            obj.Date = datetime([floor(other(:, 3)), other(:, [4, 5, 8, 9, 10])]);\n            \n            obj.Magnitude       = other(:, 6);\n            obj.MagnitudeType   = repmat(categorical(missing), size(obj.Magnitude));\n            \n            obj.EventID = generate_event_ids(obj.Date);\n            if exist('mta', 'var')\n                obj.OtherFields{1}=mta;\n            end\n        end\n        \n        function obj = fromStruct(other)\n            % requires exact names: [Longitude, Latitude, (or XYZ)], Magnitude, Depth, Date, MagnitudeType, Name[, Filter]\n            obj=ZmapCatalog();\n            if isfield(other, 'Name'), obj.Name = other.Name;end\n            if isfield(other, 'Date')\n                if ~isdatetime(other.Date)\n                    error('ZMAP:ZmapCatalog:unableToConvertFrom',...\n                        'Incoming dates must have datetime values, not %s',class(other.Date))\n                end\n                obj.Date = other.Date(:);\n            end\n            if isfield(other, 'XYZ')\n                obj.XYZ = other.XYZ;\n            elseif isfield(other, 'Latitude')\n                obj.XYZ=[other.Longitude(:), other.Latitude(:), other.Depth(:)];\n            elseif isfield(other, 'X')\n                obj.XYZ=[other.X(:), other.Y(:), other.Z(:)];\n            else\n                error('ZMAP:ZmapCatalog:unableToConvertFrom',...\n                    ['unable to determine XYZ or Latitude/Longitude/Depth. Please make sure the',...\n                    ' field names are exact. ''XYZ'' or ''Latitude'',''Longitude'', and ''Depth'''])\n            end\n            \n            if isfield(other,'EventID')\n                obj.EventID = other.EventID;\n            else\n                if ~isempty(obj.Date)\n                    obj.EventID = generate_event_ids(obj.Date);\n                else\n                    obj.EventID = generate_event_ids(1:size(obj.XYZ,1));\n                end\n            end\n            if isfield(other, 'Magnitude')\n                obj.Magnitude = other.Magnitude(:);\n            end\n            if isfield(other, 'MagnitudeType')\n                obj.MagnitudeType = other.MagnitudeType(:);\n            end\n        end\n        \n    end\n    methods(Static, Hidden)\n        \n        function val = GetFieldnamesForColorby()\n            if iscartesian(ZmapGlobal.Data.ref_ellipsoid)\n                val = {'Z', 'Date', 'Magnitude', '-none-'};\n            else\n                val = {'Depth', 'Date', 'Magnitude', '-none-'};\n            end\n        end\n        \n        function s = display_order()  % To be implemented by every ZmapCatalog subclass\n            % get fields to display, in order.\n            \n            if iscartesian(ZmapCatalog.DefaultRefEllipsoid())\n                    s = {'Name', 'Type', 'Date', 'DateSpan',...\n                        'X', 'Y', 'Z', 'LengthUnit',...\n                        'Magnitude', 'MagnitudeType',...\n                        'IsSortedBy', 'SortDirection' ...\n                        };\n            else\n                    % get fields to display, in order.\n                    s = {'Name', 'Type', 'Date', 'DateSpan',...\n                        'RefEllipsoid',...\n                        'Longitude', 'Latitude', 'Depth', 'LengthUnit',...\n                        'Magnitude', 'MagnitudeType',...\n                        'IsSortedBy', 'SortDirection', ...\n                        };\n            end\n        end\n        \n        function mbnel = fields_that_must_be_nevent_length()  % To be implemented by every ZmapCatalog subclass\n            mbnel = {'Date', 'Magnitude', 'XYZ','EventID'};\n        end\n        \n        function pef = possibly_empty_fields()  % To be implemented by every ZmapCatalog subclass\n            % fields that may either match the # of events, or be empty\n            pef = {'MagnitudeType', 'Filter'};\n        end\n        \n\n    end\nend\n\n\nfunction EventIDs = generate_event_ids(values_to_sort_by, prefix)\n    if ~exist('prefix','var')\n        prefix = 'zmapunk.';\n    end\n    [~, orig_idx] = sort(values_to_sort_by);\n    fmtstr=\"n%0\" + ceil(log10(numel(orig_idx))+1) + \"d\";\n    EventIDs = strcat(string(prefix), arrayfun(@(n)sprintf(fmtstr,n),orig_idx));\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/ZmapCatalog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2324117424376167}}
{"text": "function [newDietModel,pointsModel,roiFlux,pointsModelSln,menuChanges] = nutritionAlgorithmWBM(model,obj,objMinMax,rois,roisMinMax,options)\n% Identifies the minimal changes to a diet necessary to get a desired\n% change in one or more reactions of interest. One may enter a metabolite\n% of the pointsModel instead of a reaction and the algorithm will optimize the\n% diet with a sink or demand reaction for the corresponding metabolite of\n% interest.\n%\n% USAGE:\n%\n%    [newDietModel,pointsModel,slnMin,slnMax,pointsModelSln,itemsRemoved,itemsAdded] = nutritionAlgorithmWBM(pointsModel,obj,objMinMax,rois,roisMinMax,options)\n%\n%     Example: [newDietModel,pointsModel,roiFlux,pointsModelSln,itemsRemoved,itemsAdded] = nutritionAlgorithmWBM(WBmodel,'Whole_body_objective_rxn','max',{},{})\n%\n% INPUTS:\n%    pointsModel:          COBRA pointsModel structure with the fields:\n%                      * .S\n%                      * .b\n%                      * .ub\n%                      * .ub\n%                      * .mets  (required if pointsModel.SIntRxnBool absent)\n%                      * .rxns  (required if pointsModel.SIntRxnBool absent)\n%\n%   obj:           organism's objective function\n%\n%   objMinMax:     minimize ('min') or maximize ('max') objective function\n%\n%   rois:          cell array of all reactions of interest\n%\n%   roisMinMax:    cell array of 'min'/'max' entries for rois\n%\n% OPTIONAL INPUTS:\n%   options:  Structure containing the optional specifications:\n%\n%       * .foodOrMets:  dictates if the algorithm adds individual\n%       metabolites to the diet or food items. Default is food items.\n%       \"Food Cat\" adjust algorithm to identify categories of food rather \n%       than specific items.\"AllMets\" allows any dietary metabolite into \n%       the solution and \"FoodMets\" only allows metabolites that are in \n%       the fdTable spreadsheet into the solution.\n%       Possible inputs are: \"Food Items\", \"Food Cat\", \"AllMets\", \"FoodMets\".\n%\n%       * .roiWeights:   a vector of weights for each reaction of interest\n%       default is equal to 1\n%\n%       * .weightedFoodItems: A cell vector that specifies any food items \n%       or metabolites that should be weighted and the corresponding weight. \n%\n%       * .initObjSln: provide an initial solution for the objective\n%       function. Output from optimizeWBmodel.\n%\n%       * .caloricRange: 1x2 vector defining boundries for diet calories\n%\n%       * .slnType: Specify if solution should be 'Detailed' or 'Quick'.\n%                   Default setting is 'Detailed'\n%\n%       * .roiBound: 'Unbounded' or 'Bounded'. Default is 'Bounded'.\n%\n%       * .foodAddedLimit: Specify a limit for the units of food that can\n%                          be added to the diet\n%\n%       * .foodRemovedLimit: Specify a limit for the units of food that can\n%                          be removed from the diet\n%\n%       * .freeMets: Specifies any metabolites that should be freely\n%       available to the model.\n%\n%       * .calorieWeight: set to 'True' to weight by caloric content rather\n%       than servings. Default is 'False'\n%\n%       * .graphicalAnalysis: set to 'True' include graphical analysis and\n%       'False' to not include. Default is 'False' if .slnType is set to\n%       'Quick but is 'True; if .slnType is 'Detailed'. \n%\n% OUTPUT:\n%    solution:       Structure containing the following fields:\n%\n% relaxedModel       pointsModel structure that admits a flux balance solution\n%\n% .. Authors: - Bronson R. Weston   2021-2022\n\n\ndisp('_____________________________________________________')\n%is foodOrMets variable established in the options struct?\nif exist('options','var')\n    if isfield(options,'foodOrMets')\n        foodOrMets=options.foodOrMets;\n    else\n        foodOrMets='Food Items';\n    end\nend\n\n%Identify which tables should be loaded\nif strcmp(foodOrMets,'Food Items')\n    load('fdTable.mat')\nelseif strcmp(foodOrMets,'Food Cat')\n    try\n        load('FoodCategories/fdCategoriesTable.mat')\n    catch\n        load('fdCategoriesTable.mat')\n    end\n    fdTable=fdCategoriesTable;\nelseif ~strcmp(foodOrMets,'FoodMets') && ~strcmp(foodOrMets,'AllMets')\n    error('foodOrMets invalid. Possible inputs are: \"Food Items\", \"Food Cat\", \"AllMets\", \"FoodMets\".')\nelse\n    options.graphicalAnalysis\n    try\n        strcmp(options.graphicalAnalysis,'True')\n        warning('graphicalAnalysis not available for metabolite based solutions at this time. Only for food items or categories')\n        options.graphicalAnalysis='False';\n    catch\n    end\n    load('fdTable.mat')\nend\n\nmodel = changeObjective(model,obj);\nmodel.osenseStr = objMinMax;\n\n% Determine if any rois are metabolites\nmetRois=[];\nfor i=1:length(rois)\n    if any(strcmp(model.mets,rois{i}))\n        metRois=[metRois,i];\n        %         if strcmp(slnType,'Detailed')\n        %             slnType='Quick';\n        %             disp('slnType changed to Quick because one or more rois defined as a metabolite')\n        %         end\n        if strcmp(roisMinMax{i},'max')\n            model=addDemandReaction(model,rois{i}); %adds demand reaction as 'DM_metabolite'\n            rois{i}=['DM_',rois{i}];\n            model=changeRxnBounds(model,rois{i},100000,'u');\n        else\n            model=addSinkReactions(model,rois(i),-100000,0);\n            rois{i}=['sink_',rois{i}];\n        end\n    end\nend\n\n%initialize optional variables\nroiWeights=10*ones(1,length(rois));\ninitObjSln=[];\nweightedFoodItems={};\ncaloricRange=[0 1e6];\nslnType='Detailed';\nroiBound='Bounded';\nfoodAddedLimit=1000000;\nfoodRemovedLimit=1000000;\ncalorieWeight='False';\nfreeMets={};\ntry\n    if strcmp(options.slnType,'Detailed')\n        graphicalAnalysis='True';\n    else\n        graphicalAnalysis='False';\n    end\ncatch\n    graphicalAnalysis='True';\nend\n\nif exist('options','var')\n    fn = fieldnames(options);\n    for k=1:numel(fn)\n        %         if( isnumeric(options.(fn{k})) )\n        %             % do stuff\n        %         end\n        if strcmp(fn{k},'roiWeights')\n            roiWeights=options.roiWeights;\n            if length(roiWeights)~=length(rois)\n                error('length of roiWeights vector must be the same as items rois')\n            end\n        elseif strcmp(fn{k},'foodOrMets')\n            foodOrMets=options.foodOrMets;\n        elseif strcmp(fn{k},'calorieWeight')\n            try\n                foodOrMets=options.foodOrMets;\n            catch\n            end\n            if strcmp(foodOrMets,'Food Items') || strcmp(foodOrMets,'Food Cat')\n                calorieWeight=options.calorieWeight;\n            else\n                if strcmp(options.calorieWeight,'True') || strcmp(options.calorieWeight,'true')\n                    error('\"calorieWeight\" cannot be True for metabolite solutions')\n                end\n            end\n        elseif strcmp(fn{k},'roiBound')\n            roiBound=options.roiBound;\n            if ~strcmp(roiBound,'Unbounded') && ~strcmp(roiBound,'Bounded')\n                error('Invalid roiBound input. Must be \"Unbounded\" or \"Bounded\"')\n            end\n        elseif strcmp(fn{k},'graphicalAnalysis')\n            graphicalAnalysis=options.graphicalAnalysis;\n            if ~strcmp(graphicalAnalysis,'True') && ~strcmp(graphicalAnalysis,'False')\n                error('Invalid graphicalAnalysis input. Must be \"True\" or \"False\"')\n            end\n        elseif strcmp(fn{k},'foodAddedLimit')\n            foodAddedLimit=options.foodAddedLimit;\n        elseif strcmp(fn{k},'foodRemovedLimit')\n            foodRemovedLimit=options.foodRemovedLimit;\n        elseif strcmp(fn{k},'initObjSln')\n            initObjSln=options.initObjSln;\n        elseif strcmp(fn{k},'freeMets')\n            freeMets=options.freeMets;\n        elseif strcmp(fn{k},'caloricRange')\n            caloricRange=options.caloricRange;\n        elseif strcmp(fn{k},'slnType')\n            slnType=options.slnType;\n            if ~strcmp(slnType,'Detailed') && ~strcmp(slnType,'Quick')\n                error('Invalid slnType input. Must be \"Detailed\" or \"Quick\"')\n            end\n        elseif strcmp(fn{k},'weightedFoodItems')\n            weightedFoodItems=options.weightedFoodItems;\n            if any(contains(options.weightedFoodItems(:,1),'Any_'))\n                for i=length(options.weightedFoodItems(:,1)):-1:1\n                    word=strsplit(options.weightedFoodItems{i,1},'Any_');\n                    if isempty(word{1}) %If the word starts with 'Any_'\n                        tmp=fdTable.Properties.VariableNames(contains(fdTable.Properties.VariableNames,word{2})).';\n                        tmp=[tmp,num2cell(weightedFoodItems{i,2}*ones(length(tmp),1))];\n                        weightedFoodItems(i,:)=[];\n                        weightedFoodItems=[weightedFoodItems;tmp];\n                    end\n                end\n            end\n        else\n            error(['Invalid \"options\" field entered: ', fn{k}])\n        end\n    end\nend\n\nif any(roiWeights<=0)\n    error('\"roiWeights\" variable must be greater than zero')\nend\n\n%adjust ub and lb if roiBound specifies 'Unbound'\nif strcmp(roiBound, 'Unbounded')\n    for i=1:length(rois)\n        f=find(strcmp(model.rxns,rois{i}));\n        if strcmp(roisMinMax{i},'max')\n            if model.ub(f)~=0\n                model.ub(f)=100000;\n            end\n        else\n            if model.lb(f)~=0\n                model.lb(f)=-100000;\n            end\n        end\n    end\nend\n\nfor i=1:length(freeMets)\n    str=['Diet_EX_',freeMets{i},'[d]'];\n    try\n        if strcmp(freeMets{i},'h2o')\n            model = changeRxnBounds(model, str, -1e7, 'l');\n        else\n            model = changeRxnBounds(model, str, -1e5, 'l');\n        end\n    catch\n        error(['Invalid metabolite specified in freeMets: ', freeMets{i}])\n    end\nend\n\n\n\nnewDietModel=model; %Copy original instance of model for new diet pointsModel\npointsModel=model; %Copy original instance of model for points pointsModel\n\n\n%Calculate newDietModel objective function and restrict obj in main pointsModel\nobjIndex=find(contains(model.rxns,obj));\n%\n% roiIndex=find(strcmp(newDietModel.rxns,roi));\n% disp(['Reaction of Interest = ', newDietModel.rxns{roiIndex}])\nroiIndexO=zeros(1,length(rois));\nfor i=1:length(roiIndexO)\n    roiIndexO(i)=find(strcmp(newDietModel.rxns,rois{i}));\n    disp(['Reaction of Interest ', num2str(i),' = ', newDietModel.rxns{roiIndexO(i)}])\nend\n\n\n% get flux of objective function\nif ~isempty(initObjSln)\n    model_Obj=initObjSln;\n    f1=model_Obj.f;\n    initRoiFlux=model_Obj.v(roiIndexO);\nelseif model.ub(objIndex)~=model.lb(objIndex)\n    model_Obj = optimizeWBModel(newDietModel);\n    f1=model_Obj.f;\n    initRoiFlux=model_Obj.v(roiIndexO);\nelse\n    f1=model.ub(objIndex);\n    initRoiFlux=NaN(1,length(rois));\nend\n\n\n\n\n% If sln type is detailed, check if roi is already min or maxed out and\n% if not, define min max range for roi\n\nif strcmp(slnType,'Detailed')\n    for i=1:length(rois)\n        if initRoiFlux(i)==newDietModel.lb(roiIndexO)\n            OroiFluxMin(i)=newDietModel.lb(roiIndexO(i));\n        else\n            pointsModel = changeObjective(pointsModel,rois{i});\n            pointsModel.osenseStr = 'min';\n            sln = optimizeWBModel(pointsModel);\n            OroiFluxMin(i)=sln.v(roiIndexO(i));\n        end\n        if initRoiFlux(i)==newDietModel.ub(roiIndexO)\n            OroiFluxMax(i)=newDietModel.ub(roiIndexO(i));\n        else\n            pointsModel = changeObjective(pointsModel,rois{i});\n            pointsModel.osenseStr = 'max';\n            sln = optimizeWBModel(pointsModel);\n            OroiFluxMax(i)=sln.v(roiIndexO(i));\n        end\n    end\nend\npointsModel=addMetabolite(pointsModel, 'unitOfFoodAdded[dP]');\npointsModel=addMetabolite(pointsModel, 'unitOfFoodRemoved[dP]');\npointsModel=addMetabolite(pointsModel, 'unitOfFoodChange[dP]');\npointsModel=addMetabolite(pointsModel, 'roiPoint[roiP]');\npointsModel=addMetabolite(pointsModel, 'point[P]');\n\nfdTableMod=fdTable;\npro_Dindex=find(contains(fdTableMod.Var1,'pro_D')); %for now, remove pro_D from table.\nfdTableMod(pro_Dindex,:)=[];\n% eIndex=find(contains(fdTableMod.Var1,'Energy in Kcal'));  %remove Energy row from table.\n% fdTableMod(eIndex,:)=[];\n\n%Now add row for unitOfFoodAdded variable\ntableChange=num2cell(ones(1,length(fdTableMod.Properties.VariableNames)-1));\ntableChange=['unitOfFoodAdded',tableChange];\ntableChange=cell2table(tableChange,'VariableNames',fdTableMod.Properties.VariableNames);\nfdTableMod=[fdTableMod;tableChange];\n\n%Modify unitOfFoodAdded points based on weight from weightedFoodItems\nif ~isempty(weightedFoodItems)\n    fdTableMod(end, fdTableMod.Properties.VariableNames(weightedFoodItems(:,1)))=(weightedFoodItems(:,2).');\nend\n\nif strcmp(foodOrMets,'Food Items') || strcmp(foodOrMets,'Food Cat')\n    %Specify all food reactions and food metabolites\n    if strcmp(calorieWeight,'True')\n        fdTableMod{end,2:end}=fdTableMod{end-1,2:end}/206.28;\n    end\n    foodRxns=fdTableMod.Properties.VariableNames(2:end);\n    foodRxns=strcat('Food_Added_EX_',foodRxns);\n    foodRxns=strcat(foodRxns,'[d]');\n    foodMetabolites= fdTableMod.Var1;\n    foodMetabolites= strcat(foodMetabolites.','[d]');\n    uof=find(contains(foodMetabolites,'unitOfFoodAdded'));\n    foodMetabolites{uof}='unitOfFoodAdded[dP]';\n    %Include food added reaction to pointsModel\n    sMatrix=-1*table2array(fdTableMod(1:length(foodMetabolites),2:end));\n    pointsModel = addMultipleReactions(pointsModel, foodRxns, foodMetabolites, sMatrix, 'lb', -100000*ones(1,length(foodRxns)), 'ub', zeros(1,length(foodRxns)));\n    pointsModel = addMultipleReactions(pointsModel, {'Point_EX_unitOfFoodRemoved2Change[dp]','Point_EX_unitOfFoodAdded2Change[dp]','Point_EX_unitOfFoodChange[dP]_[P]','Point_EX_Point[P]'}, {'unitOfFoodRemoved[dP]','unitOfFoodAdded[dP]','unitOfFoodChange[dP]','point[P]'}, [-1 0 0 0;0 -1 0 0;1 1 -1 0;0 0 1 -1], 'lb', [-1000000,-1000000, -1000000,-1000000], 'ub', [foodRemovedLimit,foodAddedLimit,1000000,1000000]);\n    % pointsModel = addMultipleReactions(pointsModel, {'Point_EX_unitOfFoodChange[dP]_[P]','Point_EX_Point[P]','Excretion_EX_Energy'}, {'unitOfFoodChange[dP]','point[P]','Energy in Kcal[d]'}, [-1 0 0;1 -1 0; 0 0 -1], 'lb', [-1000000,-1000000,caloricRange(1)], 'ub', [1000000,1000000,caloricRange(2)]);\nelseif strcmp(foodOrMets,'AllMets') || strcmp(foodOrMets,'allMets')\n    foodRxns= find(contains(pointsModel.rxns,'Diet_EX_'));\n    foodMetabolites= foodRxns;\n    foodMetabolites=regexprep(pointsModel.rxns(foodMetabolites),'Diet_EX_','');\n    foodRxns=pointsModel.rxns(foodRxns);\n    foodRxns=regexprep(foodRxns,'Diet_EX_','Food_Added_EX_');\n    foodMetabolites{end+1}='unitOfFoodAdded[dP]';\n    \n    %Include food added reaction to pointsModel\n    sMatrix=-1*eye(length(foodRxns));\n    sMatrix=[sMatrix;-1*ones(1,length(foodRxns))];\n    pointsModel = addMultipleReactions(pointsModel, foodRxns, foodMetabolites, sMatrix, 'lb', -100000*ones(1,length(foodRxns)), 'ub', zeros(1,length(foodRxns)));\n    pointsModel = addMultipleReactions(pointsModel, {'Point_EX_unitOfFoodAdded2Change[dp]','Point_EX_unitOfFoodChange[dP]_[P]','Point_EX_Point[P]'}, {'unitOfFoodAdded[dP]','unitOfFoodChange[dP]','point[P]'}, [-1 0 0;1 -1 0;0 1 -1], 'lb', [-1000000, -1000000,-1000000], 'ub', [foodAddedLimit,1000000,1000000]);\nelseif strcmp(foodOrMets,'FoodMets') || strcmp(foodOrMets,'foodMets')\n    foodMetabolites= fdTableMod.Var1;\n    foodMetabolites= strcat(foodMetabolites.','[d]');\n    uof=find(contains(foodMetabolites,'unitOfFoodAdded'));\n    foodMetabolites{uof}='unitOfFoodAdded[dP]';\n    foodRxns=foodMetabolites;\n    foodRxns(uof)=[];\n    f=find(contains(foodMetabolites,'Energy_in_Kcal'));\n    foodRxns(f)=[];\n%     foodRxns=regexprep(foodRxns,'Diet_EX_','Food_Added_EX_');\n    foodRxns=strcat('Food_Added_EX_',foodRxns);\n    foodMetabolites(f)=[];\n    %     foodRxns= strcat('Food_Added_EX_',foodRxns);\n    %Include food added reaction to pointsModel\n    sMatrix=-1*eye(length(foodRxns));\n    sMatrix=[sMatrix;-1*ones(1,length(foodRxns))];\n    pointsModel = addMultipleReactions(pointsModel, foodRxns, foodMetabolites, sMatrix, 'lb', -100000*ones(1,length(foodRxns)), 'ub', zeros(1,length(foodRxns)));\n    pointsModel = addMultipleReactions(pointsModel, {'Point_EX_unitOfFoodAdded2Change[dp]','Point_EX_unitOfFoodChange[dP]_[P]','Point_EX_Point[P]'}, {'unitOfFoodAdded[dP]','unitOfFoodChange[dP]','point[P]'}, [-1 0 0;1 -1 0;0 1 -1], 'lb', [-1000000, -1000000,-1000000], 'ub', [foodAddedLimit,1000000,1000000]);\nelse\n    error('Invalid foodOrMets specification')\nend\n\n\nuof=find(contains(foodMetabolites,'unitOfFoodAdded[dP]'));\nfoodMetabolites{uof}='unitOfFoodRemoved[dP]';\nif strcmp(foodOrMets,'Food Items') || strcmp(foodOrMets,'Food Cat')\n    %Identify food items already in the diet\n    foodDietIndex=find(contains(pointsModel.rxns,'Food_EX_'));\n    foodInDietIndex=foodDietIndex(pointsModel.lb(foodDietIndex)<0);\n    %Build reaction matrix for food to be removed from diet\n    sMatrix=zeros(length(foodMetabolites),length(foodInDietIndex));\n    for i=1:length(foodInDietIndex)\n        foodItem = regexprep(pointsModel.rxns{foodInDietIndex(i)},'Food_EX_','');\n        foodRxn=strcat('Food_Removed_EX_',foodItem);\n%         foodItem = regexprep(foodItem,'\\[d\\]','');\n%         sMatrix(:,i)=fdTableMod.(foodItem);\n%         sMatrix(end,i)=-1/sMatrix(end,i);\n%         sMatrix(:,i)\n        RxnFormula=printRxnFormula(pointsModel,pointsModel.rxns{foodInDietIndex(i)},0);\n        [metaboliteList, stoichCoeffList, ~]=parseRxnFormula(RxnFormula{1});\n        metaboliteList=[metaboliteList,{'unitOfFoodRemoved[dP]'}];\n        stoichCoeffList=-1*stoichCoeffList;\n        stoichCoeffList=[stoichCoeffList,-1];\n        pointsModel = addMultipleReactions(pointsModel, {foodRxn}, metaboliteList, stoichCoeffList, 'lb', pointsModel.ub(foodInDietIndex(i)), 'ub', 0);\n    end\n    \n%     pointsModel = addMultipleReactions(pointsModel, foodRxns, foodMetabolites, sMatrix, 'lb', pointsModel.ub(foodInDietIndex), 'ub', zeros(1,length(foodRxns)));\nelse\n    \n    %Build reaction matrix for food to be removed from diet\n    sMatrix=-1*sMatrix;\n    sMatrix(end,:)=-1./sMatrix(end,:);\n    foodRxns = regexprep(foodRxns,'Food_Added_EX_','Food_Removed_EX_');\n    pointsModel = addMultipleReactions(pointsModel, foodRxns, foodMetabolites, sMatrix, 'lb', -1000000*ones(1,length(foodRxns)), 'ub', zeros(1,length(foodRxns)));\n    \nend\n\n%note that previous line makes food removal lb equal to food consumption ub\n%as more food should not be able to be removed than the food consumption\n%capabilities. If removing all of a food item yeilds the optimum solution,\n%the diet consumption of said food item should hug the ub and food removal\n%will then be equivalent to said ub yeilding 0.\n\n\n% Introduce any sink or demand reactions if necessary\n% if ~isempty(metRois)\n%     for i=length(metRois):-1:1\n%         if strcmp(roisMinMax{metRois(i)},'max')\n%             pointsModel = addMultipleReactions(pointsModel, {strcmp(rois{metRois(i)},'_Demand')}, {rois{metRois(i)},'roiPoint[roiP]'}, [-1; -1*roiWeights(metRois(i))], 'lb', 0, 'ub', 1000000);\n%             rois{metRois(i)}=[];\n%             roiIndexO(metRois(i))=[];\n%         else\n%             pointsModel = addMultipleReactions(pointsModel, {strcmp(rois{metRois(i)},'_Sink')}, {rois{metRois(i)},'roiPoint[roiP]'}, [-1; roiWeights(metRois(i))], 'lb', -1000000, 'ub', 0);\n%             rois{metRois(i)}=[];\n%             roiIndexO(metRois(i))=[];\n%         end\n%     end\n% end\n\n%Get roi Indexes\nfor i=1:length(rois)\n    roiIndexP(i)=find(strcmp(pointsModel.rxns,rois{i}));\nend\nroiUB=pointsModel.ub(roiIndexP);\nroiLB=pointsModel.lb(roiIndexP);\n\n%replace roi function\nstoich=pointsModel.S(:,roiIndexP);\nif length(roiIndexP)>1\n    metInd=find(any(stoich.'~=0));\n    metsRoi=pointsModel.mets(any(stoich.'~=0)).';\n    metsStoich=full(stoich(any(stoich.'~=0),:));\nelse\n    metsRoi=pointsModel.mets(find(stoich~=0)).';\n    metsStoich=full(stoich(find(stoich~=0)));\nend\n\nweightVector=zeros(1,length(roiIndexP));\nweightVector(contains(roisMinMax,'max'))=-1;\nweightVector(contains(roisMinMax,'min'))=1;\nmetsStoich=[metsStoich;weightVector.*roiWeights;zeros(1,length(roiIndexP))];\n\nfor i=1:length(rois)\n    evalc('[pointsModel,~,~]= removeRxns(pointsModel, rois{i})');\n% [pointsModel,~,~]= removeRxns(pointsModel, rois{i});\nend\n\npointsModel = addMultipleReactions(pointsModel, [rois,'Point_EX_roiPoints[roiP]_[P]'], [metsRoi,'roiPoint[roiP]','point[P]'], [metsStoich,[zeros(length(metsStoich(:,1))-2,1);-1;1]], 'lb', [roiLB.',-1000000], 'ub', [roiUB.',1000000]);\ncaloriesRxn=find(contains(pointsModel.rxns,'EX_DietEnergy'));\npointsModel.lb(caloriesRxn)=caloricRange(1);\npointsModel.ub(caloriesRxn)=caloricRange(2);\n\n\n%Find solution\npointsModel = changeObjective(pointsModel,'Point_EX_Point[P]');\npointsModel.osenseStr = 'min';\npointsModelSln = optimizeWBModel(pointsModel);\n% pointsModelSln.v(roiIndex)\n\ndisp(['Solution points =',num2str(pointsModelSln.f)])\ndisp([num2str(pointsModelSln.v(find(strcmp(pointsModel.rxns,'Point_EX_unitOfFoodChange[dP]_[P]')))),' come from diet']);\ndisp([num2str(pointsModelSln.v(find(strcmp(pointsModel.rxns,'Point_EX_roiPoints[roiP]_[P]')))),' come from roi']);\nfoodAddedIndexes=find(contains(pointsModel.rxns,'Food_Added_EX_'));\nfoodRemovedIndexes=find(contains(pointsModel.rxns,'Food_Removed_EX_'));\nslnIndexes1=foodAddedIndexes(pointsModelSln.v(foodAddedIndexes)<0);\nslnIndexes2=foodRemovedIndexes(pointsModelSln.v(foodRemovedIndexes)<0);\n\ndisp('Food items of interest are:')\nT=table([pointsModel.rxns(slnIndexes1);pointsModel.rxns(slnIndexes2)],pointsModelSln.v([slnIndexes1;slnIndexes2]),'VariableNames',{'Food Rxn', 'Flux'})\nif ~strcmp(foodOrMets,'AllMets') && ~strcmp(foodOrMets,'FoodMets')\n    disp(['Diet Energy = ',num2str(pointsModelSln.v(contains(pointsModel.rxns,'EX_DietEnergy')))])\nend\n\n%Add and remove relevant food items from diet in newDietModel\nif strcmp(foodOrMets,'Food Items') || strcmp(foodOrMets,'Food Cat')\n    foodItemsAdd= regexprep(pointsModel.rxns(slnIndexes1),'Food_Added_EX_','Food_EX_');\n    foodItemsRemove= regexprep(pointsModel.rxns(slnIndexes2),'Food_Removed_EX_','Food_EX_');\nelse\n    foodItemsAdd= regexprep(pointsModel.rxns(slnIndexes1),'Food_Added_EX_','Diet_EX_');\n    foodItemsRemove= regexprep(pointsModel.rxns(slnIndexes2),'Food_Removed_EX_','Diet_EX_');\nend\nmodelOindexAdd=zeros(1,length(foodItemsAdd));\nsl2IndexAdd=zeros(1,length(foodItemsAdd));\nmodelOindexRemove=zeros(1,length(foodItemsRemove));\nsl2IndexRemove=zeros(1,length(foodItemsRemove));\nfor i=1:length(foodItemsAdd)\n    modelOindexAdd(i)=find(contains(newDietModel.rxns,foodItemsAdd(i)));\n    sl2IndexAdd(i)=find(contains(pointsModel.rxns,foodItemsAdd(i)));\nend\nfor i=1:length(foodItemsRemove)\n    modelOindexRemove(i)=find(contains(newDietModel.rxns,foodItemsRemove(i)));\n    sl2IndexRemove(i)=find(contains(pointsModel.rxns,foodItemsRemove(i)));\nend\nnewDietModel.lb(modelOindexAdd)=(pointsModelSln.v(sl2IndexAdd)+pointsModelSln.v(slnIndexes1))*1.01;\nnewDietModel.ub(modelOindexAdd)=(pointsModelSln.v(sl2IndexAdd)+pointsModelSln.v(slnIndexes1))*0.99;\nnewDietModel.lb(modelOindexRemove)=(pointsModelSln.v(sl2IndexRemove)-pointsModelSln.v(slnIndexes2))*1.01;\nnewDietModel.ub(modelOindexRemove)=(pointsModelSln.v(sl2IndexRemove)-pointsModelSln.v(slnIndexes2))*0.99;\n\nif strcmp(graphicalAnalysis,'True')\n    [ogCatTable] = getDietComposition(model,'Off');\n    [newCatTable] = getDietComposition(newDietModel,'Off');\n    OgMacros=ogCatTable.('Mass (g)');\n    NewCategories=newCatTable.('Category');\n    NewMacros=newCatTable.('Mass (g)');\n    figure()\n    t = tiledlayout(1,2,'TileSpacing','compact');\n    ax1 = nexttile;\n    pie(ax1,OgMacros(1:4))\n    title('Original Diet')\n    ax2 = nexttile;\n    pie(ax2,NewMacros(1:4))\n    title('New Diet')\n    legend(NewCategories(1:4),'Location','South')\nend\n\nmenuChanges=T;\nif strcmp(slnType,'Quick')\n    for i=1:length(rois)\n        ind=find(strcmp(pointsModel.rxns,rois{i}));\n        disp([rois{i},' flux = ', num2str(pointsModelSln.v(ind))])\n    end\n    roiFlux(i)=pointsModelSln.v(ind);\n    slnRanges=pointsModelSln.v(roiIndexP);\n    %     menuChanges.itemsRemoved=[];\n    %     menuChanges.itemsAdded=[];\n    %     menuChanges.fullMenu=[];\n    newDietModel = changeObjective(newDietModel,obj);\n    newDietModel.osenseStr = objMinMax;\n    return\nend\n\n\n%Find new obj flux with new diet\n\nif model.ub(objIndex)~=model.lb(objIndex)\n    model_Obj = optimizeWBModel(newDietModel);\n    f2=model_Obj.f;\n    newDietModel=changeRxnBounds(newDietModel,obj,f2,'b'); %constrain pointsModel obj flux\nelse\n    f2=model.ub(objIndex);\nend\n\ndisp(['f1 =',num2str(f1), ' & f2=', num2str(f2)])\n\n%Compute new min max ranges for roi with new diet\n%%\nfor i=1:length(rois)\n    disp(rois{i})\n    newDietModel = changeObjective(newDietModel,rois{i});\n    newDietModel.osenseStr = 'min';\n    tmp=optimizeWBModel(newDietModel);\n    slnMin.(['Rxn',num2str(i)]) = tmp;\n    NroiFluxMin(i)=slnMin.(['Rxn',num2str(i)]).v(roiIndexO(i));\n    newDietModel.osenseStr = 'max';\n    tmp=optimizeWBModel(newDietModel);\n    slnMax.(['Rxn',num2str(i)]) = tmp;\n    NroiFluxMax(i)=slnMax.(['Rxn',num2str(i)]).v(roiIndexO(i));\n    disp(['Original Diet RoI range = ', num2str(OroiFluxMin(i)), ':', num2str(OroiFluxMax(i))])\n    disp(['New Diet RoI range = ', num2str(NroiFluxMin(i)), ':', num2str(NroiFluxMax(i))])\nend\n\n% slnMin\nroiFlux=[slnMin.',slnMax.'];\nnewDietModel.ub(objIndex)=model.ub(objIndex);\nnewDietModel.lb(objIndex)=model.lb(objIndex);\nnewDietModel = changeObjective(newDietModel,obj);\nnewDietModel.osenseStr = objMinMax;\n\ndisp('___________________________________________________________________')\n\n\nend\n\n%TO DO:\n% -Impliment itemsRemoved and itemsAdded\n% -Introduce option for metabolite adjustments\n% -Include intelligent default weighting for roi\n% -slnMin & slnMax turn to structs or convert to flux values\n\n%Finished:\n%-introduced Quick/Detailed functionality\n%-renamed variables to be more obvious\n%-commented code\n\n% figure()\n% t = tiledlayout(2,2,'TileSpacing','compact');\n% ax1 = nexttile;\n% pie(ax1,OgMacros(1:4))\n% title('Original Diet')\n% ax2 = nexttile;\n% x=pie(ax2,NewMacros(1:4))\n% title('New Diet')\n% legend(NewCategories(1:4),'Location','South')\n% ax3 = nexttile;\n% bar(ax3,(NewMacros(1:4)-OgMacros(1:4))./OgMacros(1:4))\n% ylim([-1 14])\n% ax4= nexttile;\n% legend(x,NewCategories(1:4))", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/wholeBody/Nutrition_Modelling_Toolbox/nutritionAlgorithmWBM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.23232309016166738}}
{"text": "classdef AcceleratedForwardBackward < SplittingAlgorithm\n\n    properties (Access = private)\n        gradientMethod\n        proximal\n        momentum\n    end\n    \n    methods (Access = public)\n        \n        function obj = AcceleratedForwardBackward(cParams)\n            obj.proximal = cParams.proximal;\n            obj.createGradientMethods(cParams);\n            obj.createMomentum(cParams);\n        end\n        \n        function update(obj)\n            obj.momentum.apply();\n            obj.gradientMethod.compute();\n            obj.proximal.solve();\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function createGradientMethods(obj,cParams)\n            s = cParams.gradientMethodParams;\n            obj.gradientMethod = GradientMethod(s);\n        end\n        \n        function createMomentum(obj,cParams)\n            s = cParams.momentumParams;\n            obj.momentum = Momentum(s);\n        end\n       \n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/ImageProcessing/Algorithms/SplittingAlgorithms/AcceleratedForwardBackward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2323091998129193}}
{"text": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction Pass = filtering(P,inputs)\n\n% ---------------------------------------------------------------------\n% FILTERING.M       Filters noise from point clouds.\n%\n% Version 3.0.0\n% Latest update     3 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Filters the point cloud as follows:\n% \n% 1) the possible NaNs are removed.\n% \n% 2) (optional, done if filter.k > 0) Statistical kth-nearest neighbor \n% distance outlier filtering based on user defined \"k\" (filter.k) and\n% multiplier for standard deviation (filter.nsigma): Determines the \n% kth-nearest neighbor distance for all points and then removes the points \n% whose distances are over average_distance + nsigma*std. Computes the \n% statistics for each meter layer in vertical direction so that the\n% average distances and SDs can change as the point density decreases.\n% \n% 3) (optional, done if filter.radius > 0) Statistical point density \n% filtering based on user defined ball radius (filter.radius) and multiplier \n% for standard deviation (filter.nsigma): Balls of radius \"filter.radius\"\n% centered at each point are defined for all points and the number of\n% points included (\"point density\") are computed and then removes the points \n% whose density is smaller than average_density - nsigma*std. Computes the \n% statistics for each meter layer in vertical direction so that the\n% average densities and SDs can change as the point density decreases.\n% \n% 4) (optional, done if filter.ncomp > 0) Small component filtering based\n% on user defined cover (filter.PatchDiam1, filter.BallRad1) and threshold\n% (filter.ncomp): Covers the point cloud and determines the connected\n% components of the cover and removes the points from the small components\n% that have less than filter.ncomp cover sets.\n%\n% 5) (optional, done if filter.EdgeLength > 0) cubical downsampling of the \n% point cloud based on user defined cube size (filter.EdgeLength): \n% selects randomly one point from each cube\n%\n% Does the filtering in the above order and thus always applies the next \n% fitering to the point cloud already filtered by the previous methods. \n% Statistical kth-nearest neighbor distance outlier filtering and the \n% statistical point density filtering are meant to be exlusive to each\n% other.\n%\n% Inputs:\n% P         Point cloud\n% inputs    Inputs structure with the following subfields:\n%   filter.EdgeLength   Edge length of the cubes in the cubical downsampling\n%   filter.k            k of knn method\n%   filter.radius       Radius of the balls in the density filtering\n%   filter.nsigma       Multiplier for standard deviation, determines how\n%                         far from the mean the threshold is in terms of SD.\n%                         Used in both the knn and the density filtering\n%   filter.ncomp        Threshold number of components in the small\n%                         component filtering\n%   filter.PatchDiam1   Defines the patch/cover set size for the component \n%                         filtering\n%   filter.BallRad1     Defines the neighbors for the component filtering\n%   filter.plot         If true, plots the filtered point cloud\n% Outputs:\n% Pass      Logical vector indicating points passing the filtering\n% ---------------------------------------------------------------------\n\n% Changes from version 2.0.0 to 3.0.0, 3 May 2022:\n% Major changes and additions.\n% 1) Added two new filtering options: statistical kth-nearest neighbor \n%    distance outlier filtering and cubical downsampling.\n% 2) Changed the old point density filtering, which was based on given\n%    threshold, into statistical point density filtering, where the\n%    threshold is based on user defined statistical measure\n% 3) All the input parameters are given by \"inputs\"-structure that can be\n%    defined by \"create_input\" script   \n% 4) Streamlined the coding and what is displayed\n\n%% Initial data processing\n% Only double precision data\nif ~isa(P,'double')\n  P = double(P);\nend\n% Only x,y,z-data\nif size(P,2) > 3\n  P = P(:,1:3);\nend\nnp = size(P,1);\nnp0 = np;\nind = (1:1:np)';\nPass = false(np,1);\n\ndisp('----------------------')\ndisp(' Filtering...')\ndisp(['  Points before filtering:  ',num2str(np)])\n\n%% Remove possible NaNs\nF = ~any(isnan(P),2);\nif nnz(F) < np\n  disp(['  Points with NaN removed:  ',num2str(np-nnz(Pass))])\n  ind = ind(F);\nend \n\n%% Statistical kth-nearest neighbor distance outlier filtering\nif inputs.filter.k > 0\n  % Compute the knn distances\n  Q = P(ind,:);\n  np = size(Q,1);\n  [~, kNNdist] = knnsearch(Q,Q,'dist','euclidean','k',inputs.filter.k);\n  kNNdist = kNNdist(:,end);\n\n  % Change the threshold kNNdistance according the average and standard \n  % deviation for every vertical layer of 1 meter in height\n  hmin = min(Q(:,3));\n  hmax = max(Q(:,3));\n  H = ceil(hmax-hmin);\n  F = false(np,1);\n  ind = (1:1:np)';\n  for i = 1:H\n    I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1;\n    points = ind(I);\n    d = kNNdist(points);\n    J = d < mean(d)+inputs.filter.nsigma*std(d);\n    points = points(J);\n    F(points) = 1;\n  end\n  ind = ind(F);\n  disp(['  Points removed as statistical outliers:  ',num2str(np-length(ind))])\nend\n\n%% Statistical point density filtering\nif inputs.filter.radius > 0\n  Q = P(ind,:);\n  np = size(Q,1);\n\n  % Partition the point cloud into cubes\n  [partition,CC] = cubical_partition(Q,inputs.filter.radius);\n\n  % Determine the number of points inside a ball for each point\n  NumOfPoints = zeros(np,1);\n  r1 = inputs.filter.radius^2;\n  for i = 1:np\n    if NumOfPoints(i) == 0\n      points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1,CC(i,3)-1:CC(i,3)+1);\n      points = vertcat(points{:,:});\n      cube = Q(points,:);\n      p = partition{CC(i,1),CC(i,2),CC(i,3)};\n      for j = 1:length(p)\n        dist = (Q(p(j),1)-cube(:,1)).^2+(Q(p(j),2)-cube(:,2)).^2+(Q(p(j),3)-cube(:,3)).^2;\n        J = dist < r1;\n        NumOfPoints(p(j)) = nnz(J);\n      end\n    end\n  end\n\n  % Change the threshold point density according the average and standard \n  % deviation for every vertical layer of 1 meter in height\n  hmin = min(Q(:,3));\n  hmax = max(Q(:,3));\n  H = ceil(hmax-hmin);\n  F = false(np,1);\n  ind = (1:1:np)';\n  for i = 1:H\n    I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1;\n    points = ind(I);\n    N = NumOfPoints(points);\n    J = N > mean(N)-inputs.filter.nsigma*std(N);\n    points = points(J);\n    F(points) = 1;\n  end\n  ind = ind(F);\n  disp(['  Points removed as statistical outliers:  ',num2str(np-length(ind))])\nend\n\n%% Small component filtering\nif inputs.filter.ncomp > 0\n  % Cover the point cloud with patches\n  input.BallRad1 = inputs.filter.BallRad1;\n  input.PatchDiam1 = inputs.filter.PatchDiam1;\n  input.nmin1 = 0;\n  Q = P(ind,:);\n  np = size(Q,1);\n  cover = cover_sets(Q,input);\n\n  % Determine the separate components\n  Components = connected_components(cover.neighbor,0,inputs.filter.ncomp);\n\n  % The filtering\n  B = vertcat(Components{:}); % patches in the components\n  points = vertcat(cover.ball{B}); % points in the components\n  F = false(np,1);\n  F(points) = true;\n  ind = ind(F);\n  disp(['  Points with small components removed:  ',num2str(np-length(ind))])\nend\n\n%% Cubical downsampling\nif inputs.filter.EdgeLength > 0\n  Q = P(ind,:);\n  np = size(Q,1);\n  F = cubical_downsampling(Q,inputs.filter.EdgeLength);\n  ind = ind(F);\n  disp(['  Points removed with downsampling:  ',num2str(np-length(ind))])\nend\n\n%% Define the output and display summary results\nPass(ind) = true;\nnp = nnz(Pass);\ndisp(['  Points removed in total: ',num2str(np0-np)])\ndisp(['  Points removed in total (%): ',num2str(round((1-np/np0)*1000)/10)])\ndisp(['  Points left: ',num2str(np)])\n\n%% Plot the filtered and unfiltered point clouds\nif inputs.filter.plot\n  plot_comparison(P(Pass,:),P(~Pass,:),1,1,1)\n  plot_point_cloud(P(Pass,:),2,1)\nend\n", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/main_steps/filtering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.23222279986964126}}
{"text": "function [gamma,phase,dta,alpha,xmesh_lv,ymesh_lv,zmesh_lv]=dicomrt_GAMMAcal2D(evalm,refm,dose_xmesh,dose_ymesh,dose_zmesh,slice,resf,range,dta_criteria,dd_criteria,voi,voiselect,pbopt)\n% dicomrt_GAMMAcal2D(evalm,refm,dose_xmesh,dose_ymesh,dose_zmesh,slice,resf,range,dta_criteria,dd_criteria,voi,voiselect,pbopt);\n%\n% Calculates 2D gamma distribution for a 2D dataset using a 2D algorithm.\n%\n% evalm is the 2D matrix to evaluate.\n% refm is the reference 2D matrix.\n%   Both eval and ref can be a TPS generated dataset or a MC generated dataset.\n%   Doses are normalised to the target dose whenever is possible.\n%   If no normalization dose is provided within the data it is assumed that matrices are already normalised.\n% dose_xmesh, dose_ymesh, are the coordinates of the center of the pixels for eval and ref.\n% slice is the number of the slice on which gamma should be calculated\n% resf is the \"resolution factor\". Each voxel is divided resf times to allow dose to be interpolated\n%   and quantities calculated. The higher resf the more accurate the calculation is, the slower the \n%   function will be.\n% range is the \"search range\". Range is the number of pixel about (j,i) that is considered for calculation.\n%   If a dta or a dd match is not found within the search range gamma and all the other quantities in that point\n%   will be set to infinite value.\n% dta_criteria is the Distance-to-agreement criteria in cm (e.g. 0.3).\n% dd_criteria:\n%   1) IF matrices ARE NOT NORMALIZED before calling the function \n%      dta_criteria is the percentage dose difference (e.g. =0.03);\n%   2) IF matrices ARE already NORMALIZED before calling the function\n%      dd_criteria must be given accordingly to the normalization applyed \n%      (e.g. =0.03 for 3% over dose norm =1Gy, or =1.98 for 3% over dose norm=66Gy).\n% voi and voiselect are the vois' cell array and the # of the voi to be used for the gamma calculation respectively.\n%   They have to be specified together. Both matrices will be masked and reduced in size accordingly with the selected\n%   voi's dimensions. This reduce calculation time especially for the 3D algorithm.\n% pbopt progress bar option (OPTIONAL): =0 (default) no progress bar is displayed, ~0 progress bar is displayed\n% \n% Example: \n%\n% [gamma1_2,phase1_2,dta1_2,alpha1_2,xmesh,ymesh]=dicomrt_GAMMAcal2D(image_eval,image_ref, ...\n%                                                             xmesh_red,ymesh_red,40,2,4,0.3,0.03);\n%\n% returns the calculated gamma function for image_eval vs image_ref at slice # 40 in gamma1_2. \n% Gamma is calculated with 3%-3mm DD-DTA criteria.\n% The phase is returned in phase1_2, the dta matrix in dta1_2.\n% The function return also the direction cosines in alpha1_2. These are the \n% direction cosines on the gamma vector in the two dimensional space xy. The direction\n% cosines may provide useful information in detecting systematic spatial displacements between eval and ref.\n% Coordinates of the xy location where gamma is defined are returned in xmesh and ymesh.\n%\n% The concept of gamma function was developed by Low et al Med. Phys. 25 656-661.\n%\n% See also dicomrt_gvhcal, dicomrt_gahcal\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument and set-up some parameters and variables\nerror(nargchk(10,13,nargin))\n\nif nargin >10 & (exist('voi')==1 & exist('voiselect')~=1) | (exist('voi')~=1 & exist('voiselect')==1)\n    error('dicomrt_GAMMAcal2D: Check VOI and voi2plot: they must be both present or both absent. Exit now!');\nend\n\nif exist('pbopt')~=1\n    pbopt=0;\nend\n\n% Suppress warnings\nwarning off MATLAB:divideByZero\n\n% Check case and set-up some parameters and variables\n[eval_temp,type_dose_one,label1,PatientPosition]=dicomrt_checkinput(evalm);\n[ref_temp,type_dose_two,label2,PatientPosition]=dicomrt_checkinput(refm);\nlocal_eval=dicomrt_varfilter(eval_temp);\nref=dicomrt_varfilter(ref_temp);\n\n% Get DICOM-RT toolbox dataset info\nlocal_eval_pointer=eval_temp{1,1};\nlocal_eval_header=local_eval_pointer{1};\nref_pointer=ref_temp{1,1};\nref_header=ref_pointer{1};\n\n[voi_temp]=dicomrt_checkinput(voi);\nvoi=dicomrt_varfilter(voi_temp);\n\nif strcmpi(type_dose_one,'rtplan')==1 & (strcmpi(type_dose_two,'mc')==1 | strcmpi(type_dose_two,'unknown')==1)\n    targetdose_one=getfield(local_eval_header.DoseReferenceSequence,'Item_1','TargetPrescriptionDose'); % normalisation factor\n    % Mask arrays\n    temp=ref;\n    % temp(find(local_eval==0))=0;\n    % local_eval(find(temp==0))=0;\n    % Normalise dose and calculate dose difference\n    eval_norm_temp=local_eval(:,:,slice)/targetdose_one*100;\n    ref_norm_temp=temp(:,:,slice)/targetdose_one*100;\nelseif strcmpi(type_dose_two,'rtplan')==1 & (strcmpi(type_dose_one,'mc')==1 | strcmpi(type_dose_one,'unknown')==1)\n    targetdose_two=getfield(ref{1,1}.DoseReferenceSequence,'Item_1','TargetPrescriptionDose'); % normalisation factor\n    % Mask arrays\n    temp=local_eval;\n    % temp(find(ref==0))=0;\n    % ref(find(temp==0))=0;\n    % Normalise dose and calculate dose difference\n    eval_norm_temp=temp(:,:,slice)/targetdose_two*100;\n    ref_norm_temp=ref(:,:,slice)/targetdose_two*100;\nelseif strcmpi(type_dose_one,'rtplan')==1 & strcmpi(type_dose_two,'rtplan')==1\n    targetdose_one=getfield(local_eval_header.DoseReferenceSequence,'Item_1','TargetPrescriptionDose'); % normalisation factor\n    targetdose_two=getfield(ref_header.DoseReferenceSequence,'Item_1','TargetPrescriptionDose'); % normalisation factor\n    % no mask is performed. We assume TPS dose are calculated on the same patient using the same patient outline outline\n    % Normalise dose and calculate dose difference\n    eval_norm_temp=local_eval(:,:,slice)/targetdose_one*100;\n    ref_norm_temp=ref(:,:,slice)/targetdose_two*100;\nelseif (strcmpi(type_dose_one,'mc')==1 | strcmpi(type_dose_one,'unknown')==1) & ...\n        (strcmpi(type_dose_one,'mc')==1 | strcmpi(type_dose_two,'unknown')==1)\n    eval_norm_temp=local_eval(:,:,slice);\n    ref_norm_temp=ref(:,:,slice);\nelse\n    error('dicomrt_GAMMAcal2D: Cannot determine dose arrays format. Exit now!');\nend\n\n% Mask matrices as appropriate\nif exist('voi')==1 & exist('voiselect')==1\n    [locate_voi_min_x,locate_voi_max_x,locate_voi_min_y,locate_voi_max_y] = dicomrt_voiboundaries(...\n        dose_xmesh,dose_ymesh,dose_zmesh,voi_temp,voiselect,PatientPosition);\n    eval_norm=eval_norm_temp(locate_voi_min_y:locate_voi_max_y,locate_voi_min_x:locate_voi_max_x);\n    ref_norm=ref_norm_temp(locate_voi_min_y:locate_voi_max_y,locate_voi_min_x:locate_voi_max_x);\nelse\n    locate_voi_min_x=1;\n    locate_voi_max_x=length(dose_xmesh);\n    locate_voi_min_y=1;\n    locate_voi_max_y=length(dose_ymesh);\n    eval_norm=eval_norm_temp;\n    ref_norm=ref_norm_temp;\nend\n\n% \n% Define parameters\n% radians to degrees conversion factor\nr2d=360/(2*pi);\nd2r=2*pi/360;\n\n% Retrieve basic information\npixel_spacing_x=dicomrt_mmdigit(dose_xmesh(2)-dose_xmesh(1),7);\npixel_spacing_y=dicomrt_mmdigit(dose_ymesh(2)-dose_ymesh(1),7);\n\n% 2D algorithm\n%\n% create grid for matrix interpolation\n% this is done using the resolution factor resf\n%[xmesh,ymesh]=dicomrt_build2dgrid(dose_xmesh-pixel_spacing_x/resf,dose_ymesh-pixel_spacing_y/resf);\n\n% Start calculating elapsed time\n% tic\n\ndisp('(+) Initializing ...');\n\n[xmesh,ymesh]=dicomrt_build2dgrid(dose_xmesh(locate_voi_min_x:locate_voi_max_x),...\n    dose_ymesh(locate_voi_min_y:locate_voi_max_y));\nxmesh_res=imresize(xmesh,resf,'bilinear');\nymesh_res=imresize(ymesh,resf,'bilinear');\n\n% These variables are exported to use with other functions\nxmesh_lv=xmesh(1,:);\nymesh_lv=ymesh(:,1);\nzmesh_lv=dose_zmesh(slice);\n\n% Normalize quantities\neval_norm=eval_norm./dd_criteria;\nref_norm=ref_norm./dd_criteria;\nxmesh=xmesh./dta_criteria;\nymesh=ymesh./dta_criteria;\nxmesh_res=xmesh_res./dta_criteria;\nymesh_res=ymesh_res./dta_criteria;\n\n% interpolate reference matrix \neval_norm_interp(:,:)=interp2(xmesh,ymesh,eval_norm(:,:),xmesh_res,ymesh_res);\n\n% Define output size\ngamma=zeros(size(ref_norm));\nphase=zeros(size(ref_norm));\ndta=zeros(size(ref_norm));\nalpha=zeros(size(ref_norm));\n\n% logical steps being taken:\n%\n% 0) So far the reference matrix was modified to comply with the resolution parameter resf input by the user.\n%    Two new matrices which incorporate the dose difference criteria (dd_criteria) were also built.\n% 1) The search_range parameter will be used now to define an area around each voxel of the new reference matrices.\n%    This area is called Search Area (SA) and will be temporary stored onto a matrix called Transit Area (TA).\n%    Distance to agreemenet (DTA) will be then searched within TA for each point of the evaluation matrix.\n% 2) If one or more DTA matches are found the dose difference will be calculated for the minimum of the DTA matches.\n%\n% 1a) Calculate voxels that will define the search volume in 3D\n\ndisp('(+) Calculating ...');\n\nif pbopt~=0\n    h = waitbar(0,'Calculation progress');\n    set(h,'Name','dicomrt_GAMMAcal2D: calculates gamma function');\nend\n\nfor j=1:size(ref_norm,1)       % loop over y\n    for i=1:size(ref_norm,2)   % loop over x\n        % all voxels in the new matrices are used for the DTA search. A portion of the new matrices will be copied\n        % in the temporary matrix called volume. In order to do this we need to calculate the index that refer to \n        % the portion of the matrix to copy.\n        if i==1\n            iSAmax=range*resf+resf;\n            iSAmin=1;\n        elseif i>1 & i< range +1\n            iSAmax=resf*i+range*resf;\n            iSAmin=1;\n        elseif i>=range +1 & i<size(ref_norm,2)-range\n            iSAmax=resf*i+range*resf;\n            iSAmin=i*resf-(resf-1)-range*resf;\n        elseif i>=size(ref_norm,2)-range\n            iSAmax=size(eval_norm_interp,2);\n            iSAmin=i*resf-(resf-1)-range*resf;\n        end\n        \n        if j==1\n            jSAmax=range*resf+resf;\n            jSAmin=1;\n        elseif j>1 & j< range +1\n            jSAmax=resf*j+range*resf;\n            jSAmin=1;\n        elseif j>=range +1 & j<size(ref_norm,1)-range\n            jSAmax=resf*j+range*resf;\n            jSAmin=j*resf-(resf-1)-range*resf;\n        elseif j>=size(ref_norm,1)-range\n            jSAmax=size(eval_norm_interp,1);\n            jSAmin=j*resf-(resf-1)-range*resf;\n        end\n        \n        % debug start\n        %display(['i is: ',num2str(i),' - j is: ', num2str(j)]);\n        %display(['iSAmin is: ',num2str(iSAmin),' - iSAmax is: ', num2str(iSAmax)]);\n        %display(['jSAmin is: ',num2str(jSAmin),' - jSAmax is: ', num2str(jSAmax)]);\n        %if j==64 & i==22\n        %    disp('debug');\n        %end\n        \n        temp_xmesh_res=xmesh_res(jSAmin:jSAmax,iSAmin:iSAmax);\n        temp_ymesh_res=ymesh_res(jSAmin:jSAmax,iSAmin:iSAmax);\n        temp_eval_norm=eval_norm_interp(jSAmin:jSAmax,iSAmin:iSAmax);\n        \n        temp_dta=zeros(size(temp_eval_norm));\n        %temp_dta(:,:)=nan;\n        temp_dta(:,:)=inf;\n        \n        temp_dd=zeros(size(temp_eval_norm));\n        %temp_dd(:,:)=nan;\n        temp_dd(:,:)=inf;\n        \n        temp_gamma=zeros(size(temp_eval_norm));\n        %temp_gamma(:,:)=nan;\n        temp_gamma(:,:)=inf;\n        \n        dd_spot=eval_norm(j,i)-ref_norm(j,i);\n                \n        [lo]=find(temp_eval_norm<=ref_norm(j,i)+1 & temp_eval_norm>ref_norm(j,i)-1);\n        \n        % initialize variable: lo will contain the location (number) of the pixel\n        % where the match was found. Pixel numbering is done following the example\n        % below for a 2d matrix:\n        %\n        % A=\n        %\n        % 1 1 1   1|  /|  /|\n        % 2 2 2    | / | / |\n        % 1 3 1    |/  |/  |9\n        %\n        % 6 is the number of the pixel which contains the value 3 and it is the\n        % result of the following command:\n        %\n        % find(A(:,:)==3)\n\n        if isempty(lo)~=1\n            temp_dta(lo)=sqrt((temp_xmesh_res(lo)-xmesh(j,i)).^2+(temp_ymesh_res(lo)-ymesh(j,i)).^2);\n            temp_dd(lo)=temp_eval_norm(lo)-ref_norm(j,i);\n            temp_gamma(lo)=sqrt(temp_dta(lo).^2+temp_dd(lo).^2);\n            [temp_gamma_min,temp_gamma_min_index]=min(temp_gamma(lo));\n            [gamma(j,i),index]=min([temp_gamma_min sqrt(dd_spot.^2)]);\n            % the following if is due because dicomrt_mask, which is used to calculate DVHs GVHs and GAHs,\n            % mask matrices to zero. This makes impossible to disguish between a point outside the VOI from\n            % a point with dose or gamma equal to 0.\n            % In practice this is not a problem for DVHs but can represent a problem for gamma\n            % calculation. A value 0 or 0.001 do not change the meaning of gamma.\n            %\n            if gamma(j,i)==0\n                gamma(j,i)=0.01;\n            end\n            %\n            if index==2\n                phase(j,i)=0;\n                dta(j,i)=0;\n                alpha(j,i)=0;\n            else\n                phase(j,i)=asin(temp_dd(lo(temp_gamma_min_index))./gamma(j,i))*r2d;\n                dta(j,i)=temp_dta(lo(temp_gamma_min_index));\n                alpha(j,i)=acos(((temp_xmesh_res(lo(temp_gamma_min_index))-xmesh(j,i))./dta(j,i)))*r2d;\n                %alpha(j,i)=acos((temp_xmesh_res(lo(temp_gamma_min_index))-xmesh(j,i))/...\n                %    (gamma(j,i)*cos(d2r*phase(j,i))))*r2d;\n                %alpha(j,i)=acos((temp_xmesh_res(lo(temp_gamma_min_index))-xmesh(j,i))/...\n                %    temp_dta(lo(temp_gamma_min_index)))*r2d;\n                %alpha(j,i)=acos(temp_dta(lo(temp_gamma_min_index))/(gamma(j,i)*cos(d2r*phase(j,i))))*r2d;\n                %alpha(j,i)=acos((temp_xmesh_res(lo(temp_gamma_min_index))-xmesh(j,i))/...\n                %    (gamma(j,i)*cos(phase(j,i))))*r2d;\n                %alpha(j,i)=asin(temp_dd(lo(temp_gamma_min_index))*sin(phase(j,i)*d2r))*r2d;\n            end\n        else\n            %gamma(j,i)=nan;\n            gamma(j,i)=inf;\n            %phase(j,i)=nan;\n            phase(j,i)=inf;\n            %dta(j,i)=nan;\n            dta(j,i)=inf;\n            %alpha(j,i)=nan;\n            alpha(j,i)=inf;\n        end\n        if pbopt~=0\n            waitbar(j/size(ref_norm,1),h);\n        end\n    end\nend\ndisp('(=) Calculation completed.');\nif pbopt~=0\n    close(h)\nend\n\n% Returns elapsed time\n% toc\n\n% Plot\n%figure;\n%set(gcf,'Name',['dicomrt_GAMMAcal2D: local_eval= ',inputname(1),', ref= ',inputname(2)]);\n%surf(gamma,phase,'XData',dose_xmesh(locate_voi_min_x:locate_voi_max_x),'Ydata',dose_ymesh(locate_voi_min_y:locate_voi_max_y));\n%colormap jet;\n%shading interp;\n%title(['gamma/phase',' Z= ',num2str(dose_zmesh(slice))],'FontSize',16);\n%xlabel('X axis (cm)','FontSize',12);\n%ylabel('Y axis (cm)','FontSize',12);\n%grid on;\n%colorbar;\n%set(gca,'XLim',[min(dose_xmesh(locate_voi_min_x:locate_voi_max_x)) max(dose_xmesh(locate_voi_min_x:locate_voi_max_x))]);\n%set(gca,'YLim',[min(dose_ymesh(locate_voi_min_y:locate_voi_max_y)) max(dose_ymesh(locate_voi_min_y:locate_voi_max_y))]);\n%set(gca,'ZLim',[min(min(gamma)) max(max(gamma))]);\n%set(gca,'ZLim',[min(min(gamma)) 1]);\n\n%figure;\n%set(gcf,'Name',['dicomrt_GAMMAcal2D: local_eval= ',inputname(1),', ref= ',inputname(2)]);\n%surf(gamma,alpha,'XData',dose_xmesh(locate_voi_min_x:locate_voi_max_x),'Ydata',dose_ymesh(locate_voi_min_y:locate_voi_max_y));\n%colormap jet;\n%shading interp;\n%title(['gamma/alpha',' Z= ',num2str(dose_zmesh(slice))],'FontSize',16);\n%xlabel('X axis (cm)','FontSize',12);\n%ylabel('Y axis (cm)','FontSize',12);\n%grid on;\n%colorbar;\n%set(gca,'XLim',[min(dose_xmesh(locate_voi_min_x:locate_voi_max_x)) max(dose_xmesh(locate_voi_min_x:locate_voi_max_x))]);\n%set(gca,'YLim',[min(dose_ymesh(locate_voi_min_y:locate_voi_max_y)) max(dose_ymesh(locate_voi_min_y:locate_voi_max_y))]);\n%set(gca,'ZLim',[min(min(gamma)) max(max(gamma))]);\n%set(gca,'ZLim',[min(min(gamma)) 1]);\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/analysis/dicomrt_GAMMAcal2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.2322017059287032}}
{"text": "function [noiseVariance, debiasedNoiseVariance, IQEstimate, noiseEstimateOomen] = realized_noise_estimate(price, time, timeType, options)\n% Estimation of the optimal bandwidth to use when estimating the quadratic variation using a Realized Kernel\n%\n% USAGE:\n%   [NOISEVARIANCE,DEBIASEDNOISEVARIANCE,IQESIQESTIMATETIMATE,NOISEVARIANCEOOMEN] \n%                        = realized_kernel_select_bandwidth(PRICE,TIME,TIMETYPE,OPTIONS)\n%\n% INPUTS:\n%   PRICE       - m by 1 vector of prices\n%   TIME        - m by 1 vector of times where TIME(i) corresponds to PRICE(i)\n%   TIMETYPE    - String describing the way times are measured\n%               'wall'    24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n%               'seconds' Time measured in seconds past midnight on the first day\n%               'unit'  Unit normalized date format, e.g. .1, .234, .9. Unit normalized times are\n%                 more general than the other types and can be applied to data from more than one\n%                 calendar day\n%   OPTIONS     - Realized kernel options structure.  See help realized_kernel_options\n%\n% OUTPUTS:\n%   NOISEVARIANCE         - Bandi-Russel noise variance estimate \n%   DEBIASEDNOISEVARIANCE - Debiased Bandi-Russel noise variance estimate using the adjustment of BNHLS\n%   IQESTIMATE            - An estimate of the lower bound of the IQ based on low-freuqency returns\n%   NOISEVARIANCEOOMEN    - Estimate using Oomen (2006) alternative AC(1) estimator\n%\n% COMMENTS:\n%   This is a helper function for REALIZED_KERNEL.  See Barndorf-Nielsen, Hansen, Lunde and Shephard\n%   (2008) for details about the optimal selection of bandwidth\n%\n%  See also REALIZED_KERNEL, REALIZED_PRICE_FILTER, REALIZED_KERNEL_WEIGHTS\n%  REALIZED_KERNEL_SELECT_LAG_LENGTH, REALIZED_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin~=4\n    error('Seven inputs required.')\nend\nif size(price,2)>size(price,1)\n    price=price';\nend\nif size(price,2)>1\n    error('PRICE must be a m by 1 vector.')\nend\nif size(time,2)>size(time,1)\n    time=time';\nend\nif any(diff(time)<0)\n    error('TIME must be sorted and increasing')\nend\nif size(time,2)>1 || length(time)~=length(price)\n    error('TIME must be a m by 1 vector.')\nend\ntime = double(time);\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','matlab'})\n    error('TIMETYPE must be one of ''wall'', ''seconds'' or ''Matlab''.');\nend\n\n% List of flat top kernels\nflatTopKernelList = {'bartlett','twoscale','2ndorder','epanechnikov',...\n    'cubic','multiscale','5thorder','6thorder','7thorder','8thorder','parzen',...\n    'th1','th2','th5','th16'};\n\n% List of non flat top kernels\nnonFlatTopKernelList = {'nonflatparzen','qs','fejer','thinf','bnhls'};\n\n% Combined kernel list\nkernelList = [flatTopKernelList nonFlatTopKernelList];\n\nif ~isfield(options,'medFrequencyKernel') || ~ismember(options.medFrequencyKernel,kernelList)\n    error('KERNEL must be a field of OPTIONS and one of the listed types.')\nend\n\nmedFrequencySamplingType = options.medFrequencySamplingType;\nmedFrequencySamplingInterval = options.medFrequencySamplingInterval;\nmedFrequencyKernel = options.medFrequencyKernel;\nmedFrequencyBandwidth = options.medFrequencyBandwidth;\nif ~isscalar(medFrequencySamplingInterval) || floor(medFrequencySamplingInterval)~=medFrequencySamplingInterval || medFrequencySamplingInterval<=0\n    error('MEDIUMFREQUENCYTIME must be a postive integer scalar value.');\nend\n\nIQEstimationSamplingType = options.IQEstimationSamplingType;\nIQEstimationSamplingInterval = options.IQEstimationSamplingInterval;\nif ~isscalar(IQEstimationSamplingInterval) || floor(IQEstimationSamplingInterval)~=IQEstimationSamplingInterval || IQEstimationSamplingInterval<=0\n    error('LOWFREQUENCYTIME must be a postive integer scalar value.');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% To compute the \"optimal\" bandwidth an estimate of the noise and the QV using low frequency data\nlowFrequencyRealizedVariance = realized_variance(price,time, timeType , IQEstimationSamplingType, IQEstimationSamplingInterval);\n\nnoiseVarianceSamplingType = options.noiseVarianceSamplingType;\nnoiseVarianceSamplingInterval = options.noiseVarianceSamplingInterval;\n\n% Compute the noiseVariance using the debiased version of Bandi-Russell, using all prices\nnoiseVariance = realized_variance(price, time, timeType , noiseVarianceSamplingType , noiseVarianceSamplingInterval);\n% Compute the effective 'n' to use in the Bandi-Russel estimator\nnoiseFilteredPrice = realized_price_filter(price, time, timeType , noiseVarianceSamplingType , noiseVarianceSamplingInterval);\nif options.useAdjustedNoiseCount\n    % Only count the number of non-zero returns\n    n = sum(diff(noiseFilteredPrice)~=0);\nelse\n    n = length(noiseFilteredPrice) - 1;\nend\nnoiseVariance = noiseVariance/(2*n);\n\nnoiseReturns = diff(log(noiseFilteredPrice));\nn = length(noiseReturns);\nnoiseEstimateOomen = -1/(n-1) * noiseReturns(1:end-1)'*noiseReturns(2:end);\n\n% Require a realized kernel estimate to adjust the variance\nmedFrequencyOptions = realized_options('kernel');\nmedFrequencyOptions.kernel = medFrequencyKernel;\nmedFrequencyOptions.bandwidth = medFrequencyBandwidth;\nmedFrequencyOptions.endTreatment = 'stagger';\n\nmedFreuqencyRealizedKernel = realized_kernel(price, time, timeType, medFrequencySamplingType, medFrequencySamplingInterval, medFrequencyOptions);\nmedFrequencyRealizedVariance = realized_variance(price,time, timeType , medFrequencySamplingType, medFrequencySamplingInterval);\n% Use the BNHLS corrected noise estimate\ndebiasedNoiseVariance = exp( log(noiseVariance) - medFreuqencyRealizedKernel/medFrequencyRealizedVariance);\nIQEstimate = lowFrequencyRealizedVariance^2;", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_noise_estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2321394484026449}}
{"text": "function [muX,SigmaX,suffStat] = VBA_EKF(y,u,posterior,dim,options,flag)\n% standard EKF & computation of the predictive density\n% function [muX,SigmaX,suffStat] = VBA_EKF(y,u,posterior,dim,options,flag)\n%\n% This function inverts any nonlinear state-space model of the form:\n%   y_t = g( x_t,u_t,phi ) + e_t\n%   x_t+1 = f( x_t,u_t,theta ) + f_t\n% using a standard extended Kalman filter (EKF).\n%\n% IN :          [ see VBA_NLStateSpaceModel.m ]\n%   - y: pxn_t mesurements matrix\n%   - u: mxn_t known input matrix (which is required as an argument in\n%   the obvservation/evolution functions)\n%        \n%   - posterior: posterior pdf structure (see VBA_NLStateSpaceModel.m).\n%   This is used to extract first and second order parameters of the\n%   generative model (theta, phi, alpha, sigma), as well as the initial\n%   conditions of the hidden states (X0).\n%   - dim: a structure variable containing the dimensions of the 3 sets of\n%   model unknown variables (see VBA_NLStateSpaceModel.m)\n%   - options: user-defined structure containing specific informations\n%   regarding the model, ie (see VBA_check.m):\n%       .f_fname (resp. g_fname): name/handle of the function that outputs\n%       the evolution (resp. observation) of the hidden states.\n%       .u0: the mx1 initial value of the input {0}\n%       .inF: a (possibly structure) variable containing the additional\n%       (internal) fixed parameters which may have to be sent to the\n%       evolution function (eg pointing to different variants) {[]}\n%       .inG: idem for the observation function {[]}\n%   -  flag: a switch for computing just the mode of the deterministic\n%   predictive density (flag=0), the 1st and 2d order statistics of the EKF\n%   ({flag=1}), or the 1st and 2d order statistics of the predictive\n%   density (flag = 2).\n%\n% OUT:\n%   - muX: posterior mean of the hidden states X (nxn_t matrix)\n%   - SigmaX: covariance matrices of the variational posterior pdf of\n%       the dynamic hidden-states.\n\nif numel(options.sources) > 1\n    error('*** EKF is not yet compatible with multisource observations');\nend\n\nif options.sources.type > 1\n    error('*** EKF is not yet compatible with multinomial observations');\nend\n\n% By default, this function implements an EKF:\nif ~exist('flag','var') || isempty(flag)\n    flag = 1;\nend\n\n% This checks and fills in required dummy variables\nif isempty(u)\n    u = zeros(1,dim.n_t);\nend\n[dim.p,dim.n_t] = size(y);\ntry\n    dim.u;\ncatch\n    dim.u = size(u,1);\nend\nif isfield(options,'microU') && options.microU\n    u = VBA_getU(u,options,dim,'2macro');\nend\nif ~isfield(options,'nout_f')\n    options.nout_f = nargout(options.f_fname);\nend\nif ~isfield(options,'nout_g')\n    options.nout_g = nargout(options.g_fname);\nend\nif ~isfield(options,'OnLine')\n    options.OnLine = 0;\nend\ntry\n    X0 = posterior.muX0;\n    SigmaX0 = posterior.SigmaX0;\ncatch\n    X0 = zeros(dim.n,1);\n    SigmaX0 = zeros(dim.n,dim.n);\nend\ntry\n    theta = posterior.muTheta;\ncatch\n    theta = [];\nend\ntry\n    phi = posterior.muPhi;\ncatch\n    phi = [];\nend\ntry\n    iQx = options.priors.iQx;\n    iQy = options.priors.iQy;\ncatch\n    iQx = cell(dim.n_t,1);\n    iQy = cell(dim.n_t,1);\n    for t= 1:dim.n_t\n        iQx{t} = eye(dim.n);\n        iQy{t} = eye(dim.p);\n    end\nend\n\n\nswitch flag\n    case 0\n        suffStat = [];\n        str = 'deterministic time series';\n    case {1,2}\n        try\n            alpha = posterior.a_alpha(end)./posterior.b_alpha(end);\n            if options.sources.type == 0\n                sigma = posterior.a_sigma(end)./posterior.b_sigma(end);\n            end\n        catch\n            error('Not enough info in posterior structure!')\n        end\n        mStar = zeros(dim.n,dim.n_t);\n        SigmaX = cell(dim.n_t,1);\n        %--- Initialize sufficient statistics time-series ---%\n        suffStat = VBA_getSuffStat(options);\n        if isequal(flag,1)\n            str = 'standard EKF';\n        else\n            str = 'predictive density';\n        end\nend\nmuX = zeros(dim.n,dim.n_t);\ngx = zeros(dim.p,dim.n_t);\n\n\n% First time iteration (from initial conditions)\nif ~options.OnLine && options.verbose\n    fprintf(1,['Deriving ',str,' ...'])\nend\nif flag>=1\n    %--- Prediction\n    [fx0,dF_dX0] = VBA_evalFun('f',X0,theta,u(:,1),options,dim,1);\n    mStar(:,1) = fx0;\n    Rp = dF_dX0'*SigmaX0*dF_dX0 + 1./alpha.*VBA_inv(iQx{1});\n    if flag == 1 % EKF update\n        [gx(:,1),dG_dX] = VBA_evalFun('g',mStar(:,1),phi,u(:,1),options,dim,1);\n        iRp = pinv(Rp);\n        C =  dG_dX*iQy{1}*dG_dX';\n        iSX = iRp + sigma*C;\n        SigmaX{1} = pinv( iSX );\n        muX(:,1) = mStar(:,1) + sigma.*SigmaX{1}*dG_dX*iQy{1}* (y(:,1)-gx(:,1));\n    else % Predictive density\n        muX(:,1) = mStar(:,1);\n        SigmaX{1} = Rp;\n    end\n    % get predicted observation at the mode\n    [gx(:,1),dG_dX] = VBA_evalFun('g',muX(:,1),phi,u(:,1),options,dim,1);\n    suffStat.dy(:,1) = y(:,1) - gx(:,1);\n    if options.sources.type == 0\n        suffStat.vy(:,1) = diag( sigma.^-1.*pinv(iQy{1}) + dG_dX'*SigmaX{1}*dG_dX );\n        suffStat.dy2 = suffStat.dy2 + suffStat.dy(:,1)'*iQy{1}*suffStat.dy(:,1);\n    else\n        suffStat.vy(:,1) = gx(:,1).*(1-gx(:,1));\n        suffStat.logL = y(:,1)'*log(gx(:,1)) + (1-y(:,1))'*log(1-gx(:,1));\n    end\n    suffStat.dx(:,1) = muX(:,1) - fx0;\n    suffStat.dx2 = suffStat.dx2 + suffStat.dx(:,1)'*iQx{1}*suffStat.dx(:,1);\nelse\n    muX(:,1) = VBA_evalFun('f',X0,theta,u(:,1),options,dim);\nend\n\n\n% Loop over time samples\nif ~options.OnLine && options.verbose\n    fprintf(1,'%6.2f %%',0)\nend\nfor t = 1:dim.n_t-1\n    if flag >= 1\n        %-- Prediction\n        [fx,dF_dX] = VBA_evalFun('f',muX(:,t),theta,u(:,t+1),options,dim,t+1);\n        mStar(:,t+1) = fx;\n        Rp = dF_dX'*SigmaX{t}*dF_dX + 1./alpha.*VBA_inv(iQx{t+1});\n        if flag == 1    % EKF update\n            [gx(:,t+1),dG_dX] = VBA_evalFun('g',mStar(:,t+1),phi,u(:,t+1),options,dim,t+1);\n            C =  dG_dX*iQy{t+1}*dG_dX';\n            iRp = pinv(Rp);\n            iSX = iRp + sigma*C;\n            SigmaX{t+1} = pinv( iSX );\n            muX(:,t+1) = mStar(:,t+1) + sigma.*SigmaX{t+1}*dG_dX*iQy{t+1}* (y(:,t+1)-gx(:,t+1));\n        else\n            muX(:,t+1) = mStar(:,t+1);\n            SigmaX{t+1} = Rp;\n        end\n        % get predicted observation at the mode\n        [gx(:,t+1),dG_dX] = VBA_evalFun('g',muX(:,t+1),phi,u(:,t+1),options,dim,t+1);\n        suffStat.dy(:,t+1) = y(:,t+1) - gx(:,t+1);\n        if options.sources.type == 0\n            suffStat.vy(:,t+1) = diag( sigma.^-1.*pinv(iQy{t+1}) + dG_dX'*SigmaX{t+1}*dG_dX );\n            suffStat.dy2 = suffStat.dy2 + suffStat.dy(:,t+1)'*iQy{t+1}*suffStat.dy(:,t+1);\n        else\n            suffStat.vy(:,t+1) = gx(:,t+1).*(1-gx(:,t+1));\n            suffStat.logL = suffStat.logL + y(:,t+1)'*log(gx(:,t+1)) + (1-y(:,t+1))'*log(1-gx(:,t+1));\n        end\n        suffStat.dx(:,t+1) = muX(:,t+1) - fx;\n        suffStat.dx2 = suffStat.dx2 + suffStat.dx(:,t+1)'*iQx{t+1}*suffStat.dx(:,t+1);\n    else\n        muX(:,t+1) = VBA_evalFun('f',muX(:,t),theta,u(:,t+1),options,dim);\n    end\n    if ~options.OnLine && isequal(mod(t,32),0) && options.verbose\n        fprintf(1,repmat('\\b',1,8))\n        fprintf(1,'%6.2f %%',100*t/dim.n_t)\n    end\nend\nif ~options.OnLine  && options.verbose\n    fprintf(1,repmat('\\b',1,8))\n    fprintf(' OK.')\n    fprintf('\\n')\nend\nif flag >= 1\n    suffStat.gx = gx;\nend\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/VBA_EKF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23212001802571694}}
{"text": "function y = bwdpr1(Lden, b) %#ok\n% y = bwdpr1(Lden, b)\n%\n% BWDPR1  Solves \"PROD_k L(pk,betak)' * y = b\", where\n%     L(p,beta) = eye(n) + tril(p*beta',-1).\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi, dpr1fact, fwdpr1\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\n%Indicate to the user Matlab cannot find the SeDuMi binaries\nsedumi_binary_error();", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/bwdpr1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2321200180257169}}
{"text": "function test_bug1483\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_selectdata ft_selectdata_new ft_selectdata_old\n\n%% first confirm the reported bug, i.e. the incapability of ft_selectdata_new\n% to select 'rpt'\n\n% create some dummy data\nfor k = 1:5\n  data.trial{k} = ones(2,3).*k;\n  data.time{k}  = -1:1;\nend\ndata.label = {'chan1';'chan2'};\n\nfreq.powspctrm = rand(5,2,3);\nfreq.dimord    = 'rpt_chan_freq';\nfreq.label     = {'chan1';'chan2'};\nfreq.freq      = [1 2 3];\nfreq.cumtapcnt = ones(5,1);\n\n% old style -> this does not work anymore because ft_selectdata in its old\n% implementation has been moved to compat/obsolete, and currently the input\n% data checking is so strict, that a non cfg-like data structure causes a\n% crash\n%dataold1 = ft_selectdata(data, 'rpt', 2:4);\n%dataold2 = ft_selectdata(data, 'channel', data.label(1));\n\n%freqold1 = ft_selectdata(freq, 'rpt', 2:4);\n%freqold2 = ft_selectdata(freq, 'channel', freq.label(1));\n\n\n% new style\ncfg = [];\ncfg.trials = 2:4;\ndatanew1 = ft_selectdata(cfg, data);\nfreqnew1 = ft_selectdata(cfg, freq);\n\ncfg = [];\ncfg.channel = data.label(1);\ndatanew2 = ft_selectdata(cfg, data);\nfreqnew2 = ft_selectdata(cfg, freq);\n\n\n% BUG CONFIRMED\n\n%%\n\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1483.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23212001802571686}}
{"text": "BTB_memo= BTB;\nBTB.RawDir= fullfile(BTB.DataDir, 'demoRaw');\nBTB.MatDir= fullfile(BTB.DataDir, 'demoMat');\n\n% add more to the list if you want to do it in a row\nsubdir_list= {'VPkg_08_08_07'};\n% you could have more files also\nbasename_list= {'calibration_motorimagery', ...\n                'feedback_motorimagery'};\n\n% definition of classes based on markers \nstimDef= {1, 2, 3;\n          'left','right', 'foot'};\n\n\n% load raw files (with filtering), define classes and montage,\n% and save in matlab format\nfor k= 1:length(subdir_list);\n for ib= 1:length(basename_list),\n  subdir= subdir_list{k};\n  sbj= subdir(1:find(subdir=='_',1,'first')-1);\n  file= fullfile(subdir, [basename_list{ib} sbj]);\n  fprintf('converting %s\\n', file)\n  \n  [cnt, mrk_orig, hdr] = file_readBV(file);\n  \n  % create mrk and mnt\n  mrk= mrk_defineClasses(mrk_orig, stimDef);\n  mrk.orig= mrk_orig;\n  mnt= mnt_setElectrodePositions(cnt.clab);\n  mnt= mnt_setGrid(mnt, 'M+EOG+EMG');\n  \n  % save in matlab format\n  file_saveMatlab(file, cnt, mrk, mnt, 'Vars','hdr');\n end\nend\n\nBTB= BTB_memo;\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/demos/demo_convert_MotorImagery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23194161390836884}}
{"text": "function [timeZoneInfo,displayName]=getTimeZoneInfo(timeZoneName,Jul1,Jul2)\n%GETTIMEZONEINFO Get information about a time zone. If a date is provided,\n%                one can obtain an offset from UTC taking daylight savings\n%                time into account, if relevant. Note, however, that many\n%                countries only add a leap second at their local midnight\n%                and not when UTC does, so the offsets might be off by a\n%                second around when a leap second is added.\n%\n%INPUTS: timeZoneName The name of the time zone. This is one of the short\n%                   names returned by getTimeZoneList(). A meaningless\n%                   input will cause UTC to be returned.\n%           Jul1,Jul2 Optionally, the time as a pseudo-Julian date in UTC.\n%                   The units of the date are days. The full date is the\n%                   sum of both terms. The date is broken into two parts to\n%                   provide more bits of precision. It does not matter how\n%                   the date is split. If this input is provided, then\n%                   daylight savings time information can be provided on\n%                   the output.\n%\n%OUTPUTS: timeZoneInfo A 2X1 or 4X1 (if a UTC date is provided) providing\n%                   information on the time zone. timeZoneInfo(1) is the\n%                   offset from UTC in seconds for time time zone, without\n%                   daylight savings time. timeZoneInfo(2) is true if the\n%                   time zone is listed as having ever supported daylight\n%                   savings time or if it is listed as ever supporting it\n%                   in the future. timeZoneInfo(3) is the offset in seconds\n%                   from UTC at the given date and timeZoneInfo(4) is true\n%                   if the time zone is in daylight savings time at the\n%                   given date.\n%       displayName A more detailed version of timeZoneName.\n%\n%This function just calls the appropriate Java commands to obtain time zone\n%information.\n%\n%EXAMPLE:\n%For the Easten Time Zone of the United States on 11 January 2016, one can\n%use\n% [UTC1,UTC2]=Cal2UTC(2016,1,11,0,0,0);\n% [timeZoneInfo,displayName]=getTimeZoneInfo('EST5EDT',UTC1,UTC2)\n%One will see that daylight savings time is honored, but is not active at\n%the given time, so both offsets are -18000 second (=-5 hours).\n%\n%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\ntimeZone=java.util.TimeZone.getTimeZone(timeZoneName);\n\ndisplayName=char(timeZone.getDisplayName());\n\nif(nargin>1&&~isempty(Jul1))\n    timeZoneInfo=zeros(4,1);\n    timeZoneInfo(1)=timeZone.getRawOffset()/1e3;\n    timeZoneInfo(2)=timeZone.observesDaylightTime() || timeZone.useDaylightTime();\n    \n    [TT1,TT2]=UTC2TT(Jul1,Jul2);\n    [UTCRef1,UTCRef2]=Cal2UTC(1970,1,1,0,0,0);\n    [TTRef1,TTRef2]=UTC2TT(UTCRef1,UTCRef2);\n\n    %It should be that TT1>TT2 and TTRef1>TTRef2 due to how the conversion\n    %functions work.\n    %There are 86400 seconds in all Julian days in terrestrial time. The\n    %multiplication by 1000 turns it into milliseconds.\n    timeDiffMilliSeconds=int64((TT1-TTRef1)*86400*1000)+int64((TT2-TTRef2)*86400*1000);\n\n    timeZoneInfo(3)=timeZone.getOffset(timeDiffMilliSeconds)/1e3;\n    timeZoneInfo(4)=timeZoneInfo(1)~=timeZoneInfo(3);%Must currently be in DST.\nelse\n    timeZoneInfo=zeros(2,1);\n    timeZoneInfo(1)=timeZone.getRawOffset()/1e3;\n    timeZoneInfo(2)=timeZone.observesDaylightTime() || timeZone.useDaylightTime();\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Time/getTimeZoneInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23194161390836884}}
{"text": "function [ALLEEG cfg] = pop_stat_surrogateStats(ALLEEG,typeproc,varargin)\n%\n% Return surrogate statistics based on a surrogate distribution (bootstrap, jacknife, etc).\n% Each surrogate distribution should approximate the distribution of the\n% estimator. \n%\n%\n% Input:\n%\n%   ALLEEG:         EEGLAB dataset to preprocess. Must contain .CAT.PConn\n%                   with surrogate distributions\n%   typeproc:       Reserved for future use. Use 0\n%\n% Optional:         \n%\n%   <'Name',value> pairs as defined in stat_surrogate()\n%   \n% Output:\n%\n%   ALLEEG:         EEG structure(s) with Stats object stored in\n%                   ALLEEG.CAT.Stats\n%   cfg:            Argument specification structure.\n%\n%\n% See Also: stat_surrogate()\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual.\n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift\n% \n% Author: Tim Mullen 2010-2011, SCCN/INC, UCSD. \n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nif nargin<2\n    typeproc = 0;\nend\n\nfcnName     = strrep(mfilename,'pop_','');\nfcnHandle   = str2func(fcnName);\n\n% check the dataset\nres = hlp_checkeegset(ALLEEG,{'pconn'});\nif ~isempty(res)\n    error(['SIFT:' fcnName],res{1});\nend\n\nif isfield(ALLEEG(1).CAT.configs,fcnName)\n    % get default configuration (from prior use) and merge with varargin\n    varargin = [hlp_struct2varargin(ALLEEG(1).CAT.configs.(fcnName)) varargin];\nend\n\n% reset the defaults if we have multiple EEG datasets\n% this ensures that config selections stored in each datset (i.e. Hbase) \n% don't conflict with the allowable selection when two datasets are present\nif length(ALLEEG)>1 && ~isempty(varargin)\n    idx = find(ismember_bc(varargin(1:2:end),'statTest'))*2;\n    if ~isempty(idx)\n        for k=1:length(idx)\n            varargin{idx(k)} = {}; \n        end\n    end\nend\n\nif strcmpi(typeproc,'nogui')\n    % get the config from function\n    cfg = arg_tovals(arg_report('rich',fcnHandle,[{'EEG',ALLEEG},varargin]),false);\nelse\n    % render the GUI\n    [PGh figh] = feval(['gui_' fcnName],ALLEEG,varargin{:});\n    \n    if isempty(PGh)\n        % user chose to cancel\n        cfg = [];\n        return;\n    end\n    \n    % get the specification of the PropertyGrid\n    ps = PGh.GetPropertySpecification;\n    cfg = arg_tovals(ps,false);\nend\n\ndrawnow;\n\nif strcmpi(typeproc,'cfg_only')\n    return;\nend\n\n% execute the low-level function\n[Stats ConnMean] = feval(fcnHandle,'EEG',ALLEEG,cfg);\n\nif isempty(Stats)\n    % user canceled\n    return;\nend\n    \n% store statistics and (optionally) the mean of the bootstrap estimator\nif length(ALLEEG)>1 && any(strcmp(cfg.statTest.arg_selection,{'Hab'}))\n    % create a new dataset containing expected difference between conds\n%     EEG2         = ALLEG(2);\n%     EEG2.data    = -EEG2.data;  % invert data so average is mean ERP difference\n%     EEG2.icaact  = -EEG2.icaact;\n%     EEG_new           = pop_mergeset(ALLEEG(1),EEG2,1);\n    \n    \n    EEG_new = ALLEEG(1);\n    EEG_new.CAT = rmfield(EEG_new.CAT,'PConn');\n    % compute ERP condition difference\n    for fn={'data','icaact','srcpot'}\n        if isfield(EEG_new,fn{1}) && ~isempty(EEG_new.(fn{1}))\n            EEG_new.(fn{1}) = mean(ALLEEG(Stats.diffOrder(1)).(fn{1}),3) ...\n                            - mean(ALLEEG(Stats.diffOrder(2)).(fn{1}),3);\n        end\n    end\n    EEG_new.trials    = 1;\n    EEG_new.epoch     = [];\n    EEG_new.setname   = cfg.statTest.datasetOrder;\n    EEG_new.condition = cfg.statTest.datasetOrder;\n    EEG_new = eeg_checkset(EEG_new);\n    \n    EEG_new.CAT.Conn  = ConnMean;  % condition difference\n    EEG_new.CAT.configs.(fcnName) = cfg;\n    EEG_new.CAT.Stats = Stats;\n    \n    EEG_new.CAT.configs.vis_TimeFreqGrid = [];\n    EEG_new.CAT.configs.vis_causalBrainMovie3D = [];\n    \n    % store the new EEG dataset\n    [ALLEEG EEG_new] = eeg_store(ALLEEG,EEG_new,length(ALLEEG)+1);\n    ALLEEG = EEG_new;\nelseif length(ALLEEG)==1\n\n    if ~isempty(cfg)\n        % store the configuration structure\n        ALLEEG.CAT.configs.(fcnName) = cfg;\n    end\n\n    ALLEEG.CAT.Stats = Stats;\n\n    if ~isempty(ConnMean)\n        % replace Conn object with mean of bootstrap distribution\n        % insert missing fields into new Conn object\n%         extrafields = setdiff_bc(fieldnames(ALLEEG.CAT.Conn),hlp_getConnMethodNames(ALLEEG.CAT.Conn));\n%         for i=1:length(extrafields)\n%             ConnMean(cnd).(extrafields{i}) = ALLEEG.CAT.Conn.(extrafields{i});\n%         end \n        ALLEEG.CAT.Conn = ConnMean;\n        \n        ALLEEG.CAT.configs.vis_TimeFreqGrid = [];\n        ALLEEG.CAT.configs.vis_causalBrainMovie3D = [];\n    end\nend\n\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/pop/pop_stat_surrogateStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23194161390836884}}
{"text": "function [n, freqs] = plx_adchan_freqs(filename)\n% plx_adchan_freq(filename): read the per-channel frequencies for analog channels from a .plx or .pl2 file\n%\n% [n, freqs] = plx_adchan_freq(filename)\n%\n% INPUT:\n%   filename - if empty string, will use File Open dialog\n%\n% OUTPUT:\n%   freqs - array of frequencies\n%   n - number of channels\n\nif nargin ~= 1\n    error 'expected 1 input argument';\nend\n\n[ filename, isPl2 ] = internalPL2ResolveFilenamePlx( filename );\nif isPl2 == 1\n    pl2 = PL2GetFileIndex(filename);\n    n = numel(pl2.AnalogChannels);\n    if n > 0\n        freqs = zeros(n,1);\n        for i=1:n\n            freqs(i,1) = pl2.AnalogChannels{i}.SamplesPerSecond;\n        end\n    end\n    return;\nend\n\n[n,freqs] = mexPlex(12, filename);\n\nend", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/plexonSDK/plx_adchan_freqs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23194161390836882}}
{"text": "function cvx_erase( p )\n\nglobal cvx___\npstr = cvx___.problems( p );\n% n_variables, n_equalities, n_cones\ncp = pstr.checkpoint + 1;\nnf = cp(1);\nif nf <= 2,\n    cvx___.classes     = int8(3);\n    cvx___.cones       = zeros(0,1);\n    cvx___.exponential = zeros(0,1);\nelseif length( cvx___.classes ) >= nf,\n    cvx___.classes( nf : end, : ) = [];\n    if ~isempty( cvx___.exponential ),\n        cvx___.exponential( nf : end, : ) = [];\n        cvx___.logarithm( nf : end, : ) = [];\n        if ~any( cvx___.exponential ),\n            cvx___.exponential = zeros(0,1);\n            cvx___.logarithm = zeros(0,1);\n        end\n    end\nend\nne = cp(2);\nif ne <= 1,\n    cvx___.equalities = {};\n    cvx___.inequality = false(0,1);\n    cvx___.n_equality = 0;\nelseif length( cvx___.equalities ) >= ne,\n    cvx___.n_equality = cvx___.n_equality - ...\n        sum( cellfun( @(x)size(x,2), cvx___.equalities( ne : end ) ) );\n    cvx___.equalities( ne : end ) = [];\n    cvx___.inequality( ne : end ) = [];\nend\nnc = cp(3);\nif nc <= 1,\n    cvx___.cones = [];\nelse\n    cvx___.cones( nc : end ) = [];\nend\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/lib/cvx_erase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45326184801538605, "lm_q1q2_score": 0.2319416139083688}}
{"text": "function rasterSegs = structUnion(rasterSegs1, rasterSegs2, scanNum, planC)\n%\"structUnion\"\n%   Find the union between two structures given their entire set of\n%   rasterSegments.  Performs this intersect one slice at a time to save\n%   memory. Returns rasterSegments representing the new structure.\n%\n%   By JRA 10/1/03\n%\n%   rasterSegs1    : rasterSegments of first structure\n%   rasterSegs2    : rasterSegments of second structure\n%   scanNum        : single scanNumber that both raster segs are defined on.\n%   planC          : CERR planC\n%\n%   rasterSegs     : rasterSegments of union of structures 1 & 2.\n%\n%Usage: \n%   rasterSegs = structUnion(rasterSegs1, rasterSegs2, scanNum, planC)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n\nindexS = planC{end};\nrasterSegs = [];\n\n%sort input rasterSegments by CTSliceValue\nrasterSegs1 = sortrows(rasterSegs1, 6);\nrasterSegs2 = sortrows(rasterSegs2, 6);\n\n%get list of CTSlices to iterate over.\nslices1 = unique(rasterSegs1(:,6));\nslices2 = unique(rasterSegs2(:,6));\n\n%for union, need to worry about slices where either structure has segments.\nslicesToCalculate = union(slices1, slices2);\n\n%for each slice we are calculating on, create a mask for each structure and\n%intersect them. Then convert from that mask to raster segments.\nfor i=1:length(slicesToCalculate)\n    sliceNum = slicesToCalculate(i);\n    rasterIndices = find(rasterSegs1(:,6) == sliceNum);\n    mask1 = rasterToMask(rasterSegs1(rasterIndices,:), scanNum, planC);\n    rasterIndices = find(rasterSegs2(:,6) == sliceNum);\n    mask2 = rasterToMask(rasterSegs2(rasterIndices,:), scanNum, planC);\n    unionMask = mask1 | mask2;\n    rasterSegs = [rasterSegs;maskToRaster(unionMask, sliceNum, scanNum, planC)];\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/structUnion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23184219694033362}}
{"text": "function test_bug1708\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY test_bug1708 ft_denoise_synthetic\n\n% reported bug is that ft_denoise_synthetic leads to nans in coilpos and\n% coilori\n\n% try to reproduce first\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg/preproc_ctf275.mat'));\n\ncfg  = [];\ncfg.gradient = 'none';\ndata = ft_denoise_synthetic(cfg, data);\n\ncfg = [];\ncfg.gradient = 'G3BR';\ndata = ft_denoise_synthetic(cfg, data);\n\nassert(all(isfinite(data.grad.coilori(:))));\nassert(all(isfinite(data.grad.coilpos(:))));\nassert(all(isfinite(data.grad.chanori(:))));\nassert(all(isfinite(data.grad.chanpos(:))));\n\n%%%% SOMEHOW the test data got lost along the way, therefore it seems\n%%%% wisest to just uncomment the next section.\n% load('test_bug1708.mat');\n% \n% avgData2 = ft_denoise_synthetic(cfg, avgData); % this confirmed the bug\n% \n% % however avgData had G1BR balancing, could it be caused by the fact that\n% % this balancing is not undone?\n% \n% cfg = [];\n% cfg.gradient = 'none';\n% avgData3 = ft_denoise_synthetic(cfg, avgData);\n% cfg.gradient = 'G3BR';\n% avgData4 = ft_denoise_synthetic(cfg, avgData3);\n% \n% % this indeed seems to be the case\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1708.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23173994123009908}}
{"text": "function [S, v, f, ORIGIN] = read_vf(fname, patch)\n% function [S, v, f, ORIGIN] = read_vf(fname, patch)\n% This function reads a matfile with vertices/faces-information in it.\n% if [fname '.mat'] cannot be found, a '.geo'- or 'asc'-file is searched\n% converted and saved as a matfile.\n% S(1) = nr of surfaces\n% S(2) = nr of vertices\n% S(3) = nr of faces\n% v: n x 3 matrix of vertices\n% f: m x 4 matrix of faces\n% ORIGIN: coordinates (2D or 3D) of ORIGIN in mm space, where the coordinates\n% [0 0 0] in vertices space are mapped to.\n\n% fname: filename of mat-file to be opened\n% patch: flag: if 1, try to get patch-information, i.e. indices of vertices and faces\n% in generating original surface, if 0, we don't need this information\n\n\n%\n% read_vf.m\n%\n% Original Author: Bruce Fischl\n% CVS Revision Info:\n%    $Author: nicks $\n%    $Date: 2011/03/02 00:04:12 $\n%    $Revision: 1.3 $\n%\n% Copyright \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\nfn = spm_str_manip(fname, 'r');\n\nsource = 0;\n\nif ~exist([fn '.mat'])\n   % Try to open asc-file\n   if patch == 0 | ~exist([fn '.asc'], 'file')\n      % Try to open geo-file\n      if patch == 1 \n         % no mat- or asc-file\n         error(sprintf('Cannot find patch-infomation, file %s not found', [fn '.asc']))\n      elseif ~exist([fn '.geo'], 'file')\n         error(sprintf('Cannot find %s or convert a geo- or asc-file to it.', [fn '.mat']))\n      else\n         [S, v, f] = read_moviebyu([fn '.geo']);\n         source = 2;\n      end\n   else\n      [S, v, fi] = read_asc([fn '.asc']);\n      source = 1;\n   end\nelse\n   load([fn '.mat']);\n   if patch == 1 & exist('fi') ~= 1\n      % used asked for patch information, but mat-file didn't contain this information\n      % so open asc-file (can happen, if asc-file wasn't present when mat-file\n      % was generated\n      if exist ([fn '.asc'], 'file')\n         [S, v, fi] = read_asc([fn '.asc']);\n         save([fn '.mat'], 'fi', 'v', '-append');\n         source = 1;\n      else\n         error(sprintf('Cannot find %s', [fn '.asc']));\n      end\n   elseif patch == 0 & exist('f') ~= 1\n      % no patch information needed, try to get plain f\n      if exist ([fn '.geo'], 'file')\n         [S, v, f] = read_moviebyu([fn '.geo']);\n         save([fn '.mat'], 'f', '-append');\n         source = 2;\n      else\n         error(sprintf('Cannot find %s', [fn '.geo']));\n      end\n   end\n   \n   if patch == 0 & size(v, 2) ~= 3\n      v = v(:, 2:4);\n   end\nend\n\nif source == 1 | source == 2\n   % Assume that ORIGIN is [128 128 128]\n   ORIGIN = [128 128 128];\nend\n\nif source == 1\n   save([fn '.mat'], 'S', 'v', 'fi', 'ORIGIN');\nelseif source == 2\n   save([fn '.mat'], 'S', 'v', 'f', 'ORIGIN'); \nend\n\nif patch == 1\n   f = fi;\nend   \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/read_vf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23173994123009906}}
{"text": "% Saving Input Files In Parts Example\n%\n% This example demonstrates how to save the HDF5 input files required by\n% the C++ code in parts. It builds on the Running C++ Simulations Example. \n%\n% author: Bradley Treeby\n% date: 3rd December 2013\n% last update: 13th February 2014\n%  \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see <http://www.gnu.org/licenses/>. \n\nclear all; \n\n% modify this parameter to run the different examples\nexample_number = 1;\n% 1: Save the input data to disk in parts\n% 2: Reload the output data from disk\n\n% input and output filenames (these must have the .h5 extension)\ninput_filename  = 'example_input.h5';\noutput_filename = 'example_output.h5';\n\n% pathname for the input and output files\npathname = tempdir;\n\n% remove input file if it already exists\nif example_number == 1 && exist([pathname input_filename], 'file')\n    delete([pathname input_filename]);\nend\n\n% load HDF5 constants\nrun([getkWavePath 'private/getH5Literals']);\n\n% =========================================================================\n% SIMULATION SETTINGS\n% =========================================================================\n\n% set the properties of the computational grid\nNx = 256;                   % number of grid points in the x direction\nNy = 128;                   % number of grid points in the y direction\nNz = 64;                    % number of grid points in the z direction\ndx = 0.1e-3;                % grid point spacing in the x direction [m]\ndy = 0.1e-3;                % grid point spacing in the y direction [m]\ndz = 0.1e-3;                % grid point spacing in the z direction [m]\nNt = 1200;                  % number of time steps\ndt = 15e-9;                 % time step [s]\n\n% set the properties of the perfectly matched layer \npml_x_size  = 10;           % [grid points]\npml_y_size  = 10;           % [grid points]\npml_z_size  = 10;           % [grid points]\npml_x_alpha = 2;            % [Nepers/grid point]\npml_y_alpha = 2;            % [Nepers/grid point]\npml_z_alpha = 2;            % [Nepers/grid point]\n\n% define a scattering ball\nball_radius = 20;           % [grid points]\nball_x      = Nx/2 + 40;    % [grid points]\nball_y      = Ny/2;         % [grid points]\nball_z      = Nz/2;         % [grid points]\n\n% define the properties of the medium\nc0_background   = 1500;     % [kg/m^3]\nc0_ball         = 1800;     % [kg/m^3]\nrho0_background = 1000;     % [kg/m^3]\nrho0_ball       = 1200;     % [kg/m^3]\nalpha_coeff     = 0.75;     % [dB/(MHz^y cm)]\nalpha_power     = 1.5;\n\n% define a the properties of a single square source element facing in the\n% x-direction \nsource_y_size   = 60;       % [grid points]\nsource_z_size   = 30;       % [grid points]\nsource_freq     = 2e6;      % [Hz]\nsource_strength = 0.5e6;    % [Pa]\n\n% =========================================================================\n% WRITE THE INPUT FILE\n% =========================================================================\n\nif example_number == 1\n\n    % ---------------------------------------------------------------------\n    % WRITE THE MEDIUM PARAMETERS\n    % ---------------------------------------------------------------------\n    \n    % update command line status\n    tic; fprintf('Writing medium parameters... ');\n\n    % :::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::\n\n    % create the scattering ball and density matrix\n    ball       = makeBall(Nx, Ny, Nz, ball_x, ball_y, ball_z, ball_radius, [], true);\n    rho0       = rho0_background*ones(Nx, Ny, Nz, 'single');   \n    rho0(ball) = rho0_ball;\n\n    % make sure the input is in the correct data format\n    eval(['rho0 = ' MATRIX_DATA_TYPE_MATLAB '(rho0);']);\n    \n    % save the density matrix to both regular and staggered grid parameters\n    writeMatrix([pathname input_filename], rho0, 'rho0'); \n    writeMatrix([pathname input_filename], rho0, 'rho0_sgx');\n    writeMatrix([pathname input_filename], rho0, 'rho0_sgy');\n    writeMatrix([pathname input_filename], rho0, 'rho0_sgz');\n\n    % clear variable to free memory\n    clear('rho0');\n    \n    % :::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::\n\n    % create the sound speed matrix\n    c0       = c0_background*ones(Nx, Ny, Nz, 'single');   \n    c0(ball) = c0_ball;\n    \n    % set the reference sound speed to the maximum in the medium\n    c_ref = max(c0(:));\n\n    % get the sound speed at the location of the source\n    c_source = min(c0(:));\n    \n    % make sure the input is in the correct data format\n    eval(['c0 = ' MATRIX_DATA_TYPE_MATLAB '(c0);']);\n    \n    % save the sound speed matrix\n    writeMatrix([pathname input_filename], c0, 'c0');\n\n    % clear variable to free memory\n    clear('c0', 'ball');\n\n    % :::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::---:::\n\n    % make sure the inputs are in the correct data format\n    eval(['alpha_coeff = ' MATRIX_DATA_TYPE_MATLAB '(alpha_coeff);']);\n    eval(['alpha_power = ' MATRIX_DATA_TYPE_MATLAB '(alpha_power);']);\n\n    % save the absorption variables\n    writeMatrix([pathname input_filename], alpha_coeff, 'alpha_coeff');\n    writeMatrix([pathname input_filename], alpha_power, 'alpha_power');\n\n    % clear variables to free memory\n    clear('alpha_coeff', 'alpha_power');\n\n    % ---------------------------------------------------------------------\n    % WRITE THE SOURCE PARAMETERS\n    % ---------------------------------------------------------------------\n\n    % update command line status\n    toc; tic; fprintf('Writing source parameters... ');\n\n    % define a square source mask facing in the x-direction using the\n    % normal k-Wave syntax\n    p_mask = false(Nx, Ny, Nz);\n    p_mask(1 + pml_x_size, Ny/2 - source_y_size/2:Ny/2 + source_y_size/2, Nz/2 - source_z_size/2:Nz/2 + source_z_size/2) = 1;\n\n    % find linear source indices\n    p_source_index = find(p_mask == 1);\n    p_source_index = reshape(p_source_index, [], 1);\n\n    % make sure the input is in the correct data format\n    eval(['p_source_index = ' INTEGER_DATA_TYPE_MATLAB '(p_source_index);']);\n\n    % save the source index matrix\n    writeMatrix([pathname input_filename], p_source_index, 'p_source_index');\n\n    % clear variables to free memory\n    clear p_mask p_source_index;\n\n    % define a time varying sinusoidal source\n    p_source_input  = source_strength.*sin(2*pi*source_freq*(0:(Nt-1))*dt);\n\n    % apply an cosine ramp to the beginning to avoid startup transients\n    ramp_length = round((2*pi/source_freq)/dt);\n    p_source_input(1:ramp_length) = p_source_input(1:ramp_length).*(-cos( (0:(ramp_length-1))*pi/ramp_length ) + 1)/2;\n\n    % scale the source magnitude to be in the correct units for the code\n    p_source_input = p_source_input .* (2*dt./(3*c_source*dx));\n    \n    % cast matrix to single precision\n    eval(['p_source_input = ' MATRIX_DATA_TYPE_MATLAB '(p_source_input);']);\n\n    % save the input signal\n    writeMatrix([pathname input_filename], p_source_input, 'p_source_input');\n\n    % clear variables to free memory\n    clear('p_source_input');\n\n    % ---------------------------------------------------------------------\n    % WRITE THE SENSOR PARAMETERS\n    % ---------------------------------------------------------------------\n\n    % update command line status\n    toc; tic; fprintf('Writing sensor parameters... ');\n\n    % define a sensor mask through the central plane\n    sensor_mask = false(Nx, Ny, Nz);\n    sensor_mask(:, :, Nz/2) = 1;\n\n    % extract the indices of the active sensor mask elements\n    sensor_mask_index = find(sensor_mask);\n    sensor_mask_index = reshape(sensor_mask_index, [], 1);\n\n    % make sure the input is in the correct data format\n    eval(['sensor_mask_index = ' INTEGER_DATA_TYPE_MATLAB '(sensor_mask_index);']);\n\n    % save the sensor mask\n    writeMatrix([pathname input_filename], sensor_mask_index, 'sensor_mask_index');\n\n    % clear variables to free memory\n    clear('sensor_mask', 'sensor_mask_index');\n\n    % ---------------------------------------------------------------------\n    % WRITE THE GRID PARAMETERS AND FILE ATTRIBUTES\n    % ---------------------------------------------------------------------\n\n    % update command line status\n    toc; tic; fprintf('Writing grid parameters and attributes... ');\n\n    % write grid parameters\n    writeGrid([pathname input_filename], [Nx, Ny, Nz], [dx, dy, dz], ...\n        [pml_x_size, pml_y_size, pml_z_size], [pml_x_alpha, pml_y_alpha, pml_z_alpha], ...\n        Nt, dt, c_ref);\n\n    % write flags\n    writeFlags([pathname input_filename]);\n\n    % set additional file attributes\n    writeAttributes([pathname input_filename]);\n\n    toc;\n    \n    % display the required syntax to run the C++ simulation\n    disp(['Using a terminal window, navigate to the ' filesep 'binaries folder of the k-Wave Toolbox']);\n    disp('Then, use the syntax shown below to run the simulation:');\n    if isunix\n        disp(['./kspaceFirstOrder3D-OMP -i ' pathname input_filename ' -o ' pathname output_filename ' --p_final --p_max']);\n    else\n        disp(['kspaceFirstOrder3D-OMP.exe -i ' pathname input_filename ' -o ' pathname output_filename ' --p_final --p_max']);\n    end    \n\n    return\n\n% =========================================================================\n% READ THE OUTPUT FILE AND PLOT VISUALISATION\n% =========================================================================\n\nelse\n    \n    % load output data from the C++ simulation\n    sensor_data.p_final = h5read([pathname output_filename], '/p_final');\n    sensor_data.p_max   = h5read([pathname output_filename], '/p_max');\n\n    % take an x-y slice through the final pressure output (this is recorded\n    % over the entire grid)\n    sensor_data.p_final = squeeze(sensor_data.p_final(:, :, Nz/2));\n\n    % reshape the maximum pressure output (this is recorded at the grid points\n    % specified by the sensor mask)\n    sensor_data.p_max = reshape(sensor_data.p_max, [Nx, Ny]);\n\n    % add a display mask\n    ball_outline = makeCircle(Nx, Ny, ball_x, ball_y, ball_radius);\n    sensor_data.p_max  (ball_outline == 1) = max(sensor_data.p_max(:));\n    sensor_data.p_final(ball_outline == 1) = max(sensor_data.p_final(:));\n\n    % remove the pml\n    sensor_data.p_max   = sensor_data.p_max  (1 + pml_x_size:end - pml_x_size, 1 + pml_y_size:end - pml_y_size);\n    sensor_data.p_final = sensor_data.p_final(1 + pml_x_size:end - pml_x_size, 1 + pml_y_size:end - pml_y_size);\n\n    % get a suitable plot scale\n    x_vec = (0:(Nx-2*pml_x_size-1))*dx;\n    y_vec = (0:(Ny-2*pml_y_size-1))*dy;\n    [x_sc, scale, prefix] = scaleSI(max([x_vec, y_vec]));\n\n    % plot the final pressure field in the x-y plane\n    figure;\n    subplot(1, 2, 1);\n    imagesc(y_vec*scale, x_vec*scale, sensor_data.p_final, [-1, 1]*source_strength);\n    colormap(getColorMap);\n    xlabel(['y [' prefix 'm]']);\n    ylabel(['x [' prefix 'm]']);\n    axis image;\n    title('Final Pressure Field');\n\n    % plot the maximum pressure field in the x-y plane\n    subplot(1, 2, 2);\n    imagesc(y_vec*scale, x_vec*scale, sensor_data.p_max, [-2, 2]*source_strength);\n    colormap(getColorMap);\n    xlabel(['y [' prefix 'm]']);\n    ylabel(['x [' prefix 'm]']);\n    axis image;\n    title('Maximum Pressure');\n\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_cpp_io_in_parts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23171579230926337}}
{"text": "function [expressionRxns, parsedGPR, gene_used, signifRxns] = mapExpressionToReactions(model, expressionData, minSum)                                          \n% Determines the expression data associated to each reaction present in\n% the model \n%\n% USAGE:\n%\n%    [expressionRxns parsedGPR, gene_used] = mapExpressionToReactions(model, expressionData) \n%    [expressionRxns, parsedGPR, gene_used, signifRxns] =  mapExpressionToReactions(model, expressionData, minSum)\n%\n% INPUTS:\n%\tmodel                   model strusture\n%\texpressionData          mRNA expression data structure\n%       .gene               \tcell array containing GeneIDs in the same\n%                               format as model.genes\n%       .value                  Vector containing corresponding expression\n%                               value (FPKM/RPKM)\n%       .sig:               [optional field] Vector containing significance values of\n%                           expression corresponding to expression values in\n%                           expressionData.value (ex. p-values)\n%\n% OPTIONAL INPUT:\n%    minSum:         instead of using min and max, use min for AND and Sum\n%                    for OR (default: false, i.e. use min)\n%\n% OUTPUTS:\n%   expressionRxns:         n x 1 non-negative value for reaction expression, corresponding to model.rxns.\n%                           expressionRxns(j) is NaN when there is no expression data for the genes corresponding to reaction j.\n%   parsedGPR:              cell matrix containing parsed GPR rule\n%   gene_used:              gene identifier, corresponding to model.rxns, from GPRs\n%                           whose value (expression and/or significance) was chosen for that\n%                           reaction\n%\n% OPTIONAL OUTPUTS:\n%   signifRxns:              significance of reaction expression, corresponding to model.rxns.\n\n%\n% Authors:\n%       - Anne Richelle, May 2017 - integration of new extraction methods \n%       - Chaitra Sarathy, Oct 2019, add significance value as optional input\n\nif ~exist('minSum','var')\n    minSum = false;\nend\n\nif isfield(expressionData, 'sig') \n    exprSigFlag = 1; \nelse\n    exprSigFlag = 0;\nend \n\n% Extracting GPR data from model\nparsedGPR = GPRparser(model,minSum);\n\n\nif exprSigFlag == 0\n\n    % Find wich genes in expression data are used in the model\n    % Returns vectors of gene identifiers and corresponding gene expression\n    % levels for each gene present in the model ('model.genes').\n    [gene_id, gene_expr] = findUsedGenesLevels(model,expressionData);\n\n    % Link the gene to the model reactions\n    % Map gene expression to reaction expression using the GPR rules. An AND\n    % will be replaced by MIN and an OR will be replaced by MAX.\n    [expressionRxns,  gene_used] = selectGeneFromGPR(model, gene_id, gene_expr, parsedGPR, minSum);\n    \nelse\n    \n    [gene_id, gene_expr, gene_sig] = findUsedGenesLevels(model, expressionData);\n    [expressionRxns,  gene_used, signifRxns] = selectGeneFromGPR(model, gene_id, gene_expr, parsedGPR, minSum, gene_sig);\n    \nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/transcriptomics/preprocessing/mapExpressionToReactions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23164922552692593}}
{"text": "function grid = GetSearchGrid(model, material, fix, fixedvals)\n% Returns a list of parameter combinations for the specified model\n% for the GridSearch function to use in search for the combination\n% that best fits a set of measurements.\n%\n% grid=GetSearchGrid(model, material, fix, fixedvals)\n% returns a list of parameter combinations for the model that\n% are realistic for a particular material type.\n%\n% model is a string specifying the model.\n%\n% material is a string specifying the type of material, which\n% determines the range of each parameter in the grid.\n% Options are:\n% invivo\n% invivopreterm\n% invivowhitematter\n% fixedwhitematter\n%\n% fix is a list of binary numbers specifying which\n% model parameters have fixed values.  By default the\n% list is all zeros so no parameters are fixed.\n%\n% fixedvals is an array the same size as fix that specifies\n% the fixed values of any fixed parameters.  Entries in\n% fixedvals in locations where fix has value zero are not\n% used.\n%\n% author: Daniel C Alexander (d.alexander@ucl.ac.uk)\n%         Gary Hui Zhang     (gary.zhang@ucl.ac.uk)\n%\n\nif(nargin<3)\n    fix=zeros(6);\n    fixedvals = zeros(6);\nend\n\nif(strcmp(material, 'invivo'))\n    fs = [0.0 0.25 0.5 0.75 1.0];\n    dpars = [13.0 17.0 21.0]*1E-10;\n    disos = [10.0 20.0 30.0 50.0]*1E-10;\n    Rs=[0.5 1 2 4]*1E-6;\n    irfracs=[0 0.1 0.2 0.3];\n    fisos=[0.0 0.25 0.5 0.75 1.0];\n    kappas = [0.5 1 2 4 8];\n    fic = [0.3 0.5 0.7];\nelseif(strcmp(material, 'exvivo'))\n    fs = [0.0 0.25 0.5 0.75 1.0];\n    dpars = [3.0 4.5 6.0 7.5]*1E-10;\n    disos = [5.0 10.0 15.0]*1E-10;\n    Rs=[1 2 4 8]*1E-6;\n    irfracs=[0 0.1 0.2 0.3];\n    fisos=[0.0 0.25 0.5 0.75 1.0];\n    kappas = [0.5 1 2 4 8];\n    fic = [0.3 0.5 0.7];\nelseif(strcmp(material, 'invivopreterm'))\n    fs = [0.0 0.1 0.2 0.3];\n    dpars = [13.0 17.0 21.0]*1E-10;\n    disos = [10.0 20.0 30.0 50.0]*1E-10;\n    Rs=[1 2 4 8]*1E-6;\n    irfracs=[0 0.1 0.2 0.3];\n    fisos=[0.0 0.25 0.5 0.75 1.0];\n    kappas = [0.5 1 2 4 8];\n    fic = [0.3 0.5 0.7];\nelseif(strcmp(material, 'invivowhitematter'))\n    fs = [0.5 0.7 0.9];\n    dpars = [10.0 13.0 15.0 17.0 19.0 21.0 23.0 25.0]*1E-10;\n    disos = [10.0 20.0 30.0 50.0]*1E-10;\n    Rs=[1 2 4 8]*1E-6;\n    irfracs=[0 0.1 0.2 0.3];\n    fisos=[0 0.2 0.4];\n    kappas = [4 8 16 32 64 128];\n    fic = [0.3 0.5 0.7];\nelseif(strcmp(material, 'postmortemwhitematter'))\n    fs = [0.5 0.7 0.9];\n    dpars = [2.0 3.0 4.0 5.0 6.0]*1E-10;\n    disos = [5.0 10.0 15.0]*1E-10;\n    Rs=[1 2 4 8]*1E-6;\n    irfracs=[0 0.1 0.2 0.3];\n    fisos=[0 0.2 0.4];\n    kappas = [4 8 16 32 64 128];\n    fic = [0.3 0.5 0.7];\nelse\n    error(['Unknown material: ', tissue]);\nend\n\n% Adjust for fixed parameters.  The first two parameters are the same for\n% all models.\nif(fix(1))\n    fs = [fixedvals(1)];\nend\nif(fix(2))\n    dpars = [fixedvals(2)];\nend\n\nif(strcmp(model, 'CylSingleRadTortGPD'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars);\n    grid = zeros(3, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                pars = [fs(j) dpars(k) Rs(i)];\n                grid(:,ind) = pars;\n                ind = ind + 1;\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadGPD'))\n    if(fix(4))\n        Rs = [fixedvals(4)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars);\n    grid = zeros(4, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                % Set dperp using the standard tortuosity model for\n                % randomly placed cylinders unless fixed.\n                dperp = dpars(k)*(1-fs(j));\n                if(fix(3))\n                    dperp = fixedvals(3);\n                end\n                pars = [fs(j) dpars(k) dperp Rs(i)];\n                grid(:,ind) = pars;\n                ind = ind + 1;\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadTortIsoGPD'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n    if(fix(4))\n        fisos = [fixedvals(4)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos);\n    grid = zeros(4, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    pars = [fs(j) dpars(k) Rs(i) fisos(l)];\n                    grid(:,ind) = pars;\n                    ind = ind + 1;\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadIsoV_GPD') || strcmp(model, 'CylSingleRadIsoV_GPD_B0'))\n    if(fix(4))\n        Rs = [fixedvals(4)];\n    end\n    if(fix(5))\n        fisos = [fixedvals(5)];\n    end\n    if(fix(6))\n        disos = [fixedvals(6)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos)*length(disos);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    for m=1:length(disos)\n                        % Set dperp using the standard tortuosity model for\n                        % randomly placed cylinders unless fixed.\n                        dperp = dpars(k)*(1-fs(j));\n                        if(fix(3))\n                            dperp = fixedvals(3);\n                        end\n                        pars = [fs(j) dpars(k) dperp Rs(i) fisos(l) disos(m)];\n                        grid(:,ind) = pars;\n                        ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadTortIsoV_GPD') || strcmp(model, 'CylSingleRadTortIsoV_GPD_B0'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n    if(fix(4))\n        fisos = [fixedvals(4)];\n    end\n    if(fix(5))\n        disos = [fixedvals(5)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos)*length(disos);\n    grid = zeros(5, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    for m=1:length(disos)\n                        pars = [fs(j) dpars(k) Rs(i) fisos(l) disos(m)];\n                        grid(:,ind) = pars;\n                        ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadIsoDotGPD'))\n    if(fix(4))\n        Rs = [fixedvals(4)];\n    end\n    if(fix(5))\n        irfracs = [fixedvals(5)];\n    end\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(irfracs);\n    grid = zeros(5, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(irfracs)\n                    dperp = dpars(k)*(1-fs(j));\n                    pars = [fs(j) dpars(k) dperp Rs(i) irfracs(l)];\n                    grid(:,ind) = pars;\n                    ind = ind + 1;\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'CylSingleRadIsoResTortIsoV_GPD') || strcmp(model, 'CylSingleRadIsoResTortIsoV_GPD_B0')...\n        || strcmp(model, 'CylSingleRadIsoStickTortIsoV_GPD') || strcmp(model, 'CylSingleRadIsoStickTortIsoV_GPD_B0')...\n        || strcmp(model, 'CylSingleRadIsoSphereTortIsoV_GPD') || strcmp(model, 'CylSingleRadIsoSphereTortIsoV_GPD_B0')...\n        || strcmp(model, 'CylSingleRadIsoDotTortIsoV_GPD') || strcmp(model, 'CylSingleRadIsoDotTortIsoV_GPD_B0'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n    if(fix(4))\n        irfracs = [fixedvals(4)];\n    end\n    if(fix(5))\n        fisos = [fixedvals(5)];\n    end\n    if(fix(6))\n        disos = [fixedvals(6)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos)*length(disos);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    for m=1:length(disos)\n                        for n=1:length(irfracs)\n                            pars = [fs(j) dpars(k) Rs(i) irfracs(n) fisos(l) disos(m)];\n                            grid(:,ind) = pars;\n                            ind = ind + 1;\n                        end\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'Stick'))\n    numCombs = length(fs)*length(dpars);\n    grid = zeros(3, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            % Set dperp using the standard tortuosity model for\n            % randomly placed cylinders unless fixed.\n            dperp = dpars(j)*(1-fs(i));\n            if(fix(3))\n                dperp = fixedvals(3);\n            end\n            pars = [fs(i) dpars(j) dperp];\n            grid(:,ind) = pars;\n            ind = ind + 1;\n        end\n    end\nelseif(strcmp(model, 'StickIsoV_B0'))\n    if(fix(4))\n        fisos = [fixedvals(4)];\n    end\n    if(fix(5))\n        disos = [fixedvals(5)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos);\n    grid = zeros(5, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    % Set dperp using the standard tortuosity model for\n                    % randomly placed cylinders unless fixed\n                    dperp = dpars(j)*(1-fs(i));\n                    if(fix(3))\n                        dperp = fixedvals(3);\n                    end\n                    pars = [fs(i) dpars(j) dperp fisos(k) disos(l)];\n                    grid(:,ind) = pars;\n                    ind = ind + 1;\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'StickTortIsoV_B0'))\n    if(fix(3))\n        fisos = [fixedvals(3)];\n    end\n    if(fix(4))\n        disos = [fixedvals(4)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos);\n    grid = zeros(4, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    pars = [fs(i) dpars(j) fisos(k) disos(l)];\n                    grid(:,ind) = pars;\n                    ind = ind + 1;\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonStick') || strcmp(model, 'WatsonSHStick'))\n    numCombs = length(fs)*length(dpars)*length(kappas);\n    grid = zeros(4, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n\t\t  for k=1:length(kappas)\n                % Set dperp using the standard tortuosity model for\n                % randomly placed cylinders unless fixed.\n                dperp = dpars(j)*(1-fs(i));\n                if(fix(3))\n                    dperp = fixedvals(3);\n                end\n                pars = [fs(i) dpars(j) dperp kappas(k)];\n                grid(:,ind) = pars;\n                ind = ind + 1;\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonSHStickIsoV_B0'))\n    if(fix(4))\n        kappas = [fixedvals(4)];\n    end\n    if(fix(5))\n        fisos = [fixedvals(5)];\n    end\n    if(fix(6))\n        disos = [fixedvals(6)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    for m=1:length(kappas)\n                      dperp = dpars(j)*(1-fs(i));\n                      if(fix(3))\n                          dperp = fixedvals(3);\n                      end\n                      pars = [fs(i) dpars(j) dperp kappas(m) fisos(k) disos(l)];\n                      grid(:,ind) = pars;\n                      ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonSHStickIsoVIsoDot_B0'))\n    if(fix(5))\n        fisos = [fixedvals(5)];\n    end\n    if(fix(6))\n        disos = [fixedvals(6)];\n    end\n    if(fix(7))\n        irfracs = [fixedvals(7)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas)*length(irfracs);\n    grid = zeros(7, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    for m=1:length(kappas)\n                        for n=1:length(irfracs)\n                          dperp = dpars(j)*(1-fs(i));\n                          if(fix(3))\n                             dperp = fixedvals(3);\n                          end\n                          pars = [fs(i) dpars(j) dperp kappas(m) fisos(k) disos(l) irfracs(n)];\n                          grid(:,ind) = pars;\n                          ind = ind + 1;\n                        end\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonStickTort') || strcmp(model, 'WatsonSHStickTort'))\n    numCombs = length(fs)*length(dpars)*length(kappas);\n    grid = zeros(3, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n\t\t  for k=1:length(kappas)\n                pars = [fs(i) dpars(j) kappas(k)];\n                grid(:,ind) = pars;\n                ind = ind + 1;\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonSHStickTortIsoV_B0'))\n    if(fix(4))\n        fisos = [fixedvals(4)];\n    end\n    if(fix(5))\n        disos = [fixedvals(5)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas);\n    grid = zeros(5, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    for m=1:length(kappas)\n                      pars = [fs(i) dpars(j) kappas(m) fisos(k) disos(l)];\n                      grid(:,ind) = pars;\n                      ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonSHStickTortIsoVIsoDot_B0'))\n    if(fix(4))\n        fisos = [fixedvals(4)];\n    end\n    if(fix(5))\n        disos = [fixedvals(5)];\n    end\n    if(fix(6))\n        irfracs = [fixedvals(6)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas)*length(irfracs);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    for m=1:length(kappas)\n                        for n=1:length(irfracs)\n                          pars = [fs(i) dpars(j) kappas(m) fisos(k) disos(l) irfracs(n)];\n                          grid(:,ind) = pars;\n                          ind = ind + 1;\n                        end\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'WatsonSHCylSingleRadTortIsoV_GPD') || strcmp(model, 'WatsonSHCylSingleRadTortIsoV_GPD_B0'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n    if(fix(5))\n        fisos = [fixedvals(5)];\n    end\n    if(fix(6))\n        disos = [fixedvals(6)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    for m=1:length(disos)\n                      for n=1:length(kappas)\n                        pars = [fs(j) dpars(k) Rs(i) kappas(n) fisos(l) disos(m)];\n                        grid(:,ind) = pars;\n                        ind = ind + 1;\n                      end\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'BinghamCylSingleRadTortIsoV_GPD_B0'))\n    if(fix(3))\n        Rs = [fixedvals(3)];\n    end\n    if(fix(7))\n        fisos = [fixedvals(7)];\n    end\n    if(fix(8))\n        disos = [fixedvals(8)];\n    end\n\n    numCombs = length(Rs)*length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas);\n    grid = zeros(8, numCombs);\n    ind = 1;\n    for i=1:length(Rs)\n        for j=1:length(fs)\n            for k=1:length(dpars)\n                for l=1:length(fisos)\n                    for m=1:length(disos)\n                        for n=1:length(kappas)\n                            pars = [fs(j) dpars(k) Rs(i) kappas(n) 0 0 fisos(l) disos(m)];\n                            grid(:,ind) = pars;\n                            ind = ind + 1;\n                        end\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'BinghamStickTortIsoV_B0'))\n    if(fix(6))\n        fisos = [fixedvals(6)];\n    end\n    if(fix(7))\n        disos = [fixedvals(7)];\n    end\n\n    numCombs = length(fs)*length(dpars)*length(fisos)*length(disos)*length(kappas);\n    grid = zeros(7, numCombs);\n    ind = 1;\n    for i=1:length(fs)\n        for j=1:length(dpars)\n            for k=1:length(fisos)\n                for l=1:length(disos)\n                    for m=1:length(kappas)\n                        pars = [fs(i) dpars(j) kappas(m) 0 0 fisos(k) disos(l)];\n                        grid(:,ind) = pars;\n                        ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'ExCrossingCylSingleRadGPD'))\n    R1s = Rs;\n    R2s = Rs;\n    if(fix(4))\n        R1s = [fixedvals(4)];\n    end\n\n    if(fix(5))\n        R2s = [fixedvals(5)];\n    end\n\n    numCombs = length(R1s)*length(R2s)*length(fs)*length(dpars)*length(fic);\n    grid = zeros(6, numCombs);\n    ind = 1;\n    for i=1:length(R1s)\n        for j=1:length(R2s)\n            for k=1:length(fs)\n                for l=1:length(dpars)\n                    for m=1:length(fic)\n                        % Set dperp using the standard tortuosity model for\n                        % randomly placed cylinders unless fixed.\n                        dperp = dpars(l)*(1-fs(k));\n                        if(fix(3))\n                            dperp = fixedvals(3);\n                        end                        \n                        pars = [fs(k) dpars(l) dperp R1s(i) R2s(j) fic(m)];\n                        grid(:,ind) = pars;\n                        ind = ind + 1;\n                    end\n                end\n            end\n        end\n    end\nelseif(strcmp(model, 'ExCrossingCylSingleRadIsoDotTortIsoV_GPD_B0'))\n    R1s = Rs;\n    R2s = Rs;\n    if(fix(3))\n        R1s = [fixedvals(3)];\n    end\n\n    if(fix(4))\n        R2s = [fixedvals(4)];\n    end\n    \n    if(fix(6))\n        irfracs = [fixedvals(6)];\n    end\n    \n    if(fix(7))\n        fisos = [fixedvals(7)];\n    end\n    \n    if(fix(8))\n        disos = [fixedvals(8)]; \n    end\n    \n    numCombs = length(R1s)*length(R2s)*length(fs)*length(dpars)*length(fic)*length(irfracs)*length(fisos)*length(disos);\n    grid = zeros(8, numCombs);\n    ind = 1;\n    for i=1:length(R1s)\n        for j=1:length(R2s)\n            for k=1:length(fs)\n                for l=1:length(dpars)\n                    for m=1:length(fic)\n\t\t\t\t\t\t\t\t for n=1:length(irfracs)\n\t\t\t\t\t\t\t\t\t\tfor p=1:length(fisos)\n\t\t\t\t\t\t\t\t\t\t\t for q=1:length(disos)\n\t\t\t\t\t\t  \t\t\t\t  \t\t  pars = [fs(k) dpars(l) R1s(i) R2s(j) fic(m) irfracs(n) fisos(p) disos(q)];\n\t\t\t\t\t\t  \t\t\t\t  \t\t  grid(:,ind) = pars;\n\t\t\t\t\t\t  \t\t\t\t  \t\t  ind = ind + 1;\n\t\t\t\t\t\t\t\t\t \t\t end\n\t\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t end\n                    end\n                end\n            end\n        end\n    end\nelse\n    error(['Starting combinations not implemented for model: ', model]);\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/fitting/GetSearchGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2315175899515296}}
{"text": "% A revised implementation of \n% \"Diving Into Haze-Lines: Color restoration of Underwater Images\",\n% Dana Berman, Tali Treibitz, Shai Avidan, BMVC 2017.\n%\n% Author: Dana Berman, 2017. \n%\n% This code is provided under the attached LICENSE.md.\n\n%% Set paths, clear variables\nclear variables; dbstop if error;\n\n% External libraries used: the toolbox by Piotr Dollar and the Structures Edge \n% Detector \n% https://github.com/pdollar/toolbox\ntoolbox_path = fullfile('utils', 'toolbox');\n% https://github.com/pdollar/edges\nedges_path = fullfile('utils', 'edges');\n\naddpath('utils')\naddpath(edges_path)\naddpath(genpath(toolbox_path))\n\n% Suppress Warning regarding image size\nwarning('off', 'Images:initSize:adjustingMag');\nfeature('DefaultCharacterSet', 'UTF8');\n\n%% Folders etc.\n% A few example input images are saves in this sub-directory. \n% The code can run on either sRGB or raw images\nimages_dir = 'images';\nlisting = cat(1, dir(fullfile(images_dir, '*_input.jpg')), ...\n    dir(fullfile(images_dir, '*.CR2')));\n\n% The final output will be saved in this directory:\nresult_dir = fullfile(images_dir, 'results');\n\n% Preparations for saving results.\nif ~exist(result_dir, 'dir'), mkdir(result_dir); end\njetmap = jet(256);  % Colormap for transmission.\nverbose = false;    % Whether to print and save verbose details.\nmax_width = 2010;   % Maximum image width - larger images will be resized.\n\n%% Actual running\nfor i_img = 1:length(listing)\n    [img_out, trans_out, A, estimated_water_type] = uw_restoration(...\n        listing(i_img).name, listing(i_img).folder, edges_path, max_width, ...\n        result_dir, verbose);\n\n    [~, img_name, ~] = fileparts(listing(i_img).name);\n    % Some images have '_input' suffix, which is confusing in output\n    % filename, and therefore removed.\n    img_name = strrep(img_name, '_input', '');\n    % Save the enhanced image and the transmission map.\n    imwrite(im2uint8(img_out), fullfile(result_dir, [img_name, '_output_img.jpg']));\n    imwrite(im2uint8(trans_out), jetmap, fullfile(result_dir, [img_name, '_output_trans.jpg']));\nend  % loop on different images\n", "meta": {"author": "danaberman", "repo": "underwater-hl", "sha": "c9c8c69287ce1e7dd1434a01f078809849a23ce2", "save_path": "github-repos/MATLAB/danaberman-underwater-hl", "path": "github-repos/MATLAB/danaberman-underwater-hl/underwater-hl-c9c8c69287ce1e7dd1434a01f078809849a23ce2/main_underwater_restoration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23151758995152957}}
{"text": "clear\naddpath('../PDM_helpers/');\naddpath(genpath('../fitting/'));\naddpath('../models/');\naddpath(genpath('../face_detection'));\naddpath('../CCNF/');\n\n%% loading the patch experts\n   \n[clmParams, pdm] = Load_CLM_params_66();\n\n% A CLM-Z model trained on Multi-PIE and BU-4DFE\n[patches] = Load_Patch_Experts( '../models/clmz/', 'svr_patches_multi_pie_*.mat', '../models/clmz/', 'svr_depth_patches_*.mat', clmParams);\n\nclmParams.multi_modal_types  = patches(1).multi_modal_types;\n\n%%\n\nimages = {'sample_depth_imgs/1.jpg', 'sample_depth_imgs/2.jpg', 'sample_depth_imgs/3.jpg', 'sample_depth_imgs/4.jpg', 'sample_depth_imgs/5.jpg'};\nimages_depth = {'sample_depth_imgs/1d.png', 'sample_depth_imgs/2d.png', 'sample_depth_imgs/3d.png', 'sample_depth_imgs/4d.png', 'sample_depth_imgs/5d.png'};\nverbose = true;\n\nfor img=1:numel(images)\n\n    image_orig = imread(images{img});           \n    \n    image_depth = imread(images_depth{img});\n            \n    % Need to convert from the disparity to depth values, and threshold\n    image_depth = 10000./(image_depth);\n    image_depth(image_depth > 300) = 0;\n\n    % First attempt to use the Matlab one (fastest but not as accurate, if not present use yu et al.)\n    [bboxs] = detect_faces(image_orig, {'cascade', 'zhu'});\n\n    if(size(image_orig,3) == 3)\n        image = rgb2gray(image_orig);\n    end              \n\n    %%\n\n    if(verbose)\n        f = figure;    \n        if(max(image(:)) > 1)\n            imshow(double(image_orig)/255, 'Border', 'tight');\n        else\n            imshow(double(image_orig), 'Border', 'tight');\n        end\n        axis equal;\n        hold on;\n    end\n\n    for i=1:size(bboxs,2)\n\n        % Convert from the initial detected shape to CLM model parameters\n        bbox = bboxs(:,i);\n\n        % Use the initial global and local params for clm fitting in the image\n        [shape,~,~,lhood,lmark_lhood,view_used] = Fitting_from_bb(image, image_depth, bbox, pdm, patches, clmParams);\n\n        % shape correction for matlab format\n        shape = shape + 1;\n\n        if(verbose)\n\n            % valid points to draw (not to draw self-occluded ones)\n            v_points = logical(patches(1).visibilities(view_used,:));\n\n            try\n                plot(shape(v_points,1), shape(v_points',2),'.r','MarkerSize',20);\n                plot(shape(v_points,1), shape(v_points',2),'.b','MarkerSize',10);\n            catch warn\n\n            end\n        end\n\n    end\n    hold off;\n    \nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/demo/face_image_depth_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.23151758406849463}}
{"text": "function keypointsAll= inf2keypointsImgBP(expidx,parts,annolist_gt)\n\nfprintf('inf2keypointsImgBP()\\n');\n\np = rcnn_exp_params(expidx);\nconf = rcnn_config('sub_dir', '/cachedir/test', 'exp_dir', [p.expDir '/' p.shortName]);\nif (isfield(p,'infDir'))\n    infDir = p.infDir;\nelse\n    infDir = [conf.cache_dir '/inference'];    \nend\n\nkeypointsAll = repmat(struct('imgname','','det',nan(16,3)), length(annolist_gt), 1);\n\nfor imgidx = 1:length(annolist_gt)\n    \n    fprintf('.');\n    \n    fnameInf = [infDir '/imgidx_' padZeros(num2str(imgidx-1),5) '.mat'];\n%     if (~exist(fnameInf,'file'))\n%         continue;\n%     end\n    load(fnameInf,'predAll');\n    \n    keypointsAll(imgidx).imgname = annolist_gt(imgidx).image.name;\n    assert(length(p.pidxs) == length(predAll));\n    \n    for i = 1:length(p.pidxs)\n        pidx = p.pidxs(i);\n        % part is a joint\n        assert(parts(pidx+1).pos(1) == parts(pidx+1).pos(2));\n        jidx = parts(pidx+1).pos(1);\n        \n        det = predAll{i};\n%         [val,id] = max(det(:,4)); % for not swapped minus factor graph (expidx 326)\n        [val,id] = max(det(:,5));\n        \n        x = det(id,1);\n        y = det(id,2);\n        keypointsAll(imgidx).det(jidx+1,:) = [[x y] val];\n    end\n    if (~mod(imgidx, 100))\n        fprintf(' %d/%d\\n',imgidx,length(keypointsAll));\n    end\nend\nfprintf(' done\\n');\n\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/eval/inf2keypointsImgBP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2314620930124601}}
{"text": "function stamps(start_step,end_step,patches_flag,est_gamma_parm,patch_list_file,stamps_PART_limitation)\n%STAMPS Stanford Method for Persistent Scatterers\n%   STAMPS(START_STEP,END_STEP,PATCHES_FLAG,EST_GAMMA_FLAG) Default is to run all steps.\n%   A subset of steps may be selected with START_STEP and/or END_STEP\n%   STEP 1 = Initial load of data\n%   STEP 2 = Estimate gamma \n%   STEP 3 = Select PS pixels\n%   STEP 4 = Weed out adjacent pixels\n%   STEP 5 = Correct wrapped phase for spatially-uncorrelated look angle error and merge patches\n%   STEP 6 = Unwrap phase\n%   STEP 7 = Calculate spatially correlated look angle (DEM) error \n%   STEP 8 = Filter spatially correlated noise \n%   STEP 0 = Continue from the last known stage till the end-stage selected\n%   \n%   PATCHES_FLAG Default 'y'. Set to 'n' to process all data as one patch\n%\n%   EST_GAMMA_PARM is an optional parameter passed to PS_EST_GAMMA_QUICK\n%\n%   PATCH_LIST_FILE is an optional argument specifying the file list of\n%   patches to be processed. Note that from step 5 and above one should use\n%   all patches to merge results.\n%\n%   If current directory is a single patch, stamps only operates in the\n%   current directory, but if current directory contains many patches,\n%   stamps operates on them all.\n%\n%   Andy Hooper, June 2006\n\n%   =================================================================\n%   07/2006 AH: END_STEP added\n%   09/2006 AH: ps_load removed (obsolete)\n%   09/2006 AH: small baselines added \n%   11/2006 AH: patches added\n%   01/2007 AH: calculate spatially correlated look angle error added\n%   03/2009 AH: simultaneously estimate velocity when SCLA estimated\n%   03/2009 AH: smooth SCLA for unwrapping iteration\n%   03/2010 AH: move ps_cal_ifg_std to after merge step\n%   12/2012 AH: add gamma option\n%   12/2012 DB: add patch_list_file argument as option\n%   09/2013 DB: update the stamps version number \n%   09/2015 DB: Check if patches do have PS before proceeding with\n%               processing.\n%   09/2015 DB: Fix when running stamps in a patch folder mode when no PS are left\n%   09/2015 AH: allow for non-differentiation of caps by dir\n%   01/2016 DB: include stamps_save in step 1-4.\n%   08/2016 AH: Fix bug of scn_kriging_flag not being set\n%   06/2017 DB: Catching when no PS are left from step 1, allow for re-run\n%               when parameters have changed.\n%   06/2017 DB: Option to continue from last know processing step\n%   08/2107 AH: Removed catch as proceeds also when error in Step 1\n%   =================================================================\n\nnfill=40;\nfillstr=[repmat('#',1,nfill),'\\n'];\nskipstr='\\n';\nmsgstr=fillstr;\n\nfprintf(skipstr);\nlogit(fillstr);\nmsgstr(round(nfill)/2-12:round(nfill/2)+13)=' StaMPS/MTI Version 4.0b6 ';\nlogit(msgstr);\nmsgstr(round(nfill)/2-12:round(nfill/2)+13)='  Beta version, Jun 2018  ';\nlogit(msgstr);\nlogit(fillstr);\nfprintf(skipstr);\n\n\n\nquick_est_gamma_flag=getparm('quick_est_gamma_flag');\nreest_gamma_flag=getparm('select_reest_gamma_flag');\nunwrap_method=getparm('unwrap_method');\nunwrap_prefilter_flag=getparm('unwrap_prefilter_flag');\nsmall_baseline_flag=getparm('small_baseline_flag');\ninsar_processor=getparm('insar_processor');\nscn_kriging_flag=getparm('scn_kriging_flag');\n\nif nargin<1 || isempty(start_step)==1\n    start_step=1;\nend\n\nif nargin<2 || isempty(end_step)==1\n    end_step=8;\nend\n\nif nargin<3 || isempty(patches_flag)==1\n    if start_step<6\n        patches_flag='y';\n    else\n        patches_flag='n';\n    end\nend\n\nif nargin<4 || isempty(est_gamma_parm)==1\n    est_gamma_parm=0;\nend\n\nif nargin<5 || isempty(patch_list_file)     % [DB] allow for own specified patch list file\n    patch_list_file = 'patch.list';\n    new_patch_file = 0;\nelse\n    % use own file\n    new_patch_file = 1;\nend\n\n% In support of the multi-core option limit processing to steps 1-5a,\n% 5b-upwards, or the old method where all is processed together.\nif nargin<6 || isempty(stamps_PART_limitation)\n    stamps_PART_limitation=0;\nend\nstamps_PART1_flag='y';\nstamps_PART2_flag='y';\nif stamps_PART_limitation==1\n    stamps_PART2_flag='n';\nend\nif stamps_PART_limitation==2\n    stamps_PART1_flag='n';\nend\n\nif strcmpi(patches_flag,'y')\n    if exist(patch_list_file,'file')\n        fid=fopen(patch_list_file);\n        i=0;\n        while 1\n            nextline=fgetl(fid);\n            if ischar(nextline)\n                i=i+1;\n                patchdir(i).name=nextline;\n            else\n                break\n            end\n        end\n\tfclose(fid)\n    else\n        patchdir=dir('PATCH_*');\n        patchdir = patchdir(find(~cellfun(@(x) strcmpi(x,'patch_noover.in'),{patchdir(:).name})));\n    end\n    if isempty(patchdir)\n        patches_flag='n';\n    else\n        ps_parms_default\n        patches_flag='y';\n    end\nend\n\nif ~strcmpi(patches_flag,'y')\n    patchdir(1).name='.';\n    logit('Will process current directory only')\nelse\n    logit('Will process patch subdirectories')\nend\n\ncurrdir=pwd;\n\nnfill=40;\nfillstr=[repmat('#',1,nfill),'\\n'];\nmsgstr=fillstr;\n\n\n\n\n\n% limit the processing to step 1-5a\nstart_step_or = start_step;\nif strcmpi(stamps_PART1_flag,'y')\n  for i=1:length(patchdir)\n    if ~isempty(patchdir(i).name)\n      cd(patchdir(i).name)\n      patchsplit=strsplit(pwd,'/');\n      %fprintf(skipstr);\n      %logit(sprintf('Processing %s',patchsplit{end}))\n    \n      % store if patch dir is empty\n      if exist('no_ps_info.mat','file')~=2\n         stamps_step_no_ps = zeros([5 1 ]);       % keep for the first 5 steps only\n         save('no_ps_info.mat','stamps_step_no_ps')\n      end\n      \n\n        % if start_step is 0, then start from the latest stage it was\n        if start_step_or==0\n            % check the processing stage of stamps for all the patches\n            % step 4 find a ps_weed file\n            % step 3 find a ps_select file\n            % step 2 find a pm file\n            % step 1 find a ps file\n            % or no PS in case stamps_step_no_ps is found with a 1 in there \n\n            if exist('weed1.mat','file')==2\n                   start_step=5;\n                   setpsver(2);\n            elseif exist('select1.mat','file')==2\n                   start_step=4;\n            elseif exist('pm1.mat','file')==2\n                   start_step=3;\n            elseif exist('ps1.mat','file')==2\n                   start_step=2;\n            else\n                start_step=1;\n            end\n\n            if start_step>end_step\n                fprintf(['\\n' patchsplit{end} ': already up to end stage ' num2str(end_step) ' \\n'])\n            else\n                fprintf(['\\n' patchsplit{end} ': complete up to stage ' num2str(start_step-1) ' \\n'])\n            end\n        end\n\n\n\n      \n      if start_step==1\n        msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 1 ';\n        fprintf(skipstr);\n        logit(fillstr);\n        logit(msgstr);\n        logit(fillstr)\n        logit(['Directory is ',patchsplit{end}])\n        fprintf(skipstr);\n        if strcmpi(small_baseline_flag,'y')\n%             try \n                if strcmpi(insar_processor,'gamma') | strcmpi(insar_processor,'snap')\n                    sb_load_initial_gamma;\n                elseif strcmpi(insar_processor,'gsar')\n                    sb_load_initial_gsar;\n                elseif  strcmpi(insar_processor,'isce')\n                    if exist('data_inc','var')==0\n                        % already in patch dir, file contained in the InSAR dir\n                        inc_angle = ['..' filesep 'inc_angle.raw'];\n                        if exist(inc_angle,'file')~=2\n                             inc_angle = ['..' filesep inc_angle];\n                        end\n                        if exist(inc_angle,'file')==2\n                            fprintf('Found inc angle file, will load the data \\n')\n                            data_inc = (load_isce(inc_angle));\n                        else\n                            data_inc=[];\n                        end\n                    end\n                    sb_load_initial_isce(data_inc)\n                else\n                    sb_load_initial;\n                end\n                load('no_ps_info.mat');\n                % reset as we are currently re-processing\n                stamps_step_no_ps(1:end)=0;\n                \n%             catch\n% \n%                load('no_ps_info.mat');\n%                % reset as we are currently re-processing\n%                stamps_step_no_ps(1:end)=0;\n%                fprintf('***No PS points left. Updating the stamps log for this****\\n')\n%                % update the flag indicating no PS left in step 1\n%                stamps_step_no_ps(1)=1;\n%                psver =1;\n%                save('psver.mat','psver')\n%                 \n%             end\n            save('no_ps_info.mat','stamps_step_no_ps')\n\n        else\n%             try \n                if strcmpi(insar_processor,'gamma') | strcmpi(insar_processor,'snap')\n                    ps_load_initial_gamma;\n                elseif strcmpi(insar_processor,'gsar')\n                    ps_load_initial_gsar;\n                elseif  strcmpi(insar_processor,'isce')\n                     if exist('data_inc','var')==0\n                        % already in patch dir, file contained in the InSAR dir\n                        inc_angle = ['..' filesep 'inc_angle.raw'];\n                        if exist(inc_angle,'file')~=2\n                             inc_angle = ['..' filesep inc_angle];\n                        end\n                        if exist(inc_angle,'file')==2\n                            fprintf('Found inc angle file, will load the data \\n')\n                            data_inc = (load_isce(inc_angle));\n                        else\n                            data_inc=[];\n                        end\n                    end\n                    ps_load_initial_isce(data_inc)  \n         \n                else\n                    ps_load_initial;\n                end\n                load('no_ps_info.mat');\n                % reset as we are currently re-processing\n                stamps_step_no_ps(1:end)=0;\n%             catch\n%                 load('no_ps_info.mat');\n%                 % reset as we are currently re-processing\n%                 stamps_step_no_ps(1:end)=0;\n%                 fprintf('***No PS points left. Updating the stamps log for this****\\n')\n%                 % update the flag indicating no PS left in step 1\n%                 stamps_step_no_ps(1)=1;\n%                 save('no_ps_info.mat','stamps_step_no_ps')\n%                 psver =1;\n%                 save('psver.mat','psver')\n% \n%             end\n            save('no_ps_info.mat','stamps_step_no_ps')\n        end\n        elseif start_step <=4\n            setpsver(1)\n      end\n\n        \n      \n      \n        if start_step<=2 & end_step >=2 \n            msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 2 ';\n            fprintf(skipstr);\n            logit(fillstr);\n            logit(msgstr);\n            logit(fillstr)\n            logit(['Directory is ',patchsplit{end}])\n            fprintf(skipstr);\n\n            % check if step 1 had more than 0 PS points\n            load('no_ps_info.mat');\n            % reset as we are currently re-processing\n            stamps_step_no_ps(2:end)=0;\n            \n            % run step 2 when there are PS left in step 1\n            if stamps_step_no_ps(1)==0\n                if strcmpi(quick_est_gamma_flag,'y')\n                    ps_est_gamma_quick(est_gamma_parm);\n                else\n                    ps_est_gamma(est_gamma_parm);\n                end\n            else\n                stamps_step_no_ps(2)=1;\n                fprintf('No PS left in step 1, so will skip step 2 \\n')\n            end  \n            save('no_ps_info.mat','stamps_step_no_ps')\n        end\n\n        if start_step<=3 & end_step >=3 \n            msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 3 ';\n            fprintf(skipstr);\n            logit(fillstr);\n            logit(msgstr);\n            logit(fillstr)\n            logit(['Directory is ',patchsplit{end}])\n            fprintf(skipstr);\n\n            \n            \n            % check if step 2 had more than 0 PS points\n            load('no_ps_info.mat');\n            % reset as we are currently re-processing\n            stamps_step_no_ps(3:end)=0;\n            \n            % run step 3 when there are PS left in step 2\n            if stamps_step_no_ps(2)==0\n                if strcmpi(quick_est_gamma_flag,'y') & strcmpi(reest_gamma_flag,'y')\n                    ps_select;\n                else\n                    ps_select(1);\n                end\n            else\n                fprintf('No PS left in step 2, so will skip step 3 \\n')\n                stamps_step_no_ps(3)=1;\n            end              \n            save('no_ps_info.mat','stamps_step_no_ps')\n        end\n\n        if start_step<=4 & end_step >=4 \n            msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 4 ';\n            fprintf(skipstr);\n            logit(fillstr);\n            logit(msgstr);\n            logit(fillstr)\n            logit(['Directory is ',patchsplit{end}])\n            fprintf(skipstr);\n\n            % check if step 3 had more than 0 PS points\n            load('no_ps_info.mat');\n            % reset as we are currently re-processing\n            stamps_step_no_ps(4:end) =0;       % keep for the first 5 steps only\n            \n\n            % run step 4 when there are PS left in step 3\n            if stamps_step_no_ps(3)==0\n                if strcmpi(small_baseline_flag,'y')\n                    ps_weed(0,1);\n                else\n                    ps_weed;\n                end\n            else\n                fprintf('No PS left in step 3, so will skip step 4 \\n')\n                stamps_step_no_ps(4)=1;\n\n            end\n            save('no_ps_info.mat','stamps_step_no_ps')\n        end\n\n        if start_step<=5 & end_step >=5 \n            msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 5 ';\n            fprintf(skipstr);\n            logit(fillstr);\n            logit(msgstr);\n            logit(fillstr)\n            logit(['Directory is ',patchsplit{end}])\n            fprintf(skipstr);\n\n\n            % check if step 4 had more than 0 PS points\n            load('no_ps_info.mat');\n            % reset as we are currently re-processing\n            stamps_step_no_ps(5:end) = 0;       % keep for the first 5 steps only\n            \n            % run step 5 when there are PS left in step 3\n            if stamps_step_no_ps(4)==0\n                ps_correct_phase;\n            else\n                fprintf('No PS left in step 4, so will skip step 5 \\n')\n                stamps_step_no_ps(5)=1;\n            end\n            save('no_ps_info.mat','stamps_step_no_ps')\n        end\n\n\n        cd(currdir)\n      end\n    end\nend\n\npatchsplit=strsplit(pwd,'/');\n\n\n% check if one can process second part of step 5b and above\nif strcmpi(stamps_PART2_flag,'y')\n    %%% Loop throught the patches and update the patch.list and keep only those\n    %%% that have PS left.\n    if patches_flag=='y'\n        % go in reverse order such patches can be dropped when needed\n\n        fid = fopen('patch.list_new','w');\n        for i=1:length(patchdir)\n            % check the file with the PS information\n            filename_PS_check = [patchdir(i).name filesep 'no_ps_info.mat'];\n\n            % assume by default to keep patch for backward compatibility\n            keep_patch = 1;\n            if exist(filename_PS_check,'file')==2\n                load(filename_PS_check)\n                if sum(stamps_step_no_ps)>=1\n                   keep_patch=0; \n                end\n            end\n\n            % update the patch list.\n            if keep_patch==1\n                fprintf(fid,[patchdir(i).name '\\n']);\n            end\n            if i==length(patchdir)\n               fclose(fid) ;\n            end\n        end\n\n        % update the files such in futhre the new patch list will be used.\n        movefile('patch.list','patch.list_old');\n        movefile('patch.list_new','patch.list');\n    end\n\n\n    if start_step<=5 & end_step >=5 \n        abord_flag=0;\n        if patches_flag=='y'\n            fprintf(skipstr);\n            logit(['Directory is ',patchsplit{end}])\n            fprintf(skipstr);\n            ps_merge_patches\n        else\n            % this is processing of an individual patch\n            % see if there are any PS left\n            if exist('no_ps_info.mat','file')==2\n                load('no_ps_info.mat')\n                if sum(stamps_step_no_ps)>=1\n                   abord_flag=1; \n                end\n            end\n        end\n\n        % see if step 5 can be ran\n        if abord_flag==0 \n            ps_calc_ifg_std;\n        else\n            fprintf('No PS left in step 4, so will skip step 5 \\n')\n        end\n    end\n\n\n    if start_step<=6 & end_step >=6 \n        msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 6 ';\n        fprintf(skipstr);\n        logit(fillstr);\n        logit(msgstr);\n        logit(fillstr)\n        logit(['Directory is ',patchsplit{end}])\n        fprintf(skipstr);\n\n        ps_unwrap\n        if strcmpi(small_baseline_flag,'y')\n            sb_invert_uw\n        end\n    end\n\n    if start_step<=7 & end_step >=7 \n        msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 7 ';\n        fprintf(skipstr);\n        logit(fillstr);\n        logit(msgstr);\n        logit(fillstr)\n        logit(['Directory is ',patchsplit{end}])\n        fprintf(skipstr);\n\n        if strcmpi(small_baseline_flag,'y')\n            ps_calc_scla(1,1)   % small baselines\n            ps_smooth_scla(1)\n            ps_calc_scla(0,1) % single master\n        else\n            ps_calc_scla(0,1)\n            ps_smooth_scla\n        end\n    end\n\n    if start_step<=8 & end_step >=8\n        msgstr(round(nfill)/2-3:round(nfill/2)+4)=' Step 8 ';\n        fprintf(skipstr);\n        logit(fillstr);\n        logit(msgstr);\n        logit(fillstr)\n        logit(['Directory is ',patchsplit{end}])\n        fprintf(skipstr);\n\n        if strcmpi(scn_kriging_flag,'y')\n            ps_scn_filt_krig\n        else\n            ps_scn_filt\n        end\n    end\nend\n\nlogit(1);\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/stamps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.23134705241485998}}
{"text": "function clbvalpl(var1)\n    %clbvalpl.m                      A.Allmann\n    %\n    %   Calculates Freq-Mag functions (b-value) for a catalog\n    %   works on cluscat or newclcat\n\n    % Last modification 8/95\n\n    global newclcat cluscat mess bfig backcat\n    global ttcat ttm text3 text4 newcat txt1 txt2 txt3\n\n\n    if var1==1\n        if isempty(ttcat)\n            if ~isempty(newclcat)  &&  ~isempty(backcat)\n                if length(newclcat(:,1))>length(backcat(:,1))\n                    newcat=cluscat;\n                else\n                    newcat=newclcat;\n                end\n            elseif isempty(newclcat)              %set catalog for bvalue-plot\n                newcat=cluscat;\n            else\n                newcat=newclcat;\n            end\n        else\n            newcat=ttcat;\n        end\n\n        [existFlag,figNumber]=figure_exists('b-value curve',1);\n        if existFlag\n            figure_w_normalized_uicontrolunits(bfig);\n            clf reset;\n            set(bfig,'visible','off')\n        else\n            bfig=figure;                     %build figure for plot\n        end\n        set(bfig,'Units','normalized','NumberTitle','off','Name','b-value curve');\n        set(gcf,'pos',[ 0.435  0.8 0.5 0.5])\n        matdraw\n        uicontrol('Style','Pushbutton',...\n            'Callback','myprint',...\n            'Units','normalized',...\n            'String','Print','Position',[0.02 .68 .08 .05]);\n\n        uicontrol('Style','Pushbutton',...\n            'Callback','set(bfig,''visible'',''off'');welcome;done',...\n            'Units','normalized',...\n            'String','Close','Position',[0.02 .88 .08 .05]);\n        uicontrol('Style','Pushbutton',...\n            'Callback','clinfo(8)',...\n            'Units','normalized',...\n            'String','Info','Position',[0.02 .78 .08 .05]);\n\n\n        set(gcf,'visible','on');\n    end\n    maxmag = max(newcat.Magnitude);\n\n    % number of mag units\n    nmagu = (maxmag*10)+1;\n\n    bval = zeros(1,nmagu);\n    % bvalsum = zeros(1,nmagu);\n    bvalsum3 = zeros(1,nmagu);\n\n    [bval,xt2] = hist(newcat.Magnitude,(0:0.1:maxmag));\n    % bvalsum = cumsum(bval);                        % N for M <=\n    bvalsum3 = cumsum(bval(length(bval):-1:1));    % N for M >= (counted backwards)\n    xt3 = (maxmag:-0.1:0);\n\n    % backg_be = log10(bvalsum);\n    backg_ab = log10(bvalsum3);\n    orient tall\n    rect = [0.2,  0.3, 0.70, 0.6];           % plot Freq-Mag curves\n    axes('position',rect);\n    % semilogy(xt2,bvalsum,'om')\n    % hold on\n    % semilogy(xt2,bvalsum,'-.m')\n    semilogy(xt3,bvalsum3,'-.m')\n    hold on\n    semilogy(xt3,bvalsum3,'om')\n    if var1==1\n        xlabel('Magnitude ')\n        ylabel('Cumulative Number')\n    end\n    figure_w_normalized_uicontrolunits(mess);\n    clf;\n    str=['Please select two magnitudes \\newlineto be used in the calculation \\newlineof the straightline fit.\\newlineWait to push Info or Close\\newlineafter the selection'];\n    te = text(0.01,0.9,str) ;\n\n    set(te,'FontSize',14);\n    set(gca,'visible','off');\n\n\n    disp('Please select two magnitudes to be used in the caclulation of the straight   line fit')\n\n    figure_w_normalized_uicontrolunits(bfig)\n    if var1==2\n        delete(ttm);delete(text3);delete(text4);delete(txt1);delete(txt2);delete(txt3);\n    end\n    seti = uicontrol('Units','normal',...\n        'Position',[.4 .01 .2 .05],'String','Select Mag1 ');\n\n    pause(1)\n\n    par2 = 0.1 * max(bvalsum3);\n    par3 = 0.12 * max(bvalsum3);\n    M1b = [];\n    M1b = ginput(1);\n    tt3=num2str(fix(100*M1b(1))/100);\n    text3=text( M1b(1),M1b(2),['|: M1=',tt3] );\n    set(seti,'String','Select Mag2');\n\n    pause(0.1)\n\n    M2b = [];\n    M2b = ginput(1);\n    tt4=num2str(fix(100*M2b(1))/100);\n    text4=text( M2b(1),M2b(2),['|: M2=',tt4] );\n\n    pause(0.1)\n    delete(seti)\n\n    eqnumber=length(find(newcat.Magnitude>M1b(1) & newcat.Magnitude<M2b(1)));\n    tt6=num2str(eqnumber);\n\n    ll = xt3 > M1b(1) & xt3 < M2b(1);\n    x = xt3(ll);\n    y = backg_ab(ll);\n    [p,s] = polyfit(x,y,1);                   % fit a line to background\n    f = polyval(p,x);\n    f = 10.^f;\n    hold on\n    ttm= semilogy(x,f,'b');                         % plot linear fit to backg\n    set(ttm,'LineWidth',2)\n    r = corrcoef(x,y);\n    r = r(1,2);\n    std_backg = std(y - polyval(p,x));      % standard deviation of fit\n\n    p=-p(1,1);\n    p=fix(100*p)/100;\n    std_backg=fix(100*std_backg)/100;\n    tt2=num2str(std_backg);\n    tt1=num2str(p);\n\n    rect=[0 0 1 1];\n    h2=axes('position',rect);\n    set(h2,'visible','off');\n    txt1=text(.16, .18,['B-Value: ',tt1]);\n    txt2=text(.16, .12,['Standard Deviation: ',tt2]);\n    txt3=text(.16, .06,['Eqs in limits: ',tt6]);\n    uicontrol('Style','Pushbutton',...\n        'Callback','clbvalpl(2)',...\n        'Units','normalized',...\n        'String','Repeat','Position',[0.7 .1 .12 .08]);\n    welcome;\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/declus/clbvalpl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.2312225701435944}}
{"text": "% Visualize all the inception_4c filters in bvlc_googlenet. \n% Because of the size, I splitted the visualization map into 32*16 grids,\n% with each grid contains visualization of 4 filters.\n% This code is messay, I will refactor it in the future.\n% Based on paper:\n% Feng Wang, Haijun Liu, Jian Cheng, \n% Visualizing Deep Neural Network by Alternately Image Blurring and Deblurring\ncaffe.reset_all();\ncaffe.set_mode_gpu();\ngpu_id = 0;  % we will use the first gpu in this demo\ncaffe.set_device(gpu_id);\noriginal_prototxt = 'D:\\deepLearning\\caffe-windows\\models\\bvlc_googlenet\\googlenet.prototxt';\nnet_weights = 'D:\\deepLearning\\caffe-windows\\models\\bvlc_googlenet\\thinned.caffemodel';\nlayer_name = 'inception_4c/output';\npattern_index=400;\nchannels = 512;\ninitial_size = [400 400];\n[field_size, field_stride] = getReceptiveField(original_prototxt, net_weights, layer_name, pattern_index, initial_size);\nfield_size = ceil(field_size ./ field_stride) .* field_stride;\nborder = field_stride(1);\nmap_border = border ./ field_stride;\nif max(field_size) > 224\n%     error('field_size:(%d,%d),field_stride:(%d,%d), please increase the initial size.',field_size(1),field_size(2),field_stride(1),field_stride(2));\n    field_size = [224 224];\n    field_size = ceil(field_size ./ field_stride) .* field_stride;\n    map_stride = ceil((field_size + border) ./ field_stride);\nelse\n    map_stride = ceil((field_size + border) ./ field_stride);\nend;\n\nvert_num = 32;\nhori_num = 16;\ntotal_map = reshape(1:vert_num*hori_num,hori_num,vert_num)';\nvert_split = vert_num/16;\nhori_split = hori_num/8;\nfor vert_ind = 1:16\nfor hori_ind = 1:8\n%     disp([layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png']);\n%     if exist([layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png'],'file')\n%         continue;\n%     end;\n% vert_ind = 2;\n% hori_ind = 2;\ncaffe.reset_all();\ncurrent_map = total_map((vert_ind-1)*vert_split+1:vert_ind*vert_split,(hori_ind-1)*hori_split+1:hori_ind*hori_split)';\n\nheight = vert_split * (field_size(1)+border(1)) + border(1);\nwidth = hori_split * (field_size(2)+border(1)) + border(1);\n\nvgg_mean =  [103.939, 116.779, 123.68];\nmean_image = permute(repmat(vgg_mean',[1,width,height]),[2,3,1]);\ninput_data = randn(width, height, 3, 1, 'single')*50;\n\nfor need_negative=1:1\noriginal_net_model = fileread(original_prototxt);\noriginal_net_model = strrep(original_net_model,'negative_slope:0#4c','negative_slope:1#4c');\n\nvisualize_prototxt = strrep(original_prototxt,'.prototxt','_visualize.prototxt');\n\nfid = fopen(visualize_prototxt,'w');\nproto_txt{1} = 'name: \"Visualize\"';\nproto_txt{2} = 'input: \"data\"';\nproto_txt{3} = 'input_dim: 1';\nproto_txt{4} = 'input_dim: 3';\nproto_txt{5} = ['input_dim: ' num2str(height)];\nproto_txt{6} = ['input_dim: ' num2str(width)];\nfor i=1:6\n    fprintf(fid,'%s\\r\\n',proto_txt{i});\nend;\n\nfprintf(fid,'%s\\r\\n',original_net_model);\nfclose(fid);\n\nif need_negative == 0\n    input_data = randn(width, height, 3, 1, 'single')*50;\nend;\nall_grad = zeros(width, height, 3, 1, 'single');\n\nvisualize_net = caffe.Net(visualize_prototxt,net_weights,'test');\nvisualize_net.blobs(visualize_net.inputs{1}).set_data(input_data);\nvisualize_net.forward_to(layer_name);\ntarget_blob = visualize_net.blob_vec(visualize_net.name2blob_index(layer_name));\noutput_data = target_blob.get_data();\nbackward_mask = zeros(size(output_data,1), size(output_data,2),'uint16');\nbackward_label = zeros(size(output_data,1), size(output_data,2),'uint16');\nbackward_data = zeros(size(output_data,1), size(output_data,2),channels, 'uint16');\nlabel_mat = repmat(1:channels,size(output_data,1) * size(output_data,2),1)';\nif map_stride(1) > 0\n    backward_mask(ceil(map_stride(1)/2+map_border(1)):map_stride(1):end, ceil(map_stride(2)/2+map_border(2)):map_stride(2):end) = 1;\n    backward_label(backward_mask==1) = current_map(:);\n    for i=1:channels\n        backward_data(:,:,i) = (backward_label == i);\n    end;\nelse\n    backward_mask(floor(size(backward_mask,1)/2),floor(size(backward_mask,2)/2)) = 1;\nend;\nitem_num = sum(backward_mask(:));\ntarget_blob = visualize_net.blob_vec(visualize_net.name2blob_index(layer_name));\ndata_blob = visualize_net.blob_vec(visualize_net.name2blob_index('data'));\nfor i=1:channels\n    if i>384 && i<=448\n    backward_data(:,:,i) =  backward_data(:,:,i) * 2;\n    end;\nend;\n\nweight_decay = 0;\nuse_color_prior = false;\nnum_cluster=6;\ncolor_prior = 0.5;\nlong_size = 512;\nif need_negative==0\n    tv_norm = 0;\n    use_image_blur = false;\n    use_image_deblur = false;\nelse\n    tv_norm = 0;\n    use_image_blur = true;\n    use_image_deblur = true;\nend;\n\nif need_negative==0\n    lr = 10;\nelse\n    lr=200;\nend;\nmax_lr = 50;\nmomentum = 0.8;\nmomentum2 = 0.99;\nlastgrad = zeros(size(mean_image));\nlastgrad2 = zeros(size(mean_image));\nlast_cost = -9999999999999;\nblurred = false;\nnumLast = 0;\n\nfor iter = 1:1000\n    bak_data = input_data;\n    bak_grad = lastgrad;\n    visualize_net.blobs(visualize_net.inputs{1}).set_data(input_data);\n    visualize_net.forward_to(layer_name);\n    output_data = target_blob.get_data();\n    output_data(backward_data==0) = -999;\n    output_map = max(output_data,[],3);\n    min_cost = min(output_map(backward_mask==1));\n    if min_cost>300 && need_negative==0\n        disp(min_cost);\n        break;\n    end;\n    cost = sum(output_map(backward_mask==1)) / item_num;\n    if need_negative == 0\n        for i=1:channels\n            if output_map(backward_label == i) > 300\n                backward_data(:,:,i) = 0;\n                backward_mask(backward_label == i) = 0;\n            end;\n        end;\n        fprintf('iter=%d,lr=%f,this_cost=%f,last_cost=%f,min_cost=%f,min_num=%d\\n',iter,lr,cost, last_cost,min_cost,sum(sum(backward_mask==1)));\n    else\n        fprintf('iter=%d,lr=%f,this_cost=%f,last_cost=%f,image_norm=%f,min_cost=%f\\n',iter,lr,cost, last_cost,norm(input_data(:)),min_cost);\n    end;\n%     output_data(:) = 0;\n%     output_data(:,:,pattern_index) = backward_mask;\n    target_blob.set_diff(backward_data);\n    visualize_net.backward_from(layer_name);\n    grad = data_blob.get_diff();\n    all_grad = all_grad + grad;\n    if iter==20\n        input_data(all_grad==0) = 0;\n    end;\n    \n    if tv_norm > 0\n        I = input_data(:,:,:,1);\n        Gx = (I(2:end-1,:,:) - I(1:end-2,:,:)) - (I(3:end,:,:) - I(2:end-1,:,:));\n        Gx = [(I(1,:,:) - I(2,:,:)); Gx; (I(end,:,:) - I(end-1,:,:))];\n        Gy = (I(:,2:end-1,:) - I(:,1:end-2,:)) - (I(:,3:end,:) - I(:,2:end-1,:));\n        Gy = [(I(:,1,:) - I(:,2,:)) Gy (I(:,end,:) - I(:,end-1,:))];\n        grad = grad - tv_norm * (Gx+Gy);\n    end;\n    \n    if weight_decay > 0\n        grad = grad - weight_decay * I;\n    end;\n    \n    if use_color_prior\n        gmm_prior = gaussian_net.forward({input_data});\n        sum_gp = zeros(size(mean_image,1),size(mean_image,2));\n        sum_prob_gradient = zeros(size(mean_image));\n        for i=1:num_cluster\n            gp = bsxfun(@minus,input_data(:,:,:,1),reshape(colorObj.mu(i,:),[1 1 3])) .* gmm_prior{1}(:,:,(i-1)*3+1:i*3);\n            gp = sum(gp,3);\n            gp = colorObj.PComponents(i) * exp(-gp);\n            sum_prob_gradient = sum_prob_gradient + bsxfun(@times,gp,gmm_prior{1}(:,:,(i-1)*3+1:i*3));\n            sum_gp = sum_gp + gp;\n        end;\n        sum_prob_gradient = bsxfun(@rdivide,sum_prob_gradient,sum_gp);\n        sum_prob_gradient(isnan(sum_prob_gradient)) = 0;\n        input_data(:,:,:,1) = input_data(:,:,:,1) - lr * color_prior * sum_prob_gradient;\n    end;\n    if need_negative==1\n        %%%%%%%%%%%%%%%%%%%%%%%%gd linear search\n        lastgrad = (1 - momentum) * lr * grad   + momentum * lastgrad;%/ norm(res(:))\n        input_data(:,:,:,1) = input_data(:,:,:,1) + lastgrad;\n    else\n        %%%%%%%%%%%%%%%%%%%%%%%%adam\n        lastgrad = (1 - momentum) * grad   + momentum * lastgrad;%/ norm(res(:))\n        lastgrad2 = (1 - momentum2) * grad.^2 + momentum2 * lastgrad2;%/ norm(res(:))\n        lg_correct = lastgrad ./ (1 - momentum^iter);\n        lg2_correct = lastgrad2 ./ (1 - momentum2^iter);\n        input_data(:,:,:,1) = input_data(:,:,:,1) + lr * lg_correct ./ (sqrt(lg2_correct) + 1e-8);\n    end;\n%     input_data(:,:,:,1) = input_data(:,:,:,1) / norm(input_data(:));\n    \n    k = mod(iter,10);\n    if k==1\n        H = fspecial('gaussian',[7 7],1.2);\n        if use_image_blur\n            input_data(:,:,:,1) = imfilter(input_data(:,:,:,1),H,'same');\n            blurred = true;\n        end\n    end;\n    if k==6\n        H = fspecial('gaussian',[7 7],1);\n        if use_image_deblur\n            input_data(:,:,:,1) = deconvlucy(input_data(:,:,:,1), H);\n            blurred = false;\n        end;\n    end;\n    \n    if (need_negative==1 && cost>last_cost)\n        last_cost = cost;\n        numLast = 0;\n    else\n        numLast = numLast + 1;\n    end;\n    if (need_negative==0 && min_cost>last_cost)\n        last_cost = min_cost;\n        numLast = 0;\n    else\n        numLast = numLast + 1;\n    end;\n    if numLast>100\n        break;\n    end;\n    if lr<1e-5\n        break;\n    end;\n    \n    %%%%%%%%%%%%%%%%%%%%%%gd\n    \n    if mod(iter,100)==0\n        output = mean_image + input_data(:,:,:,1);\n        output = output(:, :, [3, 2, 1]);\n        output = permute(output, [2 1 3]);\n        figure(3);\n        imshow(uint8(output));\n%         title('generated image');\n        I = output;\n    end;\nend;\nend;\n% imwrite(uint8(output),[layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png']);\nend;\nend;", "meta": {"author": "happynear", "repo": "DeepVisualization", "sha": "6e39593b1b4bd3087e0486da97733c1228ca7420", "save_path": "github-repos/MATLAB/happynear-DeepVisualization", "path": "github-repos/MATLAB/happynear-DeepVisualization/DeepVisualization-6e39593b1b4bd3087e0486da97733c1228ca7420/FilterVis/GoogLeNet_Visualization_4c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.23122256136407496}}
{"text": "function planC = createExpandedStructure2D(structNum, margin, planC)\n% function createExpandedStructure2D(structNum, margin, planC)\n%\n% APA, 09/09/2014\n% AI, 09/19/17 Updated to allow margin<0\n\nif ~exist('planC','var')\n    global planC\nend\n\nglobal stateS\n\nindexS = planC{end};\n\nscanNum = getStructureAssociatedScan(structNum,planC);\n\nnewStructNum = length(planC{indexS.structures}) + 1;\n\n%newStructS = newCERRStructure(scanNum, planC, newStructNum);\n\nrasterSegs = getRasterSegments(structNum, planC);\n\n% Get Rastersegments +/- margin, thus creating an halo\nif margin>0\nhalo = structMargin(rasterSegs, margin, scanNum, planC);\nrasterSegsExpanded = structUnion(halo, rasterSegs, scanNum, planC); % Expand rastersegments by margin\nelse\nhalo = structMargin(rasterSegs, -margin, scanNum, planC);\nrasterSegsExpanded = structDiff(rasterSegs, halo, scanNum, planC); % Shrink rastersegments by margin\nend\n\n% Get Contours from rasterSegs\ncontourS = rasterToPoly(rasterSegsExpanded, scanNum, planC);\n\n% Generate Structure Name\nstrName = planC{indexS.structures}(structNum).structureName;\nstrName = [strName,' + 2D_',num2str(margin)];\n\n% Create New structure\n%Make an empty structure, assign name/contour.\nnewstr = newCERRStructure(scanNum, planC, newStructNum);\nnewstr.contour = contourS;\nnewstr.structureName = strName;\nnewstr.associatedScan = scanNum;\nnewstr.assocScanUID = planC{indexS.scan}(scanNum).scanUID;\nnumStructs = length(planC{indexS.structures});\n\n%Append new structure to planC.\nif ~isempty(planC{indexS.structures})\n    planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newstr, numStructs+1, []);\nelse\n    planC{indexS.structures} = newstr;\nend\n\n%Update uniformized data.\nplanC = updateStructureMatrices(planC, numStructs+1);\n\n% Refresh View\nif ~isempty(stateS) && isfield(stateS,'handle') && isfield(stateS.handle,'CERRSliceViewer') && isnumeric(stateS.handle.CERRSliceViewer)\n    stateS.structsChanged = 1;\n    CERRRefresh\nend\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/createExpandedStructure2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23118063874073336}}
{"text": "function out = convert_caffe2img( out )\n    assert(length(size(out)) <= 4, 'Only support at most 4-D data for convert.');\n    out = single(permute(out(:,:,end:-1:1,:), [2 1 3 4]));\nend\n", "meta": {"author": "liuyuisanai", "repo": "RSA-for-object-detection", "sha": "626ad81172b260ecf8257a80731e5236fe41cb63", "save_path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection", "path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection/RSA-for-object-detection-626ad81172b260ecf8257a80731e5236fe41cb63/predict/utils/convert_caffe2img.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23118063874073333}}
{"text": "function gasConst = getIdealGasConstant()\n    gasConst = 8.31447; %m^3*Pa/(K*mol)\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/aerobrake/getIdealGasConstant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23111686994105915}}
{"text": "function a = eq( x, y )\n\n%Disciplined convex programming information for EQ (==):\n%   Both the left- and right-hand sides of an equality constraint must\n%   be affine (or constant). If either side of the constraint is complex,\n%   then the real and imaginary portions are constrained separately.\n%\n%Disciplined geometric programming information for EQ (>):\n%   Both the left- and right-hand sides of an equality constraint must\n%   be log-affine, which includes positive constants and monomials.\n\nevalin( 'caller', 'cvx_verify' );\nb = cvx_pushcnstr( x, y, '==' );\nif nargout, a = b; end\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/builtins/@cvxcnst/eq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2311168699410591}}
{"text": "function y = choosvd(n, d)\n\nif n <= 100 \n    if d / n <= 0.02\n        y = 1;\n    else\n        y = 0;\n    end\nelseif n <= 200\n    if d / n <= 0.06\n        y = 1;\n    else\n        y = 0;\n    end\nelseif n <= 300\n    if d / n <= 0.26\n        y = 1;\n    else\n        y = 0;\n    end\nelseif n <= 400\n    if d / n <= 0.28\n        y = 1;\n    else\n        y = 0;\n    end\nelseif n <= 500\n    if d / n <= 0.34\n        y = 1;\n    else\n        y = 0;\n    end\nelse\n    if d / n <= 0.38\n        y = 1;\n    else\n        y = 0;\n    end\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/ALM/choosvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.23111686994105907}}
{"text": "function coeffVar = compute_coeff_var(this, varargin)\n% computes standard deviation image (coeff_var) over 4th dimension of MrImage\n% NOTE: short-cut for compute_stat_image('coeff_var')\n%\n%   Y = MrImage()\n%   coeffVar = Y.compute_coeff_var('PropertyName', PropertyValue)\n%\n% This is a method of class MrImage.\n%\n% IN\n%   'PropertyName'\n%               'selectedVolumes'       [1,nVols] vector of selected\n%                                       volumes for statistical calculation\n% OUT\n%   coeffVar         MrImage holding voxel-wise coefficient of variation\n%                     image (coeff_var), i.e. 1./snr \n%                     (with thresholding to avoid Inf-values)\n%\n% EXAMPLE\n%   Y = MrImage()\n%   coeffVar = Y.compute_coeff_var('selectedVolumes', [6:100])\n%\n%   See also MrImage compute_stat_image\n\n% Author:   Saskia Klein & Lars Kasper\n% Created:  2014-07-06\n% Copyright (C) 2014 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\n\ncoeffVar = this.compute_stat_image('coeff_var', varargin{:});\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImage/compute_coeff_var.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2311168639097607}}
{"text": "function [R, t] = read4PCSResults(filename)\n\n M = dlmread(filename);\n R = M(1:3, 1:3);\n t = M(1:3, 4);\n \n\n\n\nend", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/utils/read4PCSResults.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.23111686390976066}}
{"text": "function rtk = detslip_gf_L1L5(rtk,obsr,obsb,nav)\n\nsat=obsr.sat;\n\ng1=gfobs_L1L5(obsr,obsb,nav.lam(sat,:));\nif rtk.opt.nf<=2||g1==0,return;end\n\ng0=rtk.sat(sat).gf2;\nrtk.sat(sat).gf2=g1;\n\nif g0~=0&&abs(g1-g0)>rtk.opt.csthres(1)\n    rtk.sat(sat).slip(1)=bitor(rtk.sat(sat).slip(1),1);\n    rtk.sat(sat).slip(3)=bitor(rtk.sat(sat).slip(3),1);\nend\n    \nreturn", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/relpos/detslip_gf_L1L5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23104289488531496}}
{"text": "% eegplotgold() - display EEG data in a clinical format\n%\n% Usage:\n% >> eegplotgold('dataname', samplerate, 'chanfile', 'title', yscaling, range)\n%\n% Inputs:\n%   'dataname' - quoted name of a desktop global variable (see Ex. below)\n%   samplerate - EEG sampling rate in Hz (0 -> default 256 Hz)\n%   'chanfile' - file of channel info in topoplot() style\n%                                        (0 -> channel numbers)\n%   'title'    - plot title string       (0 -> 'eegplotgold()')\n%   yscaling   - initial y scaling factor (0 - default is 300)\n%   range      - how many seconds to display in window (0 -> 10)\n%\n% Note: this version of eegplotgold() reguires that your data matrix \n%       be defined as a global variable before running this routine. \n%\n% Example:  >> global dataname\n%           >> eegplotgold('dataname')\n%\n% Author: Colin Humphries, CNL, Salk Institute, La Jolla, 3/97\n%\n% See also: eegplot(), eegplotold(), eegplotsold()\n\n% Copyright (C) Colin Humphries, CNL, Salk Institute 3/97 from eegplotold()\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n% 4-4-97 shortened name to eegplotgold() -sm\n% 5-20-97 added read of icadefs.m for MAXEEGPLOTCHANS -sm\n% 8-10-97 Clarified chanfile type -sm\n% 01-25-02 reformated help & license, added links -ad \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction y = eegplotold(dataname, samplerate, channamefile, titleval, yscaling, range)\n\neval (['global ',dataname])\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Define defaults\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% set initial spacing\n\neval(['DEFAULT_SPACING = max(max(',dataname,''')-min(',dataname,'''));'])\n\n%  spacing_var/20 = microvolts/millimeter with 21 channels\n%  for n channels: 21/n * spacing_var/20 = microvolts/mm\n%  for clinical data.\n\nDEFAULT_SAMPLERATE = 256;\t% default rate in Hz.\nDEFAULT_PLOTTIME = 10;\t\t% default 10 second window\nDEFAULT_TITLE = 'eegplotgold()';\nerrorcode=0;\t\t\t    % initialize error indicator\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Allow for different numbers of arguments\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 6\n   PLOT_TIME = DEFAULT_PLOTTIME;\nelse\n   PLOT_TIME = range;\nend\nif nargin < 5\n   spacing_var = DEFAULT_SPACING;\nelse\n   spacing_var = yscaling;\nend\nif spacing_var == 0\n   spacing_var = DEFAULT_SPACING;\nend\n\nif nargin < 4\n   titleval = DEFAULT_TITLE;\nend\nif titleval == 0\n   titleval = DEFAULT_TITLE;\nend\nif nargin < 3 \n\tchannamefile = 0;\nend\nif nargin < 2\n   samplerate = DEFAULT_SAMPLERATE;\nend\nif samplerate == 0,\n\tsamplerate = DEFAULT_SAMPLERATE;\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Define internal variables\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nSAMPLE_RATE = samplerate;\ntime = 0;\neval(['[chans,frames] = size(',dataname,');'])\t\t%size of data matrix\n\nmaxtime = frames / samplerate;       %size of matrix in seconds\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Read the channel names \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  if channamefile ~=0,\t\t% read file of channel names\n\tchid = fopen(channamefile,'r');\n\tif chid <3,\n\t\tfprintf('plotdata: cannot open file %s.\\n',channamefile);\n\t\terrorcode=2;\n\t\tchannamefile = 0;\n\telse\n\t\tfprintf('Chan info file %s opened\\n',channamefile);\n\tend;\n\n    icadefs;   % read MAXEEGPLOTCHANS from icadefs.m\n\tif errorcode==0,\n\t\tchannames = fscanf(chid,'%s',[6 MAXEEGPLOTCHANS]);\n\t\tchannames = channames';\n    \t[r c] = size(channames);\n\t\tfor i=1:r\n\t\t\tfor j=1:c\n\t\t\t\tif channames(i,j)=='.',\n\t\t\t\t\tchannames(i,j)=' ';\n\t\t\t\tend;\n\t\t\tend;\n\t\tend;\n\t\t% fprintf('%d channel names read from file.\\n',r);\n\t\tif (r>chans)\n\t\t\tfprintf('Using first %d names.\\n',chans);\n\t\t\tchannames = channames(1:chans,:);\n\t\tend;\n\t\tif (r<chans)\n\t\t\tfprintf('Only %d channel names read.\\n',r);\n\t\tend;\n\tend;\n  end\n  if channamefile ==0, % plot channel numbers\n\tchannames = [];\n\tfor c=1:chans\n\t\tif c<10,\n\t\t\tnumeric = ['   ' int2str(c)];\t% four-character fields\n\t\telse\n\t\t\tnumeric = ['  '  int2str(c)];\n\t\tend\n\t\tchannames = [channames;numeric];\n\tend;\n  end; % setting channames\n\nchannames = str2mat(channames, ' ');\t% add padding element to Y labels\n\n\nXlab = num2str(time);\nfor j = 1:1:PLOT_TIME\n   Q = num2str(time+j);\n   Xlab = str2mat(Xlab, Q);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set Graph Characteristics\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   figure;\t\t\t\t% plot a new figure\t\n   fighandle = gcf;\n   orient landscape\t\t% choose landscape printer mode\n   hold on;\n   set(gcf,'NumberTitle','off')\n   set(gcf,'Name',['EEGPLOTOLD #',num2str(gcf)])\n   set (gca, 'xgrid', 'on')\t\t\t\t%Xaxis gridlines only\n   set (gca, 'GridLineStyle','-')\t\t\t%Solid grid lines\n   set (gca, 'XTickLabels', Xlab)\t\t\t%Use Xlab for tick labels\n   set (gca, 'Box', 'on')\t\t\t\t\n   set (gca, 'XTick', time*samplerate:1.0*samplerate:PLOT_TIME*samplerate) \n   set (gca, 'Ytick', 0:spacing_var:chans*spacing_var)  % ytickspacing on channels\n   set (gca, 'TickLength', [0.001 0.001])\n   title(titleval)\t\t\t\t\t% title is titleval\n   axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]);       % set axis values\n   set (gca, 'YTickLabels', flipud(channames))   \t% write channel names\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Plot the selected EEG data epoch\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor i = 1:chans\t\t\t\n   if (maxtime-time>PLOT_TIME)  \n      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(time+PLOT_TIME*samplerate));'])\n   else\n      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(maxtime*samplerate));'])\n   end\n   F = F - mean(F) + i*spacing_var;\n   plot (F,'clipping','off')\nend \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Plot Scaling I\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nline([(PLOT_TIME+.3)*samplerate,(PLOT_TIME+.3)*samplerate],[1.5*spacing_var 2.5*spacing_var],'clipping','off','color','w')\nline([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[2.5*spacing_var,2.5*spacing_var],'clipping','off','color','w')\nline([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[1.5*spacing_var,1.5*spacing_var],'clipping','off','color','w')\ntext((PLOT_TIME+.5)*samplerate,2*spacing_var,num2str(round(spacing_var)),'clipping','off')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% User Control Routines\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n   slider_position = [.125 .030 .3 .024];   % position of user-controlled slider\n   edit_position = [.65 .025 .1 .05];       % position of edit box\n   slider_position2 = [.8 .03 .1 .024];\n   b1_position = [.175 .022 .09 .047];\n   b2_position = [.29 .022 .09 .047];\n   b3_position = [.125 .022 .045 .047];\n   b4_position = [.385 .022 .045 .047];\n\n   Max_Space = 1;\n   Min_Space = DEFAULT_SPACING*2;\n%   User_Data_Mat = [data;zeros(1,length(data))];\n\naxhandle = gca;\n   User_Data_Mat(1) = samplerate;\n   User_Data_Mat(2) = PLOT_TIME;\n   User_Data_Mat(3) = spacing_var;\n   User_Data_Mat(4) = time;\n   User_Data_Mat(5) = maxtime;\n   User_Data_Mat(6) = axhandle;\n   User_Data_Mat(7) = 1;  % color\n   User_Data_Mat(8) = frames;\n   User_Data_Mat(9) = chans;\n   User_Data_Mat(12) = 1;\n\n   tstring1 = 'data1973 = get(gcf,''UserData'');';\n   tstring2 = 'set(gcf,''UserData'',data1973);';\n   tstring3 = 'eegdrawgv(gcf);';\n\n   TIMESTRING = [tstring1,'if (data1973(4)-data1973(2))<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - data1973(2);','end;',tstring2,tstring3,'clear data1973'];\n\n   hb = uicontrol('Style','PushButton','Units','Normalized','position',b1_position,'String','PREV','Callback',TIMESTRING);\n\n   TIMESTRING = [tstring1,'if (data1973(4)+data1973(2))>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + data1973(2);','end;',tstring2,tstring3,'clear data1973'];\n\n   hf = uicontrol('Style','PushButton','Units','Normalized','position',b2_position,'String','NEXT','Callback',TIMESTRING);\n\n   TIMESTRING = [tstring1,'if (data1973(4)-1)<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - 1;','end;',tstring2,tstring3,'clear data1973'];\n\n   hbos = uicontrol('Style','PushButton','Units','Normalized','position',b3_position,'String','<<','Callback',TIMESTRING);\n\n   TIMESTRING = [tstring1,'if (data1973(4)+1)>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + 1;','end;',tstring2,tstring3,'clear data1973'];\n\n   hfos = uicontrol('Style','PushButton','Units','Normalized','position',b4_position,'String','>>','Callback',TIMESTRING);\n\n   TIMESTRING = [tstring1,'time1973 = get(gco,''string'');','time1973 = str2num(time1973);','data1973(4) = time1973;',tstring2,tstring3,'clear time1973 data1973'];\n\n   w=uicontrol('style','edit','units','normalized','HorizontalAlignment','left','position',edit_position,'UserData',axhandle,'callback',TIMESTRING);\n\nTIMESTRING = [tstring1,'data1973(3) = get(gco,''value'');',tstring2,tstring3,'clear time1973 data1973'];\n\nu=uicontrol('style','slider','units','normalized','position',slider_position2,'Max',Max_Space,'Min',Min_Space,'value',spacing_var,'UserData',axhandle,'callback',TIMESTRING);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n%Set up ui menus\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Window menu:\n\nTIMESTRING = ['fighand1973 = gcf;','delete(fighand1973);','clear fighand1973;'];\n\nfm1 = uimenu('Label','Window');\nfm2 = uimenu(fm1,'Label','Close ','UserData',fighandle,'Callback',TIMESTRING);\n\n%Display menu:\n\nTIMESTRING = [tstring1,'out1973 = gettext(''Input new windowlength(sec).'');','if isempty(out1973);','out1973 = 0;','else;','data1973(2) = str2num(out1973);',tstring2,tstring3,'end;','clear data1973 out1973'];\n\ndm1 = uimenu('Label','Display');\ndm2 = uimenu(dm1,'Label',' Window Length','Interruptible','yes','Callback',TIMESTRING);\ndm3 = uimenu(dm1,'Label',' Color');\n\nTIMESTRING = [tstring1,'data1973(7) = 1;',tstring2,tstring3,'clear data1973;'];\n\ndm4 = uimenu(dm3,'Label','Yellow ','UserData',axhandle,'Interruptible','yes','Callback',TIMESTRING);\n\nTIMESTRING = [tstring1,'data1973(7) = 2;',tstring2,tstring3,'clear data1973;'];\n\ndm5 = uimenu(dm3,'Label','White ','UserData',axhandle,'Interruptible','yes','Callback',TIMESTRING);\n\nTIMESTRING = ['label1973 = gettext(''Enter new title.'');','if isempty(label1973);','label1973 = 0;','else;','title(label1973);','end;','clear label1973;'];\n\ndm6 = uimenu(dm1,'Label','Title ','Interruptible','yes','Callback',TIMESTRING);\n\nTIMESTRING = [tstring1,'Check1973 = get(data1973(10),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(10),''Checked'',''off'');','set(data1973(6),''XGrid'',''off'');','else;','set(data1973(10),''Checked'',''on'');','set(data1973(6),''XGrid'',''on'');','end;','clear data1973 Check1973;'];\n\ndm7 = uimenu(dm1,'Label','Grid','Checked','on','Callback',TIMESTRING);\n\nUser_Data_Mat(10) = dm7;\n\nTIMESTRING = [tstring1,'Check1973 = get(data1973(11),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(11),''Checked'',''off'');','data1973(12)= 0;','else;','set(data1973(11),''Checked'',''on'');','data1973(12) = 1;','end;',tstring2,tstring3,'clear data1973 Check1973;'];\n\ndm8 = uimenu(dm1,'Label','Scaling I','Checked','on','Callback',TIMESTRING);\n\nUser_Data_Mat(11) = dm8;\n\n%Settings menu:\n\nsm1 = uimenu('Label','Settings');\n\nTIMESTRING = [tstring1,'Srate1973 = gettext(''Enter new samplerate'');','if isempty(Srate1973);','Srate1973 = 0;','else;','data1973(1) = str2num(Srate1973);','data1973(5) = data1973(8)/data1973(1);','data1973(4) = 0;',tstring2,tstring3,'end;','clear Srate1973 data1973'];\n\nsm2 = uimenu(sm1,'Label','Samplerate','Interruptible','yes','Callback',TIMESTRING);\n\n%Electrodes menu:\n\nem1 = uimenu('Label','Electrodes');\n\nTIMESTRING = [tstring1,'ChanNamefile1973 = gettext(''Enter Electrode file to load.'');','if isempty(ChanNamefile1973);','ChanNamefile1973=0;','else;','ChanNames1973 = loadelec(ChanNamefile1973);','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNamefile1973 ChanNames1973'];\n\nem2 = uimenu(em1,'Label','Load Electrode File ','Interruptible','yes','Callback',TIMESTRING);\n\nTIMESTRING = [tstring1,'ChanNames1973 = makeelec(data1973(9));','if isempty(ChanNames1973);','ChanNames1973=0;','else;','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNames1973'];\n\nem3 = uimenu(em1,'Label','Make Electrode File ','Interruptible','yes','Callback',TIMESTRING);\n\nset(axhandle,'UserData',dataname)\nset(fighandle,'UserData',User_Data_Mat)\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/miscfunc/eegplotgold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.23099940948404143}}
{"text": "function [output, layerOut] = FeatureTree2(visible, para, layer)\n% remove target and cost function nodes if any\nfor i=1:length(layer)\n    if strcmpi(layer{i}.name, 'target') || strcmpi(layer{i}.name, 'cross_entropy') || strcmpi(layer{i}.name, 'mse') || strcmpi(layer{i}.name, 'logistic')\n        layer{i}.name = 'ignore';\n    end\n    if i > max(para.out_layer_idx)  % we don't compute layers that is after the last output layer\n        layer{i}.name = 'ignore';\n    end\nend\npara.NET.sentenceMinibatch = 1;\n[minibatch] = MinibatchPackaging_tree4(visible, para);\n\noutput = {};\nfor utt_i = 1:minibatch.nBatch\n    PrintProgress(utt_i, minibatch.nBatch, 100);\n    batch_data = GetMinibatch2(minibatch, para, utt_i);\n    \n    % Use mode=3 to generate network output only\n    if nargout>1\n        [~, layerOut{utt_i}, output{utt_i}] = DNN_Cost10(layer, batch_data, para,3);\n    else\n        [~, ~, output{utt_i}] = DNN_Cost10(layer, batch_data, para,3);\n    end\nend\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/tools/FeatureTree2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23088937528910858}}
{"text": "% JN Kather 2018\n\nfunction [lgraph,imageInputSize,networkType] = getAndModifyNet(nnmodel,hyperparam,numOutputClasses)\n\n% load pre-trained network model for transfer learning\nswitch nnmodel\n    case 'vgg19'\n        rawnet = vgg19;   \n        networkType = 'series';\n    case 'vgg16'\n        rawnet = vgg16;\n        networkType = 'series';\n    case 'alexnet'\n        rawnet = alexnet;\n        networkType = 'series';\n    case 'inceptionv3'\n        rawnet = inceptionv3;\n        networkType = 'DAG';\n        layersForRemoval = {'predictions', 'predictions_softmax','ClassificationLayer_predictions'};\n        layersForReconnection = {'avg_pool','fc'};\n    case 'googlenet'\n        rawnet = googlenet;\n        networkType = 'DAG';\n        layersForRemoval = {'loss3-classifier','prob','output'};\n        layersForReconnection = {'pool5-drop_7x7_s1','fc'};\n    case 'resnet18' \n        rawnet = resnet18;\n        networkType = 'DAG';\n        layersForRemoval = {'fc1000', 'prob','ClassificationLayer_predictions'};\n        layersForReconnection = {'pool5','fc'};\n    case 'resnet50' \n        rawnet = resnet50;\n        networkType = 'DAG';\n        layersForRemoval = {'ClassificationLayer_fc1000', 'fc1000_softmax','fc1000'};\n        layersForReconnection = {'avg_pool','fc'};\n    case 'resnet101'\n        rawnet = resnet101;\n        networkType = 'DAG';\n        layersForRemoval = {'fc1000', 'prob','ClassificationLayer_predictions'};\n        layersForReconnection = {'pool5','fc'};\n    case 'squeezenet'\n        rawnet = squeezenet;\n        networkType = 'DAG';   \n        layersForRemoval = {'pool10', 'prob','ClassificationLayer_predictions'};\n        layersForReconnection = {'relu_conv10','fc'};\n    case 'inceptionresnetv2'\n        rawnet = inceptionresnetv2;\n        networkType = 'DAG';   \n        layersForRemoval = {'predictions', 'predictions_softmax','ClassificationLayer_predictions'};\n        layersForReconnection = {'avg_pool','fc'};\n    otherwise\n        error('wrong network model specified');\nend\n\n% prune and rewire network\nswitch networkType\n    case 'series' % e.g. alexnet\n        lgraph = rawnet.Layers;\n        % freeze shallow layers\n        freezeIndex = 1:(numel(lgraph)-hyperparam.hotLayers);\n        lgraph(freezeIndex) = freezeWeights(lgraph(freezeIndex));\n        % overwrite penultimate and last layer\n        lgraph(end-2) = fullyConnectedLayer(numOutputClasses,'Name','fc',...\n            'WeightLearnRateFactor',hyperparam.learnRateFactor,...\n            'BiasLearnRateFactor',hyperparam.learnRateFactor);\n        lgraph(end) = classificationLayer;\n        imageInputSize = lgraph(1).InputSize(1:2);\n    case 'DAG' % e.g. googlenet\n        % freeze shallow layers\n        lgraph = layerGraph(rawnet); % convert network to layer graph\n        layers = lgraph.Layers;      % extract layers\n        connections = lgraph.Connections; % exctract connections\n        freezeIndex = 1:(numel(layers)-hyperparam.hotLayers);\n        layers(freezeIndex) = freezeWeights(layers(freezeIndex));\n        lgraph = createLgraphUsingConnections(layers,connections);\n        % remove old layers\n        lgraph = removeLayers(lgraph,layersForRemoval);\n        % add new layers and connect\n        newLayers = [\n            fullyConnectedLayer(numOutputClasses,'Name','fc',...\n            'WeightLearnRateFactor', hyperparam.learnRateFactor,...\n            'BiasLearnRateFactor', hyperparam.learnRateFactor),...\n            softmaxLayer('Name','softmax'),...\n            classificationLayer('Name','classoutput')];\n        lgraph = addLayers(lgraph,newLayers);\n        lgraph = connectLayers(lgraph,layersForReconnection{1},layersForReconnection{2});\n        imageInputSize = lgraph.Layers(1).InputSize(1:2);\n    otherwise, error('undefined network type');\nend\nend\n", "meta": {"author": "jnkather", "repo": "MSIfromHE", "sha": "27b351b9220583271cd2bcedbc9e75459916e06c", "save_path": "github-repos/MATLAB/jnkather-MSIfromHE", "path": "github-repos/MATLAB/jnkather-MSIfromHE/MSIfromHE-27b351b9220583271cd2bcedbc9e75459916e06c/subroutines/getAndModifyNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23088936366002435}}
{"text": "hydro = struct();\n\nhydro = readNEMOH(hydro,'../Ellipsoid/');\n% hydro = readWAMIT(hydro,'../../WAMIT/Ellipsoid/ellipsoid.out',[]);\n% hydro = combineBEM(hydro); % Compare to WAMIT\nhydro = radiationIRF(hydro,10,[],[],[],[]);\nhydro = radiationIRFSS(hydro,[],[]);\nhydro = excitationIRF(hydro,15,[],[],[],[]);\nwriteBEMIOH5(hydro)\nplotBEMIO(hydro)\n\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/examples/BEMIO/NEMOH/Ellipsoid/bemio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23087156540677797}}
{"text": "% SPM5 UPDATE 23/11/07\n% Sets the default values for the FieldMap toolbox\n%\n% FORMAT pm_defaults_Trio_eFoV_dn\n%_______________________________________________________________________\n%\n% This file is intended for use with the Siemens fieldmap sequence\n% on the Trio scanner at the AMRIG/FIL and the eFoV EPI sequences with\n% PE blips=+1:\n% \n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Chloe Hutton and Jesper Andersson\n% $Id: pm_defaults_Trio_eFoV_dn.m 5015 2012-10-24 13:40:07Z guillaume $\n\nglobal pm_def\n\n% Defaults for creating field map. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.INPUT_DATA_FORMAT = 'PM';      % 'RI' = load two real and \n                                      % imaginary image pairs\n                                      % 'PM' = load one or two\n                                      % phase and magnitude image\n                                      % pairs.\npm_def.SHORT_ECHO_TIME = 10.0;        % Short echo time in ms for Trio\npm_def.LONG_ECHO_TIME = 12.46;        % Long echo time in ms for Trio\npm_def.MASKBRAIN = 1;                 % Do brain masking (1 or 0,\n                      % 0 for EPI fieldmaps)\n\n% Defaults for unwrapping options. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.UNWRAPPING_METHOD = 'Mark3D';  % Unwrapping options are:\n                                      % 'Huttonish', 'Mark3D' or 'Mark2D'\npm_def.FWHM = 10;                     % FWHM of Gaussian filter used to \n                                      % implement weighted smoothing of\n                                      % unwrapped maps.\npm_def.PAD = 0;                       % Size of padding kernel if required.\npm_def.WS = 1;                        % Weighted or normal smoothing.\n\n% Flags for brain extraction\n%=======================================================================\npm_def.MFLAGS.TEMPLATE = fullfile(spm('Dir'),'toolbox','FieldMap','T1.nii');\npm_def.MFLAGS.FWHM = 5;     % In mm\npm_def.MFLAGS.NERODE = 2;   % In voxels\npm_def.MFLAGS.NDILATE = 4;  % In voxels\npm_def.MFLAGS.THRESH = 0.5;\npm_def.MFLAGS.REG = 0.02;   % A larger value helps segmentation to converge\npm_def.MFLAGS.GRAPHICS = 0; % A larger value helps segmentation to converge\n\n% Defaults for converting field map to voxel displacement map.\n%=======================================================================\npm_def.EPI_BASED_FIELDMAPS = 0;         % EPI=1, other=0.\npm_def.K_SPACE_TRAVERSAL_BLIP_DIR = +1; % +ve k-space = 1, -ve = -1.\npm_def.TOTAL_EPI_READOUT_TIME = 37.0;   % Trio eFoV EPI RO time \n\n% Defaults for Unwarping.\n%=======================================================================\npm_def.DO_JACOBIAN_MODULATION = 0;    % Do jacobian modulation to adjust \n                                      % for compression or stretching\n                                      % No = 0, Yes = 1\n                      \n                      \n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/FieldMap/FIL/pm_defaults_Trio_eFoV_dn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.2308689167235299}}
{"text": "%%  Virtual Painter 1\n%% discription\n% Virtual Painter - this software allows you to draw a picture on the screen\n% By following the red color\n% \n% Have the option to choose what color to paint by moving the red color to the desired color:\n% Red, green, blue.\n% \n% To close the program, have received faint image on the screen\n% \n% Note: In order to achieve optimal results have run the program in the light of fluorescent lamp.\n% % Operating Instructions\n% To paint the color red object we vote to act as follows:\n%% Play and exit:\n%\n% * To start the video: click on the Play button.\n% * To exit from the function: Display to the camera very dark image ,\n%    for example you can cover the camera with your hand,\n%    Or turn off the light in the room.After doing so\n%    The Camera and function should be closed automatically.\n%% Notes\n%  The identification of red objects in the picture depends on the lighting of the room.\n%  Lighting Fluorescent light is the most appropriate lighting to this function to identify red objects.\n%\n%  first edited  in 8/06/2013 Saturday .\n%  by Oren berkovich.\n\n\nfunction virtualpaint()    \n    \n\n            \n%% creat figure and uicontrol \n      figure('menubar','none')  \n    \n\n    ply= uicontrol('style','togg','units','normalized',...\n        'position',[0.1 0.1 0.1 0.1],'str','Play','callback',{@PlayvideoLive});    \n    \n    uicontrol('style','text','str' ,'exit- cover the eye of the camera ',...\n        'units','normalized','position',[0.2 0.1 0.5 0.05])\n  \n    %% main function\n    function PlayvideoLive(~,~)\n   \n        set(ply,'enable','off');\n        pause(0.5);\n        \n        try\n    imaqreset\n    vid = videoinput('winvideo', 1, 'YUY2_160x120');\n    vid.ReturnedColorspace = 'rgb';\n    set(vid,'framesperTrigger',10,'TriggerRepeat',Inf);\n       \n      color='y';\n      x=[];\n      y=[];\n      Eraser='non';\n      %\n        tic  \n   \n    start(vid);\n        catch ex\n            err=errordlg(ex.message);\n            uiwait(err)\n            close gcf\n            return\n        end\n\n      while islogging(vid)\n\n    \n    tv=getdata(vid,1);\n    \n    r=tv(:,:,1,1);\n    g=tv(:,:,2,1);\n    b=tv(:,:,3,1);\n    \n    flushdata(vid);\n    \n    %% Find the differences of each object\n\nrg=r-g;\ngb=g-b;\nrggb=rg-gb;\n\n\n%% build the color filters\n\nfilter=rggb>26;\nfilter=uint8(filter);\nF=filter.*rggb;\n\n%% Remove objects less than the pixel size prescribing function\n\n \n bw=imfill(F,'holes');\n \n bw=bwareaopen(bw,50);\n %%\n \n\n %% Identify the position of the marked\n W=regionprops(bw,'Centroid');\n if isempty(W)==0\n     %axis([0 160 0 120])\n\n x=horzcat(x,W(1).Centroid(1));\n y=horzcat(y,W(1).Centroid(2));\n\n  elseif length(W)==2\n     hold on\n     line([W(1).Centroid(1) W(2).Centroid(1)],[W(1).Centroid(2) W(2).Centroid(2)],'color','r','linew',2)\n \n end\n  %% erse mode\n      if length(x)==100\n          Eraser='era';    \n      end\n      \n      if eq(Eraser,'era')==1\n           x=x(2:length(x));\n           y=y(2:length(y));\n           if  isempty(x)==1\n               Eraser='non';\n           end\n      end\n      %%\n hold on\n\n if isempty(x)==0\ncolor=rgbcolor(x(length(x)),y(length(y)),color);\nplot(x,y,'color',color,'linew',4) \n end\n \n %% Rebuild the RGB image, if the part has been lightened\n \n\n \n    figure(gcf)\n    hold off\n    imshow(tv(:,:,:,1))\n    \n    state =mean2(r);\n    if state<20&&toc>20;\n       break\n    end\n   \n      end    \n      % after you exit the loop \n       stop(vid)\n       imaqreset\n\n       close gcf\n       clc\n       disp('good by')\n    end\n    \n     \n    end\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42149-virtual-painter/virtualpaint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23082156443522486}}
{"text": "function IM = generateQIBInfluence(IM, structROIV, sampleRateV)\n%\"generateQIBInfluence\"\n%   Uses the QIB engine to populate the beamlet fields of an IM structure.\n%   StructROIV is the list of structures, sampleRateV is a vector of sample\n%   rates, one for each structROIV.\n%   The doses are stored in sparse format.\n%   The stored index is with respect to the structure mask registered to the\n%   uniformized CT scan.\n%\n%   This code was broken out of a function by JOD and CZ.\n%\n%JRA  26 Aug 2004\n%LM:  14 Sept 05, JOD, fixed bug in call to mtoxyz\n%     17 Dec  05, JOD, fixed bug in un-downsampled ROI\n%                      definition; added comments to clarify calculation, and a small speedup change.\n%     05 Jul  06, JJW, added missing inverse square law; added sigma_100 \n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n\n%-----------Generate influence matrices---------------------%\n%Loop over structures (i.e. goal terms)\n\nglobal planC\nglobal stateS\nindexS = planC{end};\n\n%obtain associated scanNum for structures. It is assumed that all the\n%structures are associated to same scan (which is checked in IMRTP.m)\nscanNum = getStructureAssociatedScan(structROIV(1));\n\nfor i = 1 : length(structROIV)\n\n    if sampleRateV(i) ~= 1\n\n        %Ensures that interpolative downsampling won't miss edge points:\n        maskSingle3D = getSurfaceExpand(structROIV(i),0.5,1);\n        if rem(log2(sampleRateV(i)),1) ~= 0\n            error('Sample factor must (currently) be a power of 2.')\n        end\n        maskSample3D = getDown3Mask(maskSingle3D, sampleRateV(i), 1);\n        %Get a mask of where to sample points\n        tmp = logical(maskSample3D) & maskSingle3D;\n        clear maskSample3D, maskSingle3D;\n\n    else\n\n        tmp = getUniformStr(structROIV(i));\n\n    end\n\n    scanIndV = find(tmp(:));  %Indices with respect to the uniformized scan.\n    [rowV, colV, sliceV] = find3d(tmp); clear tmp;     %returns locations of mask voxels\n\n    %[xV,yV,zV] = mtoxyz(rowV,colV,sliceV,1,planC,'uniform'); change by\n    %JOD.\n    [xV,yV,zV] = mtoxyz(rowV,colV,sliceV,scanNum,planC,'uniform');\n\n    doseV = zeros(size(xV));\n\n    numPts = length(xV);\n\n    pM = [xV(:),yV(:),zV(:)];   %Location of dose calc points, downsampled.\n\n    PBCounter = 1;\n\n    QIBDataS = loadPBData;\n\n    for j = 1 : length(IM.beams)\n\n        disp(['Compute doses to structure number ' num2str(structROIV(i)) ' for beam ' num2str(j) '.'])\n\n        %Get beamlet data for this beam and this structure\n\n        sourceM = repmat([IM.beams(j).x, IM.beams(j).y, IM.beams(j).z],numPts,1);\n\n        pRelM = pM - sourceM;    %get relative vector direction from source to dose calc points.\n\n        RTOGPBVectorsM = IM.beams(j).RTOGPBVectorsM;\n\n        str = int2str(size(RTOGPBVectorsM,1));\n\n        disp(['numPBs = ' str])\n\n\n        PBM = [];\n        for PBNum = 1 : size(RTOGPBVectorsM,1)\n\n            if mod(PBNum, 25) == 0 | (PBNum == size(RTOGPBVectorsM,1))\n                disp(['Computed ' int2str(PBNum) ' out of ' str]); pause(0.003);\n                try\n                    IMRTPGui('status', j, length(IM.beams), structROIV(i), PBNum, size(RTOGPBVectorsM,1));\n                end\n            end\n\n            PBV = RTOGPBVectorsM(PBNum,:);\n\n            distSamplePts = IM.beams(j).CTTraceS(PBNum).distSamplePts;\n            cumDensity    = IM.beams(j).CTTraceS(PBNum).cumDensityRay;\n\n            distV = pRelM * PBV';    %Each row is the dot product of (the un-normalized) source-to-calc point\n                                     %direction and the PB unit vector.\n                                     %Hence, this is the distance along the PB ray line for each dose calc point.\n\n            qM = sourceM + distV * PBV;  %The last term gives the vector i, j, and k components of\n                                         %distance to the depth of closest approach.\n                                         %Each row of sourceM is the i,j,k position of the source.\n                                         %So vector sum locates the positions of closest approach\n                                         %to the dose calc points.\n\n            rM  = pM - qM;    %Each row of pM is the x, y, z location of a dose calc point.\n                              %rM is then the vector pointing from the dose calc point to the point\n                              %at which the PB vector makes closest approach.\n\n            %Trap points which are too far away to need dose calcs\n            %Uses sepsq if possible, much faster.\n            try\n                rDistVSquared = sepsq([0 0 0]', rM');  %mex file speedup\n                goV = rDistVSquared < (IM.params.cutoffDistance^2);\n            catch\n                rDistV = (rM(:,1).^2 + rM(:,2).^2 + rM(:,3).^2);    %if mex not there\n                goV = rDistV < IM.params.cutoffDistance^2;         %Mod by JOD to speedup, Dec 05.\n            end\n\n            rGoM = rM(goV,:);\n            %       rGoDistV = rDistV(goV);\n            distGoV = distV(goV);\n\n            %We ignore the slight tilt of PB cross-sections with respect to the longitudinal axis.\n\n            [gantryVectorsM] = RTOGVectors2Gantry(rGoM, IM.beams(j).gantryAngle);\n            Xb = gantryVectorsM(:,1);\n            Yb = gantryVectorsM(:,2);\n\n            tmpV=clip(distGoV,0.001,max(distSamplePts) - 0.001,'limits');\n\n            %get cum density at that point\n            radDepthV = interp1([0, distSamplePts],[0, cumDensity],tmpV);\n\n            %Get the widths of the PBs at that distance\n            PBWidth_YbV = IM.beams(j).beamletDelta_y * distGoV/IM.beams(j).isodistance; %This is the width 'out-of-plane'\n            PBWidth_XbV = IM.beams(j).beamletDelta_x * distGoV/IM.beams(j).isodistance; %This is the width 'in-plane'\n\n            %compute dose using QIB\n            [A_zV, a_zV, B_zV, b_zV] = GetPBConsts(radDepthV, IM.beams(j).beamEnergy, QIBDataS, 'nearest');\n\n            doseFlag = IM.params.DoseTerm;\n\n            sigmaVal_100 = IM.beams(j).sigma_100;\n            \n            doseV = getQIBDose([Xb,Yb], radDepthV, PBWidth_XbV, PBWidth_YbV, ...\n                QIBDataS, A_zV, a_zV, B_zV, b_zV, IM.beams(j).beamEnergy, doseFlag, sigmaVal_100, distGoV);\n\n            % apply inverse square law: \n            % (divide by depth dependent area of beamlet scaled to isocenter distance)\n            doseV = IM.beams(j).beamletDelta_x * IM.beams(j).beamletDelta_y * doseV ./ (PBWidth_XbV .* PBWidth_YbV);\n            \n            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    %This function selectively eliminates some scatter components, if invoked.\n            doseV = applyIMRTCompression(IM.params, doseV);\n            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n            %-----------Construct the dose matrix---------------------%\n\n            indNZV = [doseV == 0];\n            whereV = goV;     %First trap on distance\n            ind0V = find(whereV);\n            whereV(ind0V(indNZV)) = 0;    %zero out indices where dose was not computed from within QIB routine.\n            [indV] = find(whereV);        %indV returns locations where dose is non-zero.\n            doseV(indNZV) = [];           %eliminate dose entries which were zero.\n\n            beamlet = createIMBeamlet(doseV, scanIndV(indV), j, length(goV));\n\n            IM.beamlets(structROIV(i),PBCounter) = beamlet;\n            IM.beamlets(structROIV(i),PBCounter).structureName = planC{planC{end}.structures}(structROIV(i)).structureName;\n            IM.beamlets(structROIV(i),PBCounter).sampleRate = sampleRateV(i);\n\n            PBCounter = PBCounter + 1;\n        end\n\n    end\n\n    clear xV yV zV sourceM pM pRelM qM rM rDistV rGoM rowV sliceV;\n\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/generateQIBInfluence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.23076256059823247}}
{"text": "function s1 = resize_scales(s0,dim,args)\n% Resize scalefactors \n% _________________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id$\n\ndim = [dim ones(1,max(numel(args)-numel(dim),0))];\nargs1 = cell(1,numel(args));\nfor i=1:numel(args),\n    if max(args{i})>dim(i) || min(args{i})<1,\n        error('Index exceeds matrix dimensions (1).');\n    end;\n\n    if size(s0,i)==1,\n        args1{i} = ones(size(args{i}));\n    else\n        args1{i} = args{i};\n    end;\nend;\n\ns1 = s0(args1{:});\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm8/@file_array/private/resize_scales.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23053502841593615}}
{"text": "%% Example script to visualize the aircraft simulation data\n% Add the path of the aircraft_3d_animation function\naddpath('../src/');\n% path of the *.mat file containing the 3d model information\nmodel_info_file = '../3d_models/x15_3d_model.mat';\n% Load the simulation data\n% load('scissors_maneuver.mat')\n% load('breakaway_maneuver.mat')\n% load('split_s_maneuver.mat')\n% load('departure.mat')\nload('departure2.mat')\n% define the reproduction speed factor\nspeedx = 1; \n% Do you want to save the animation in a mp4 file? (0.No, 1.Yes)\nisave_movie = 1;\n% Movie file name\nmovie_file_name = 'departure2.mp4';\n\n% -------------------------------------------------------------------------\n% The frame sample time shall be higher than 0.02 seconds to be able to \n% update the figure (CPU/GPU constraints)\nframe_sample_time = max(0.02, tout(2)-tout(1));\n% Resample the time vector to modify the reproduction speed\nt_new   = tout(1):frame_sample_time*(speedx):tout(end);\n% Resample the recorded data\nact     = interp1(tout, act, t_new','linear');\nstick   = interp1(tout, stick, t_new','linear');\ny_new   = interp1(tout, yout, t_new','linear');\n% We have to be careful with angles with ranges\ny_new(:, 7)  = atan2(interp1(tout, sin(yout(:, 7)), t_new','linear'), interp1(tout, cos(yout(:, 7)), t_new','linear')) * 180 / pi;\ny_new(:, 8)  = atan2(interp1(tout, sin(yout(:, 8)), t_new','linear'), interp1(tout, cos(yout(:, 8)), t_new','linear')) * 180 / pi;\ny_new(:, 9)  = atan2(interp1(tout, sin(yout(:, 9)), t_new','linear'), interp1(tout, cos(yout(:, 9)), t_new','linear')) * 180 / pi;\n% Assign the data\nheading_deg           =  y_new(:, 7);\npitch_deg             =  y_new(:, 8);\nbank_deg              =  y_new(:, 9);\nroll_command          = -stick(:, 2);\npitch_command         = -stick(:, 1);\nangle_of_attack_deg   =  y_new(:, 2) * 180 / pi;\nangle_of_sideslip_deg =  y_new(:, 3) * 180 / pi;\nfligh_path_angle_deg  =  y_new(:, 22) * 180 / pi;\nmach                  =  y_new(:, 21);\naltitude_ft           = -y_new(:, 12);\nnz_g                  =  y_new(:, 19);\n% Flight control surfaces\ndr     = -act(:, 8);\ndf1    =  act(:, 6);\ndf2    =  act(:, 5);\ndf3    =  act(:, 4);\ndf4    =  act(:, 3);\n% Control array assignation\n% (modify the order according to your particular 3D model)\ncontrols_deflection_deg = [ 0.25 * (df1(:) + df2(:) - df3(:) - df4(:)), ...\n                           -0.25 * (df1(:) + df2(:) - df3(:) - df4(:)), ...\n                            0.25 * (df1(:) + df2(:) + df3(:) + df4(:)), ...\n                            0.25 * (df1(:) + df2(:) + df3(:) + df4(:)), ...\n                            df1(:) * 0, ...\n                            df1(:) * 0, ...\n                            dr(:)];\n\n%% Run aircraft_3d_animation function\n% -------------------------------------------------------------------------\naircraft_3d_animation(model_info_file,...\n    heading_deg, ...            Heading angle [deg]\n    pitch_deg, ...              Pitch angle [deg]\n    bank_deg, ...               Roll angle [deg]\n    roll_command, ...           Roll  stick command [-1,+1] [-1 -> left,            +1 -> right]\n    pitch_command, ...          Pitch stick command [-1,+1] [-1 -> full-back stick, +1 -> full-fwd stick]\n    angle_of_attack_deg, ...    AoA [deg]\n    angle_of_sideslip_deg, ...  AoS [deg]\n    fligh_path_angle_deg, ...   Flight path angle [deg]\n    mach, ...                   Mach number\n    altitude_ft, ...            Altitude [ft]\n    nz_g,  ...                  Vertical load factor [g]\n    controls_deflection_deg, ...Flight control deflection (each column is a control surface)\n    frame_sample_time, ...      Sample time [sec]\n    speedx, ...                 Reproduction speed\n    isave_movie, ...            Save the movie? 0-1\n    movie_file_name);           % Movie file name", "meta": {"author": "Ro3code", "repo": "aircraft_3d_animation", "sha": "fa0cdebd6988e11761eadd1b6f73a48b8c6a552e", "save_path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation", "path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation/aircraft_3d_animation-fa0cdebd6988e11761eadd1b6f73a48b8c6a552e/examples/run_animation_x15.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.2304703468484636}}
{"text": "%% Example of using KST class for interfacing with KUKA iiwa robots\n\n% soft real-time control of the KUKA robot with\n% impedence\n% Moving the joints of the robot using a sinusoidal function\n\n% The external torques are plotted in real-time during the test\n% the feedback from the measured torques can be used to for a closed loop\n% control\n\n% First start the server on the KUKA iiwa controller\n% Then run this script using Matlab\n\n% This code was tested using Matlab 2013b\n\n% This example works with Sunrise application version KST_1.7  and higher.\n% Copyright Mohammad SAFEEA, 26th-June-2018\n\nclose all;clear;clc;\nwarning('off')\n%% Create the robot object\nip='172.31.1.147'; % The IP of the controller\narg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820\narg2=KST.Medien_Flansch_elektrisch; % choose the type of flange\nTef_flange=eye(4); % transofrm matrix of EEF with respect to flange\niiwa=KST(ip,arg1,arg2,Tef_flange); % create the object\n\n%% Start a connection with the server\nflag=iiwa.net_establishConnection();\nif flag==0\nreturn;\nend\npause(1);\ndisp('Doing some stuff')\n    \n%% Move point to point to an initial position\njPos={0,0,0,-pi/2,0,pi/2,0};\nrelVel=0.15;\niiwa.movePTPJointSpace(jPos, relVel); % move to initial configuration\n\n%% Pause for 3 seocnds\npause(3); \n\n%% Tool/Impedance parameters   \nmassOfTool=0.5; % the mass of the tool attached to flange in Kg\ncOMx=0; % X coordinate of the center of mass of the tool in (mm)\ncOMy=0; % Y coordinate of the center of mass of the tool in (mm)\ncOMz=40; % Z coordinate of the center of mass of the tool in (mm)\ncStiness=900; % cartizian stifness\nrStifness=80; % rotational stifness\nnStifness=50; % null space stifness\n\n% Start the soft realtime control with impedance\niiwa.realTime_startImpedanceJoints(massOfTool,cOMx,cOMy,cOMz,...\ncStiness,rStifness,nStifness);\n\nw=0.6; % motion constants, frequency rad/sec\nA=0.2; % motion constants, amplitude of motion\n\na=datevec(now);\nt0=a(6)+a(5)*60+a(4)*60*60; % calculate initial time\n\ndt=0;\ntstart=t0;\ncounter=0;\nduration=0.5*60; %0.5 minutes\n\n%% Control loop\n% real time plot handles\n colors={'k','b','r','g','c','m','y'};\n figureHandle=figure('Units','inches','Position',[0 0 5 3.75]);\n numOfSamples=120; % number of samples to show in the plot\n timeVec=1:numOfSamples;\n tawVec=zeros(7,numOfSamples);\n plotHandle=[];\n for i=1:7\n    plotHandle=[plotHandle,plot(timeVec,tawVec(i,:),colors{i},'LineWidth',2)];\n    hold on;\n end\n% format the plot\nylim([0,8]);\ntemp=title('External torques');\nset(temp,'FontSize',16);\ntemp=xlabel('Time (seconds)');\nset(temp,'FontSize',14);\ntemp=ylabel('Distance (m)');\nset(temp,'FontSize',14);\n\n\nwhile(dt<duration)\n %% perform trajectory calculation here\n  a=datevec(now);\n  time=a(6)+a(5)*60+a(4)*60*60;\n  dt=time-t0;\n\n  temp=A*(1-cos(w*dt));\n    for dacount=1:7\n        jPosCommand{dacount}=jPos{dacount}+temp;\n    end\n  counter=counter+1;\n  %% Send joint positions to robot\n  taw=iiwa.sendJointsPositionsExTorque(jPosCommand);\n\n  tawTemp=zeros(7,1);\n  for i=1:7\n      tawTemp(i)=taw{i};\n      torque_array(i,counter)=taw{i};\n  end\n  % delete first measurment\n  tawVec(:,1)=[];\n  % add new measurment to end of arrays\n  tawVec=[tawVec,tawTemp];\n  % update plots data\n  for i=1:6\n    set(plotHandle(i),'YData',tawVec(i,:));\n  end\n  set(plotHandle(7),'YData',tawVec(i,:));\n  % show plot data\n  set(figureHandle,'Visible','on');\n\nend\n\n\n%% Stop the realtime control with impedence motion\niiwa.realTime_stopImpedanceJoints();\nfprintf('\\n Motion stopped \\n');\npause(2);\n\n%% turn off the server\niiwa.net_turnOffServer();\n\nwarning('on')\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/KSTclass_Tutorial_realTimeImpedencePlotTorqueFeedBack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.23047034201023156}}
{"text": "function f = sinh( f )\n%SINH   Hyperbolic sine of a SEPARABLEAPPROX.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty check: \nif ( isempty( f ) )    \n    return\nend \n\nf = compose( f, @sinh ); \n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@separableApprox/sinh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23035401238477957}}
{"text": "function y = guard_interval(Ng,Nfft,NgType,ofdmSym)\nif NgType==1\n  y=[ofdmSym(Nfft-Ng+1:Nfft) ofdmSym(1:Nfft)];\nelseif NgType==2\n  y=[zeros(1,Ng) ofdmSym(1:Nfft)];\nend", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/\u7b2c4\u7ae0 OFDM\u6982\u8ff0/\u4eff\u771fOFDM\u4f20\u8f93\u7cfb\u7edf/guard_interval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23035401238477957}}
{"text": "% Script: call_Omorifit.m\n% -----------------------\n% Script to input parameters for a modified Omori law fit and calculate fit to data\n% Calculation is done in function plot_llkstest\n% The function works on the catalog newt2!!!\n% J.Woessner\n% last update: 19.08.03\n\nreport_this_filefun(mfilename('fullpath'));\n% Get input parameters\nprompt  = {,'Enter length of learning period (days)','Enter number of bootstraps:'};\ntitle   = 'Parameters ';\nlines= 1;\nif exist('time') &&  exist('bootloops')\n    time = num2str(time);\n    bootloops = num2str(bootloops);\n    def     = {time,bootloops};\n    answer  = inputdlg(prompt,title,lines,def);\n    time = str2double(answer{1});\n    timef = 1;\n    bootloops = str2double(answer{2});\n\nelse\n    def     = {'50','50'};\n    answer  = inputdlg(prompt,title,lines,def);\n    time = str2double(answer{1});\n    timef = 1;\n    bootloops = str2double(answer{2});\nend\n\n% maepi is the mainshock of sequence\nplot_llkstest(newt2,time,timef,bootloops,maepi);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/afterrate/call_Omorifit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23035401238477954}}
{"text": "function rtk=udpos_rtkins(rtk,tt) %#ok\n\nins=rtk.ins;\nrtk.x(1:15)=0;   \nrtk.P(1:15,1:15)=0;\n\n% lever arm correction\npos=ins.pos+ins.Mpv*ins.Cnb*ins.lever;\nvel=ins.vel+ins.Cnb*askew(ins.web)*ins.lever;\n\nrtk.x(1:15)=[ins.att;vel;pos;ins.bg;ins.ba];\nrtk.P(1:15,1:15)=ins.P;\n\nreturn", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss_ins_tc/rtkins/udpos_rtkins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23023565490675166}}
{"text": "function [data, labels, imind] = mcmcGenerateRandomSegments3(imsegs, imdir, ...\n            adjlist, spdata, edata, vclassifierSP, hclassifierSP, eclassifier)  \n% Generate random segments for training good (1) vs. bad (-1) segments\n% segment, where good segments consist entirely of one label\n        \nnimages = numel(imsegs);\nnfeatures = 36;\n\nnsegments = 60000;\n\ndisp(num2str(nimages))\n\ndata = zeros(nsegments, nfeatures);\n\nlabels = zeros(nsegments, 1);\n\nimind = zeros(nsegments, 1);\n\ncount = 0;\n\nfor f = 1:nimages\n\n    disp([num2str(f) ': ' imsegs(f).imname])\n    \n    im = im2double(imread([imdir '/' imsegs(f).imname]));\n    %imdata = mcmcComputeImageData(im, imsegs(f)) ;\n    \n    segimage = imsegs(f).segimage;\n    \n    %features{f} = mcmcGetSegmentFeatures(imsegs(f), spfeatures{f}, imdata,\n    %gtmaps{f}, [1:max(gtmaps{f})]);\n    \n    [pvSP, phSP, pE, smap] = mcmcInitialize(spdata{f}, edata{f}, ...\n        adjlist{f}, imsegs(f), vclassifierSP, hclassifierSP, eclassifier, 'labels');\n\n    origmap = smap;\n    \n    while count < round(nsegments*(f/nimages))            \n        \n        %figure(1), hold off, imshow(label2rgb(origmap(segimage)))\n        [smap, newseg, origseg, segadjmat] =  ...\n            mcmcGenerateProposals(pE, adjlist{f}, smap, im, segimage);\n        \n        % display segments\n        %figure(2), hold off, imagesc(label2rgb(smap(segimage)));\n        %figure(1), displaySegmentGraph(im, smap(segimage), segadjmat);        \n        \n        neighborseg = [newseg find(segadjmat(newseg, :))];\n           \n        % keep all potential segments as data points\n        sind = find(smap==newseg); \n        for ni = neighborseg\n            smap2 = smap;\n            smap2(sind) = ni;\n            if ni~=newseg\n                sind2 = find(smap2 > newseg);\n                smap2(sind2) = smap2(sind2) - 1;\n                if ni > newseg\n                    ni = ni - 1;\n                end\n            end\n            count = count + 1;\n            \n            data(count, :) = mcmcGetSegmentationFeatures(pvSP, phSP, pE, adjlist{f}, imsegs(f).npixels, smap2, ni);\n            %data(count, :) = mcmcGetSegmentFeatures(imsegs(f), spdata{f}, imdata, smap2, ni);\n            \n            labels(count) = getMixUniLabel(imsegs(f), smap2, ni); % 0 for mix, 1 for uni\n            \n            imind(count) = f;\n            \n            if count == nsegments \n                break;\n            end\n            \n        end      \n        \n        % remove possibility of returning to previous state\n        if numel(neighborseg)>1\n            neighborseg(find(neighborseg==origseg)) = [];\n        end\n        \n        % randomly select neighbor\n        nn = numel(neighborseg);\n        goodind = find(labels((count-nn+1):count)); % good neighbors\n        w = 0.25*ones(nn, 1);\n        w(goodind) = 0.5; % so that a uniform segment is twice as likely to be picked\n        w = cumsum(w / sum(w));\n        ri = find(rand(1) < w);           \n        \n        ni = neighborseg(ri(1)); % get neighbor segment\n        \n        % attach segment newseg to segment ni (unless newseg==ni)\n        smap(sind) = ni;\n        if ni~=newseg\n            sind2 = find(smap > newseg);\n            smap(sind2) = smap(sind2) - 1;           \n        end        \n        %figure(3), hist(smap, [1:max(smap)])        \n\n%         mask = zeros([size(im, 1) size(im, 2)]);       \n%         mask(find(smap(segimage)==ni)) = 1;        \n%         disp(num2str([max(smap) labels(count-nn+ri(1))]))\n%         figure(2), hold off, imagesc(im .* repmat(mask, [1 1 3])), axis image                         \n    end\n    \n    disp(num2str(mean(labels(1:count)==1)))\n    \nend\n\n% remove segments that are not clearly good or bad\nind = find(labels==0);\nlabels(ind) = [];\ndata(ind, :) = [];\nimind(ind) = [];\n% end mcmcGenerateRandomSegments3\n\n            \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\nfunction label = getMixUniLabel(imsegs, smap, si)\n% returns -1 for mixed; 0 for neither; 1 for uniform\n\nlcount = zeros(numel(imsegs.label_names), 1);\nsind = find(smap==si);\n\nfor k = sind'    \n    slab = imsegs.labels(k);\n    if slab > 0\n        lcount(slab) = lcount(slab) + imsegs.npixels(k);\n    end\nend\nnpix = sum(lcount);\n\nif npix > 0 \n    lcount = lcount / npix;\nelse\n    label = 0;\n    return;\nend\n\nlabel = 0;\nif max(lcount) < 0.95 || ((1-max(lcount))*npix > 500)\n    label = -1;\nelseif max(lcount) > 0.99\n    label = 1;\nend\n    \n    \n    \n\n        ", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/mcmc/mcmcGenerateRandomSegments3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2302356549067516}}
{"text": "function [poly,poly_idx,opendat,boudat] = extract_boundary(v_start,v_end,bnde,pts,order,opendat,boudat,type,type2)\n% DESCRIPTION: Given a set of boundary edges and a starting and ending index\n%              of a singly- or multi-polygonal region, organize them in a\n%              winding order and/or add them to an existing opendat/boudat\n%              structure. The program breaks up the boundary so that it\n%              will never exceed 100,000 nodes to avoid memory allocation\n%              issues adcprep.\n%\n% INPUTS:\n%      v_start: the starting index of the boundary you want to trace\n%        v_end: the ending index of the boundary you want to trace.\n%         bnde: the indices of each boundary edge as a nbnde x 2 matrix\n%         pts:  the x,y locations of all the points in the region\n%               stored as an np x 2 matrix.\n%         order:the order in which the traversal takes place\n%               counter-clockwise (0) or clockwise (1).\n%         opendat: open boundary information from a pre-existing grid\n%          boudat: land boundary information from a pre-exist\n% OUTPUTS:\n%          poly: the boundary of each enclosing polygon sorted in winding-order\n%                poly is returned as a cell-array of length number of polys.\n%      poly_idx: indices of the polygon coordinates in the same format as\n%                poly\n%       opendat: open boundary information with appened open bou\n%       boudat: land boundary information with appended land bou\n%         type: flux(1) or elevation (2) type bc\n%        type2: if flux, zero flux (20) or non-zero flux river (22) bc\n%\n% kjr,UND,CHL,2017\n%\n%                                           TRAVERSAL METHOD\n% Pick any unvisited edge segment [v_start,v_next] and add these vertices to the polygon loop.\n% Find the unvisited edge segment [v_i,v_j] that has either v_i = v_next or v_j = v_next and add the other vertex (the one not equal to v_next) to the polygon loop.\n% Reset v_next as this newly added vertex, mark the edge as visited and continue from 2.\n% Traversal is done when we get back to v_start.\n% NOTE: that the signed area will be positive if the vertices are\n% oriented counterclockwise, and will be negative if it is oriented clockwise\nbnde= unique(bnde,'rows');\nactive = true(size(bnde,1),1);\np = 0;\nexceed = 50e3; %100e3;\n\n[rt,~] = find(v_start==bnde);\nif isempty(rt), disp('v_start does not exist on boundary, check numbering'); return; end\nr  = rt(order+1); % change this only here to from 1 to 2 or 2 to 1 to go left or right\ntsel = bnde(r,:);\nsel  = tsel(tsel~=v_start);\nv_next = sel;\nactive(r) = 0;\n% cut up boundary so land boundary never exceeds 100k nodes.\ncut = true;\nwhile cut\n    p = p + 1;\n    if(p > 1 )\n        [rt,~] = find(v_next==bnde & active);\n        r  = rt(1);\n        tsel = bnde(r,:);\n        sel  = tsel(tsel~=v_next);\n        v_next = sel;\n        active(r) = 0;\n    end\n    \n    temp = [];\n    temp2= [];\n    \n    temp  = pts(bnde(r,:)',:);\n    temp2 = bnde(r,:)';\n    if v_next ~= temp2(2)\n      % swap \n      temp = flipud(temp); \n      temp2 = flipud(temp2); \n    end\n    \n    k = 2;\n    while v_next~=v_end % terminates when we reach v_end\n        rt= (v_next==bnde(:,1) | v_next==bnde(:,2)) &  active;\n        r = find(rt,1);\n        tsel = bnde(r,:);\n        sel=tsel(tsel~=v_next);\n        k = k + 1;\n        temp(k,:)= pts(sel,:);\n        temp2(k,:)= sel;\n        active(r) = 0;\n        v_next = sel;\n        % exceeded max xize, break\n        if (k > exceed),disp('exceed'); break, end\n        % reached ending vertex, break\n        if(v_next==v_end), cut=false; disp('reached ending'); end\n        % exhausted all edges and couldn't connect\n        if(~any(active)), cut=false; disp('coudln''t conntect'); break, end\n    end\n    if length(temp) == 2\n        cut = false;\n    end\n    poly{p}     = temp;\n    poly_idx{p} = temp2;\n    [area] = parea(poly{p}(:,1),poly{p}(:,2));\n    if order == 0 % ccw\n        if sign(area)<0\n            poly{p} = flipud(poly{p});\n            poly_idx{p} = flipud(poly_idx{p});\n        end\n    else % cw\n        if sign(area)>0\n            poly{p} = flipud(poly{p});\n            poly_idx{p} = flipud(poly_idx{p});\n        end\n    end\nend\nfor ii = 1 : p\n    hold on; plot(poly{ii}(:,1),poly{ii}(:,2),'r-','linewi',2);\nend\n\nif ~exist('type','var') \n   type = input('What kind of boundary is this, 1 (flux) or 2 (elevation)?');\nend\n\n% if populated\nif ~isempty(boudat)\n    if(type==1)\n        nbou = boudat.nbou;\n        nvel = boudat.nvel;\n        nvell= boudat.nvell;\n        nbvv = boudat.nbvv;\n        ibtype = boudat.ibtype;\n        if ~exist('type2','var') \n           type2 = input('What kind of flux boundary is it, 20 (Mainland), 21 (Island), 22 (River)?');\n        end\n        for ii = 1 : length(poly)\n            nbou = nbou + 1;\n            nvell(nbou) = length(poly{ii}(:,1));\n            nvel = nvel + nvell(nbou);\n            nbvv(1:nvell(nbou),nbou) = int32(poly_idx{ii}(:));\n            ibtype(nbou) = type2;\n        end\n        boudat.nbou = nbou ;\n        boudat.nvel = nvel ;\n        boudat.nvell = nvell ;\n        boudat.ibtype = ibtype ;\n        boudat.nbvv = nbvv ;\n    end\nend\n\n% if populated \nif ~isempty(opendat)\n    if type==2\n        nope = opendat.nope;\n        nvdll= opendat.nvdll;\n        neta = opendat.neta;\n        ibtype=opendat.ibtype;\n        nbdv  = opendat.nbdv;\n        \n        for ii = 1 : length(poly)\n            nope = nope + 1;\n            nvdll(nope) = length(poly_idx{ii}(:,1));\n            neta = neta + nvdll(nope);\n            ibtype(nope) = 0;\n            nbdv(1:nvdll(nope),nope) = poly_idx{ii}(:,1);\n        end\n        % ocean boundary\n        opendat.nope = nope ;\n        opendat.neta = neta ;\n        opendat.nvdll = nvdll ;\n        opendat.ibtype = ibtype ;\n        opendat.nbdv = nbdv ;\n        \n    end\nend\n\n% if empty \nif isempty(opendat)\n    if(type==2)\n        % nothing populated\n        nope = 0 ; \n        nvdll = []  ; \n        neta = 0 ; \n        nbdv = [] ; \n        for ii = 1 : length(poly)\n            nope = nope + 1;\n            nvdll(nope) = length(poly_idx{ii}(:,1));\n            neta = neta + nvdll(nope);\n            ibtype(nope) = 0;\n            nbdv(1:nvdll(nope),nope) = poly_idx{ii}(:,1);\n        end\n        % ocean boundary\n        opendat.nope = nope ;\n        opendat.neta = neta ;\n        opendat.nvdll = nvdll ;\n        opendat.ibtype = ibtype ;\n        opendat.nbdv = nbdv ;\n    end\nend\n\n% if empty \nif isempty(boudat)\n    if type==1\n        nbou = 0; nvel = 0; nvell = []; nbbv = [] ; \n        if ~exist('type2','var') \n           type2 = input('What kind of flux boundary is it, 20(island),22(River)?');\n        end\n        for ii = 1 : length(poly)\n            nbou = nbou + 1;\n            nvell(nbou) = length(poly{ii}(:,1));\n            nvel = nvel + nvell(nbou);\n            nbvv(1:nvell(nbou),nbou) = poly_idx{ii}(:);\n            ibtype(nbou) = type2;\n        end\n        boudat.nbou = nbou ;\n        boudat.nvel = nvel ;\n        boudat.nvell = nvell ;\n        boudat.ibtype = ibtype ;\n        boudat.nbvv = nbvv ;\n    end\nend\n\nend\n% helper function, computes area of polygon\nfunction [area]=parea(x,y)\nn    = length(x);\nxp   = [x; x(1)];\nyp   = [y; y(1)];\narea = 0;\nfor i = 1:n\n    area = area + det([xp(i), xp(i+1); yp(i), yp(i+1)]);\nend\narea = 1/2*area;\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/extract_boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.23023565490675157}}
{"text": "%evaluate on the val2 set from imagenet2013 \n%use the default parameters as used in the demo:\n%% load pre-trained edge detection model and set opts (see edgesDemo.m)\naddpath(genpath('../'));\n\nmodel=load('models/forest/modelBsds'); model=model.model;\nmodel.opts.multiscale=0; model.opts.sharpen=2; model.opts.nThreads=4;\n\n%% set up opts for edgeBoxes (see edgeBoxes.m)\nopts = edgeBoxes;\nopts.alpha = .65;     % step size of sliding window search\nopts.beta  = .75;     % nms threshold for object proposals\nopts.minScore = .01;  % min score of boxes to detect\nopts.maxBoxes = 1e4;  % max number of boxes to detect\n\n\n%config specifies the image location location to save output etc.\nconfig=createConfig();\nimageLoc=config.path.imageLoc;\nsaveLoc=config.path.outputLoc;\next=config.opts.imageExt;\n\nimageExt=config.opts.imageExt;\nimages=dir([imageLoc '*' imageExt]);\n\n\nfor i=1:length(images)\n\n\timageName=images(i).name;\n\tim=imread([imageLoc imageName]);\n\tif(size(im, 3) == 1)\n\t\tim=repmat(im,[1,1,3]);\n\tend\n\tbbs=edgeBoxes(im,model,opts);\n\tif(isfield((config.opts),'numProposals'))\n\t\tnumProposals=config.opts.numProposals;\n\t        if(size(bbs,1)>=numProposals)\n        \t        bbs=bbs(1:numProposals);\n        \telse\n                \tfprintf('Only %d proposals were generated for image: %s\\n',size(bbs,1),imageName);\n        \tend\n\tend\n \t%edges boxes produces baoxes as \"[x y w, h]\"\n\t%we convert to [x y x+w y+h]==[xmin ymin xmax ymax]\n        boxes=bbs(:,1:4);\n\tboxes=[boxes(:,1) boxes(:,2) boxes(:,1)+ boxes(:,3) boxes(:,2)+boxes(:,4)];\n\tproposals.boxes= boxes;\n\tproposalFileName=strrep(imageName,imageExt,'.mat');\n\n\tsave([saveLoc proposalFileName], 'proposals');\nend\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/edgeBoxes/releaseV3/experimentsMLPlab/generateProposalsForImages.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23023564916092623}}
{"text": "function wt = wfbtput(d,k,w,wt,forceStr)\n%WFBTPUT  Put node to the filterbank tree\n%   Usage:  wt = wfbtput(d,k,w,wt);\n%           wt = wfbtput(d,k,w,wt,'force');\n%\n%   Input parameters:\n%           d   : Level in the tree (0 - root).\n%           k   : Index (array of indexes) of the node at level *d* (starting at 0).\n%           w   : Node, basic wavelet filterbank.\n%           wt  : Wavelet filterbank tree structure (as returned from\n%                 |wfbtinit|).\n%\n%   Output parameters:\n%           wt : Modified filterbank structure.\n%\n%   `wfbtput(d,k,w,wt)` puts the basic filterbank *w* to the filter\n%   tree structure *wt* at level *d* and index(es) *k*. The output is a\n%   modified tree structure. *d* and *k* have to specify unconnected output\n%   of the leaf node. Error is issued if *d* and *k* points to already\n%   existing node. For possible formats of parameter *w* see help of |fwt|.\n%   Parameter *wt* has to be a structure returned by |wfbtinit|.\n%   \n%   `wfbtput(d,k,w,wt,'force')` does the same but replaces node at *d* and *k*\n%   if it already exists. If the node to be replaced has any children, \n%   the number of outputs of the replacing node have to be equal to number of\n%   outputs of the node beeing replaced.\n%\n%   Examples:\n%   ---------\n%\n%   This example shows magnitude frequency responses of a tree build from\n%   the root:::\n%\n%      % Initialize empty struct\n%      wt = wfbtinit();\n%      % Put root node to the empty struct\n%      wt1 = wfbtput(0,0,'db8',wt);\n%      % Connect a different nodes to both outputs of the root\n%      wt2 = wfbtput(1,[0,1],'db10',wt1);\n%      % Connect another nodes just to high-pass outputs of nodes just added\n%      wt3 = wfbtput(2,[1,3],'db10',wt2);\n%      % Add another node at level 3\n%      wt4 = wfbtput(3,1,'db16',wt3);\n%      \n%      % Create identical filterbanks\n%      [g1,a1] = wfbt2filterbank(wt1,'freq');\n%      [g2,a2] = wfbt2filterbank(wt2,'freq');\n%      [g3,a3] = wfbt2filterbank(wt3,'freq');\n%      [g4,a4] = wfbt2filterbank(wt4,'freq');\n%\n%      % Plot frequency responses of the growing tree. Linear scale \n%      % (both axis) is used and positive frequencies only are shown.\n%      subplot(4,1,1);\n%      filterbankfreqz(g1,a1,1024,'plot','linabs','posfreq');\n%      subplot(4,1,2);\n%      filterbankfreqz(g2,a2,1024,'plot','linabs','posfreq');\n%      subplot(4,1,3);\n%      filterbankfreqz(g3,a3,1024,'plot','linabs','posfreq');\n%      subplot(4,1,4);\n%      filterbankfreqz(g4,a4,1024,'plot','linabs','posfreq');\n%\n\n% AUTHOR: Zdenek Prusa\n  \nif nargin<4\n   error('%s: Too few input parameters.',upper(mfilename)); \nend\n\n%if isfield(wt,'dualnodes')\n%    error('%s: Cannot modify the dual-tree struct.',upper(mfilename));\n%end\n\ndo_force = 0;\nif nargin==5\n    if ~ischar(forceStr)\n        error('%s: Fifth parameter should be a string.',upper(mfilename));\n    end\n    if strcmpi(forceStr,'force')\n        do_force = 1;\n    end\nend\n\n% This was replaced. Calling ltfatargheler was too slow.\n%definput.flags.force = {'noforce','force'};\n%[flags,kv]=ltfatarghelper({},definput,varargin);\n\nnode = fwtinit(w);\n\noldnodecount = numel(wt.nodes);\nnodeschanged = [];\n\n[nodeNoArray,nodeChildIdxArray] = depthIndex2NodeNo(d,k,wt);\n\nfor ii=1:numel(nodeNoArray)\n nodeNo = nodeNoArray(ii);\n nodeChildIdx = nodeChildIdxArray(ii);\nif(nodeNo==0)\n    % adding root \n    if(~isempty(find(wt.parents==0,1)))\n        if(do_force)\n           rootId = find(wt.parents==0,1);\n           % if root has children, check if the new root has the same\n           % number of them\n           if(~isempty(find(wt.children{rootId}~=0,1)))\n              if(length(w.g)~=length(wt.nodes{rootId}.g))\n                 error('%s: The replacing root have to have %d filters.',mfilename,length(wt.nodes{rootId}.g)); \n              end\n           end\n        else\n            error('%s: Root already defined. Use FORCE option to replace.',mfilename);  \n        end\n        wt.nodes{rootId} = node;\n        nodeschanged(end+1) = rootId;\n        \n        if isfield(wt,'dualnodes') \n            wt.dualnodes{rootId} = node; \n        end\n        continue;\n    end\n    wt.nodes{end+1} = node;\n    wt.parents(end+1) = nodeNo;\n    wt.children{end+1} = [];\n    \n    if isfield(wt,'dualnodes') \n        wt.dualnodes{end+1} = node; \n    end\n    continue;\nend\n\nchildrenIdx = find(wt.children{nodeNo}~=0);\nfound = find(childrenIdx==nodeChildIdx,1);\nif(~isempty(found))\n   if(do_force)\n     %check if childrenIdx has any children\n     tmpnode = wt.children{nodeNo}(found);  \n     if(~isempty(find(wt.children{tmpnode}~=0, 1)))\n         if length(node.g)~=length(wt.nodes{tmpnode}.g)\n            error('%s: The replacing node must have %d filters.',mfilename,length(wt.nodes{tmpnode}.g)); \n         end\n     end\n     wt.nodes{tmpnode} = node;\n     nodeschanged(end+1) = tmpnode;\n     if isfield(wt,'dualnodes') \n         wt.dualnodes{tmpnode} = node; \n     end\n     % Since we are replacing a node, all links are already correct\n     continue;\n   else\n       error('%s: Such node (depth=%d, idx=%d) already exists. Use FORCE option to replace.',mfilename,d,k); \n   end\nend\n\nwt.nodes{end+1} = node;\nwt.parents(end+1) = nodeNo;\nwt.children{end+1} = [];\nwt.children{nodeNo}(nodeChildIdx) = numel(wt.parents);\n\nif isfield(wt,'dualnodes') \n    wt.dualnodes{end+1} = node; \nend\n\nend\n\n% We have to correctly shuffle filters in the just added (or modified) filters\n% if the tree was already defined as frequency ordered.\nif wt.freqOrder\n      wt = nat2freqOrder(wt,[nodeschanged,oldnodecount+1:numel(wt.nodes)]);\nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/wavelets/wfbtput.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23023564341510075}}
{"text": "% dipfit_erpeeg - fit multiple component dipoles using DIPFIT \n%\n% Usage:\n%         >> [ dipole model EEG] = dipfit_erpeeg(data, chanlocs, 'key', 'val', ...);\n%\n% Inputs:\n%  data      - input data [channel x point]. One dipole per point is\n%              returned.\n%  chanlocs  - channel location structure (returned by readlocs()).\n%\n% Optional inputs:\n%  'settings'  - [cell array] dipfit settings (arguments to the \n%                pop_dipfit_settings() function). Default is none.\n%  'dipoles'   - [1|2] use either 1 dipole or 2 dipoles contrain in\n%                symetry. Default is 1.\n%  'dipplot'   - ['on'|'off'] plot dipoles. Default is 'off'.\n%  'plotopt'   - [cell array] dipplot() 'key', 'val' options. Default is\n%                'normlen', 'on', 'image', 'fullmri'\n%\n% Outputs:\n%  dipole      - dipole structure ('posxyz' field is the position; 'momxyz'\n%                field is the moment and 'rv' the residual variance)\n%  model       - structure containing model information ('vol.r' field is \n%                radius, 'vol.c' conductances, 'vol.o' the 3-D origin and\n%                'chansel', the selected channels).\n%  EEG         - faked EEG structure containing erp activation at the place\n%                of ICA components but allowing to plot ERP dipoles.\n%\n% Note: residual variance is set to NaN if Dipfit does not converge\n%  \n% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Nov. 2003\n\n% Copyright (C) 10/2003 Arnaud Delorme, SCCN/INC/UCSD, arno@sccn.ucsd.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [dipoles, model, EEG] = dipfit_erpeeg(DATA, chanlocs, varargin);\n    \n    if nargin < 1\n        help dipfit_erpeeg;\n        return;\n    end;\n    \n    ncomps = size(DATA,2);\n    if size(DATA,1) ~= length(chanlocs)\n        error('# of row in ''DATA'' must equal # of channels in ''chanlocs''');\n    end;\n        \n    % faking an EEG dataset\n    % ---------------------\n    EEG          = eeg_emptyset;\n    EEG.data     = rand(size(DATA,1), 1000);\n    EEG.nbchan   = size(DATA,1);\n    EEG.pnts     = 1000;\n    EEG.trials   = 1;\n    EEG.chanlocs = chanlocs;\n    EEG.icawinv    = [ DATA DATA ];\n    EEG.icaweights = zeros(size([ DATA DATA ]))';\n    EEG.icasphere  = zeros(size(DATA,1), size(DATA,1));\n    %EEG            = eeg_checkset(EEG);\n    EEG.icaact     = EEG.icaweights*EEG.icasphere*EEG.data(:,:);\n    EEG.icaact     = reshape( EEG.icaact, size(EEG.icaact,1), size(EEG.data,2), size(EEG.data,3));\n    \n    % uses mutlifit to fit dipoles\n    % ----------------------------\n    EEG            = pop_multifit(EEG, [1:ncomps], varargin{:});\n    \n    % process outputs\n    % ---------------\n    dipoles = EEG.dipfit.model;\n    if isfield(dipoles, 'active')\n        dipoles = rmfield(dipoles, 'active');\n    end;\n    if isfield(dipoles, 'select')\n        dipoles = rmfield(dipoles, 'select');\n    end;\n    model   = EEG.dipfit;\n    if isfield(model, 'model')\n        model   = rmfield(model, 'model');\n    end;\n    return;\n    \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/dipfit_erpeeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2302306371364612}}
{"text": "% StackExchange Signal Processing Q79314\n% https://dsp.stackexchange.com/questions/79314\n% Image Segmentation Using Deep Learning\n% References:\n%   1.  \n% Remarks:\n%   1.  B\n% TODO:\n% \t1.  C\n% Release Notes\n% - 1.0.000     27/11/2021\n%   *   First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx           = 0;\nfigureCounterSpec   = '%04d';\n\ngenerateFigures = ON;\n\n\n%% Simulation Parameters\n\nimageSetFolderName  = 'ImageSet';\nmaskSetFolderName   = 'MaskSet';\n\nresizePostName = 'Resize';\n\nnumRows     = 64; \nnumCols     = 64; \n\n\n%% Generate Data\n\nsFiles = dir(strcat(imageSetFolderName, resizePostName, FILE_SEP, '*.jpg'));\nfor ii = 1:length(sFiles)\n    mI = imread(strcat(sFiles(ii).folder, FILE_SEP, sFiles(ii).name));\n    assert(size(mI, 1) == numRows);\n    assert(size(mI, 2) == numCols);\n    assert(size(mI, 3) == 3);\nend\n\nsFiles = dir(strcat(maskSetFolderName, resizePostName, FILE_SEP, '*.png'));\nfor ii = 1:length(sFiles)\n    mI = imread(strcat(sFiles(ii).folder, FILE_SEP, sFiles(ii).name));\n    assert(size(mI, 1) == numRows);\n    assert(size(mI, 2) == numCols);\n    assert(size(mI, 3) == 1);\nend\n\n\n%% Restore Defaults\n\n% set(0, 'DefaultFigureWindowStyle', 'normal');\n% set(0, 'DefaultAxesLooseInset', defaultLoosInset);\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q79314/VerifyPhotos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23017174404733068}}
{"text": "% subsref() - index eegdata class\n%\n% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008\n\n% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction res = subsref(obj,s)\n\n    if strcmpi(s(1).type, '.')\n        res = builtin('subsref', obj, s);\n        return;\n    end;\n    \n    tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });\n\n    subs = s(1).subs;\n    finaldim = cellfun('length', subs);\n    \n    % one dimension input\n    % -------------------\n    if length(s) > 1 || ~strcmpi(s(1).type, '()')\n        error('MMO can only map single array data files');\n    end;\n    \n    % deal with transposed data\n    % -------------------------\n    if obj.transposed, s = transposeindices(obj, s); end;\n\n    % convert : to real sizes\n    % -----------------------\n    lastdim = length(subs);\n    if isstr(subs{end}) && ndims(obj) > lastdim\n        for index = lastdim+1:ndims(obj)\n            if index > length(obj.dimensions)\n                subs{index} = 1;\n            else\n                subs{index} = [1:obj.dimensions(index)]; \n            end;\n        end;\n    end;\n    for index = 1:length(subs)\n        if isstr(subs{index}) % can only be \":\"\n            if index > length(obj.dimensions)\n                subs{index} = 1;\n            else\n                subs{index} = [1:obj.dimensions(index)]; \n            end;\n        end;\n    end;\n    finaldim = cellfun(@length, subs);\n    finaldim(lastdim) = prod(finaldim(lastdim:end));\n    finaldim(lastdim+1:end) = [];\n\n    % non-transposed data\n    % -------------------\n    res = tmpMMO.data.x(subs{:});\n    if length(finaldim) == 1, finaldim(2) = 1; end;\n    res = reshape(res, finaldim);\n    if obj.transposed\n        if finaldim(end) == 1, finaldim(end) = []; end;\n        if length(finaldim) <= 2, res = res';\n        else\n            res = reshape(res, [finaldim(1)*finaldim(2) finaldim(3)])';\n            res = reshape(res, [finaldim(3) finaldim(1) finaldim(2)]);\n        end;\n    end;\n    \n        \n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/@mmo/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23017174404733068}}
{"text": "classdef GradientVariationWithRadiusExperiment < handle\n       \n    properties (Access = private)\n       iMesh\n       gExperiment\n    end\n    \n    properties (Access = private)\n       nameCase\n       inputFiles\n       outputFolder\n       levelSetParams         \n    end\n    \n    methods (Access = public)\n        \n        function obj = GradientVariationWithRadiusExperiment(s)\n            obj.init(s);\n        end\n        \n        function compute(obj)\n            for im = 1:numel(obj.inputFiles)\n                obj.iMesh = im;\n                obj.createGradientVariationExperiment();\n                obj.computeGradientVariationWithRadius();\n            end\n        end\n    end\n        \n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.nameCase       = cParams.nameCase;\n            obj.inputFiles     = cParams.inputFiles; \n            obj.outputFolder   = cParams.outputFolder;\n            obj.levelSetParams = cParams.levelSetParams;            \n        end\n        \n        function createGradientVariationExperiment(obj)\n            s.inputFile = obj.inputFiles{obj.iMesh};\n            s.iMesh     = obj.iMesh;\n            s.levelSetParams = obj.levelSetParams;            \n            g = GradientVariationExperiment(s);\n            obj.gExperiment = g;\n        end\n        \n        function computeGradientVariationWithRadius(obj) \n            s.mesh                 = obj.gExperiment.backgroundMesh;\n            s.regularizedPerimeter = obj.gExperiment.regularizedPerimeter;\n            s.inputFile            = obj.inputFiles{obj.iMesh};\n            s.nameCase             = obj.nameCase;\n            s.outputFolder         = obj.outputFolder;\n            s.domainLength         = obj.gExperiment.domainLength();            \n            gComputer = GradientVariationWithRadiusComputer(s);\n            gComputer.compute();\n        end                 \n        \n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/PerimeterExperiments/GradientVariationWithRadiusExperiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23017174404733065}}
{"text": "function [warnings,errors] = svargplvmCheckSNR(SNR, errLimit, warLimit, throwError,displ)\n% SVARGPLVMCHECKSNR Check Signal to Noise Ratio after\n% optimisation, to ensure that the trivial local minimum\n% of learning only noise is avoided.\n% DESC Check SNR of optimised model\n% FORMAT\n% ARG SNR: the SNR of optiomised model in a cell array (one cell per\n% modality)\n% ARG errLimit: Optional, the limit below which an error message\n% is printed\n% ARG warLimit: Optional, the limit below which a warning message\n% is printed\n% RETURN warnings: in an array, representing all modalities where\n% the SNR is low enough to be considered a warning\n%\n% COPYRIGHT: Andreas C. Damianou, 2013\n%\n% VARGPLVM\n\nif nargin < 5 || isempty(displ), displ = true; end\nif nargin < 4 || isempty(throwError), throwError = true; end \nif nargin < 3 || isempty(warLimit), warLimit = 10; end\nif nargin < 2 || isempty(errLimit), errLimit = 2; end\nif nargin < 1, error('Not enough arguments given'); end\n\nerrStr = sprintf(['\\nThis means that a bad local minimum has been reached\\n', ...\n    'where everything is explained by noise. Please try a different\\n', ...\n    'initialisation and/or consult the manual.\\n']);\nwarStr = sprintf(['\\nThis means that a bad local minimum has been reached\\n', ...\n    'where most signal is explained by noise. Consider trying a different\\n', ...\n    'initialisation and/or consult the manual.\\n']);\n\nerrors = [];\nwarnings = [];\nfor i = 1:length(SNR)\n    if ~isempty(SNR{i}) && SNR{i} <= errLimit\n        errors = [errors i];\n    end\nend\n\nif ~isempty(errors)\n    errMsg = 'Error! Low SNR in modalities: ';\n    errMsg = [errMsg num2str(errors)];\n    errMsg = [errMsg errStr];\n    if displ\n        for j=1:length(SNR)\n            fprintf('# SNR%d = %.6f\\n', j, SNR{j})\n        end\n    end\n    if throwError\n        error(errMsg);\n    end\nelse\n    for i = 1:length(SNR)\n        if ~isempty(SNR{i}) && SNR{i} <= warLimit\n            warnings = [warnings i];\n        end\n    end\nend\n\nif ~isempty(warnings) && displ\n    warMsg = 'WARNING! Low SNR in modalities: ';\n    warMsg = [warMsg num2str(warnings)];\n    warMsg = [warMsg warStr];\n    warning(warMsg);\nend", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/svargplvmCheckSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23017117030618786}}
{"text": "function incircle()     \n    %   Matlab script to input initial parameters for circle0 routine\n    %   in main Map Window\n    % turned into function by Celso G Reyes 2017\n    \n    error('replaced by circle_select_dlg');\n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n\n    %                                                R. Zuniga, 6/94\n    \n    report_this_filefun();\n    %\n    if isempty(ZG.newcat), \n        ZG.newcat = copy(ZG.primeCatalog); \n    end   % verify whether to start with\n    % original catalogue\n    % make the interface for input\n    %\n    fig=figure('ToolBar','none');\n    clf;\n    cla;\n    set(fig,'Name','Circle-Map Control Panel');\n    %  set(gcf,'visible','off');\n    set(gca,'visible','off');\n    set(fig,'pos',[ 0.22  0.4 0.30 0.30])\n    \n    %\n    freq_field1=uicontrol('Style','edit',...\n        'Position',[.80 .70 .15 .10],...\n        'Units','normalized','String',num2str(ZG.ni),...\n        'callback',@callbackfun_001);\n    \n    freq_field2=uicontrol('Style','edit',...\n        'Position',[.80 .55 .15 .10],...\n        'Units','normalized','String',num2str(rad),...\n        'callback',@callbackfun_002);\n    \n    freq_field3=uicontrol('Style','edit',...\n        'Position',[.70 .40 .22 .10],...\n        'Units','normalized','String',num2str(ya0,5),...\n        'callback',@callbackfun_003);\n    \n    freq_field4=uicontrol('Style','edit',...\n        'Position',[.70 .25 .22 .10],...\n        'Units','normalized','String',num2str(xa0,6),...\n        'callback',@callbackfun_004);\n    \n    close_button=uicontrol('Style','Pushbutton',...\n        'Position',[.05 .85 .15 .1 ],...\n        'Units','normalized','Callback',@(~,~)close(),'String','Cancel');\n    \n    button1=uicontrol('Style','Pushbutton',...\n        'Position',[.35 .15 .3 .1 ],...\n        'Units','normalized',...\n        'callback',@callbackfun_005,...\n        'String','Center by Cursor');\n    \n    button2=uicontrol('Style','Pushbutton',...\n        'Position',[.10 .05 .2 .1 ],...\n        'Units','normalized',...\n        'callback',@callbackfun_006,...\n        'String','Fix Radius');\n    \n    button3=uicontrol('Style','Pushbutton',...\n        'Position',[.70 .05 .3 .1 ],...\n        'Units','normalized',...\n        'callback',@callbackfun_007,...\n        'String','ni Closest Events');\n    \n    txt5 = text(...\n        'Position',[0. 0.75 0 ],...\n        'FontSize',ZmapGlobal.Data.fontsz.m ,...\n        'FontWeight','bold',...\n        'String','Number of events (ni):');\n    \n    txt4 = text(...\n        'Position',[0. 0.58 0 ],...\n        'FontSize',ZmapGlobal.Data.fontsz.m ,...\n        'FontWeight','bold',...\n        'String','Radius (km):');\n    \n    txt3 = text(...\n        'Position',[0. 0.41 0 ],...\n        'FontSize',ZmapGlobal.Data.fontsz.m ,...\n        'FontWeight','bold',...\n        'String','Latitude of center:');\n    \n    txt2 = text(...\n        'Position',[0. 0.24 0 ],...\n        'FontSize',ZmapGlobal.Data.fontsz.m ,...\n        'FontWeight','bold',...\n        'String','Longitude of center:');\n    \n    set(gcf,'visible','on');\n    \n    \n    \n    function callbackfun_001(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ZG.ni=str2double(mysrc.String);\n    end\n    \n    function callbackfun_002(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        rad=str2double(mysrc.String);\n    end\n    \n    function callbackfun_003(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ya0=str2double(mysrc.String);\n        mysrc.String=num2str(ya0,6);\n    end\n    \n    function callbackfun_004(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        xa0=str2double(mysrc.String);\n        mysrc.String=num2str(xa0,6);\n    end\n    \n    function callbackfun_005(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ic = 1;\n        circle0;\n    end\n    \n    function callbackfun_006(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ic = 2;\n        circle0;\n    end\n    \n    function callbackfun_007(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ic = 3;\n        circle0;\n    end\n    function circle0() \n        %   \"circle0\"  selects events by :\n        %   the Ni closest earthquakes to the center\n        %   the maximum radius of a circle.\n        %   the center point can be interactively selected or fixed by given\n        %   coordinates (as given by incircle).\n        %   Resets ZG.newcat and ZG.newt2.     Operates on the map window on  \"primeCatalog\".\n        %                                                  R.Z. 6/94\n        %\n        % turned into function by Celso G Reyes 2017\n        \n        ZG=ZmapGlobal.Data; % used by get_zmap_globals\n        \n        report_this_filefun();\n\n        delete(findobj('Tag','plos1'));\n        new = a;\n        figure(mess);\n        clf\n        set(gca,'visible','off')\n        \n        if ic == 1 | ic == 0\n            te = text(0.01,0.90,'\\newlinePlease use the LEFT mouse button or the cursor to \\newlineselect the center point. The coordinates of the center \\newlinewill be displayed on the control window.\\newline \\newlineOperates on the main subset of the catalogue. \\newlineEvents selected form the new subset to operate on (ZG.newcat).');\n            set(te,'FontSize',12);\n            \n            % Input center of circle with mouse\n            %\n            axes(h1)\n            \n            [xa0,ya0]  = ginput(1);\n            \n            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];\n            stri = stri1;\n            pause(0.1)\n            set(gcf,'Pointer','arrow')\n            plot(xa0,ya0,'+c');\n            incircle\n            \n            \n        elseif ic == 2\n            figure(map);\n            axes(h1)\n            ZG.newt2 = ZG.primeCatalog.selectRadius(ya0, xa0, rad,'kilometer');\n            %\n            % plot events on map as 'x':\n            \n            set(gca,'NextPlot','add')\n            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');\n            set(gcf,'Pointer','arrow')\n            \n            \n            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6) '; R = ' num2str(rad) ' km'];\n            stri = stri1;\n            ZG.newt2.sort('Date');\n            ZG.newcat = ZG.newt2;                   % resets ZG.newcat and ZG.newt2\n            ctp=CumTimePlot(ZG.newt2);\n            ctp.plot();\n            \n            ic = 1;\n            \n        elseif ic == 3\n            figure(map);\n            axes(h1)\n            %  calculate distance for each earthquake from center point\n            [ZG.newt2, max_km] = ZG.primeCatalog.selectClosestEvents(ya0, xa0, [], ni);\n            messtext = ['Radius of selected Circle: ' num2str(max_km)  ' km' ];\n            disp(messtext)\n            \n            \n            % plot events on map as 'x':\n            \n            set(gca,'NextPlot','add')\n            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');\n            set(gcf,'Pointer','arrow')\n            \n            ZG.newcat = ZG.newt2;                   % resets ZG.newcat\n            \n            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];\n            stri = stri1;\n            ctp=CumTimePlot(ZG.newt2);\n            ctp.plot();\n            \n            ic = 1;\n            \n        end      % if ic\n    end\n    \nend\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/circle_selections/incircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017117030618783}}
{"text": "function WriteMhaFile(filename, img_size, resolution, data_type, offset)\n% WRITEMHAFILE  Write the header part of a MetaImage file (.mha)\n%\n% WRITEMHAFILE(FILENAME, IMG_SIZE, RESOLUTION, DATA_TYPE, OFFSET)\n%\n%   FILENAME is the path and name of the file to be written, e.g.\n%   'foo.mha'.\n%\n%   IMG_SIZE is a 3-vector with the size of the output volume.\n%\n%   RESOLUTION is a 3-vector with the voxel size in the 3 directions.\n%\n%   DATA_TYPE is a string with the data type as given my Matlab, e.g.\n%   'uint8', 'short', 'uint16'.\n%\n%   OFFSET is a vector with the real world coordinates in metres (not index\n%   coordinates) of the first voxel in the volume. For example,\n%   OFFSET=[0.014552, 0.010486, 0.00142]. By default, OFFSET=[0 0 0].\n%\n%   See also: WriteRawFile, writemetaimagefile.\n\n% Author(s): Ramon Casero <rcasero@gmail.com> and Vicente Grau\n% Copyright \u00a9 2009-2012 University of Oxford\n% Version: 0.1.1\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\n% check arguments\nerror(nargchk(4, 5, nargin, 'struct'));\nerror(nargoutchk(0, 0, nargout, 'struct'));\n\n% defaults\nif (nargin < 5 || isempty(offset))\n    offset = [0.0 0.0 0.0];\nend\n\n[path, name] = fileparts(filename);\n\n% open file for writing\nfid=fopen(filename, 'w');\nif(fid<=0) \n    fprintf('Impossible to open file %s\\n', filename);\nend\n\nndims=numel(resolution);\n\nif(ndims == 3)\n    fprintf(fid, 'NDims = 3\\n');\n\n    fprintf(fid, 'DimSize = %d %d %d\\n', img_size(2), img_size(1), img_size(3));\n\n    if(strcmp(data_type, 'uint8'))\n        fprintf(fid, 'ElementType = MET_UCHAR\\n');\n    elseif(strcmp(data_type, 'short'))\n        fprintf(fid, 'ElementType = MET_SHORT\\n');\n    elseif (strcmp(data_type, 'uint16'))\n        fprintf(fid, 'ElementType = MET_USHORT\\n');\n    else\n        error('Not implemented data type')\n    end\n\n    fprintf(fid, 'Offset = %1.6f %1.6f %1.6f\\n', ...\n        offset(1), offset(2), offset(3));\n\n    fprintf(fid, 'ElementSpacing = %1.12f %1.12f %1.12f\\n', resolution(1), resolution(2), resolution(3));\n\nelseif(ndims==4)\n    fprintf(fid, 'NDims = 4\\n');\n\n    fprintf(fid, 'DimSize = %d %d %d %d\\n', img_size(2), img_size(1), img_size(3), img_size(4));\n\n    if(strcmp(data_type, 'uint8'))\n        fprintf(fid, 'ElementType = MET_UCHAR\\n');\n    elseif(strcmp(data_type, 'short'))\n        fprintf(fid, 'ElementType = MET_SHORT\\n');\n    elseif (strcmp(data_type, 'uint16'))\n        fprintf(fid, 'ElementType = MET_USHORT\\n');\n    else\n        error('Not implemented data type')\n    end\n\n    fprintf(fid, 'Offset = %1.6f %1.6f %1.6f\\n', ...\n        offset(1), offset(2), offset(3));\n\n    fprintf(fid, 'ElementSpacing = %1.12f %1.12f %1.12f %1.12f\\n', resolution(1), resolution(2), resolution(3), resolution(4));\n       \nend\n\nfprintf(fid, 'ElementByteOrderMSB = False\\n');\n\nfprintf(fid, 'ElementDataFile = %s\\n', [name, '.raw']);\n\nfclose(fid);\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/FileFormatToolbox/WriteMhaFile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2301711703061878}}
{"text": "function [source] = ft_sourcedescriptives(cfg, source)\n\n% FT_SOURCEDESCRIPTIVES computes descriptive parameters of the source\n% analysis results.\n%\n% Use as\n%   [source] = ft_sourcedescriptives(cfg, source)\n%\n% where cfg is a structure with the configuration details and source is the\n% result from a beamformer source estimation. The configuration can contain\n%   cfg.cohmethod        = 'regular', 'lambda1', 'canonical'\n%   cfg.powmethod        = 'regular', 'lambda1', 'trace', 'none'\n%   cfg.supmethod        = 'chan_dip', 'chan', 'dip', 'none' (default)\n%   cfg.projectmom       = 'yes' or 'no' (default = 'no')\n%   cfg.eta              = 'yes' or 'no' (default = 'no')\n%   cfg.kurtosis         = 'yes' or 'no' (default = 'no')\n%   cfg.keeptrials       = 'yes' or 'no' (default = 'no')\n%   cfg.keepcsd          = 'yes' or 'no' (default = 'no')\n%   cfg.keepnoisecsd     = 'yes' or 'no' (default = 'no')\n%   cfg.keepmom          = 'yes' or 'no' (default = 'yes')\n%   cfg.keepnoisemom     = 'yes' or 'no' (default = 'yes')\n%   cfg.resolutionmatrix = 'yes' or 'no' (default = 'no')\n%   cfg.feedback         = 'no', 'text' (default), 'textbar', 'gui'\n%\n% The following option only applies to timecourses.\n%   cfg.flipori          = 'yes' or 'no' (default = 'no')\n%\n% The following option only applies to single-trial timecourses.\n%   cfg.fixedori         = 'within_trials' or 'over_trials' (default = 'over_trials')\n%\n% If repeated trials are present that have undergone some sort of\n% resampling (i.e. jackknife, bootstrap, singletrial or rawtrial), the mean,\n% variance and standard error of mean will be computed for all source\n% parameters. This is done after applying the optional transformation\n% on the power and projected noise.\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_MATH\n\n% Copyright (C) 2004-2015, Robert Oostenveld & Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar source\nft_preamble provenance source\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% check if the input data is valid for this function\n% source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes');\n\n% cfg = ft_checkconfig(cfg, 'forbidden',   {'trials'});    % trial selection is not implented here, you may want to consider ft_selectdata\n\n% DEPRECATED by roboos on 13 June 2013\n% see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2199 for more details\n% support for this functionality can be removed at the end of 2013\ncfg = ft_checkconfig(cfg, 'deprecated',  {'transform'}); % please use ft_math instead\n\n% set the defaults\ncfg.transform        = ft_getopt(cfg, 'transform',        []);\ncfg.projectmom       = ft_getopt(cfg, 'projectmom',       'no'); % if yes -> svdfft\ncfg.numcomp          = ft_getopt(cfg, 'numcomp',          1);\ncfg.powmethod        = ft_getopt(cfg, 'powmethod',        []); % see below\ncfg.cohmethod        = ft_getopt(cfg, 'cohmethod',        []); % see below\ncfg.feedback         = ft_getopt(cfg, 'feedback',         'textbar');\ncfg.supmethod        = ft_getopt(cfg, 'supmethod',        'none');\ncfg.resolutionmatrix = ft_getopt(cfg, 'resolutionmatrix', 'no');\ncfg.eta              = ft_getopt(cfg, 'eta',              'no');\ncfg.fa               = ft_getopt(cfg, 'fa',               'no');\ncfg.kurtosis         = ft_getopt(cfg, 'kurtosis',         'no');\ncfg.keeptrials       = ft_getopt(cfg, 'keeptrials',       'no');\ncfg.trials           = ft_getopt(cfg, 'trials',           'all');\ncfg.keepcsd          = ft_getopt(cfg, 'keepcsd',          'no');\ncfg.keepmom          = ft_getopt(cfg, 'keepmom',          'yes');\ncfg.keepnoisecsd     = ft_getopt(cfg, 'keepnoisecsd',     'no');\ncfg.keepnoisemom     = ft_getopt(cfg, 'keepnoisemom',     'yes');\ncfg.fwhm             = ft_getopt(cfg, 'fwhm',             'no');\ncfg.fwhmremovecenter = ft_getopt(cfg, 'fwhmremovecenter', 0);\ncfg.fwhmmethod       = ft_getopt(cfg, 'fwhmmethod',       'barnes');\ncfg.fwhmmaxdist      = ft_getopt(cfg, 'fwhmmaxdist',      []);\ncfg.fixedori         = ft_getopt(cfg, 'fixedori',         'over_trials');\ncfg.flipori          = ft_getopt(cfg, 'flipori',          'no');\n\n% only works for mne\ncfg.demean         = ft_getopt(cfg, 'demean',         'yes');\ncfg.baselinewindow = ft_getopt(cfg, 'baselinewindow', [-inf 0]);\ncfg.zscore         = ft_getopt(cfg, 'zscore',         'yes');\n\nzscore = strcmp(cfg.zscore, 'yes');\ndemean = strcmp(cfg.demean, 'yes');\n\nif ischar(cfg.trials) && strcmp(cfg.trials,'all')\n  % do nothing\nelseif ischar(cfg.trials)\n  ft_error('only ''all'' is allowed for string input for cfg.trials');\nelse\n  % check whether there's a trial field in the source structure, and\n  % subselect, otherwise error\n  if isfield(source, 'trial')\n    source.trial = source.trial(cfg.trials);\n    if isfield(source, 'cumtapcnt'), source.cumtapcnt = source.cumtapcnt(cfg.trials,:); end\n  else\n    ft_error('subselecting trials in ft_sourcedescriptives is currently only possible with a ''trial'' field');\n  end\nend\n\n% get desired method from source structure\nsource.method = ft_getopt(source,'method',[]);\n\n% this is required for backward compatibility with the old sourceanalysis\nif isfield(source, 'method') && strcmp(source.method, 'randomized')\n  source.method = 'randomization';\nelseif isfield(source, 'method') && strcmp(source.method, 'permuted')\n  source.method = 'permutation';\nelseif isfield(source, 'method') && strcmp(source.method, 'jacknife')\n  source.method = 'jackknife';\nend\n\n% determine the type of data, this is only relevant for a few specific types\nispccdata = isfield(source, 'avg')   && isfield(source.avg, 'csdlabel');\nislcmvavg = isfield(source, 'avg')   && isfield(source, 'time') && isfield(source.avg,   'mom') && any(size(source.avg.pow)==1);\nislcmvtrl = isfield(source, 'trial') && isfield(source, 'time') && isfield(source.trial, 'mom');\nismneavg  = isfield(source, 'avg')   && isfield(source, 'time') && isfield(source.avg,   'mom') && size(source.avg.pow, 2)==numel(source.time);\n\n% check the consistency of the defaults\nif strcmp(cfg.projectmom, 'yes')\n  if isempty(cfg.powmethod)\n    cfg.powmethod = 'regular'; % set the default\n  elseif ~strcmp(cfg.powmethod, 'regular')\n    ft_error('unsupported powmethod in combination with projectmom');\n  end\n  if isempty(cfg.cohmethod)\n    cfg.cohmethod = 'regular'; % set the default\n  elseif ~strcmp(cfg.cohmethod, 'regular')\n    ft_error('unsupported cohmethod in combination with projectmom');\n  end\nelse\n  if isempty(cfg.powmethod)\n    cfg.powmethod = 'lambda1'; % set the default\n  end\n  if isempty(cfg.cohmethod)\n    cfg.cohmethod = 'lambda1'; % set the default\n  end\nend\n\n% this is required for backward compatibility with an old version of sourcedescriptives\nif isfield(cfg, 'singletrial'), cfg.keeptrials = cfg.singletrial;  end\n\n% do a validity check on the input data and specified options\nif strcmp(cfg.resolutionmatrix, 'yes')\n  if ~isfield(source.avg, 'filter')\n    ft_error('The computation of the resolution matrix requires keepfilter=''yes'' in sourceanalysis.');\n  elseif ~isfield(source, 'leadfield')\n    ft_error('The computation of the resolution matrix requires keepleadfield=''yes'' in sourceanalysis.');\n  end\nend\n\nif istrue(cfg.fwhm) && ~isfield(source.avg, 'filter')\n  ft_error('computation of the fwhm requires keepfilter=''yes'' in sourceanalysis.');\nend\n\nif istrue(cfg.eta) && strcmp(cfg.cohmethod, 'svdfft')\n  ft_error('eta cannot be computed in combination with the application of svdfft');\nend\n\nif istrue(cfg.keeptrials) && ~strcmp(cfg.supmethod, 'none')\n  ft_error('you cannot keep trials when you want to partialize something');\nend\n\nif istrue(cfg.flipori) && ~istrue(cfg.projectmom)\n  ft_error('flipori requires projectmom=''yes''');\nend\n\n% set some flags for convenience\nisnoise    = isfield(source, 'avg') && isfield(source.avg, 'noisecsd');\nkeeptrials = strcmp(cfg.keeptrials, 'yes');\nprojectmom = strcmp(cfg.projectmom, 'yes');\nflipori    = strcmp(cfg.flipori, 'yes');\n\n% determine the subfunction used for computing power\nswitch cfg.powmethod\n  case 'regular'\n    powmethodfun = @powmethod_regular;\n  case 'lambda1'\n    powmethodfun = @powmethod_lambda1;\n  case 'trace'\n    powmethodfun = @powmethod_trace;\n  case 'none'\n    powmethodfun = [];\n  otherwise\n    ft_error('unsupported powmethod');\nend\n\n% represent the selection of sources in the brain as a row-vector with indices\ninsideindx = find(source.inside(:)');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ispccdata\n  % the source reconstruction was computed using the pcc beamformer\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  \n  Ndipole = size(source.pos,1);\n  \n  if ischar(source.avg.csdlabel{1}), source.avg.csdlabel = {source.avg.csdlabel}; end\n  if numel(source.avg.csdlabel)==1\n    source.avg.csdlabel = repmat(source.avg.csdlabel, [Ndipole 1]);\n  end\n  \n  dipsel     = find(strcmp(source.avg.csdlabel{1}, 'scandip'));\n  refchansel = find(strcmp(source.avg.csdlabel{1}, 'refchan'));\n  refdipsel  = find(strcmp(source.avg.csdlabel{1}, 'refdip'));\n  supchansel = find(strcmp(source.avg.csdlabel{1}, 'supchan'));\n  supdipsel  = find(strcmp(source.avg.csdlabel{1}, 'supdip'));\n  \n  % cannot handle reference channels and reference dipoles simultaneously\n  if numel(refchansel)>0 && numel(refdipsel)>0\n    ft_error('cannot simultaneously handle reference channels and reference dipole');\n  end\n  \n  % these are only used to count the number of reference/suppression dipoles and channels\n  refsel = [refdipsel refchansel];\n  supsel = [supdipsel supchansel];\n  \n  % first do the projection of the moment, if requested\n  if projectmom\n    source.avg.ori = cell(1, Ndipole);\n    ft_progress('init', cfg.feedback, 'projecting dipole moment');\n    for i=insideindx\n      ft_progress(i/length(insideindx), 'projecting dipole moment %d/%d\\n', i, length(insideindx));\n      \n      if numel(source.avg.csdlabel)>1\n        dipsel     = find(strcmp(source.avg.csdlabel{i}, 'scandip'));\n        refchansel = find(strcmp(source.avg.csdlabel{i}, 'refchan'));\n        refdipsel  = find(strcmp(source.avg.csdlabel{i}, 'refdip'));\n        supchansel = find(strcmp(source.avg.csdlabel{i}, 'supchan'));\n        supdipsel  = find(strcmp(source.avg.csdlabel{i}, 'supdip'));\n        \n        % these are only used to count the number of reference/suppression dipoles and channels\n        refsel = [refdipsel refchansel];\n        supsel = [supdipsel supchansel];\n      end\n      \n      mom     = source.avg.mom{i}(dipsel,     :);\n      ref     = source.avg.mom{i}(refdipsel,  :);\n      sup     = source.avg.mom{i}(supdipsel,  :);\n      refchan = source.avg.mom{i}(refchansel, :);\n      supchan = source.avg.mom{i}(supchansel, :);\n      % compute the projection of the scanning dipole along the direction of the dominant amplitude\n      if length(dipsel)>1, [mom, rmom]  = svdfft(mom, cfg.numcomp, source.cumtapcnt); else rmom = []; end\n      source.avg.ori{i} = rmom;\n      % compute the projection of the reference dipole along the direction of the dominant amplitude\n      if length(refdipsel)>1, [ref, rref] = svdfft(ref, 1, source.cumtapcnt); else rref = []; end\n      % compute the projection of the supression dipole along the direction of the dominant amplitude\n      if length(supdipsel)>1, [sup, rsup] = svdfft(sup, 1, source.cumtapcnt); else rsup = []; end\n      \n      % compute voxel-level fourier-matrix\n      source.avg.mom{i} = cat(1, mom, ref, sup, refchan, supchan);\n      \n      % create rotation-matrix\n      rotmat = zeros(0, length(source.avg.csdlabel{i}));\n      if ~isempty(rmom)\n        rotmat = [rotmat; rmom zeros(1,numel(refsel)+numel(supsel))];\n      end\n      if ~isempty(rref)\n        rotmat = [rotmat; zeros(1, numel(dipsel)), rref, zeros(1,numel(refchansel)+numel(supsel))];\n      end\n      if ~isempty(rsup)\n        rotmat = [rotmat; zeros(1, numel(dipsel)+numel(refdipsel)), rsup, zeros(1,numel(refchansel)+numel(supchansel))];\n      end\n      for j=1:length(supchansel)\n        rotmat(end+1,:) = 0;\n        rotmat(end,numel(dipsel)+numel(refdipsel)+numel(supdipsel)+j) = 1;\n      end\n      for j=1:length(refchansel)\n        rotmat(end+1,:) = 0;\n        rotmat(end,numel(dipsel)+numel(refdipsel)+numel(supdipsel)+numel(supchansel)+j) = 1;\n      end\n      \n      % compute voxel-level csd-matrix\n      if isfield(source.avg, 'csd'), source.avg.csd{i}           = rotmat * source.avg.csd{i} * rotmat'; end\n      % compute voxel-level noisecsd-matrix\n      if isfield(source.avg, 'noisecsd'), source.avg.noisecsd{i} = rotmat * source.avg.noisecsd{i} * rotmat'; end\n      % compute rotated filter\n      if isfield(source.avg, 'filter'),   source.avg.filter{i}   = rotmat * source.avg.filter{i}; end\n      if isfield(source.avg, 'csdlabel')\n        % remember what the interpretation is of all CSD output components\n        scandiplabel = repmat({'scandip'}, 1, cfg.numcomp);          % only one dipole orientation remains\n        refdiplabel  = repmat({'refdip'},  1, length(refdipsel)>0);  % for svdfft at max. only one dipole orientation remains\n        supdiplabel  = repmat({'supdip'},  1, length(supdipsel)>0);  % for svdfft at max. only one dipole orientation remains\n        refchanlabel = repmat({'refchan'}, 1, length(refchansel));\n        supchanlabel = repmat({'supchan'}, 1, length(supchansel));\n        % concatenate all the labels\n        source.avg.csdlabel{i} = cat(2, scandiplabel, refdiplabel, supdiplabel, refchanlabel, supchanlabel);\n      end\n      \n      % compute rotated leadfield\n      % FIXME in the presence of a refdip and/or supdip, this does not work; leadfield is Nx3\n      if isfield(source,  'leadfield')\n        % FIXME this is a proposed dirty fix\n        n1 = size(source.leadfield{i},2);\n        %n2 = size(rotmat,2) - n1;\n        n2 = size(rotmat,2) - n1 +1; %added 1 JM\n        source.leadfield{i}    = source.leadfield{i} * rotmat(1:n2, 1:n1)';\n      end\n    end % for i=insideindx\n    ft_progress('close');\n    \n    % update the indices\n    dipsel     = find(strcmp(source.avg.csdlabel, 'scandip'));\n    refchansel = find(strcmp(source.avg.csdlabel, 'refchan'));\n    refdipsel  = find(strcmp(source.avg.csdlabel, 'refdip'));\n    supchansel = find(strcmp(source.avg.csdlabel, 'supchan'));\n    supdipsel  = find(strcmp(source.avg.csdlabel, 'supdip'));\n    refsel     = [refdipsel refchansel];\n    supsel     = [supdipsel supchansel];\n  end % if projectmom\n  \n  if keeptrials\n    cumtapcnt = source.cumtapcnt(:);\n    sumtapcnt = cumsum([0;cumtapcnt]);\n    Ntrial = length(cumtapcnt);\n    \n    ft_progress('init', cfg.feedback, 'computing singletrial voxel-level cross-spectral densities');\n    for triallop = 1:Ntrial\n      source.trial(triallop).csd = cell(Ndipole, 1);  % allocate memory for this trial\n      source.trial(triallop).mom = cell(Ndipole, 1);  % allocate memory for this trial\n      \n      ft_progress(triallop/Ntrial, 'computing singletrial voxel-level cross-spectral densities %d%d\\n', triallop, Ntrial);\n      for i=insideindx\n        dat = source.avg.mom{i};\n        tmpmom = dat(:, sumtapcnt(triallop)+1:sumtapcnt(triallop+1));\n        tmpcsd = (tmpmom * tmpmom') ./cumtapcnt(triallop);\n        source.trial(triallop).mom{i} = tmpmom;\n        source.trial(triallop).csd{i} = tmpcsd;\n      end % for i=insideindx\n    end % for triallop\n    ft_progress('close');\n    % remove the average, continue with separate trials, but keep track of\n    % the csdlabel\n    csdlabel = source.avg.csdlabel;\n    source   = rmfield(source, 'avg');\n  else\n    fprintf('using average voxel-level cross-spectral densities\\n');\n    csdlabel = source.avg.csdlabel;\n  end % if keeptrials\n  \n  % process the csdlabel for each of the dipoles\n  hasrefdip  = true;\n  hasrefchan = true;\n  hassupdip  = true;\n  hassupchan = true;\n  \n  dipselcell     = cell(Ndipole,1);\n  refdipselcell  = cell(Ndipole,1);\n  refchanselcell = cell(Ndipole,1);\n  supdipselcell  = cell(Ndipole,1);\n  supchanselcell = cell(Ndipole,1);\n  \n  for i = insideindx\n    dipsel     = find(strcmp(csdlabel{i}, 'scandip'));\n    refchansel = find(strcmp(csdlabel{i}, 'refchan'));\n    refdipsel  = find(strcmp(csdlabel{i}, 'refdip'));\n    supchansel = find(strcmp(csdlabel{i}, 'supchan'));\n    supdipsel  = find(strcmp(csdlabel{i}, 'supdip'));\n    \n    hasrefdip  = ~isempty(refdipsel)  && hasrefdip; %NOTE: it has to be true for all dipoles!\n    hasrefchan = ~isempty(refchansel) && hasrefchan;\n    hassupdip  = ~isempty(supdipsel)  && hassupdip;\n    hassupchan = ~isempty(supchansel) && hassupchan;\n    \n    dipselcell{i}     = dipsel;\n    refdipselcell{i}  = refdipsel;\n    refchanselcell{i} = refchansel;\n    supdipselcell{i}  = supdipsel;\n    supchanselcell{i} = supchansel;\n  end\n  \n  if keeptrials\n    % do the processing of the CSD matrices for each trial\n    if ~strcmp(cfg.supmethod, 'none')\n      ft_error('suppression is only supported for average CSD');\n    end\n    %dipselcell = mat2cell(repmat(dipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(dipsel));\n    %if hasrefdip,  refdipselcell  = mat2cell(repmat(refdipsel(:)',  [Ndipole 1]), ones(Ndipole,1), length(refdipsel));  end\n    %if hasrefchan, refchanselcell = mat2cell(repmat(refchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(refchansel)); end\n    %if hassupdip,  supdipselcell  = mat2cell(repmat(supdipsel(:)',  [Ndipole 1]), ones(Ndipole,1), length(supdipsel));  end\n    %if hassupchan, supchanselcell = mat2cell(repmat(supchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(supchansel)); end\n    \n    ft_progress('init', cfg.feedback, 'computing singletrial voxel-level power');\n    for triallop = 1:Ntrial\n      %initialize the variables\n      source.trial(triallop).pow = zeros(Ndipole, 1);\n      if hasrefdip,  source.trial(triallop).refdippow     = zeros(Ndipole, 1); end\n      if hasrefchan, source.trial(triallop).refchanpow    = zeros(Ndipole, 1); end\n      if hassupdip,  source.trial(triallop).supdippow     = zeros(Ndipole, 1); end\n      if hassupchan, source.trial(triallop).supchanpow    = zeros(Ndipole, 1); end\n      \n      ft_progress(triallop/Ntrial, 'computing singletrial voxel-level power %d%d\\n', triallop, Ntrial);\n      source.trial(triallop).pow(source.inside) = cellfun(powmethodfun, source.trial(triallop).csd(source.inside), dipselcell(source.inside));\n      if hasrefdip,  source.trial(triallop).refdippow(source.inside)  = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refdipselcell(source.inside));  end\n      if hassupdip,  source.trial(triallop).supdippow(source.inside)  = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supdipselcell(source.inside));  end\n      if hasrefchan, source.trial(triallop).refchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refchanselcell(source.inside)); end\n      if hassupchan, source.trial(triallop).supchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supchanselcell(source.inside)); end\n      %FIXME kan volgens mij niet\n      if isnoise && isfield(source.trial(triallop), 'noisecsd')\n        % compute the power of the noise projected on each source component\n        source.trial(triallop).noise = cellfun(powmethodfun,source.trial(triallop).csd, dipselcell);\n        if hasrefdip,  source.trial(triallop).refdipnoise  = cellfun(powmethodfun,source.trial(triallop).noisecsd, refdipselcell);  end\n        if hassupdip,  source.trial(triallop).supdipnoise  = cellfun(powmethodfun,source.trial(triallop).noisecsd, supdipselcell);  end\n        if hasrefchan, source.trial(triallop).refchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refchanselcell); end\n        if hassupchan, source.trial(triallop).supchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supchanselcell); end\n      end % if isnoise\n    end % for triallop\n    ft_progress('close');\n    \n    if strcmp(cfg.keepcsd, 'no')\n      source.trial = rmfield(source.trial, 'csd');\n    end\n    \n  else\n    % do the processing of the average CSD matrix\n    for i=insideindx\n      switch cfg.supmethod\n        case 'chan_dip'\n          supindx = [supdipsel supchansel];\n          if i==insideindx(1), refsel  = refsel - length(supdipsel); end % adjust index only once\n          refchanselcell{i} = refchanselcell{i} - length(supdipsel);\n          refdipselcell{i}  = refdipselcell{i} - length(supdipsel);\n        case 'chan'\n          supindx = supchansel;\n        case 'dip'\n          supindx = supdipsel;\n          if i==insideindx(1), refsel  = refsel - length(supdipsel); end\n          refchanselcell{i} = refchanselcell{i} - length(supdipsel);\n          refdipselcell{i}  = refdipselcell{i} - length(supdipsel);\n        case 'none'\n          % do nothing\n          supindx = [];\n      end\n      tmpcsd  = source.avg.csd{i};\n      scnindx = setdiff(1:size(tmpcsd,1), supindx);\n      tmpcsd  = tmpcsd(scnindx, scnindx) - tmpcsd(scnindx, supindx)*pinv(tmpcsd(supindx, supindx))*tmpcsd(supindx, scnindx);\n      source.avg.csd{i}   = tmpcsd;\n    end % for insideindx\n    % source.avg.csdlabel = source.avg.csdlabel(scnindx);\n    \n    if isnoise && ~strcmp(cfg.supmethod, 'none')\n      source.avg = rmfield(source.avg, 'noisecsd');\n    end\n    \n    % initialize the variables\n    source.avg.pow           = nan(Ndipole, 1);\n    if hasrefdip,  source.avg.refdippow     = nan(Ndipole, 1); end\n    if hasrefchan, source.avg.refchanpow    = nan(Ndipole, 1); end\n    if hassupdip,  source.avg.supdippow     = nan(Ndipole, 1); end\n    if hassupchan, source.avg.supchanpow    = nan(Ndipole, 1); end\n    if isnoise\n      source.avg.noise         = nan(Ndipole, 1);\n      if hasrefdip,  source.avg.refdipnoise     = nan(Ndipole, 1); end\n      if hasrefchan, source.avg.refchannoise    = nan(Ndipole, 1); end\n      if hassupdip,  source.avg.supdipnoise     = nan(Ndipole, 1); end\n      if hassupchan, source.avg.supchannoise    = nan(Ndipole, 1); end\n    end % if isnoise\n    if hasrefdip||hasrefchan, source.avg.coh    = nan(Ndipole, 1); end\n    if strcmp(cfg.eta, 'yes')\n      source.avg.eta           = nan(Ndipole, 1);\n      source.avg.ori             = cell(1, Ndipole);\n    end\n    if strcmp(cfg.eta, 'yes') && ~isempty(refsel)\n      source.avg.etacsd = nan(Ndipole, 1);\n      source.avg.ucsd   = cell(1, Ndipole);\n    end\n    if strcmp(cfg.fa, 'yes')\n      source.avg.fa = nan(Ndipole, 1);\n    end\n    \n    for i=insideindx\n      dipsel = dipselcell{i};\n      refchansel = refchanselcell{i};\n      refdipsel  = refdipselcell{i};\n      refsel     = [refchansel refdipsel];\n      supchansel = supchanselcell{i};\n\n      \n      % compute the power of each source component\n      if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1\n        source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipselcell{i},dipselcell{i}), 1);\n      else\n        source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipselcell{i},dipselcell{i}));\n      end\n      \n      if hasrefdip,  source.avg.refdippow(i)  = powmethodfun(source.avg.csd{i}(refdipsel,refdipsel));   end\n      %if hassupdip,  source.avg.supdippow(i)  = powmethodfun(source.avg.csd{i}(supdipsel,supdipsel));   end\n      if hasrefchan, source.avg.refchanpow(i) = powmethodfun(source.avg.csd{i}(refchansel,refchansel)); end\n      %if hassupchan, source.avg.supchanpow(i) = powmethodfun(source.avg.csd{i}(supchansel,supchansel)); end\n      if isnoise\n        % compute the power of the noise projected on each source component\n        if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1\n          source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipselcell{i},dipselcell{i}), 1);\n        else\n          source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipselcell{i},dipselcell{i}));\n        end\n        if hasrefdip,  source.avg.refdipnoise(i)  = powmethodfun(source.avg.noisecsd{i}(refdipsel,refdipsel));   end\n        if hassupdip,  source.avg.supdipnoise(i)  = powmethodfun(source.avg.noisecsd{i}(supdipsel,supdipsel));   end\n        if hasrefchan, source.avg.refchannoise(i) = powmethodfun(source.avg.noisecsd{i}(refchansel,refchansel)); end\n        if hassupchan, source.avg.supchannoise(i) = powmethodfun(source.avg.noisecsd{i}(supchansel,supchansel)); end\n      end % if isnoise\n      \n      if ~isempty(refsel)\n        % compute coherence\n        csd = source.avg.csd{i};\n        switch cfg.cohmethod\n          case 'regular'\n            % assume that all dipoles have been projected along the direction of maximum power\n            Pd                = abs(csd(dipsel, dipsel));\n            Pr                = abs(csd(refsel, refsel));\n            Cdr               = csd(dipsel, refsel);\n            source.avg.coh(i) = (Cdr.^2) ./ (Pd*Pr);\n          case 'lambda1'\n            % compute coherence the Joachim Gross' way\n            Pd                = lambda1(csd(dipsel, dipsel));\n            Pr                = lambda1(csd(refsel, refsel));\n            Cdr               = lambda1(csd(dipsel, refsel));\n            source.avg.coh(i) = abs(Cdr).^2 ./ (Pd*Pr);\n          case 'canonical'\n            % compute canonical coherence\n            \n            ccoh = ft_connectivity_cancorr(csd([dipsel refsel],[dipsel refsel]), 'indices', [ones(1,numel(dipsel)) ones(1,numel(refsel))*2]);\n            source.avg.coh(i)  = ccoh(1,2);\n          otherwise\n            ft_error('unsupported cohmethod');\n        end % cohmethod\n      end\n      \n      % compute eta\n      if strcmp(cfg.eta, 'yes')\n        [source.avg.eta(i), source.avg.ori{i}] = csd2eta(source.avg.csd{i}(dipselcell{i},dipselcell{i}));\n        if ~isempty(refsel)\n          %FIXME this only makes sense when only a reference signal OR a dipole is selected\n          [source.avg.etacsd(i), source.avg.ucsd{i}] = csd2eta(source.avg.csd{i}(dipsel,refsel));\n        end\n      end\n      \n      %compute fa\n      if strcmp(cfg.fa, 'yes')\n        source.avg.fa(i) = csd2fa(source.avg.csd{i}(dipsel,dipsel));\n      end\n    end % for diplop\n    \n    if strcmp(cfg.keepcsd, 'no')\n      source.avg = rmfield(source.avg, 'csd');\n    end\n    if strcmp(cfg.keepnoisecsd, 'no') && isnoise\n      source.avg = rmfield(source.avg, 'noisecsd');\n    end\n    \n  end % if keeptrials\n  \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif ismneavg\n  % the source reconstruction was computed using mne and contains an average timecourse\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  \n  if demean\n    begsmp = nearest(source.time, cfg.baselinewindow(1));\n    endsmp = nearest(source.time, cfg.baselinewindow(2));\n    ft_progress('init', cfg.feedback, 'baseline correcting dipole moments');\n    for diplop=1:length(insideindx)\n      ft_progress(diplop/length(insideindx), 'baseline correcting dipole moments %d/%d\\n', diplop, length(insideindx));\n      mom = source.avg.mom{insideindx(diplop)};\n      mom = ft_preproc_baselinecorrect(mom, begsmp, endsmp);\n      source.avg.mom{insideindx(diplop)} = mom;\n    end\n    ft_progress('close');\n  end\n  \n  if projectmom\n    if isfield(source, 'tri')\n      nrm = surface_normals(source.pos, source.tri, 'vertex');\n      source.avg.phi = zeros(size(source.pos,1),1);\n    end\n    ft_progress('init', cfg.feedback, 'projecting dipole moment');\n    for diplop=1:length(insideindx)\n      ft_progress(diplop/length(insideindx), 'projecting dipole moment %d/%d\\n', diplop, length(insideindx));\n      mom = source.avg.mom{insideindx(diplop)};\n      [mom, rmom] = svdfft(mom, 1);\n      source.avg.mom{insideindx(diplop)} = mom;\n      source.avg.ori{insideindx(diplop)} = rmom;\n    end\n    if isfield(source, 'tri')\n      for diplop=insideindx\n        source.avg.phi(diplop) = source.avg.ori{diplop}*nrm(diplop,:)';\n      end\n    end\n    if isfield(source.avg, 'noisecov')\n      source.avg.noise = nan+zeros(size(source.pos,1),1);\n      for diplop=insideindx\n        rmom = source.avg.ori{diplop};\n        source.avg.noise(diplop) = rmom*source.avg.noisecov{diplop}*rmom';\n      end\n    end\n    ft_progress('close');\n  end % if projectmom\n  \n  if flipori\n    tmpmom = cat(1, source.avg.mom{source.inside});\n    [u, s, v] = svd(tmpmom, 'econ');\n    flip( source.inside) = sign(u(:,1));\n    flip(~source.inside) = nan;\n    for i=1:numel(source.inside)\n      if source.inside(i)\n        source.avg.mom{i} = flip(i) * source.avg.mom{i};\n        source.avg.ori{i} = flip(i) * source.avg.ori{i};\n      end\n    end\n  end % if flipori\n  \n  if zscore\n    begsmp = nearest(source.time, cfg.baselinewindow(1));\n    endsmp = nearest(source.time, cfg.baselinewindow(2));\n    % zscore using baselinewindow for power\n    ft_progress('init', cfg.feedback, 'computing power');\n    %source.avg.absmom = source.avg.pow;\n    for diplop=1:length(insideindx)\n      ft_progress(diplop/length(insideindx), 'computing power %d/%d\\n', diplop, length(insideindx));\n      mom = source.avg.mom{insideindx(diplop)};\n      mmom = mean(mom(:,begsmp:endsmp),2);\n      smom = std(mom(:,begsmp:endsmp),[],2);\n      pow  = sum(((mom-mmom(:,ones(size(mom,2),1)))./smom(:,ones(size(mom,2),1))).^2,1);\n      source.avg.pow(insideindx(diplop),:) = pow;\n      source.avg.mom{insideindx(diplop)}   = diag(1./smom)*mom;\n    end\n    ft_progress('close');\n  else\n    % just square for power\n    ft_progress('init', cfg.feedback, 'computing power');\n    %source.avg.absmom = source.avg.pow;\n    for diplop=1:length(insideindx)\n      ft_progress(diplop/length(insideindx), 'computing power %d/%d\\n', diplop, length(insideindx));\n      mom = source.avg.mom{insideindx(diplop)};\n      pow = sum(mom.^2,1);\n      source.avg.pow(insideindx(diplop),:) = pow;\n      %source.avg.absmom(insideindx(diplop),:) = sum(mom,1);\n    end\n    ft_progress('close');\n  end % if zscore\n  \n  if strcmp(cfg.kurtosis, 'yes')\n    fprintf('computing kurtosis based on dipole timecourse\\n');\n    source.avg.k2 = nan(size(source.pos,1),1);\n    for diplop=1:length(insideindx)\n      mom = source.avg.mom{insideindx(diplop)};\n      if length(mom)~=prod(size(mom))\n        ft_error('kurtosis can only be computed for projected dipole moment');\n      end\n      source.avg.k2(insideindx(diplop)) = kurtosis(mom);\n    end\n  end\n  \n  \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif islcmvavg\n  % the source reconstruction was computed using the lcmv beamformer and contains an average timecourse\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  \n  if projectmom\n    ft_progress('init', cfg.feedback, 'projecting dipole moment');\n    for diplop=1:length(insideindx)\n      ft_progress(diplop/length(insideindx), 'projecting dipole moment %d/%d\\n', diplop, length(insideindx));\n      mom = source.avg.mom{insideindx(diplop)};\n      [mom, rmom] = svdfft(mom, 1);\n      source.avg.mom{insideindx(diplop)} = mom;\n      source.avg.ori{insideindx(diplop)} = rmom;\n    end\n    ft_progress('close');\n  end\n  \n  if flipori\n    tmpmom = cat(1, source.avg.mom{source.inside});\n    [u, s, v] = svd(tmpmom, 'econ');\n    flip( source.inside) = sign(u(:,1));\n    flip(~source.inside) = nan;\n    for i=1:numel(source.inside)\n      if source.inside(i)\n        source.avg.mom{i} = flip(i) * source.avg.mom{i};\n        source.avg.ori{i} = flip(i) * source.avg.ori{i};\n      end\n    end\n  end\n  \n  if ~strcmp(cfg.powmethod, 'none')\n    fprintf('recomputing power based on dipole timecourse\\n')\n    source.avg.pow = nan(size(source.pos,1),1);\n    for diplop=1:length(insideindx)\n      mom = source.avg.mom{insideindx(diplop)};\n      cov = mom * mom';\n      source.avg.pow(insideindx(diplop)) = powmethodfun(cov);\n    end\n  end\n  \n  if strcmp(cfg.kurtosis, 'yes')\n    fprintf('computing kurtosis based on dipole timecourse\\n');\n    source.avg.k2 = nan(size(source.pos,1),1);\n    for diplop=1:length(insideindx)\n      mom = source.avg.mom{insideindx(diplop)};\n      if length(mom)~=prod(size(mom))\n        ft_error('kurtosis can only be computed for projected dipole moment');\n      end\n      source.avg.k2(insideindx(diplop)) = kurtosis(mom);\n    end\n  end\n  \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif islcmvtrl\n  % the source reconstruction was computed using the lcmv beamformer and contains a single-trial timecourse\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  \n  ntrial = length(source.trial);\n  \n  if projectmom && strcmp(cfg.fixedori, 'within_trials')\n    % the dipole orientation is re-determined for each trial\n    ft_progress('init', cfg.feedback, 'projecting dipole moment');\n    for trllop=1:ntrial\n      ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\\n', trllop, ntrial);\n      for diplop=1:length(insideindx)\n        mom = source.trial(trllop).mom{insideindx(diplop)};\n        [mom, rmom] = svdfft(mom, 1);\n        source.trial(trllop).mom{insideindx(diplop)} = mom;\n        source.trial(trllop).ori{insideindx(diplop)} = rmom;  % remember the orientation\n      end\n    end\n    ft_progress('close');\n  elseif projectmom && strcmp(cfg.fixedori, 'over_trials')\n    ft_progress('init', cfg.feedback, 'projecting dipole moment');\n    % compute average covariance over all trials\n    for trllop=1:ntrial\n      for diplop=1:length(insideindx)\n        mom = source.trial(trllop).mom{insideindx(diplop)};\n        if trllop==1\n          cov{diplop} = mom*mom'./size(mom,2);\n        else\n          cov{diplop} = mom*mom'./size(mom,2) + cov{diplop};\n        end\n      end\n    end\n    % compute source orientation over all trials\n    for diplop=1:length(insideindx)\n      [dum, ori{diplop}] = svdfft(cov{diplop}, 1);\n    end\n    % project the data in each trial\n    for trllop=1:ntrial\n      ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\\n', trllop, ntrial);\n      for diplop=1:length(insideindx)\n        mom = source.trial(trllop).mom{insideindx(diplop)};\n        mom = ori{diplop}*mom;\n        source.trial(trllop).mom{insideindx(diplop)} = mom;\n        source.trial(trllop).ori{insideindx(diplop)} = ori{diplop};\n      end\n    end\n    ft_progress('close');\n  end\n  \n  if ~strcmp(cfg.powmethod, 'none')\n    fprintf('recomputing power based on dipole timecourse\\n')\n    for trllop=1:ntrial\n      for diplop=1:length(insideindx)\n        mom = source.trial(trllop).mom{insideindx(diplop)};\n        cov = mom * mom';\n        source.trial(trllop).pow(insideindx(diplop)) = powmethodfun(cov);\n      end\n    end\n  end\n  \n  if strcmp(cfg.kurtosis, 'yes')\n    fprintf('computing kurtosis based on dipole timecourse\\n');\n    for trllop=1:ntrial\n      source.trial(trllop).k2 = nan(size(source.pos,1),1);\n      for diplop=1:length(insideindx)\n        mom = source.trial(trllop).mom{insideindx(diplop)};\n        if length(mom)~=numel(mom)\n          ft_error('kurtosis can only be computed for projected dipole moment');\n        end\n        source.trial(trllop).k2(insideindx(diplop)) = kurtosis(mom);\n      end\n    end\n  end\n  \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend % dealing with pcc, lcmv, dics or mne input\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isfield(source, 'avg') && isfield(source.avg, 'pow') && isfield(source.avg, 'noise') && ~ismneavg\n  % compute the neural activity index for the average\n  source.avg.nai = source.avg.pow(:) ./ source.avg.noise(:);\nend\n\nif isfield(source, 'trial') && isfield(source.trial, 'pow') && isfield(source.trial, 'noise')\n  % compute the neural activity index for the trials\n  ntrials = length(source.trial);\n  for trlop=1:ntrials\n    source.trial(trlop).nai = source.trial(trlop).pow ./ source.trial(trlop).noise;\n  end\nend\n\nif strcmp(source.method, 'randomization') || strcmp(source.method, 'permutation')\n  % compute the neural activity index for the two randomized conditions\n  source.avgA.nai = source.avgA.pow ./ source.avgA.noise;\n  source.avgB.nai = source.avgB.pow ./ source.avgB.noise;\n  for trlop=1:length(source.trialA)\n    source.trialA(trlop).nai = source.trialA(trlop).pow ./ source.trialA(trlop).noise;\n  end\n  for trlop=1:length(source.trialB)\n    source.trialB(trlop).nai = source.trialB(trlop).pow ./ source.trialB(trlop).noise;\n  end\nend\n\nif ~isempty(cfg.transform)\n  fprintf('applying %s transformation on the power and projected noise\\n', cfg.transform);\n  % apply the specified transformation on the power\n  if isfield(source, 'avg'   ) && isfield(source.avg   , 'pow'), source.avg .pow = feval(cfg.transform, source.avg .pow); end\n  if isfield(source, 'avgA'  ) && isfield(source.avgA  , 'pow'), source.avgA.pow = feval(cfg.transform, source.avgA.pow); end\n  if isfield(source, 'avgB'  ) && isfield(source.avgB  , 'pow'), source.avgB.pow = feval(cfg.transform, source.avgB.pow); end\n  if isfield(source, 'trial' ) && isfield(source.trial , 'pow'), for i=1:length(source.trial ), source.trial (i).pow = feval(cfg.transform, source.trial (i).pow); end; end\n  if isfield(source, 'trialA') && isfield(source.trialA, 'pow'), for i=1:length(source.trialA), source.trialA(i).pow = feval(cfg.transform, source.trialA(i).pow); end; end\n  if isfield(source, 'trialB') && isfield(source.trialB, 'pow'), for i=1:length(source.trialB), source.trialB(i).pow = feval(cfg.transform, source.trialB(i).pow); end; end\n  % apply the specified transformation on the projected noise\n  if isfield(source, 'avg'   ) && isfield(source.avg   , 'noise'), source.avg .noise = feval(cfg.transform, source.avg .noise); end\n  if isfield(source, 'avgA'  ) && isfield(source.avgA  , 'noise'), source.avgA.noise = feval(cfg.transform, source.avgA.noise); end\n  if isfield(source, 'avgB'  ) && isfield(source.avgB  , 'noise'), source.avgB.noise = feval(cfg.transform, source.avgB.noise); end\n  if isfield(source, 'trial' ) && isfield(source.trial , 'noise'), for i=1:length(source.trial ), source.trial (i).noise = feval(cfg.transform, source.trial (i).noise); end; end\n  if isfield(source, 'trialA') && isfield(source.trialA, 'noise'), for i=1:length(source.trialA), source.trialA(i).noise = feval(cfg.transform, source.trialA(i).noise); end; end\n  if isfield(source, 'trialB') && isfield(source.trialB, 'noise'), for i=1:length(source.trialB), source.trialB(i).noise = feval(cfg.transform, source.trialB(i).noise); end; end\nend\n\nif strcmp(source.method, 'pseudovalue')\n  % compute the pseudovalues for the beamformer output\n  avg = source.trial(1);        % the first is the complete average\n  Ntrials = length(source.trial)-1; % the remaining are the leave-one-out averages\n  pseudoval = [];\n  if isfield(source.trial, 'pow')\n    allavg = getfield(avg, 'pow');\n    for i=1:Ntrials\n      thisavg = getfield(source.trial(i+1), 'pow');\n      thisval = Ntrials*allavg - (Ntrials-1)*thisavg;\n      pseudoval(i).pow = thisval;\n    end\n  end\n  if isfield(source.trial, 'coh')\n    allavg = getfield(avg, 'coh');\n    for i=1:Ntrials\n      thisavg = getfield(source.trial(i+1), 'coh');\n      thisval = Ntrials*allavg - (Ntrials-1)*thisavg;\n      pseudoval(i).coh = thisval;\n    end\n  end\n  if isfield(source.trial, 'nai')\n    allavg = getfield(avg, 'nai');\n    for i=1:Ntrials\n      thisavg = getfield(source.trial(i+1), 'nai');\n      thisval = Ntrials*allavg - (Ntrials-1)*thisavg;\n      pseudoval(i).nai = thisval;\n    end\n  end\n  if isfield(source.trial, 'noise')\n    allavg = getfield(avg, 'noise');\n    for i=1:Ntrials\n      thisavg = getfield(source.trial(i+1), 'noise');\n      thisval = Ntrials*allavg - (Ntrials-1)*thisavg;\n      pseudoval(i).noise = thisval;\n    end\n  end\n  % store the pseudovalues instead of the original values\n  source.trial = pseudoval;\nend\n\nif strcmp(source.method, 'jackknife') || strcmp(source.method, 'bootstrap') || strcmp(source.method, 'pseudovalue') || strcmp(source.method, 'singletrial') || strcmp(source.method, 'rawtrial')\n  % compute descriptive statistics (mean, var, sem) for multiple trial data\n  % compute these for as many source parameters as possible\n  \n  % for convenience copy the trials out of the source structure\n  dip = source.trial;\n  \n  % determine the (original) number of trials in the data\n  if strcmp(source.method, 'bootstrap') %VERANDERD ER ZAT GEEN .RESAMPLE IN SOURCE\n    Ntrials = size(source.trial,2); % WAS size(source.resample, 2);\n  else\n    Ntrials = length(source.trial);\n  end\n  fprintf('original data contained %d trials\\n', Ntrials);\n  \n  % allocate memory for all elements in the dipole structure\n  sumdip = [];\n  if isfield(dip(1), 'var'),   sumdip.var    = zeros(size(dip(1).var  )); sumdip.var(~source.inside) = nan; end\n  if isfield(dip(1), 'pow'),   sumdip.pow    = zeros(size(dip(1).pow  )); sumdip.pow(~source.inside) = nan; end\n  if isfield(dip(1), 'coh'),   sumdip.coh    = zeros(size(dip(1).coh  )); sumdip.coh(~source.inside) = nan; end\n  if isfield(dip(1), 'rv'),    sumdip.rv     = zeros(size(dip(1).rv   )); sumdip.rv(~source.inside) = nan; end\n  if isfield(dip(1), 'noise'), sumdip.noise  = zeros(size(dip(1).noise)); sumdip.noise(~source.inside) = nan; end\n  if isfield(dip(1), 'nai'),   sumdip.nai    = zeros(size(dip(1).nai  )); sumdip.nai(~source.inside) = nan; end\n  sqrdip = [];\n  if isfield(dip(1), 'var'),   sqrdip.var    = zeros(size(dip(1).var  )); sqrdip.var(~source.inside) = nan; end\n  if isfield(dip(1), 'pow'),   sqrdip.pow    = zeros(size(dip(1).pow  )); sqrdip.pow(~source.inside) = nan; end\n  if isfield(dip(1), 'coh'),   sqrdip.coh    = zeros(size(dip(1).coh  )); sqrdip.coh(~source.inside) = nan; end\n  if isfield(dip(1), 'rv'),    sqrdip.rv     = zeros(size(dip(1).rv   )); sqrdip.rv(~source.inside) = nan; end\n  if isfield(dip(1), 'noise'), sqrdip.noise  = zeros(size(dip(1).noise)); sqrdip.noise(~source.inside) = nan; end\n  if isfield(dip(1), 'nai'),   sqrdip.nai    = zeros(size(dip(1).nai  )); sqrdip.nai(~source.inside) = nan; end\n  if isfield(dip(1), 'mom')\n    sumdip.mom = cell(size(dip(1).mom));\n    sqrdip.mom = cell(size(dip(1).mom));\n    for i=1:length(dip(1).mom)\n      sumdip.mom{i} = zeros(size(dip(1).mom{i}));\n      sqrdip.mom{i} = zeros(size(dip(1).mom{i}));\n    end\n  end\n  if isfield(dip(1), 'csd')\n    sumdip.csd = cell(size(dip(1).csd));\n    sqrdip.csd = cell(size(dip(1).csd));\n    for i=1:length(dip(1).csd)\n      sumdip.csd{i} = zeros(size(dip(1).csd{i}));\n      sqrdip.csd{i} = zeros(size(dip(1).csd{i}));\n    end\n  end\n  \n  for trial=1:length(dip)\n    % compute the sum of all values\n    if isfield(dip(trial), 'var'),    sumdip.var   = sumdip.var    + dip(trial).var;    end\n    if isfield(dip(trial), 'pow'),    sumdip.pow   = sumdip.pow    + dip(trial).pow;    end\n    if isfield(dip(trial), 'coh'),    sumdip.coh   = sumdip.coh    + dip(trial).coh;    end\n    if isfield(dip(trial), 'rv'),     sumdip.rv    = sumdip.rv     + dip(trial).rv;     end\n    if isfield(dip(trial), 'noise'),  sumdip.noise = sumdip.noise  + dip(trial).noise;  end\n    if isfield(dip(trial), 'nai'),    sumdip.nai   = sumdip.nai    + dip(trial).nai;    end\n    % compute the sum of squared values\n    if isfield(dip(trial), 'var'),    sqrdip.var    = sqrdip.var   + (dip(trial).var  ).^2; end\n    if isfield(dip(trial), 'pow'),    sqrdip.pow    = sqrdip.pow   + (dip(trial).pow  ).^2; end\n    if isfield(dip(trial), 'coh'),    sqrdip.coh    = sqrdip.coh   + (dip(trial).coh  ).^2; end\n    if isfield(dip(trial), 'rv'),     sqrdip.rv     = sqrdip.rv    + (dip(trial).rv   ).^2; end\n    if isfield(dip(trial), 'noise'),  sqrdip.noise  = sqrdip.noise + (dip(trial).noise).^2; end\n    if isfield(dip(trial), 'nai'),    sqrdip.nai    = sqrdip.nai   + (dip(trial).nai  ).^2; end\n    % do the same for the cell-array with mom\n    if isfield(dip(trial), 'mom')\n      for i=1:length(dip(1).mom)\n        sumdip.mom{i} = sumdip.mom{i} +  dip(trial).mom{i};\n        sqrdip.mom{i} = sqrdip.mom{i} + (dip(trial).mom{i}).^2;\n      end\n    end\n    % do the same for the cell-array with csd\n    if isfield(dip(trial), 'csd')\n      for i=1:length(dip(1).csd)\n        sumdip.csd{i} = sumdip.csd{i} +  dip(trial).csd{i};\n        sqrdip.csd{i} = sqrdip.csd{i} + (dip(trial).csd{i}).^2;\n      end\n    end\n  end\n  \n  % compute the mean over all repetitions\n  if isfield(sumdip, 'var'),    dipmean.var    = sumdip.var   / length(dip); end\n  if isfield(sumdip, 'pow'),    dipmean.pow    = sumdip.pow   / length(dip); end\n  if isfield(sumdip, 'coh'),    dipmean.coh    = sumdip.coh   / length(dip); end\n  if isfield(sumdip, 'rv'),     dipmean.rv     = sumdip.rv    / length(dip); end\n  if isfield(sumdip, 'noise'),  dipmean.noise  = sumdip.noise / length(dip); end\n  if isfield(sumdip, 'nai'),    dipmean.nai    = sumdip.nai   / length(dip); end\n  % for the cell-array with mom, this is done further below\n  % for the cell-array with csd, this is done further below\n  \n  % the estimates for variance and SEM are biased if we are working with the jackknife/bootstrap\n  % determine the proper variance scaling that corrects for this bias\n  % note that Ntrials is not always the same as the length of dip, especially in case of the bootstrap\n  if strcmp(source.method, 'singletrial')\n    bias = 1;\n  elseif strcmp(source.method, 'rawtrial')\n    bias = 1;\n  elseif strcmp(source.method, 'jackknife')\n    % Effron gives SEM estimate for the jackknife method in equation 11.5 (paragraph 11.2)\n    % to get the variance instead of SEM, we also have to multiply with the number of trials\n    bias = (Ntrials - 1)^2;\n  elseif strcmp(source.method, 'bootstrap')\n    % Effron gives SEM estimate for the bootstrap method in algorithm 6.1 (equation 6.6)\n    % to get the variance instead of SEM, we also have to multiply with the number of trials\n    bias = Ntrials;\n  elseif strcmp(source.method, 'pseudovalue')\n    % note that I have not put any thought in this aspect yet\n    ft_warning('don''t know how to compute bias for pseudovalue resampling');\n    bias = 1;\n  end\n  \n  % compute the variance over all repetitions\n  if isfield(sumdip, 'var'),    dipvar.var    = bias*(sqrdip.var    - (sumdip.var   .^2)/length(dip))/(length(dip)-1); end\n  if isfield(sumdip, 'pow'),    dipvar.pow    = bias*(sqrdip.pow    - (sumdip.pow   .^2)/length(dip))/(length(dip)-1); end\n  if isfield(sumdip, 'coh'),    dipvar.coh    = bias*(sqrdip.coh    - (sumdip.coh   .^2)/length(dip))/(length(dip)-1); end\n  if isfield(sumdip, 'rv' ),    dipvar.rv     = bias*(sqrdip.rv     - (sumdip.rv    .^2)/length(dip))/(length(dip)-1); end\n  if isfield(sumdip, 'noise' ), dipvar.noise  = bias*(sqrdip.noise  - (sumdip.noise .^2)/length(dip))/(length(dip)-1); end\n  if isfield(sumdip, 'nai' ),   dipvar.nai    = bias*(sqrdip.nai    - (sumdip.nai   .^2)/length(dip))/(length(dip)-1); end\n  \n  % compute the SEM over all repetitions\n  if isfield(sumdip, 'var'),    dipsem.var    = (dipvar.var   /Ntrials).^0.5; end\n  if isfield(sumdip, 'pow'),    dipsem.pow    = (dipvar.pow   /Ntrials).^0.5; end\n  if isfield(sumdip, 'coh'),    dipsem.coh    = (dipvar.coh   /Ntrials).^0.5; end\n  if isfield(sumdip, 'rv' ),    dipsem.rv     = (dipvar.rv    /Ntrials).^0.5; end\n  if isfield(sumdip, 'noise' ), dipsem.noise  = (dipvar.noise /Ntrials).^0.5; end\n  if isfield(sumdip, 'nai' ),   dipsem.nai    = (dipvar.nai   /Ntrials).^0.5; end\n  \n  % compute the mean and SEM over all repetitions for the cell-array with mom\n  if isfield(dip(trial), 'mom')\n    for i=1:length(dip(1).mom)\n      dipmean.mom{i} = sumdip.mom{i}/length(dip);\n      dipvar.mom{i} = bias*(sqrdip.mom{i} - (sumdip.mom{i}.^2)/length(dip))/(length(dip)-1);\n      dipsem.mom{i} = (dipvar.mom{i}/Ntrials).^0.5;\n    end\n  end\n  \n  % compute the mean and SEM over all repetitions for the cell-array with csd\n  if isfield(dip(trial), 'csd')\n    for i=1:length(dip(1).csd)\n      dipmean.csd{i} = sumdip.csd{i}/length(dip);\n      dipvar.csd{i} = bias*(sqrdip.csd{i} - (sumdip.csd{i}.^2)/length(dip))/(length(dip)-1);\n      dipsem.csd{i} = (dipvar.csd{i}/Ntrials).^0.5;\n    end\n  end\n  \n  if strcmp(source.method, 'pseudovalue')\n    % keep the trials, since they have been converted to pseudovalues\n    % and hence the trials contain the interesting data\n  elseif keeptrials\n    % keep the trials upon request\n  else\n    % remove the original trials\n    source = rmfield(source, 'trial');\n    % assign the descriptive statistics to the output source structure\n    source.avg = dipmean;\n    source.var = dipvar;\n    source.sem = dipsem;\n  end\nend\n\nif strcmp(cfg.resolutionmatrix, 'yes')\n  % this is only implemented for pcc and no refdips/chans at the moment\n  Nchan        = size(source.leadfield{insideindx(1)}, 1);\n  Ninside      = length(insideindx);\n  allfilter    = zeros(Ninside,Nchan);\n  allleadfield = zeros(Nchan,Ninside);\n  dipsel       = match_str(source.avg.csdlabel, 'scandip');\n  ft_progress('init', cfg.feedback, 'computing resolution matrix');\n  for diplop=1:length(insideindx)\n    ft_progress(diplop/length(insideindx), 'computing resolution matrix %d/%d\\n', diplop, length(insideindx));\n    % concatenate all filters\n    allfilter(diplop,:)    = source.avg.filter{insideindx(diplop)}(dipsel,:);\n    % concatenate all leadfields\n    allleadfield(:,diplop) = source.leadfield{insideindx(diplop)};\n  end\n  ft_progress('close');\n  % multiply the filters and leadfields to obtain the resolution matrix\n  % see equation 1 and 2 in De Peralta-Menendez RG, Gonzalez-Andino SL: A critical analysis of linear inverse solutions to the neuroelectromagnetic inverse problem. IEEE Transactions on Biomedical Engineering 45: 440-448, 1998.\n  source.resolution = nan(Ndipole, Ndipole);\n  source.resolution(insideindx, insideindx) = allfilter*allleadfield;\nend\n\n% compute fwhm\nif strcmp(cfg.fwhm, 'yes')\n  switch cfg.fwhmmethod\n    case 'barnes'\n      if ~isfield(source, 'dim')\n        ft_error('computation of fwhm is not possible with method ''barnes'' is not possible when the dipoles are not defined on a regular 3D grid');\n      end\n      fprintf('computing fwhm of spatial filters using method ''barnes''\\n');\n      source = estimate_fwhm1(source, cfg.fwhmremovecenter);\n    case 'gaussfit'\n      fprintf('computing fwhm of spatial filters using method ''gaussfit''\\n');\n      source = estimate_fwhm2(source, cfg.fwhmmaxdist);\n    otherwise\n      ft_error('unknown method for fwhm estimation');\n  end\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous   source\nft_postamble provenance source\nft_postamble history    source\nft_postamble savevar    source\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute eta from a csd-matrix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [eta, u] = csd2eta(csd)\n[u,s,v] = svd(real(csd));\neta     = s(2,2)./s(1,1);\nu       = u'; %orientation is defined in the rows\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute fa from a csd-matrix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [fa] = csd2fa(csd)\ns  = svd(real(csd));\nns = rank(real(csd));\ns  = s(1:ns);\nms = mean(s);\nfa = sqrt( (ns./(ns-1)) .* (sum((s-ms).^2))./(sum(s.^2)) );\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute power\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction p = powmethod_lambda1(x, ind)\n\nif nargin==1\n  ind = 1:size(x,1);\nend\ns = svd(x(ind,ind));\np = s(1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute power\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction p = powmethod_trace(x, ind)\n\nif nargin==1\n  ind = 1:size(x,1);\nend\np = trace(x(ind,ind));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute power\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction p = powmethod_regular(x, ind)\n\nif nargin==1\n  ind = 1:size(x,1);\nend\np = abs(x(ind,ind));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to obtain the largest singular value or trace of the\n% source CSD matrices resulting from DICS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction s = lambda1(x)\ns = svd(x);\ns = s(1);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_sourcedescriptives.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}}
{"text": "%% PLANETOID CLASS (planetoid.m) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The Moon class is an iteration of the spheriod obstacle class aimed\n% mostly providing a reference for satelite simulation.\n\n% Author: James A. Douthwaite 09/02/2019\n\nclassdef planetoid < obstacle_spheroid\n    properties\n        inclination;    % Inclination angle\n        orbit;          % Orbit \n        orbitalSpeed;   % Oribital speed \n        mass;           % Planetoid mass\n        axialRate = 1;  % Rotational rate about its vertical axes(rad/s)\n    end\n    %% ///////////////////////// MAIN METHODS /////////////////////////////\n    methods \n        % Constructor\n        function this = planetoid(varargin)\n            % This function constructs the cuboid obstacle. The object must\n            % be imported and represented with a global position and\n            % velocity as all other objects are in OMAS.\n                        \n            % Call the super class\n            this = this@obstacle_spheroid(varargin); \n                        \n            % IMPORT THE OBJECT'S GEOMETRY IF IT EXISTS\n            [this.GEOMETRY] = OMAS_graphics.scale(this.GEOMETRY,this.radius);  % Scale\n            \n            % //////////////// Check for user overrides ///////////////////\n            [this] = this.ApplyUserOverrides(varargin); % Recursive overrides\n            % /////////////////////////////////////////////////////////////\n        end           \n        % Setup - X = [x;x_dot]' 3D STATE VECTOR\n        function [this] = setup(this,localXYZVelocity,localXYZrotations)\n            % The state initialiser must be called 'initialise_localState'\n            % and instead calls the 'initialise_3DVelocities' function in\n            % this case. \n            [this] = this.setup_3DVelocities(localXYZVelocity,localXYZrotations);\n            % ADD A ROTATIONAL RATE\n            this.localState(12) = this.axialRate; % The earth rotates a constant rate about its z interial axis\n        end\n        % Main\n        function [this] = main(this,TIME,varargin)\n            % SIMPLE UPDATE OF LOCAL STATE\n            dt = TIME.dt;\n            X = this.localState(1:6,1);\n            U = this.localState(7:12,1);\n            \n            % SIMPLY INTEGRATE THE RATES\n            [dXdt] = this.SingleIntegratorDynamics(X,U);\n            eulerState = this.localState;\n            eulerState(1:6,1) = this.localState(1:6,1) + dt*dXdt;\n            \n            % UPDATE THE GLOBAL PROPERTIES\n            [this] = this.GlobalUpdate_3DVelocities(dt,eulerState);\n        end\n    end\nend\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/objects/planetoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2300491498313788}}
{"text": "function [varargout] = file_readBV(file, varargin)\n% FILE_READBV - load EEG data which is stored in BrainVision format.\n%                  C-functions are used for better performance. Use the\n%                  slower FILE_LOADBV if this function does not work.\n%\n% Synopsis:\n%   [CNT, MRK, HDR]= file_readBV(FILE, 'Property1',Value1, ...)\n%\n% Arguments:\n%   FILE: file name (no extension),\n%         relative to BTB.RawDir unless beginning with '/' (resp '\\').\n%         FILE may also contain the wildcard symbol '*'. In this case\n%         make sure that the order of the files (printed to the terminal)\n%         is appropriate.\n%         FILE may also be a cell array of file names.\n%\n% Properties:\n%   'CLab': Channels to load (labels or indices). Default all\n%           (which can be explicitly specified by [])\n%   'Fs': Sampling interval, must be an integer divisor of the\n%         sampling interval of the raw data. fs may also be 'raw' which means \n%         sampling rate of raw signals. Default: 'raw'.\n%   'Ival': Interval to read, [start end] in msec. It is not checked\n%           whether the whole interval could be loaded, or the file is shorter.\n%   'IvalSa': Same as 'ival' but [start end] in samples of the downsampled data.\n%   'Start': Start [msec] reading.\n%   'MaxLen': Maximum length [msec] to be read.\n%   'Filt': Filter to be applied to raw data before subsampling.\n%           opt.Filt must be a struct with fields 'b' and 'a' (as used for\n%           the Matlab function filter).\n%           Note that using opt.Filt may slow down loading considerably.\n%   'SubsamplePolicy': Function that is used for subsampling after filtering, \n%           specified as as string or a vector.\n%           Default 'subsampleByMean'. Other 'subsampleByLag'\n%           If you specify a vector it has to be the same size as lag.\n%   'LinearDerivation' : for creating bipolar channels (see\n%   procutil_biplist2projection for details)\n%\n% Remark: \n%   Properties 'Ival' and 'Start'+'MaxLen' are exclusive, i.e., you may only\n%   specify one of them.\n%\n% Returns:\n%   CNT: struct for contiuous signals\n%        .x: EEG signals (time x channels)\n%        .clab: channel labels\n%        .fs: sampling interval\n%        .scale: if this field is given, the real data are .x*.scale, \n%           and .x is int\n%   MRK: struct of marker information\n%   HDR: struct of header information\n%\n% TODO: The function so far can only read specific formats, e.g.,\n%       multiplexed, INT_16, ... The function does not even check, whether\n%       the file is in this format!\n%\n% See also: file_* procutil_biplist2projection\n%\n%Hints:\n% A low pass filter to get rid of the line noise can be designed as follows:\n%  hdr= file_readBVheader(file);\n%  Wps= [40 49]/hdr.fs*2;\n%  [n, Ws]= cheb2ord(Wps(1), Wps(2), 3, 50);\n%  [filt.b, filt.a]= cheby2(n, 50, Ws);\n% You can also use filtdemo to design your own filters.\n\n\n% Benjamin Blankertz\n\n%   2008/06/20/ - Max Sagebaum\n%               - refactored file_loadBV to read the data with read_bv.c\n%               - removed code fragments marked as obsolete\n%               - you can now use the ival option when concatinating\n%                 multiple eeg files\n%   2008/06/17  - Max Sagebaum\n%               - the iir filter was not properly send to read_bv\n%   2010/09/09  - Max Sagebaum\n%               - There was an bug in the check for the lag\n\n\n%% check if the mex file is present\nreadBV_status = exist('read_bv','file');\nif not(readBV_status == 3)\n    warning('Could not detect mex files for read_bv! Using file_loadBV instead.')\n    varargout= cell(1, nargout);\n    [varargout{:}]= file_loadBV(file, varargin{:});\n    return;\nend\n\n\n%% start file_readBV\nglobal BTB\n\nprops= {'CLab'               ''       'CHAR|CELL{CHAR}'\n        'Fs'                 'raw'    'CHAR|DOUBLE'\n        'Start'              0        'DOUBLE[1]'\n        'MaxLen'             inf      'DOUBLE[1]'\n        'Prec'               0        'DOUBLE[1]'\n        'Ival'               []       'DOUBLE[2]'\n        'IvalSa'             []       'DOUBLE[2]'\n        'SubsamplePolicy'    'mean'   'CHAR(mean lag)|DOUBLE'\n        'Filt'               []       'STRUCT(a b)'\n        'LinearDerivation'   []       'STRUCT'\n        'TargetFormat'       'bbci'   'CHAR'\n        'Verbose'            1        'BOOL'\n       };\n\nprops_readBVmarkers= file_readBVmarkers;\nprops_readBVheader= file_readBVheader;\nall_props= opt_catProps(props, props_readBVmarkers, props_readBVheader);\n\nif nargin==0,\n  varargout= {all_props};\n  return\nend\n\nopt= opt_proplistToStruct(varargin{:});\n[opt, isdefault]= opt_setDefaults(opt, props);\nopt_checkProplist(opt, all_props);\n\nmisc_checkType(file, 'CHAR|CELL{CHAR}');\n\nif ~isempty(opt.Ival),\n  if ~isdefault.Start || ~isdefault.MaxLen,\n    error('specify either ''Ival'' or ''Start''+''MaxLen'' but not both');\n  end\n  if ~isempty(opt.IvalSa),\n    error('specify either ''Ival'' or ''IvalSa'' but not both');\n  end\n  opt.Start= opt.Ival(1);\n  opt.MaxLen= diff(opt.Ival)+1;\nend\n\n%% read the headers an prepare the clab\n\nif ~iscell(file)\n  file = {file};\nend\n\nfileNames = cell(1,length(file));\nfileTitle = cell(1,length(file));\n% use BTB.RawDir as default dir\nfor filePos = 1:length(file)\n  if fileutil_isAbsolutePath(file{filePos}),\n    fileNames{filePos}= file{filePos};\n    [dmy, fileTitle{filePos}]= fileparts(file{filePos});\n  else\n    fileNames{filePos} = fullfile(BTB.RawDir, file{filePos});\n    fileTitle{filePos}= file{filePos};\n  end\nend\n\n% get all files specified with the file object\nfileNamesTemp = {};\nfor filePos = 1:length(file)\n\n  if ischar(fileNames{filePos}) && ismember('*', fileNames{filePos},'legacy'),\n    dd= dir([fileNames{filePos} '.eeg']);\n    if isempty(dd),\n      error('\\nFile not found: %s\\n', fileNames{filePos});\n    end\n    fc= cellfun(@(x)(x(1:end-4)), {dd.name}, 'UniformOutput',0);\n    \n    fileNamesTemp = cat(2,fileNamesTemp,strcat(fileparts(fileNames{filePos}), '/', fc));\n  else\n    fileNamesTemp = cat(2,fileNamesTemp,{fileNames{filePos}});\n  end\nend\nfileNames = fileNamesTemp;\nif length(fileNames)>1,\n  if opt.Verbose,\n    fprintf('concatenating files in the following order:\\n');\n    fprintf('  %s\\n', fileNames{:});\n  end\nend\n\n% now we read all headers and make some consistent checks if neeeded\nhdr = cell(1,length(fileNames));\nopt_readBVheader= opt_substruct(opt, props_readBVheader(:,1));\nfor filePos = 1:length(fileNames)\n  hdr{filePos} = file_readBVheader(fileNames{filePos}, opt_readBVheader);\n  \n  % set the clabs and the raw_fs if we are in the loop for the first time\n  if(filePos == 1)\n    cnt.clab= hdr{filePos}.clab;\n    raw_fs= hdr{filePos}.fs;\n  end\n\t\n  if ~isequal(cnt.clab, hdr{filePos}.clab),\n    warning(['inconsistent clab structure will be repaired ' ...\n             'by using the intersection']); \n    cnt.clab = intersect(cnt.clab, hdr{filePos}.clab,'legacy');\n  end\n  if isequal(opt.Fs, 'raw')\n    % if we want to read the raw data check if for each file the raw data\n    % is the same\n    if~isequal(raw_fs, hdr{filePos}.fs)\n      error('inconsistent sampling rate');\n    end\n  else\n    % if we have a specific fs check if for each file we have a positive\n    % lag\n    lag = hdr{filePos}.fs/opt.Fs;\n    if lag~=round(lag) || lag<1,\n      error('fs must be a positive integer divisor of every file''s fs');\n    end\n  end\nend\nclab_in_file= cnt.clab;\n\n% select specified channels\nif ~isempty(opt.CLab) && strcmp(opt.TargetFormat,'bbci'),\n  cnt.clab= cnt.clab(util_chanind(cnt, opt.CLab));\nend\n\n% sort channels for memory efficient application of linear derivation:\n% temporary channels are moved to the end\nif ~isempty(opt.LinearDerivation),\n  rm_clab= cell_flaten({opt.LinearDerivation.rm_clab});\n  rmidx= util_chanind(cnt.clab, rm_clab);\n  cnt.clab(rmidx)= [];\n  cnt.clab= cat(2, cnt.clab, rm_clab);\nend\n\n%% prepare the output samples\nfirstFileToRead = 1;\nfirstFileSkip = 0;\nlastFileToRead = length(fileNames);\nlastFileLength = inf;\n\n\n% check if we want to load the raw data\nif isequal(opt.Fs, 'raw'),\n  opt.Fs= raw_fs;\nend\ncnt.fs= opt.Fs;\ncnt.title = str_vec2str(fileTitle);\ncnt.file = str_vec2str(fileNames);\n\nnChans= length(cnt.clab);\n\n% get the skip and maxlen values for the data in samples for the new\n% sampling rate\nif ~isempty(opt.IvalSa),\n  if ~isdefault.Start || ~isdefault.MaxLen,\n    error('specify either <IvalSa> or <Start/MaxLen> but not both');\n  end\n  skip= opt.IvalSa(1)-1;\n  maxlen = diff(opt.IvalSa)+1;\nelse\n  skip= max(0, floor(opt.Start/1000*opt.Fs));\n  maxlen = ceil(opt.MaxLen/1000*opt.Fs);\nend\n\n%get the number of samples for every file and check from which file we have\n%to read\nnSamples = 0;\ndataSamples = 0;\ndataSize = zeros(1,length(fileNames));\nfor filePos = 1:length(fileNames)\n  % check if we can read the data with read_bv\n  % currently only 16Bit Integers are supported\n  switch hdr{filePos}.BinaryFormat\n   case 'INT_16',\n    cellSize= 2;\n    readbv_binformat(filePos)=1;\n   case 'INT_32',\n    cellSize= 4;\n    readbv_binformat(filePos)=2;\n   case {'IEEE_FLOAT_32', 'FLOAT_32'},\n    cellSize= 4;\n    readbv_binformat(filePos)=3;\n   case {'IEEE_FLOAT_64', 'FLOAT_64', 'DOUBLE'},\n    cellSize= 8;\n    readbv_binformat(filePos)=4;\n   otherwise\n    error('Precision %s not known.', hdr.BinaryFormat);\n  end\n  \n  % open the file to get the size\n  fid= fopen([fileNames{filePos} '.eeg'], 'r', hdr{filePos}.endian);\n  if fid==-1, error('%s.eeg not found', fileNames{filePos}); end\n  fseek(fid, 0, 'eof');\n  fileLen= ftell(fid);\n  fclose(fid);\n  \n  curChannels = length(hdr{filePos}.clab);\n  curLag = hdr{filePos}.fs/opt.Fs;\n  samples_in_file = floor(fileLen/(cellSize*curChannels));\n  samples_after_subsample = floor(samples_in_file / curLag);\n  dataSize(filePos) = samples_after_subsample;\n  \n  % set the new first file and the first data in this file\n  if nSamples <= skip\n    firstFileToRead = filePos;\n    firstFileSkip = skip - nSamples;\n    dataSamples = samples_after_subsample - firstFileSkip;\n  else\n    dataSamples = dataSamples + samples_after_subsample;\n  end\n  % advance to the end of the cur file\n  nSamples = nSamples + samples_after_subsample;\n  \n  % if we reach the end set the last file and stop reading\n  if nSamples >= (skip + maxlen)\n    lastFileToRead = filePos;\n    lastFileLength = samples_after_subsample - (nSamples - (skip + maxlen));\n    dataSamples = dataSamples - (samples_after_subsample - lastFileLength);\n     break;\n  else\n    % only if we have no maxlen\n    lastFileLength = samples_after_subsample;\n  end\n  \nend\n\n%% reading the data\n%create the data block for all samples\nchosen_clab = cnt.clab;\ncnt.x = zeros(dataSamples,nChans);\ncnt.T = dataSize;\n\ndataOffset = 0; % the offset for the current file\nfor filePos = firstFileToRead:lastFileToRead\n  % get the channel id for this file\n  chanids = util_chanind(clab_in_file,chosen_clab); % the -1 is for read_bv\n  \n  read_opt = struct('fs',cnt.fs, 'chanidx',chanids);\n\n  if ~isempty(opt.Filt)\n    read_opt.filt_b = opt.Filt.b;\n    read_opt.filt_a = opt.Filt.a;\n  end\n  % set the subsample filter \n  lag = hdr{filePos}.fs/opt.Fs;\n  switch opt.SubsamplePolicy,\n    case 'mean',\n      read_opt.filt_subsample = ones(1,lag)/lag;\n    case 'lag',\n      read_opt.filt_subsample = [zeros(1,lag-1) 1];\n    otherwise,\n      read_opt.filt_subsample = opt.SubsamplePolicy;\n  end\n\n  read_hdr = struct('fs',hdr{filePos}.fs, ...\n                    'nChans',hdr{filePos}.NumberOfChannels, ...\n                    'scale',hdr{filePos}.scale, ...\n                    'endian',hdr{filePos}.endian, ...\n                    'BinaryFormat',readbv_binformat(filePos));\n\n  % get the position for the data in the whole data set\n  if firstFileToRead == filePos\n    firstX = 1;\n    firstData = firstFileSkip + 1;\n  else\n    firstX = lastX + 1;\n    firstData = 1;\n  end\n\n  if lastFileToRead == filePos\n    lastX = nSamples;\n    lastData = lastFileLength;\n  else\n    lastX = firstX + dataSize(filePos) - 1 - firstFileSkip;\n    lastData = dataSize(filePos);\n  end\n\n  read_opt.data = cnt.x;\n  read_opt.dataPos = [firstX lastX firstData lastData] - 1;\n\n  % read the data, read_bv will set the data in cnt.x because of the\n  % read_opt.data options\n  read_bv([fileNames{filePos} '.eeg'], read_hdr, read_opt);\n  cnt.yUnit= hdr{filePos}.unit;\n\n  %% Markers\n  if nargout>1,\n    opt_mrk= opt_substruct(opt, props_readBVmarkers(:,1));\n    curmrk= file_readBVmarkers(fileNames{filePos}, opt_mrk);\n    curmrk.time= curmrk.time + dataOffset*1000/cnt.fs;\n    % find markers in the loaded interval\n    inival= find(curmrk.time > skip*1000/cnt.fs & ...\n                 curmrk.time <= (skip+maxlen)*1000/cnt.fs);\n    % add special case: don't loose t=0 markers\n    % NO: markers with time=0 make problems!\n    %if skip==0,\n    %  idxzero= find(curmrk.time==0);\n    %  inival= [idxzero, inival];\n    %end\n    curmrk= mrk_selectEvents(curmrk, inival);\n    %let the markers start at zero\n    curmrk.time= curmrk.time - skip*1000/cnt.fs;\n\n    if firstFileToRead == filePos\n      mrk = curmrk;\n    else\n      mrk = mrk_mergeMarkers(mrk, curmrk);\n    end\n    dataOffset = dataOffset + dataSize(filePos);\n  end\nend\nclear read_opt;\n\nif ~isempty(opt.LinearDerivation),\n  ld= opt.LinearDerivation;\n  for cc= 1:length(ld),\n    ci= util_chanind(cnt.clab, ld(cc).chan);\n    support= find(ld(cc).filter);\n    s2= util_chanind(cnt.clab, ld(cc).clab(support));\n    cnt.x(:,ci)= cnt.x(:,s2) * ld(cc).filter(support);\n    cnt.clab{ci}= ld(cc).new_clab;\n  end\n  % delete temporary channels: TODO in a memory efficient way\n  idx= util_chanind(cnt, rm_clab);\n  cnt.x(:,idx)= [];\n  cnt.clab(idx)= [];\nend\n\nvarargout= cell(1, nargout);\n\nvarargout{1}= cnt;\nif nargout > 1,\n  varargout{2} = mrk;\nend\nif nargout>2,\n  if(1 == length(hdr))\n    varargout{3} = hdr{1};\n  else\n      varargout{3}= hdr;\n  end\nend\n\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/fileio/file_readBV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2300491498313788}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email:  nickabattista@gmail.com\n% Date Created: October 8th, 2018\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs / non-invariant beams *)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us %to add a specific muscle model, please let Nick (nickabattista@gmail.com) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: helps input previous .vtk information for restarting a\n%           simulation that has ended because of power failure, etc.\n%\n%      NOTE: for restart protocol, need to have .vtk data for:\n%                       1. lagPts (Lagrangian positions)\n%                       2. u (velocity field)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [current_time,cter,ctsave,U,V,xLag,yLag,xLag_P,yLag_P,path_to_data] = help_Me_Restart(dt)\n\n% \n% NEEDS TO BE HARDCODED PER SIMULATION BASIS\n% \nctsave = 3;               % Last time-step of data saved (# at end of .vtk file);\nprint_dump = 40;           % Print_dump interval as given in input2d\n\n% Path to Simulation Data (e.g., including viz_IB2d folder)\npath_to_data = '/Users/battistn/Desktop/IB2d/matIB2d/Examples/Example_Test_Restart_Protocol/Standard_Rubberband_Restart/viz_IB2d/';\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ------------- DO NOT CHANGE BELOW --------------- %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[current_time,cter,ctsave,U,V,xLag,yLag,xLag_P,yLag_P] = pass_Back_Data_For_Restart(dt,ctsave,print_dump,path_to_data);\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_Test_Restart_Protocol/Standard_Rubberband_Restart/help_Me_Restart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2300491498313788}}
{"text": "function engine = belprop_inf_engine(fg, max_iter, momentum, tol, maximize)\n\nif nargin < 2, max_iter = length(fg.G); end\nif nargin < 3, momentum = 0; end\nif nargin < 4, tol = 1e-3; end\nif nargin < 5, maximize = 0; end\n\nengine.fgraph = fg;\nengine.max_iter = max_iter;\nengine.momentum = momentum;\nengine.tol = tol;\nengine.maximize = maximize;\n\n% store results computed by enter_evidence here\nndoms = length(fg.doms);\nnvars = length(fg.vars);\nengine.marginal_domains = cell(1, ndoms);\n\n% to compute the marginal on each variable, we need to know which domain to marginalize\n% so we represent each domain as a bit vector, and compute its (pre-evidence) weight\nengine.dom_weight = [];\n\n% engine.dom_bitv = sparse(ndoms, nvars);\n% ns = fg.node_sizes;\n% for i=1:ndoms\n%   engine.dom_bitv(i, fg.doms{i}) = 1;\n%   engine.dom_weight(i) = prod(ns(fg.doms{i}));\n% end\n\n\nengine = class(engine, 'belprop_inf_engine');\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/static/@belprop_inf_engine/Old/belprop_inf_engine_nostr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397252}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email:  nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: EXAMPLE DATA ANALYSIS CODE TO LOOK AT FLOW IN EMPTY CHANNEL\n%\n%     Note: \n%           (1) This code analyzes viz_IB2d code for channel flow in\n%               /data_analysis/Example_For_Data_Analysis/Example_Flow_In_Channel/viz_IB2d\n%           (2) Produces a plot of cross-sectional mag. of velocity for\n%               different points along the channel at three times.\n%           (3) USER-DEFINED functions are functions that users should make to\n%               analyze their specific data sets\n%           (4) MUST make sure to 'addpath' to where DA_Blackbox is, i.e.,\n%               line 61\n%           (5) MUST make sure to set path to desired dataset, i.e., in line\n%               56\n%          \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Example_Channel_Flow_Analysis()\n\n% TEMPORAL INFO FROM input2d %\ndt = 1e-4;      % Time-step\nTfinal = 0.015; % Final time in simulation\npDump=50;       % Note: 'print_dump' should match from input2d\n\n% DATA ANALYSIS INFO %\nstart=1;                             % 1ST interval # included in data analysis\nfinish=3;                            % LAST interval # included in data analysis \ndump_Times = (start:1:finish)*pDump; % Time vector when data was printed in analysis\n\n% SET PATH TO DESIRED viz_IB2d DATA and hier_IB2d DATA %\npathViz = 'viz_IB2d';\npathForce='hier_IB2d_data';\n\n% SET PATH TO DA_BLACKBOX %\naddpath('../../DA_Blackbox');\n\nfor i=start:1:finish\n    \n    % Points to desired data viz_IB2d data file\n    if i<10\n       numSim = ['000', num2str(i)];\n    elseif i<100\n       numSim = ['00', num2str(i)];\n    elseif i<1000\n       numSim = ['0', num2str(i)];\n    else\n       numSim = num2str(i);\n    end\n    \n    % Imports immersed boundary positions %\n    [xLag,yLag] = give_Lag_Positions(pathViz,numSim);\n\n    % Imports (x,y) grid values and ALL EULERIAN DATA %\n    %                      DEFINITIONS \n    %          x: x-grid                y: y-grid\n    %       Omega: vorticity           P: pressure\n    %    uMag: mag. of velocity  \n    %    uX: mag. of x-Velocity   uY: mag. of y-Velocity  \n    %    U: x-directed velocity   V: y-directed velocity\n    %    Fx: x-directed Force     Fy: y-directed Force\n    %\n    %  Note: U(j,i): j-corresponds to y-index, i to the x-index\n    %\n    % \n    Eulerian_Flags(1) = 0;   % OMEGA\n    Eulerian_Flags(2) = 0;   % PRESSURE\n    Eulerian_Flags(3) = 1;   % uMAG\n    Eulerian_Flags(4) = 0;   % uX (mag. x-component of velocity)\n    Eulerian_Flags(5) = 0;   % uY (mag. x-component of velocity)\n    Eulerian_Flags(6) = 0;   % uVEC (vector components of velocity: U,V)\n    Eulerian_Flags(7) = 0;   % Fx (x-component of force )\n    Eulerian_Flags(8) = 0;   % Fy (y-component of force)\n    Eulerian_Flags(9) = 0;   % C (concentration)\n    %\n    [x,y,Omega,P,uMag,uX,uY,U,V,Fx,Fy,C] = import_Eulerian_Data(pathViz,numSim,Eulerian_Flags);\n    \n    \n    % Imports Lagrangian Pt. FORCE (magnitude) DATA %\n    %                      DEFINITIONS \n    %\n    %      fX_Lag: forces in x-direction on boundary\n    %      fY_Lag: forces in y-direction on boundary\n    %       fLagMag: magnitude of force at boundary\n    %   fLagNorm: magnitude of NORMAL force at boundary\n    %   fLagTan: magnitude of TANGENT force at boundary\n    %\n    [fX_Lag,fY_Lag,fLagMag,fLagNorm,fLagTan] = import_Lagrangian_Force_Data(pathForce,numSim);\n    \n    %                 \n    %\n    % *** USER DEFINED FUNCTIONS TO GET DESIRED ANALYSIS PT. INDICES *** %\n    %                                                                    %\n    if i==start\n        %xPts = [0.125 0.225 0.325 0.425];\n        xPts = [0.25 0.375 0.5 0.675];\n        yPts = [0.405 0.595];\n        [xInds,yInds] = give_Desired_Analysis_Points(x,y,xPts,yPts);\n        vel_data = zeros(length(yInds),length(xInds),finish);\n        %Inds = put_x_y_Indices_Together_For_Analysis(xInds,yInds);\n    end\n    \n    %                                                                    %\n    % ***** USER DEFINED FUNCTION TO SAVE DESIRED VELOCITY DATA *****    %\n    %                                                                    %\n    vel_data = store_Desired_Magnitude_Velocity_Data(uMag,vel_data,xInds,yInds,i);\n\nend % END OF LOOP OVER ANALYZED TIME-PTS\n\n\n%                                                                    %\n% ***** USER DEFINED FUNCTION TO PLOT DESIRED VELOCITY DATA *****   %\n%                                                                    %\nyVals = y(yInds);\nplot_Desired_Data(yVals,vel_data);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% USER-FUNCTION: Finds desired analysis point indices\n%\n%        INPUTS: x: x-grid pts (row vector)\n%                y: y-grid pts (column vector)\n%                xPts: desired x-pts to analyze\n%                yPts: desired y-pts to analyze\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xInds,yInds] = give_Desired_Analysis_Points(x,y,xPts,yPts)\n\n% Get x-Indices\nxInds = zeros(length(xPts),1);\nfor i=1:length(xPts)\n   xPt = xPts(i);   % Get x-Pts\n   k = 1;           % Initialize loop iteration variable\n   while x(k) < xPt\n      xInds(i) = k; \n      k = k+1;\n   end\nend\n\n% Get y-Indices\nyIndsAux = zeros(length(yPts),1);\nfor i=1:length(yPts)\n   yPt = yPts(i);   % Get x-Pts\n   k = 1;           % Initialize loop iteration variable\n   while y(k) < yPt\n      yIndsAux(i) = k; \n      k = k+1;\n   end\nend\nyInds = yIndsAux(1):1:yIndsAux(2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% USER-FUNCTION: Rearranges desired analysis indices\n%\n%        INPUTS: xInds: indices for x-region of interest\n%                yInds: indices for y-region of interest\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Inds = put_x_y_Indices_Together_For_Analysis(xInds,yInds)\n\n% Order new index matrix %\nInds = zeros(length(xInds)*length(yInds),2);\ncount = 1;\nfor i=1:length(xInds)\n    for j=1:length(yInds)\n        Inds(count,1) = xInds(i);\n        Inds(count,2) = yInds(j);\n        count=count+1;\n    end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% USER-FUNCTION: Stores desired magnitude of velocity data\n%\n%        INPUTS: uMag: magnitude of velocity from simulation\n%                vel_data: stored mag. of velocity data in 3D-matrix\n%                xInds/yInds: indices of where to save data\n%                i: ith time-step to store data from\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vel_data = store_Desired_Magnitude_Velocity_Data(uMag,vel_data,xInds,yInds,i)\n\n% NOTE: vel_data(k,i): : k: magnitude of velocity data  (row)\n%                      : j: xPt you're storing data for (column)\n%                      : i: ith level you're storing in (level)\n\nfor j=1:length(xInds)\n    for k=1:length(yInds)\n       vel_data(k,j,i) = uMag( yInds(k),xInds(j) ); \n    end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% USER-FUNCTION: Plots magnitude of velocity data\n%\n%        INPUTS: vel_data: stored mag. of velocity data in 3D-matrix\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Desired_Data(yVals,vel_data)\n\nfs = 16; % Font Size\nlw = 5;  % Line Width\nms = 32; % MarkerSize\n\n% Set Figure Size\nFigHand = figure(1);\nset(FigHand,'Position',[100,100,1024,895]);\n%\n% Make Figure!\n%\nsubplot(3,1,1)\nmat = vel_data(:,:,1);\nmaxVal = max(max(mat));\nplot(yVals(2:end),vel_data(2:end,1,1),'.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,2,1),'r.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,3,1),'g.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,4,1),'k.-','LineWidth',lw,'MarkerSize',ms); hold on;\naxis([0.4 0.6 0 1.1*maxVal]);\nleg=legend('x=0.25','x=0.375','x=0.50','x=0.625');\ntitle('t=0.005s'); \nylabel('Mag. Velocity','FontSize',fs); xlabel('y','FontSize',fs);\nset(leg,'FontSize',fs);\nset(gca,'FontSize',fs-1);\n%\nsubplot(3,1,2)\nmat = vel_data(:,:,2);\nmaxVal = max(max(mat));\nplot(yVals(2:end),vel_data(2:end,1,2),'.-','LineWidth',lw,'MarkerSize',ms);  hold on;\nplot(yVals(2:end),vel_data(2:end,2,2),'r.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,3,2),'g.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,4,2),'k.-','LineWidth',lw,'MarkerSize',ms); hold on;\naxis([0.4 0.6 0 1.1*maxVal]);\nleg=legend('x=0.25','x=0.375','x=0.50','x=0.625');\nylabel('Mag. Velocity','FontSize',fs); xlabel('y','FontSize',fs);\nset(leg,'FontSize',fs);\nset(gca,'FontSize',fs-1);\ntitle('t=0.01s');\n%\nsubplot(3,1,3)\nmat = vel_data(:,:,3);\nmaxVal = max(max(mat));\nplot(yVals(2:end),vel_data(2:end,1,3),'.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,2,3),'r.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,3,3),'g.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(yVals(2:end),vel_data(2:end,4,3),'k.-','LineWidth',lw,'MarkerSize',ms); hold on;\naxis([0.4 0.6 0 1.1*maxVal]);\nleg=legend('x=0.25','x=0.375','x=0.50','x=0.625');\nylabel('Mag. Velocity','FontSize',fs); xlabel('y','FontSize',fs);\nset(leg,'FontSize',fs);\nset(gca,'FontSize',fs-1);\ntitle('t=0.015s');\n\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/data_analysis/analysis_in_matlab/Example_For_Data_Analysis/Example_Flow_In_Channel/Example_Channel_Flow_Analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22996647805794784}}
{"text": "function [event] = read_nexstim_event(filename)\n\n% Use as\n%   [event] = read_nexstim_event(filename)\n\n% Written by Vladimir Litvak based on the function nxeGetTriggers\n% provided by Nexstim\n%\n% Copyright (C) 2007, Vladimir Litvak\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id: read_nexstim_event.m 945 2010-04-21 17:41:20Z roboos $\n\n% trigLine - either 1(GATE), 2(TRIG1) or 3(TRIG2)\n% trigEdge - either 'rising' or 'falling'\n\nfid=fopen(filename,'r','l');\n\nnumChannels = 64;\nblockSamples = 14500;\ntrigThreshold = 2000;\ntrigChannels = [1 2 3]; % Is fixed for the present Nexstim format.\n\nfseek(fid,0,'eof');\nnumBytes = ftell(fid);\nnumSamples = (numBytes/2)/numChannels;\nnumBlocks = ceil(numSamples/blockSamples);\n\nfseek(fid,0,'bof');\ntrigPos=[];\n\nevent=[];\nfor i = 1:numBlocks\n    blockPos=(i-1)*blockSamples;\n    data = fread(fid,[numChannels blockSamples+1],'int16');\n\n    for trigLine=1:length(trigChannels);\n        trigPosRising = find(diff(data(trigChannels(trigLine),:))>trigThreshold)+blockPos;\n        trigPosFalling = find(diff(data(trigChannels(trigLine),:))<-trigThreshold)+blockPos;\n\n        if ~isempty(trigPosRising)\n            for i=1:length(trigPosRising)\n                event(end+1).type     = 'rising';\n                event(end  ).sample   =  trigPosRising(i);\n                event(end  ).value    = trigLine;\n                event(end  ).offset   = [];\n                event(end  ).duration = [];\n            end\n        end\n\n        if ~isempty(trigPosFalling)\n            for i=1:length(trigPosFalling)\n                event(end+1).type     = 'falling';\n                event(end  ).sample   =  trigPosFalling(i);\n                event(end  ).value    = trigLine;\n                event(end  ).offset   = [];\n                event(end  ).duration = [];\n            end\n        end\n\n    end\n    fseek(fid,-(2*numChannels),'cof');\nend\n\nfclose(fid);\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/read_nexstim_event.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.22990842017511665}}
{"text": "function F = plus( F, G ) \n% + PLUS of two CHEBFUN2V objects. \n%   F + G if F and G are CHEBFUN2V objects does componentwise addition. \n%\n%   F + G if F is a double and G is a CHEBFUN2V does componentwise addition. \n% \n%   F + G if F is a CHEBFUN2V and G is a double does componentwise addition.\n% \n%   PLUS(F,G) is called for the syntax F + G. \n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information. \n\n% Empty check: \nif ( isempty( F ) || isempty( G ) ) \n    F = chebfun2v; \n    return\nend\n\nif ( ~isa( F , 'chebfun2v' ) )\n    F = plus(G, F); \n    return\nend\n\nnF = F.nComponents;\n\nif ( isa(G, 'double') )              % CHEBFUN2V + DOUBLE\n    if ( numel(G) == 1 )             % CHEBFUN2V + SCALAR\n        for jj = 1 : nF \n            F.components{jj} = plus(F.components{jj}, G);\n        end\n    elseif ( numel(G) == nF )        % CHEBFUN2V + MATRIX\n        for jj = 1 : nF \n             F.components{jj} = plus(F.components{jj}, G(jj));\n        end          \n    else\n        error('CHEBFUN:CHEBFUN2V:plus:doubleSize', 'Dimension mismatch.')\n    end\nelseif ( isa(G, 'chebfun2') )        % CHEBFUN2V + CHEBFUN\n    for jj = 1 : nF \n        F.components{jj} = plus(F.components{jj}, G);\n    end\nelseif ( isa(G, 'chebfun2v') )       % CHEBFUN2V + CHEBFUN2V\n    nG = G.nComponents; \n    if ( nG ~= nF ) \n        error('CHEBFUN:CHEBFUN2V:plus:components', ...\n            'The chebfun2v objects do not have the same components.')\n    end\n    if ( G.isTransposed ~= F.isTransposed )\n        error('CHEBFUN:CHEBFUN2V:plus:transposed', 'Dimension mismatch.')\n    end\n    for jj = 1 : nF                  % Add each component together\n        F.components{jj} = plus(F.components{jj}, G.components{jj});\n    end\nelse\n    error('CHEBFUN:CHEBFUN2V:plus:type', 'Unrecongized input arguments')\nend\n\nend\n    \n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun2v/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22972390130921885}}
{"text": "function run_experiment_cfnet_conv1(imdb_video)\n%% Experiment entry point\n\n    startup;\n    opts.gpus = 1;\n    if nargin < 1\n        imdb_video = [];\n    end\n\n    opts.join.method = 'corrfilt';\n    opts.join.conf.lambda = 10;\n    opts.join.conf.window = 'cos';\n    opts.join.conf.sigma = 8;\n    opts.join.conf.target_lr = 0;\n\n    opts.branch.conf.last_layer = 'relu1';\n    opts.branch.conf.num_out     = [32];\n    opts.branch.conf.num_in      = [ 3 ];\n    opts.branch.conf.conv_stride = [ 4];\n    opts.branch.conf.pool_stride = [ 2];\n\n    opts.exemplarSize = 255;\n    opts.train.numEpochs = 100;\n\n    experiment(imdb_video, opts);\nend\n\n", "meta": {"author": "bertinetto", "repo": "cfnet", "sha": "971e7922b7f0f9140e0d995b598e8d97dece277c", "save_path": "github-repos/MATLAB/bertinetto-cfnet", "path": "github-repos/MATLAB/bertinetto-cfnet/cfnet-971e7922b7f0f9140e0d995b598e8d97dece277c/src/training/run_experiment_cfnet_conv1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}}
{"text": "function [recall, rankloss]= testNet(db, net, opts, ID, qFeat, dbFeat)\n    \n    relja_display('testNet: %s %s', opts.sessionID, ID);\n    \n    rankloss= testCoreRank(db, qFeat, dbFeat, opts.margin, opts.nNegChoice, 'nTestSample', opts.nTestRankSample);\n    recall= testCore(db, qFeat, dbFeat, 'nTestSample', opts.nTestSample, 'recallNs', opts.recallNs);\nend\n", "meta": {"author": "Relja", "repo": "netvlad", "sha": "652dbe71aa45c691961ddd9f6cf902574e6bdc2f", "save_path": "github-repos/MATLAB/Relja-netvlad", "path": "github-repos/MATLAB/Relja-netvlad/netvlad-652dbe71aa45c691961ddd9f6cf902574e6bdc2f/testNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}}
{"text": "% SB2_CONTROLSETTINGS  Set parameters to control the SPARSEBAYES algorithm\n%\n% CONTROLS = SB2_CONTROLSETTINGS\n%\n% OUTPUT ARGUMENTS:\n% \n%\tCONTROLS\tA structure whose fields control various aspects of the\n%\t\t\t\trunning of the SPARSEBAYES algorithm.\n% \n%\t.ZeroFactor\t\t\tSmall number equivalent to zero for Q^2-S\n%\t.MinDeltaLogAlpha\tTermination criterion for changes in log-alpha\n%\t.MinDeltaLogBeta\tTermination criterion for changes in log-beta\n% \n%\t.PriorityAddition\tPrefer \"addition\" operations\n%\t.PriorityDeletion\tPrefer \"deletion\" operations\n% \n%\t.BetaUpdateStart\tHow many \"fast start\" beta updates\n%\t.BetaUpdateFrequency\t\n%\t\t\t\t\t\tHow regularly to update beta after the above\n%\t.BetaMaxFactor\t\tMinimum value control for noise estimate\n% \n%\t.PosteriorModeFrequency\t\n%\t\t\t\t\t\tHow regularly to re-find the posterior mode\n% \n%\t.BasisAlignmentTest\tTest for redundant basis vectors?\n%\t.AlignmentMax\t\tBasis redundancy criterion\n% \n% NOTES:\n% \n% The various definitions in the file are effectively \"fixed\" and not\n% modified elsewhere.\n%\n% The interested user may wish to experiment with the operation of the\n% SPARSEBAYES algorithm by modifying the values the file directly. See the\n% inline comments for hints on the various control settings.\n%\n\n%\n% Copyright 2009, Vector Anomaly Ltd\n%\n% This file is part of the SPARSEBAYES library for Matlab (V2.0).\n%\n% SPARSEBAYES is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the Free\n% Software Foundation; either version 2 of the License, or (at your option)\n% any later version.\n%\n% SPARSEBAYES is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n% FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\n% more details.\n%\n% You should have received a copy of the GNU General Public License along\n% with SPARSEBAYES in the accompanying file \"licence.txt\"; if not, write to\n% the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n% MA 02110-1301 USA\n%\n% Contact the author: m a i l [at] m i k e t i p p i n g . c o m\n%\nfunction CONTROLS = SB2_ControlSettings\n\n%% Define parameters which influence the underlying operation of the \n%% SparseBayes inference algorithm\n\n% TOLERANCES\n% \n% Any Q^2-S \"relevance factor\" less than this is considered to be zero\n% \nCONTROLS.ZeroFactor\t\t\t= 1e-12;\n%\n% If the change in log-alpha for the best re-estimation is less than this,\n% we consider termination\n% \nCONTROLS.MinDeltaLogAlpha\t= 1e-3;\n%\n% In the Gaussian case, we also require a beta update to change the value\n% of log-beta (inverse noise variance) less than this to terminate\n% \nCONTROLS.MinDeltaLogBeta\t= 1e-6;\n\n% ADD/DELETE\n% \n% - preferring addition where possible will probably make the algorithm a\n% little slower and perhaps less \"greedy\"\n% \n% - preferring deletion may make the model a little more sparse and the\n% algorithm may run slightly quicker\n% \n% Note: both these can be set to 'true' at the same time, in which case\n% both take equal priority over re-estimation.\n% \nCONTROLS.PriorityAddition\t= false;\nCONTROLS.PriorityDeletion\t= true;\n\n% (GAUSSIAN) NOISE\n%\n% When to update the noise estimate\n%\n% The number of iterations from the start for which we update it every\n% iteration (to get in the right ball-park to begin with)\n% \nCONTROLS.BetaUpdateStart\t\t= 10;\n%\n% After the above, we only regularly update it after \n% a given number of iterations\n% \nCONTROLS.BetaUpdateFrequency\t= 5;\n%\n% Prevent zero-noise estimate (perfect fit) problem\n% -\teffectively says the noise variance estimate is clamped to be no\n%\tlower than variance-of-targets / BetaMaxFactor.\n% \nCONTROLS.BetaMaxFactor\t\t\t= 1e6;\n\n% POSTERIORMODE\n%\n% How many alpha updates to do in between each full posterior mode\n% computation in the non-Gaussian case\n% \n% In principle, this should be set to one (to update the posterior every\n% iteration) but it may be more efficient to do several alpha updates before\n% re-finding the posterior mode.\n% \nCONTROLS.PosteriorModeFrequency\t= 1;\n\n% REDUNDANT BASIS\n%\n% Check for basis vector alignment/correlation redundancy\n% \nCONTROLS.BasisAlignmentTest\t\t= true;\n%\nALIGNMENT_ZERO\t\t\t\t\t= 1e-3;\n%\n% If BasisAlignmentTest is true, any basis vector with inner product more\n% than MAX_ALIGNMENT with any existing model vector will not be added\n% \nCONTROLS.AlignmentMax\t\t\t= 1 - ALIGNMENT_ZERO;\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SparseBayes-2.0/SB2_ControlSettings.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.22972389467679044}}
{"text": "function ApplyQiB()\n%A rountine to execute the QIB on a computer cluster\n% Written By: Issam El Naqa    Date: 10/3/03\n% Revised by:                  Date:  \n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n% read a treatment plan in \"mat\" format\n[filename, pathname] = uigetfile('*.mat', 'Load a treatment plan');\nload([pathname,filename]);\nD=1; % downsample factor (optional)\nindexS = planC{end};\nscaleX=planC{indexS.scan}.scanInfo(1).grid1Units*D;\nscaleY=planC{indexS.scan}.scanInfo(1).grid2Units*D;\nscaleZ=planC{indexS.scan}.scanInfo(1).sliceThickness;\n% get the CT file\ninputCT=planC{indexS.scan}.scanArray;\n% apply down sampling and cropping\nvecx=145:D:394; vecy=126:D:375; vecz=40:99;\ninputCTc=inputCT(vecx,vecy,vecz);  clear inputCT \nCTdim=size(inputCTc);\n% add margins of 1 cm to the targets\nMargin=1;\nTargetStructNum=[17,18];\ninputMask1 = getMask3D(TargetStructNum(1),planC);\ninputMask2 = getMask3D(TargetStructNum(2),planC);\ninputMask=inputMask1 | inputMask2;\ninputMasks=inputMask(vecx,vecy,vecz); % just cropping\nclear planC inputMask1 inputMask2 inputMask\nb=genball(7,Margin/2,[scaleX,scaleY,scaleZ]); % plan specific\n% treat the targets separately!\ninputMaskb=convn(inputMasks,b,'same'); \neinputMask=uint8(inputMaskb>0);\nind=regexp(filename,'.mat');\nmaskfile=filename(1:ind-1);\n%save([pathname,maskfile,'_targetmask.mat'],'inputMasks','einputMask','CTdim','scaleX','scaleY','scaleZ');\ngridX_distance100=1; gridY_distance100=1;\nEnergy=6; % plan specific and is inversely proportional to the squared uncertainity\nNbeams=9; % plan specific\nSource_Distance=100;\n[x,y]=circle([0,0], Source_Distance,Nbeams);\nSCRCM=[x(1:Nbeams);y(1:Nbeams);zeros(1,Nbeams)];\n% not clear about conventions?!\nfor N=1:Nbeams\n    beam_num=N\n    % need to be worked out?!\n    [targetBeamGridCoor, numberPB(N),OSC]=mybeamgridcoordinatesVMC(einputMask,scaleX,scaleY,scaleZ,gridX_distance100,gridY_distance100,SCRCM(:,N)); % this is wrong!\n    for i=1:numberPB(N)\n        [DoseF, downCT, vCT, depthCor] = get_PB_3D(Energy,gridX_distance100,gridX_distance100,Source_Distance,angle,shift,planC);\n        %temporal saving! need to be changed to other format?!\n        str=[filename,'_beam',num2str(N),'_pb',num2str(i)];\n        fid=fopen(str,'w');\n        fwrite(fid,CTdim(1),'int32'); fwrite(fid,CTdim(2),'int32');  fwrite(fid,CTdim(3),'int32');\n        fwrite(fid,downCT,'float32'); fwrite(fid,vCT,'float32');  fwrite(fid,depthCor,'float32');\n        fwrite(fid,DoseF,'float32');\n    end\nend\n\nfunction b=genball(N,r,Scale)\n% make a ball of dimension NxNxN and radius r, scaled by Scale\nLc=floor(N/2);\nvec=-Lc:Lc;\n[x,y,z]=meshgrid(vec*Scale(1),vec*Scale(2),vec*Scale(3));\nr2=x.^2+y.^2+z.^2;\nb=zeros(N,N,N);\nb(find(r2<r^2))=1;\nreturn\n\nfunction [x,y]=circle(c, r, nsides)\n% a poly circle routine with center c, radius r, and nsides\nnsides = round(nsides);  % make sure it is an integer\na = [0:2*pi/nsides:2*pi];\nx=r*cos(a)+c(1);\ny=r*sin(a)+c(2);\n%line(x,y); uncomment for plotting\nreturn\n\n\n\n\n\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/ApplyQIB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.22965674225727117}}
{"text": "function script_rfcn_VOC0712_ResNet50_OHEM_ss()\n% script_rfcn_VOC0712_ResNet50_OHEM_ss()\n% RFCN training and testing with OHEM using ResNet50 model and selective\n% search proposals\n% --------------------------------------------------------\n% R-FCN implementation\n% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)\n% Copyright (c) 2016, Jifeng Dai\n% Licensed under The MIT License [see LICENSE for details]\n% --------------------------------------------------------\n\nclc;\nclear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));\n%% -------------------- CONFIG --------------------\nopts.caffe_version          = 'caffe_rfcn';\nopts.gpu_id                 = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\n\n% model\nmodel                       = Model.ResNet50_for_RFCN_VOC0712_OHEM();\n% cache name\nopts.cache_name             = 'rfcn_VOC0712_ResNet50_OHEM_ss';\n% config\nconf                        = rfcn_config_ohem('image_means', model.mean_image);\n% train/test data\nfprintf('Loading dataset...')\ndataset                     = [];\ndataset                     = Dataset.voc0712_trainval_ss(dataset, 'train', conf.use_flipped);\ndataset                     = Dataset.voc2007_test_ss(dataset, 'test', false);\nfprintf('Done.\\n');\n\n% do validation, or not\nopts.do_val                 = true; \n\n%% -------------------- TRAINING --------------------\n\nopts.rfcn_model        = rfcn_train(conf, dataset.imdb_train, dataset.roidb_train, ...\n                                'do_val',           opts.do_val, ...\n                                'imdb_val',         dataset.imdb_test, ...\n                                'roidb_val',        dataset.roidb_test, ...\n                                'solver_def_file',  model.solver_def_file, ...\n                                'net_file',         model.net_file, ...\n                                'cache_name',       opts.cache_name, ...\n                                'caffe_version',    opts.caffe_version);\nassert(exist(opts.rfcn_model, 'file') ~= 0, 'not found trained model');\n\n%% -------------------- TESTING --------------------\n                          rfcn_test(conf, dataset.imdb_test, dataset.roidb_test, ...\n                                'net_def_file',     model.test_net_def_file, ...\n                                'net_file',         opts.rfcn_model, ...\n                                'cache_name',       opts.cache_name,...\n                                'ignore_cache',     true);\n\nend\n", "meta": {"author": "daijifeng001", "repo": "R-FCN", "sha": "94797e0e8d15998a9ab0a76cbac3281ad907f04a", "save_path": "github-repos/MATLAB/daijifeng001-R-FCN", "path": "github-repos/MATLAB/daijifeng001-R-FCN/R-FCN-94797e0e8d15998a9ab0a76cbac3281ad907f04a/experiments/script_rfcn_VOC0712_ResNet50_OHEM_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22957436137001658}}
{"text": "function dfdocontext(varargin)\n%DFDOCONTEXT Perform context menu actions for distribution fitting tool\n\n% Copyright 2001-2004 The MathWorks, Inc.\n% $Revision: 1.1.6.7 $  $Date: 2004/03/09 16:17:04 $\nimport com.mathworks.toolbox.stats.*;\n\n\n% Special action to create context menus\nif isequal(varargin{1},'create')\n   makecontextmenu(varargin{2});\n   return\nend\n\n% Get information about what invoked this function\nobj = gcbo;\naction = get(obj,'Tag');\nh = gco;\nif isempty(h), return; end\ndffig = gcbf;\n\n% Set up variables that define some menu items\n[sizes styles markers] = getmenuitems;\nstyles{end+1} = 'none';\n\nchanged = true;   % did a line property change?\n\nswitch action\n\n % This case is triggered when we display the menu\n case {'fitcontext' 'datacontext'}\n   % Store a handle to the object that triggered this menu\n   set(obj,'UserData',h);\n\n   hObject = get(h,'UserData');\n   c = findall(obj,'Type','uimenu');\n   hBounds = findall(c,'flat','Tag','confbounds');\n   ftype = dfgetset('ftype');\n   \n   % Enable or disable as appropriate\n   hMarker = findall(c,'flat','Tag','marker');\n   if isequal(action,'datacontext')\n      hLineStyle = findall(c,'flat','Tag','linestyle');\n      hLineWidth = findall(c,'flat','Tag','linewidth');\n      hBinRules = findall(c,'flat','Tag','binrules');\n      if isequal(ftype,'probplot')\n         set(hMarker,'Enable','on');\n         set(hLineStyle,'Enable','off');\n         set(hLineWidth,'Enable','off');\n         set(hBinRules,'Enable','off');\n      elseif isequal(ftype,'pdf')\n         set(hMarker,'Enable','off');\n         set(hLineStyle,'Enable','on');\n         set(hLineWidth,'Enable','on');\n         set(hBinRules,'Enable','on');\n      else\n         set(hMarker,'Enable','off');\n         set(hLineStyle,'Enable','on');\n         set(hLineWidth,'Enable','on');\n         set(hBinRules,'Enable','off');\n      end\n   else\n      if ~hObject.iscontinuous && isequal(ftype,'pdf')\n         set(hMarker,'Enable','on');\n      else\n         set(hMarker,'Enable','off');\n      end\n   end\n   try\n      hasconfbounds = hObject.distspec.hasconfbounds;\n   catch\n      hasconfbounds = false;\n   end\n   if isequal(ftype,'pdf') || isequal(ftype,'probplot') || ...\n      (isequal(action,'fitcontext') && ~hasconfbounds) || ...\n      (isequal(action,'datacontext') && isequal(ftype,'icdf'))\n      set(hBounds,'Enable','off');\n   else\n      set(hBounds,'Enable','on');\n   end\n\n   set(c,'Checked','off');\n\n   % Fix check mark for confidence bounds\n   if hObject.showbounds\n      set(hBounds,'Checked','on');\n   end\n\n   % Fix check marks on line width and line style cascading menus\n   w = get(h,'LineWidth');\n   u = findall(c,'flat','Tag',num2str(w));\n   if ~isempty(u)\n      set(u,'Checked','on');\n   end\n   w = get(h,'LineStyle');\n   u = findall(c,'flat','Tag',w);\n   if ~isempty(u)\n      set(u,'Checked','on');\n   end\n   w = get(h,'Marker');\n   u = findall(c,'flat','Tag',w);\n   if ~isempty(u)\n      set(u,'Checked','on');\n   end\n   return\n   \n % Remaining cases are triggered by selecting menu items\n case 'confbounds'\n   hObject = get(h,'UserData');\n   hObject.showbounds = ~hObject.showbounds;\n   nm = get(hObject,'name');\n   htag = get(h,'Tag');\n   if isequal(htag,'dfdata')\n      DataSetsManager.getDataSetsManager.dataSetChanged(java(hObject),nm,nm);\n   else\n      FitsManager.getFitsManager.fitChanged(java(hObject),nm,nm);\n   end\n\n case 'color'\n   oldcolor = get(h,'Color');\n   newcolor = uisetcolor(oldcolor);\n   if ~isequal(oldcolor,newcolor)\n      set(h,'Color',newcolor);\n   end\n\n case styles\n   set(h,'LineStyle',action);\n\n case markers\n   if isequal(action,'point')\n      msize = 12;\n   else\n      msize = 6;\n   end\n   set(h,'Marker',action,'MarkerSize',msize);\n\n % Either delete a fit, or a hide a fit or data set\n case {'hidecurve' 'deletefit'}\n   htag = get(h,'Tag');\n   if isequal(htag,'distfit') || isequal(htag,'dfdata')\n      hndl = get(h,'UserData');\n      if isequal(action,'hidecurve')\n         hndl.plot = 0;\n         nm = get(hndl,'name');\n      else\n         % The delete action appears on the fit menu only, not the data set menu\n         FitsManager.getFitsManager.deleteFits(java(hndl));\n      end\n   end\n   changed = false;\n\n % Edit a fit\n case 'editfit'\n   htag = get(h,'Tag');\n   if isequal(htag,'distfit')  % should always be true\n      hndl = get(h,'UserData');\n      FitsManager.getFitsManager.editFit(hndl.name);\n   end\n   changed = false;\n\n % Bring up the \"Set Bin Width Rules\" dialog for this data set\n case 'binrules'\n   htag = get(h,'Tag');\n   if isequal(htag,'dfdata')\n      hndl = get(h,'UserData');\n      nm = get(hndl,'name');\n      bw = com.mathworks.toolbox.stats.BinWidth.getBinWidth; % get dialog\n      bw.displayBinWidth(nm); % display dialog for this data set\n   end\n   changed = false;\n \n % If the menu item is a number, it is a line width\n otherwise\n   j = str2num(action);\n   if ~isempty(j)\n      set(h,'LineWidth',j);\n   end\n\nend\n\nif changed\n   % Save plot info in the fit or data set object\n   hObject = get(h,'UserData');\n   savelineproperties(hObject);\n\n   % Update legend\n   dfupdatelegend(dffig);\nend\n\n\n% ---------------------- helper to make context menu\nfunction makecontextmenu(dffig)\n%MAKECONTEXTMENU Creates context menu for curve fitting figure\n\n% Create context menus for fits, data curve, probability plot data curves\ncFit = uicontextmenu('Parent',dffig,'Tag','fitcontext','Callback',@dfdocontext);\nuimenu(cFit,'Label','Color...','Tag','color','Callback',@dfdocontext);\n\n% Add menu items for line and marker control\nuwidth = uimenu(cFit,'Label','Line &Width','Tag','linewidth');\nustyle = uimenu(cFit,'Label','Line &Style','Tag','linestyle');\numark = uimenu(cFit,'Label','Marker','Tag','marker','Position',2);\n\n% Add menu items to control confidence bounds\nuimenu(cFit,'Label','Confidence &Bounds','Callback',@dfdocontext,...\n            'Tag','confbounds');\n\n% Get menu item labels and tags\n[sizes styles markers slabels mlabels] = getmenuitems;\n\nfor j=1:length(markers)\n   uimenu(umark,'Label',mlabels{j},'Callback',@dfdocontext,'Tag',markers{j});\nend\n\n% Sub-menus for line widths\nfor i = 1:length(sizes)\n   val = num2str(sizes(i));\n   uimenu(uwidth,'Label',val,'Callback',@dfdocontext,'Tag',val);\nend\n\n% Sub-menus for line styles\nfor j=1:length(styles)\n   uimenu(ustyle,'Label',slabels{j},'Callback',@dfdocontext,'Tag',styles{j});\nend\n\n% Copy the fit menu to create a data menu\ncData = copyobj(cFit,dffig);\nset(cData,'Tag','datacontext')\n\n% Add items for fit menus only\nuimenu(cFit,'Label','&Hide Fit','Tag','hidecurve','Callback',@dfdocontext,...\n       'Separator','on');\nuimenu(cFit,'Label','&Delete Fit','Tag','deletefit','Callback',@dfdocontext);\nuimenu(cFit,'Label','&Edit Fit','Tag','editfit','Callback',@dfdocontext);\n\n% Add items for data menus only\nuimenu(cData,'Label','&Hide Data','Tag','hidecurve',...\n       'Callback',@dfdocontext,'Separator','on');\nuimenu(cData,'Label','Set Bin &Rules','Tag','binrules',...\n       'Callback',@dfdocontext,'Separator','on');\n\n% -------------- helper to get menu item labels\nfunction [sizes,styles,markers,slabels,mlabels] = getmenuitems\n%GETMENUITEMS Get items for curve fitting context menus\nsizes = [0.5 1 2 3 4 5 6 7 8 9 10];\nstyles = {'-' '--' ':' '-.'};\nmarkers = {'+' 'o' '*' '.' 'x' 'square' 'diamond' ...\n        'v' '^' '<' '>' 'pentagram' 'hexagram'};\nslabels = {'solid' 'dash' 'dot' 'dash-dot'};\nmlabels = {'plus' 'circle' 'star' 'point' 'x-mark' 'square' 'diamond' ...\n           'triangle (down)' 'triangle (up)' 'triangle (left)' ...\n           'triangle (right)' 'pentagram' 'hexagram'};\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/weightedstats/private/dfdocontext.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.22957435584772945}}
{"text": "function tsss = tsss_config\n% configuration file for cropping\n%__________________________________________________________________________\n% Copyright (C) 2014 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: tsss_config.m 7703 2019-11-22 12:06:29Z guillaume $\n\n%--------------------------------------------------------------------------\n% D\n%--------------------------------------------------------------------------\nD        = cfg_files;\nD.tag    = 'D';\nD.name   = 'File Name';\nD.filter = 'mat';\nD.num    = [1 1];\nD.help   = {'Select the M/EEG mat file.'};\n\n%--------------------------------------------------------------------------\n% temporal\n%--------------------------------------------------------------------------\n\ntemporal = cfg_menu;\ntemporal.tag = 'temporal';\ntemporal.name = 'Do temporal denoising';\ntemporal.labels = {'Yes', 'No'};\ntemporal.val = {1};\ntemporal.values = {1,0};\ntemporal.help = {'Determines whether to use temporal denoising (tSSS)',...\n    'if not, just SSS is done.'};\n\n\n%--------------------------------------------------------------------------\n% realign\n%--------------------------------------------------------------------------\nDref        = cfg_files;\nDref.tag    = 'Dref';\nDref.name   = 'Reference dataset';\nDref.filter = 'mat';\nDref.num    = [0 1];\nDref.val    = {[]};\nDref.help   = {'Select the M/EEG mat file.',...\n    'Leave empty to realign within dataset'};\n\n\nrefind         = cfg_entry;\nrefind.tag     = 'refind';\nrefind.name    = 'Reference index';\nrefind.help    = {'Index of the reference sensors within dataset',...\n    'Normally should be 1. Set to 0 for not realigning a composite dataset'};\nrefind.strtype = 'w';\nrefind.num     = [1 1];\nrefind.val     = {1};\n\n\nrealign         = cfg_branch;\nrealign.tag      = 'realign';\nrealign.name     = 'Realign head location';\nrealign.val      = {Dref, refind};\nrealign.help     = {'Realign head location to another dataset'}';\n\n%--------------------------------------------------------------------------\n% timewin\n%--------------------------------------------------------------------------\ntimewin         = cfg_entry;\ntimewin.tag     = 'timewin';\ntimewin.name    = 'Time window';\ntimewin.help    = {'Time window (in sec) for temporal correlation',...\n    'Ignored for epoched data'};\ntimewin.strtype = 'r';\ntimewin.num     = [1 1];\ntimewin.val     = {1};\n\n%--------------------------------------------------------------------------\n% corrlimit\n%--------------------------------------------------------------------------\ncorrlimit         = cfg_entry;\ncorrlimit.tag     = 'corrlimit';\ncorrlimit.name    = 'Correlation limit';\ncorrlimit.help    = {'Correlation limit parameter for tSSS'};\ncorrlimit.strtype = 'r';\ncorrlimit.num     = [1 1];\ncorrlimit.val     = {0.98};\n\n%--------------------------------------------------------------------------\n% Lin\n%--------------------------------------------------------------------------\nLin         = cfg_entry;\nLin.tag     = 'Lin';\nLin.name    = 'Inner dimension';\nLin.help    = {'Order if the inner SSS basis'};\nLin.strtype = 'n';\nLin.num     = [1 1];\nLin.val     = {8};\n\n%--------------------------------------------------------------------------\n% Lout\n%--------------------------------------------------------------------------\nLout         = cfg_entry;\nLout.tag     = 'Lout';\nLout.name    = 'Outer dimension';\nLout.help    = {'Order if the outer SSS basis'};\nLout.strtype = 'n';\nLout.num     = [1 1];\nLout.val     = {3};\n\n%--------------------------------------------------------------------------\n% condthresh\n%--------------------------------------------------------------------------\ncondthresh         = cfg_entry;\ncondthresh.tag     = 'condthresh';\ncondthresh.name    = 'Condition number threshold';\ncondthresh.help    = {'Threshold on condition number applied for basis regularisation'};\ncondthresh.strtype = 'r';\ncondthresh.num     = [1 1];\ncondthresh.val     = {80};\n\n%--------------------------------------------------------------------------\n% ospace\n%--------------------------------------------------------------------------\n\nospace = cfg_menu;\nospace.tag = 'ospace';\nospace.name = 'Output space';\nospace.labels = {'sensor', 'SSS'};\nospace.val = {0};\nospace.values = {0,1};\nospace.help = {'Determines whether the output file is in sensor space',...\n    'or has virtual montage trasforming to SSS space.'};\n\n%--------------------------------------------------------------------------\n% prefix\n%--------------------------------------------------------------------------\nprefix         = cfg_entry;\nprefix.tag     = 'prefix';\nprefix.name    = 'Filename Prefix';\nprefix.help    = {'Specify the string to be prepended to the filenames of the output dataset. Default prefix is ''tsss_''.'};\nprefix.strtype = 's';\nprefix.num     = [1 Inf];\nprefix.val     = {'tsss_'};\n\n%--------------------------------------------------------------------------\n% tsss\n%--------------------------------------------------------------------------\ntsss          = cfg_exbranch;\ntsss.tag      = 'tsss';\ntsss.name     = 'TSSS denoising';\ntsss.val      = {D, temporal, realign, timewin, corrlimit, Lin, Lout, condthresh, ospace, prefix};\ntsss.help     = {'TSSS clean-up for Neuromag data'}';\ntsss.prog     = @eeg_tsss;\ntsss.vout     = @vout_eeg_tsss;\ntsss.modality = {'EEG'};\n\n%==========================================================================\nfunction out = eeg_tsss(job)\n% construct the S struct\nS = [];\nS.D = char(job.D);\nS.tsss       = job.temporal;\nS.Dref       = char(job.realign.Dref);\nS.refind     = job.realign.refind;\nS.t_window   = job.timewin;\nS.corr_limit = job.corrlimit;\nS.Lin        = job.Lin;\nS.Lout       = job.Lout;\nS.cond_threshold = job.condthresh;\nS.xspace     = job.ospace;\nS.prefix     = job.prefix;\nout.D        = tsss_spm_enm(S);\nout.Dfname   = {fullfile(out.D)};\n\n%==========================================================================\nfunction dep = vout_eeg_tsss(job)\n% return dependencies\ndep(1)            = cfg_dep;\ndep(1).sname      = 'TSSS-ed MEG data';\ndep(1).src_output = substruct('.','D');\ndep(1).tgt_spec   = cfg_findspec({{'strtype','e'}});\n\ndep(2)            = cfg_dep;\ndep(2).sname      = 'TSSS-ed MEG datafile';\ndep(2).src_output = substruct('.','Dfname');\ndep(2).tgt_spec   = cfg_findspec({{'filter','mat'}});", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/TSSS/tsss_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22955672649029749}}
{"text": "function output = callpenlab(model)\n\nmodel = yalmip2nonlinearsolver(model);\n\nif ~model.derivative_available\n    disp('Derivate-free call to penlab not supported')\n    error('Derivate-free call to penlab not implemented')\nend\nif model.options.savedebug\n    save penlabdebug model\nend\n\npenm = [];\npenm.Nx=length(model.linearindicies);\n\n\nif length(nnz(model.K.s)>0)\n    top = 1 + model.K.f + model.K.l + sum(model.K.q);\n    for i = 1:length(model.K.s)\n        model.vecF{i} = model.F_struc(top:top+model.K.s(i)^2-1,:);\n        top = top + model.K.s(i)^2;\n    end\nend\n\nshowprogress('Calling PENLAB',model.options.showprogress);\n\n% These are needed to avoid recomputation due to penlab double call to get\n% f and df, and g and dg\nglobal latest_x_f\nglobal latest_x_g\nglobal latest_df\nglobal latest_f\nglobal latest_G\nglobal latest_g\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_G = [];\nlatest_g = [];\nlatest_x_f = [];\nlatest_x_g = [];\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\npenm.userdata=model;\n\npenm.objfun =  @(x,Y,userdata) penlab_callback_f(x,userdata);\npenm.objgrad = @(x,Y,userdata) penlab_callback_df(x,userdata);\npenm.objhess = @(x,Y,userdata) penlab_callback_df2(x,userdata);\n\nif length(model.b)>0 | length(model.beq)>0\n    penm.lbg = [model.beq;model.b-inf];\n    penm.ubg = [model.beq;model.b];\n    penm.NgLIN = length(model.beq) + length(model.b);\n    penm.confun =  @(x,Y,userdata) penlab_callback_con(x,userdata);\n    penm.congrad = @(x,Y,userdata) penlab_callback_dcon(x,userdata);\n    penm.conhess = @(x,Y,k,userdata) penlab_callback_dcon2(x,k,userdata);\nend\n\nif model.K.s(1)>0\n    penm.NALIN=length(model.K.s);\n    penm.lbA=zeros(find(model.K.s)>0,1);\n    penm.mconfun  = @(x,Y,k,userdata) penlab_callback_matrixG(x, k,userdata);\n    penm.mcongrad = @(x,Y,k,i,userdata) penlab_callback_matrixdG(x,k,i,userdata);\nend\n\nprob=penlab(penm);  \n\nsolvertime = tic;\nprob.solve();       \nsolvertime = toc(solvertime);\nx = prob.x;\n\n% Duals currently not supported\nlambda = [];\n\nswitch 0\n    case {0,1}\n        problem = 0;\n    case {2}\n        problem = 1;\n    case {-1}\n        problem = 3;\n    case {3,4,-2,-3}\n        problem = 4;\n    case {-11,-12,-13}\n        problem = 7;\n    case {-10,-100,-101,-102,-199}\n        problem = 11;\n    otherwise\n        problem = -1;\nend\n\n% Internal format for duals\nD_struc = [];\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n    solverinput.model = model;\nelse\n    solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n    solveroutput.x = xout;  \n    solveroutput.info = info;\nelse\n    solveroutput = [];\nend\n\n% Standard interface\noutput = createoutput(x,D_struc,[],problem,'PENLAB',solverinput,solveroutput,solvertime);\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/callpenlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.22955404967741116}}
{"text": "function [cdf] = gp_kfcv_cdf(gp,x,y,varargin)\n%GP_KFCV_CDF  K-fold cross validation to predict CDF for GP model\n%\n%  Description\n%    [cdf] = GP_KFCV_CDF(GP, X, Y, OPTIONS)\n%    Performs K-fold cross-validation for a GP model given input matrix X\n%    and target vector Y.\n%\n%    OPTIONS is optional parameter-value pair\n%      z          - optional observed quantity in triplet (x_i,y_i,z_i)\n%                   Some likelihoods may use this. For example, in\n%                   case of Poisson likelihood we have z_i=E_i,\n%                   that is, expected value for ith case.\n%      yt         - optional observed yt in test points.\n%                   Default option for yt is yt=y.\n%      inf_method - inference method. Possible methods are\n%                    'MAP'      parameters optimized to MAP (default)\n%                    'MCMC'     MCMC sampling using GP_MC\n%                    'IA'       integration approximation using GP_IA\n%                    'fixed'    parameters are fixed, it either use MAP\n%                               or integration approximation, depending if\n%                               GP is a single GP structure or a GP array\n%                               (for example from GP_IA)\n%      optimf     - function handle for an optimization function, which is\n%                   assumed to have similar input and output arguments\n%                   as usual fmin*-functions. Default is @fminscg.\n%      opt        - options for the inference method. If 'MAP' is used\n%                   use optimset to set options for optimization.\n%                   Default options for optimization are 'GradObj'\n%                   is 'on', 'LargeScale' is 'off', 'Display' is 'off'\n%      k          - number of folds in CV, default k=10\n%      rstream    - number of a random stream to be used for\n%                   permuting the data befor division. This way\n%                   same permutation can be obtained for different\n%                   models. Default is 1. See doc RandStream for\n%                   more information.\n%      trindex    - k-fold CV training indices. A cell array with k\n%                   fields each containing index vector for respective\n%                   training set.\n%      tstindex   - k-fold CV test indices. A cell array with k\n%                   fields each containing index vector for\n%                   respective test set.\n%      display    - defines if messages are displayed.\n%                   - 'iter' displays output at each iteration\n%\n%    The output argument is\n%\n%           cdf- Predictive Cumulative Distribiton function evaluated in y\n%           (default) or yt.\n%\n%\n%  See also\n%    DEMO_MODELCOMPARISON1, DEMO_MODELCOMPARISON2\n%\n% Copyright (c) 2009-2010 Jarno Vanhatalo\n% Copyright (c) 2010-2011 Aki Vehtari\n% Copyright (c) 2012 Ernesto Ulloa\n\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nip=inputParser;\nip.FunctionName = 'GP_KFCV';\nip.addRequired('gp',@(x) isstruct(x) || iscell(x));\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('inf_method', 'MAP', @(x) ...\n  ismember(x,{'MAP' 'LOO' 'KFCV' 'WAIC' 'WAICV' 'WAICG' 'MCMC' 'IA' 'fixed'}))\nip.addParamValue('optimf', @fminscg, @(x) isa(x,'function_handle'))\nip.addParamValue('opt', struct(), @isstruct)\nip.addParamValue('k', 10, @(x) isreal(x) && isscalar(x) && isfinite(x) && x>0)\nip.addParamValue('rstream', 1, @(x) isreal(x) && isscalar(x) && isfinite(x) && x>0)\nip.addParamValue('trindex', [], @(x) isempty(x) || iscell(x))\nip.addParamValue('tstindex', [], @(x) isempty(x) || iscell(x))\nip.addParamValue('display', 'on', @(x) islogical(x) || ...\n  ismember(x,{'iter' 'fold'}))\nip.parse(gp, x, y, varargin{:});\nz=ip.Results.z;\nyt=ip.Results.yt;\ninf_method=ip.Results.inf_method;\noptimf=ip.Results.optimf;\nopt=ip.Results.opt;\nk=ip.Results.k;\nrstream=ip.Results.rstream;\ntrindex=ip.Results.trindex;\ntstindex=ip.Results.tstindex;\ndisplay = ip.Results.display;\nif isequal(display,'fold');display='iter';end\n\n[n,nin] = size(x);\n\ngp_orig = gp;\n\nif ismember(inf_method,{'MAP' 'LOO' 'KFCV' 'WAIC' 'WAICV' 'WAICG'})\n  optdefault=struct('Display','off');\n  opt=optimset(optdefault,opt);\nend\n\nif (isempty(trindex) && ~isempty(tstindex)) || (~isempty(trindex) && isempty(tstindex))\n  error('gp_kfcv: If you give cross-validation indexes, you need to provide both trindex and tstindex.')\nend\n\nif isempty(trindex) || isempty(tstindex)\n  [trindex, tstindex] = cvit(n, k, rstream);\nend\n\n% *** note: yt must can be: a scalar or a vector of size(y)x1 or even a matrix of\n% size(y)xN\n\nif ~isempty(yt)\n  if size(yt,1)==size(y,1)\n    yt=yt;\n  elseif size(yt,1)==1\n    yt=bsxfun(@times,ones(size(y)),yt);\n  else\n    error('size of yt does not match y nor is it a scalar');\n  end\n  ytflag=1;\nelse\n  ytflag=0;\n  yt=y;\nend\n\ncvws=[];\ntrw=[];\n% loop over the crossvalidation sets\n\nfor i=1:length(trindex)\n  if isempty(tstindex{i})\n    continue\n  end\n  \n  if isequal(display,'iter')\n    fprintf(' The CV-fold number: %d/%d \\n', i, k)\n  end\n  \n  % Set the training and test sets for i'th cross-validation set\n  xtr = x(trindex{i},:);\n  ytr = y(trindex{i},:);\n  yttr= yt(trindex{i},:);\n  \n  xtst = x(tstindex{i},:);\n  ytst = y(tstindex{i},:);\n  yttst = yt(tstindex{i},:);\n  \n  if ~isempty(z)\n    ztr = z(trindex{i},:);\n    zt = z;\n    flagz=1;\n    %* yt = y;\n    %       opt_tst.zt = z;\n    %       opt_tst.yt = y;\n  else\n    flagz=0;\n    ztr = [];\n    %*yt = y;\n    zt = [];\n    %       opt_tr = struct();\n    %       opt_tst.yt = y;\n  end\n  \n  gp = gp_orig;\n  \n  if iscell(gp)\n    gptype=gp{1}.type;\n  else\n    gptype=gp.type;\n  end\n  tstind2 = [];\n  \n  switch gptype\n    case {'FIC' 'CS+FIC'}\n      tstind2 = trindex{i};\n    case 'PIC'\n      % Set the block indices for the cv set of data points. Variable\n      % naming(e.g tstind2) because parfor loop.\n      ntr = size(xtr,1);\n      ntst = size(xtst,1);\n      trind2 = [];\n      for i1=1:length(gp.tr_index)\n        tstind2{i1} = [];\n        trind2{i1} = [];\n        for j1 = 1:length(gp.tr_index{i1})\n          indtmp = find( sum((xtr - repmat(x(gp.tr_index{i1}(j1),:),ntr,1)).^2,2) == 0 );\n          if isempty( indtmp )\n            indtmp = find( sum((xtst - repmat(x(gp.tr_index{i1}(j1),:),ntst,1)).^2,2) == 0 );\n            tstind2{i1} = [tstind2{i1} indtmp];\n          else\n            trind2{i1} = [trind2{i1} indtmp];\n          end\n        end\n      end\n      if iscell(gp)\n        for j=1:numel(gp)\n          gp{j}.tr_index=trind2;\n        end\n      else\n        gp.tr_index = trind2;\n      end\n  end\n  \n  % Conduct inference\n  switch inf_method\n    case 'MAP'\n      if flagz\n        gp=gp_optim(gp,xtr,ytr,'z',ztr(:,size(z,2)),'opt',opt, 'optimf', optimf);\n        w=gp_pak(gp);\n        cvws(i,:)=w;\n      else\n        gp=gp_optim(gp,xtr,ytr,'z',ztr,'opt',opt, 'optimf', optimf);\n        w=gp_pak(gp);\n        cvws(i,:)=w;\n      end\n    case {'LOO' 'KFCV' 'WAIC' 'WAICV' 'WAICG'}\n      if ismember('optimf',ip.UsingDefaults)\n        \n        if flagz\n          gp=gp_optim(gp,xtr,ytr,'z',ztr(:,size(z,2)),'opt',opt,'loss',inf_method);\n        else\n          gp=gp_optim(gp,xtr,ytr,'z',ztr,'opt',opt,'loss',inf_method);\n        end\n        \n      else\n        if flagz\n          gp=gp_optim(gp,xtr,ytr,'z',ztr(:,size(z,2)),'opt',opt,'loss',inf_method, 'optimf', optimf);\n        else\n          gp=gp_optim(gp,xtr,ytr,'z',ztr,'opt',opt,'loss',inf_method, 'optimf', optimf);\n        end\n      end\n      w=gp_pak(gp);\n      cvws(i,:)=w;\n    case 'MCMC'\n      if numel(gp.jitterSigma2)>1\n        gp=thin(gp,numel(gp.jitterSigma2)-1);\n      end\n      % Scaled mixture noise model is a special case\n      % where we need to modify the noiseSigmas2 vector\n      % to a right length\n      if isequal(gp.lik.type, 'lik_smt')\n        gp.lik.noiseSigmas2 = gp_orig.lik.noiseSigmas2(trindex{i});\n        gp.lik.r = gp_orig.lik.r(trindex{i});\n        gp.lik.U = gp_orig.lik.U(trindex{i});\n        gp.lik.ndata = length(trindex{i});\n      end\n      % Pick latent values for the training set in this fold\n      if isfield(gp,'latentValues')\n        if (~isfield(gp.lik, 'nondiagW') || ismember(gp.lik.type, {'Softmax', 'Multinom', ...\n            'LGP', 'LGPC'}))\n          latentValues=reshape(gp_orig.latentValues, size(y,1), size(y,2));\n          gp.latentValues=reshape(latentValues(trindex{i},:), size(y,2)*length(trindex{i}), 1);\n          % gp.latentValues=gp_orig.latentValues(trindex{i});\n        else\n          if ~isfield(gp.lik, 'xtime')\n            nl=length(gp.comp_cf);\n            gp.latentValues=gp_orig.latentValues(trindex{i}+(0:nl-1)*n);\n          else\n            ntime=size(gp.lik.xtime,1);\n            gp.latentValues=gp_orig.latentValues([1:ntime, (ntime+trindex{i})]);\n          end\n        end\n      end\n      if flagz\n        gp = gp_mc(gp, xtr, ytr, 'z', ztr(:,size(z,2)), opt);\n      else\n        gp = gp_mc(gp, xtr, ytr, 'z', ztr, opt);\n      end\n      nburnin = floor(length(gp.etr)/3);\n      gp = thin(gp,nburnin);\n    case 'IA'\n      if flagz\n        [gp,P_TH] = gp_ia(gp, xtr, ytr, 'z', ztr(:,size(z,2)), opt);\n      else\n        [gp,P_TH] = gp_ia(gp, xtr, ytr, 'z', ztr, opt);\n      end\n    case 'fixed'\n      % nothing to do here\n  end\n  \n  if iscell(gp)\n    gplik=gp{1}.lik;\n  else\n    gplik=gp.lik;\n  end\n  \n  switch inf_method\n    case {'LOO' 'KFCV' 'WAIC' 'WAICV' 'WAICG' 'MAP'}\n      if ~isfield(gplik.fh,'trcov') && isfield(gp.lik.fh,'predcdf')\n        for it=1:size(yt,2)\n          [Eft, Varft] = gp_pred(gp, xtr, ytr, x, 'tstind', tstind2, 'z', ztr(:,it), 'yt', yt(:,it), 'zt', zt(:,it));\n          cdftemp{it}= gp.lik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n        end\n      elseif isfield(gplik.fh,'trcov') && isfield(gp.lik.fh,'predcdf')\n        for it=1:size(yt,2)\n          [Eft, Varft] = gp_pred(gp, xtr, ytr, x, 'tstind', tstind2,'yt', yt(:,it));\n          cdftemp{it}= gp.lik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n        end\n      else\n        error('This likelihood has not been implemented for this function')\n      end\n    case 'MCMC'\n      nsamples=size(gp.etr,1);\n      for i2=1:nsamples\n        Gp=take_nth(gp,i2);\n        gplik=Gp.lik;\n        if ~isfield(gplik.fh,'trcov') && isfield(gp.lik.fh,'predcdf')\n          for it=1:size(yt,2)\n            [Eft, Varft] = gp_pred(Gp, xtr, ytr, x, 'tstind', tstind2, 'z', ztr(:,it), 'yt', yt(:,it), 'zt', zt(:,it));\n            cdftemp{it,i2}= gp.lik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n          end\n        elseif isfield(gplik.fh,'trcov') && isfield(gp.lik.fh,'predcdf')\n          for it=1:size(yt,2)\n            [Eft, Varft] = gp_pred(gp, xtr, ytr, x, 'tstind', tstind2,'yt', yt(:,it));\n            cdftemp{it,i2}= gp.lik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n          end\n        else\n          error('This likelihood has not been implemented for this function')\n        end\n      end\n      cdftemp = mat2cell(mean(cell2mat(cdftemp),2),repmat(1043,1,10),1);\n    case 'IA'\n      nsamples=length(gp);\n      for i2=1:nsamples\n        Gp=gp{i2};\n        gplik=Gp.lik;\n        if ~isfield(gplik.fh,'trcov') && isfield(gplik.fh,'predcdf')\n          for it=1:size(yt,2)\n            [Eft, Varft] = gp_pred(Gp, xtr, ytr, x, 'tstind', tstind2, 'z', ztr(:,it), 'yt', yt(:,it), 'zt', zt(:,it));\n            cdftemp{it,i2}= gplik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n          end\n        elseif isfield(gplik.fh,'trcov') && isfield(gplik.fh,'predcdf')\n          for it=1:size(yt,2)\n            [Eft, Varft] = gp_pred(gp, xtr, ytr, x, 'tstind', tstind2,'yt', yt(:,it));\n            cdftemp{it,i2}= gplik.fh.predcdf(gplik, Eft, Varft,yt(:,it));\n          end\n        else\n          error('This likelihood has not been implemented for this function')\n        end\n      end\n      cdftemp = mat2cell(sum(bsxfun(@times,cell2mat(cdftemp),P_TH'),2),repmat(1043,1,10),1);\n  end\n  \n  for it=1:size(yt,2)\n    cdf_cv(tstindex{i},it)=cdftemp{it}(tstindex{i},:);\n  end\n  \nend\n\ncdf=cdf_cv;\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/gp_kfcv_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22953429595699953}}
{"text": "function estimate = spm_cfg_dcm_est\n% SPM Configuration file for DCM estimation\n%__________________________________________________________________________\n% Copyright (C) 2008-2017 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin & Peter Zeidman\n% $Id: spm_cfg_dcm_est.m 7479 2018-11-09 14:17:33Z peter $\n\n% -------------------------------------------------------------------------\n% dcmmat Select DCM_*.mat\n% -------------------------------------------------------------------------\ndcmmat         = cfg_files;\ndcmmat.tag     = 'dcmmat';\ndcmmat.name    = 'Select DCM_*.mat';\ndcmmat.help    = {'Select DCM_*.mat files.'};\ndcmmat.filter  = 'mat';\ndcmmat.ufilter = '^DCM_.*\\.mat$';\ndcmmat.num     = [1 Inf];\n\n% -------------------------------------------------------------------------\n% dcmmat Select GCM_.*.mat\n% -------------------------------------------------------------------------\ngcmmat         = cfg_files;\ngcmmat.tag     = 'gcmmat';\ngcmmat.name    = 'Select GCM_*.mat';\ngcmmat.help    = {'Select GCM_*.mat files.'};\ngcmmat.filter  = 'mat';\ngcmmat.ufilter = '^GCM_.*\\.mat$';\ngcmmat.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% dir Directory\n%--------------------------------------------------------------------------\ndir         = cfg_files;\ndir.tag     = 'dir';\ndir.name    = 'Directory';\ndir.help    = {'Select the directory where the output will be written.'};\ndir.filter  = 'dir';\ndir.ufilter = '.*';\ndir.num     = [1 1];\n\n% -------------------------------------------------------------------------\n% name Model name\n%--------------------------------------------------------------------------\nname         = cfg_entry;\nname.tag     = 'name';\nname.name    = 'Name';\nname.help    = {['Specify a name for the group DCM file. The prefix GCM_' ...\n                'and suffix .mat are automatically added']};\nname.strtype = 's';\nname.num     = [0 Inf];\n\n% -------------------------------------------------------------------------\n% subj Create single subject\n%--------------------------------------------------------------------------\nsubj      = cfg_branch;\nsubj.tag  = 'subj';\nsubj.name = 'Subject';\nsubj.val  = {dcmmat};\nsubj.help = {'Subject with one or more models.'};\n\n% -------------------------------------------------------------------------\n% multiple_models Create set of subjects\n%--------------------------------------------------------------------------\nsubjects        = cfg_repeat;\nsubjects.tag    = 'subjects';\nsubjects.name   = 'Per subject';\nsubjects.values = {subj};\nsubjects.help   = {'Create the subjects and select the models for each'};\nsubjects.num    = [1 Inf];\n\n% -------------------------------------------------------------------------\n% subj Create single model\n%--------------------------------------------------------------------------\nmodel      = cfg_branch;\nmodel.tag  = 'model';\nmodel.name = 'Model';\nmodel.val  = {dcmmat};\nmodel.help = {'Corresponding model for each subject'};\n\n% -------------------------------------------------------------------------\n% subjects Create set of models\n%--------------------------------------------------------------------------\nmodels        = cfg_repeat;\nmodels.tag    = 'models';\nmodels.name   = 'Per model';\nmodels.values = {model};\nmodels.help   = {'Select DCM.mat files per model'};\nmodels.num    = [1 Inf];\n\n% -------------------------------------------------------------------------\n% output_single Output one .mat file for the group\n%--------------------------------------------------------------------------\noutput_single         = cfg_branch;\noutput_single.tag     = 'single';\noutput_single.name    = 'Create group GCM_*.mat file';\noutput_single.val     = { dir name };\noutput_single.help    = {['Creates a single group-level DCM file ' ...\n                          'containing a subjects x models cell array.']};\n                      \n% -------------------------------------------------------------------------\n% output_overwrite_gcm Output a GCM file with existing name\n%--------------------------------------------------------------------------\noutput_overwrite_gcm         = cfg_branch;\noutput_overwrite_gcm.tag     = 'overwrite_gcm';\noutput_overwrite_gcm.name    = 'Overwrite existing GCM/DCM files';\noutput_overwrite_gcm.val     = {};\noutput_overwrite_gcm.help    = {['Overwrites existing group-level DCM file ' ...\n                                 'with estimated models.']};\n\n% -------------------------------------------------------------------------\n% output_separate Output one .mat file per model\n%--------------------------------------------------------------------------\noutput_separate         = cfg_branch;\noutput_separate.tag     = 'separate';\noutput_separate.name    = 'Only save individual DCM files';\noutput_separate.val     = {};\noutput_separate.help    = {'Updated existing individual DCM.mat files'};\n\n% -------------------------------------------------------------------------\n% output Choice of how many DCM.mat files to output\n%--------------------------------------------------------------------------\noutput         = cfg_choice;\noutput.tag     = 'output';\noutput.name    = 'Output';\noutput.values  = { output_single output_overwrite_gcm output_separate };\noutput.val     = { output_single };\noutput.help    = {'How to store the estimated DCMs. The options are: ' ...\n                  ['1. Create group GCM_*.mat file - this will create a single '...\n                   'file containing a cell array, with one row per subject ' ...\n                   'and one column per DCM, containing the filenames of ' ...\n                   'the DCMs. The original DCM files will be overwritten ' ...\n                   'with the outcome of the estimation. ' ...\n                   '(Alternatively, if the input is a GCM file containing ' ...\n                   'DCM structures rather than filenames, then the output ' ...\n                   'will also be an array containing DCM structures.)'] ...\n                  ['2. Overwrite existing GCM/DCM files - as above but with ' ...\n                   'with an existing GCM filename.'] ...\n                  ['3. Only save individual DCM files - does not change the ' ...\n                   'GCM file and simply overwrites each subject''s DCM ' ...\n                   'with estimated values.']};\n\n% -------------------------------------------------------------------------\n% way Choice of ways to select DCMs (nested models)\n%--------------------------------------------------------------------------\ndcms        = cfg_choice;\ndcms.tag    = 'dcms';\ndcms.name   = 'Select DCMs';\ndcms.values = {models subjects gcmmat};\ndcms.val    = {gcmmat};\ndcms.help   = {['Select one DCM per subject, multiple DCMs per subject ' ...\n                  'or an existing group DCM file.'] ...\n                 ['If multiple DCMs are selected per subject, then ' ...\n                  'the first DCM for each subject should a ''full'' ' ...\n                  'model containing all connections of interest. Subsequent ' ...\n                  '(nested) DCMs will have certain connections switched ' ...\n                  'off.']};                   \n\n% -------------------------------------------------------------------------\n% est_type Estimation type\n%--------------------------------------------------------------------------     \nest_type        = cfg_menu;\nest_type.tag    = 'est_type';\nest_type.name   = 'Estimation type';\nest_type.labels = {'Full + BMR (default)',...\n                   'Full + BMR PEB (more accurate but slower)',...\n                   'Full (not recommended)',...\n                   'None (collate only)'};\nest_type.values = {1,2,3,4};\nest_type.val    = {1};\nest_type.help   = {['Full + BMR: Estimates the full (first) model for ' ...\n                    'each subject then uses Bayesian Model Reduction (BMR) '...\n                    'to rapidly infer the evidence / parameters for any ' ...\n                    'subsequent nested models.'] ...\n                   ['Full + BMR PEB: Iteratively estimates the full (first) '...\n                    'model for each subject, then sets the priors on each' ...\n                    'each parameter to the group mean (from a PEB model)' ...\n                    'then re-estimates. This improves estimation '...\n                    'by overcoming local optima, but takes longer.' ] ...\n                   ['Full: Estimates all models individually. Provided for '...\n                    'backward compatibility.']...\n                   ['None: Creates a group level DCM file without ' ...\n                    'performing estimation']};                             \n\n% -------------------------------------------------------------------------\n% analysis Analysis\n% -------------------------------------------------------------------------\nfmri_analysis         = cfg_menu;\nfmri_analysis.tag     = 'analysis';\nfmri_analysis.name    = 'Analysis';\nfmri_analysis.labels  = {'default (time series)','cross-spectral densities'};\nfmri_analysis.values  = {'time','csd'};\nfmri_analysis.val     = {'time'};\nfmri_analysis.help    = {['Whether to analyse in the time domain (for task-' ...\n                     'based studies or stochastic DCM) or in the frequency '...\n                     'domain (for resting state analysis with DCM for CSD']};\n                 \nfmri         = cfg_branch;\nfmri.tag     = 'fmri';\nfmri.name    = 'MRI specific options';\nfmri.val     = {fmri_analysis};\nfmri.help    = {'MRI specific options'};\n                 \n% -------------------------------------------------------------------------\n% estimate Estimate\n% -------------------------------------------------------------------------\nestimate      = cfg_exbranch;\nestimate.tag  = 'estimate';\nestimate.name = 'DCM estimation';\nestimate.val  = { dcms output est_type fmri };\nestimate.help = {['Estimate the parameters and free energy (log model ' ...\n                  'evidence) of first level DCMs for fMRI. Models ' ...\n                  'are assembled into a Subjects x Models array and ' ...\n                  'saved in group GCM_*.mat file']};\nestimate.prog = @spm_run_dcm_est;\nestimate.vout = @vout_dcm;\n\n% -------------------------------------------------------------------------\n% fmri Dynamic Causal Model for fMRI\n% -------------------------------------------------------------------------\nest         = cfg_choice; \nest.tag     = 'est';\nest.name    = 'DCM estimation';\nest.help    = {'Estimation of Dynamic Causal Models.'};\nest.values  = { estimate };\n\n%==========================================================================\nfunction out = spm_run_dcm_est(job)\n%==========================================================================\n\ndcms = job.dcms;\n\n% Get selected estimation option\nEST_FULL_BMR     = 1;\nEST_FULL_BMR_PEB = 2;\nEST_FULL         = 3;\nEST_NONE         = 4;\n\nest_type = job.est_type;\n\n% Get selected input option\nINPUT_DCM_BY_MODEL   = 1;\nINPUT_DCM_BY_SUBJECT = 2;\nINPUT_GCM            = 3;\n\nif isfield(dcms,'model')\n    input_type = INPUT_DCM_BY_MODEL;\nelseif isfield(dcms,'subj')\n    input_type = INPUT_DCM_BY_SUBJECT;\nelseif isfield(dcms,'gcmmat')\n    input_type = INPUT_GCM;\nelse\n    error('Unknown input type');\nend\n\n% Get selected output option\nOUTPUT_GCM_NEW       = 1;\nOUTPUT_GCM_OVERWRITE = 2;\nOUTPUT_DCM           = 3;\n\nif isfield(job.output,'single')\n    output_type = OUTPUT_GCM_NEW;\nelseif isfield(job.output,'overwrite_gcm')\n    output_type = OUTPUT_GCM_OVERWRITE;\nelseif isfield(job.output,'separate')\n    output_type = OUTPUT_DCM;\nelse\n    error('Unknown output type');\nend\n\nif (output_type == OUTPUT_GCM_OVERWRITE && input_type ~= INPUT_GCM)\n    error('To overwrite an existing GCM file, the input must be a GCM');\nend\n\n% Build subjects x models filename matrix\nswitch input_type\n    case INPUT_DCM_BY_MODEL\n        ns = length(dcms.model(1).dcmmat);\n        nm = length(dcms.model);\n        P  = cell(ns,nm);\n\n        for m = 1:nm\n            if length(dcms.model(m).dcmmat) ~= ns\n                error(['Please ensure all models have the same number of ' ... \n                       'subjects']);\n            end\n\n            P(:,m) = dcms.model(m).dcmmat;\n        end \n    \n    case INPUT_DCM_BY_SUBJECT\n        ns  = length(dcms.subj);\n        nm  = length(dcms.subj(1).dcmmat);\n        P = cell(ns,nm);\n\n        for s = 1:ns\n            if length(dcms.subj(s).dcmmat) ~= nm\n                error(['Please ensure all subjects have the same number of ' ... \n                       'models']);\n            end\n\n            P(s,:) = dcms.subj(s).dcmmat';\n        end\n\n    case INPUT_GCM\n        GCM = load(dcms.gcmmat{1});\n        GCM = GCM.GCM;\n        ns = size(GCM,1);\n        nm = size(GCM,2);\n        \n        if ischar(GCM{1})\n            P = GCM;\n        else\n            P = '';\n        end\nend\n\n% Validate\nif output_type == OUTPUT_DCM && isempty(P)\n    error(['Cannot save individual DCM files when the input is a GCM ' ...\n           'array of DCM structures']);\nend\n\n% Load all models into memory\nif ~isempty(P)\n    GCM = spm_dcm_load(P);   \nend\n\n% Set timeseries or CSD estimation (fMRI)\nfor s = 1:ns\n    for m = 1:nm\n        if strcmpi(job.fmri.analysis,'CSD')\n            GCM{s,m}.options.analysis   = 'CSD';\n            GCM{s,m}.options.induced    = 1;\n            GCM{s,m}.options.stochastic = 0;            \n        else\n            if isfield(GCM{s,m},'options') && isfield(GCM{s,m},'analysis')\n                GCM{s,m}.options = rmfield(GCM{s,m}.options,'analysis');\n            end\n            GCM{s,m}.options.induced = 0;\n        end\n    end\nend\n\n% Check that models 2-N are nested forms of the full model\nif nm > 1 && (est_type == EST_FULL_BMR || est_type == EST_FULL_BMR_PEB)\n    idx1 = spm_find_pC(GCM{1});\n    for m = 2:nm\n        idx = spm_find_pC(GCM{1,m});\n        if any(setdiff(idx,idx1))\n            error(['Model %d is not a nested model of model 1. This is ' ...\n                  'required for Bayesian Model Reduction (BMR). Please ' ...\n                  'introduce a full model as Model 1, or switch estimation ' ...\n                  'type to ''full'''],m);\n        end\n    end\nend\n\n% Estimate models if requested\nswitch est_type\n    case EST_FULL_BMR\n        GCM(:,1) = spm_dcm_fit(GCM(:,1));\n        \n        if nm > 1\n            GCM = spm_dcm_bmr(GCM);\n        end\n    case EST_FULL_BMR_PEB\n        GCM = spm_dcm_peb_fit(GCM);\n    case EST_FULL\n        GCM = spm_dcm_fit(GCM);    \n    case EST_NONE\n        % Do nothing\nend\n\n% Save individual DCM .mat files if requested\nif ~isempty(P) && (est_type ~= EST_NONE)\n    for s = 1:ns\n        for m = 1:nm\n            DCM = GCM{s,m};\n            F   = DCM.F;\n            Ep  = DCM.Ep;\n            Cp  = DCM.Cp;\n            save(P{s,m}, 'DCM', 'F', 'Ep', 'Cp', ...\n                spm_get_defaults('mat.format'));\n        end\n    end\nend\n\n% If filenames were provided, set the GCM to contain the filenames\nif ~isempty(P)\n    GCM = P; %#ok<NASGU>\nend\n\n% Save GCM\nif output_type == OUTPUT_GCM_NEW\n    % Create single GCM mat file\n    dir  = job.output.single.dir{1};\n    name = ['GCM_' job.output.single.name '.mat'];        \n    filename = fullfile(dir,name);\n    save(filename,'GCM', spm_get_defaults('mat.format'));\n    \n    out.gcmmat = {filename};\nelseif output_type == OUTPUT_GCM_OVERWRITE\n    % Update existing gcm file\n    filename = dcms.gcmmat{1};    \n    save(filename,'GCM', spm_get_defaults('mat.format'));\n    \n    out.gcmmat = {filename};\nend\n\nif ~isempty(P)\n    out.dcmmat = P(:,1);\nend\n\n%==========================================================================\nfunction dep = vout_dcm(job)\n%==========================================================================\ndep(1)            = cfg_dep;\ndep(1).sname      = 'DCM mat File(s) - full models';\ndep(1).src_output = substruct('.','dcmmat');\ndep(1).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\n\nif isfield(job.output,'single') || ...\n        isfield(job.output,'overwrite_gcm')\n    dep(2)            = cfg_dep;\n    dep(2).sname      = 'GCM mat File(s)';\n    dep(2).src_output = substruct('.','gcmmat');\n    dep(2).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_dcm_est.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22953429595699953}}
{"text": "function [hmm,Gamma,vpath,Xi,LL,datat] = hmmdual(data,T,hmm,Gamma,Xi,residuals)\n%\n% Dual estimation of the HMM, first Gamma and then the HMM structure\n%\n% INPUTS:\n%\n% data          observations - a struct with X (time series) and C (classes; optional)\n% T             Number of time points for each time series\n% hmm           hmm structure with options specified in hmm.train\n% Gamma         Initial state courses\n% Xi            joint probability of past and future states conditioned on data\n% residuals     in case we train on residuals, the value of those.\n%\n% OUTPUTS\n% hmm           estimated HMMMAR model\n% Gamma         estimated p(state | data)\n% vpath            estimated Viterbi path\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2019)\n%\n% edits to work for gradient computation (for Fisher kernel):\n% Christine Ahrends, Aarhus University 2022\n\n% to fix potential compatibility issues with previous versions\nhmm = versCompatibilityFix(hmm);\n\nif nargin<6, residuals = []; end\nif nargin<5, Xi = []; end\nif nargin<4, Gamma = []; end\n\nif iscell(T)\n    for i = 1:length(T)\n        if size(T{i},1)==1, T{i} = T{i}'; end\n    end\n    if size(T,1)==1, T = T'; end\n    T = cell2mat(T);\nend\ncheckdatacell;\nN = length(T);\np = hmm.train.lowrank; do_HMM_pca = (p > 0);\n    \ntrain = hmm.train;\ncheckdatacell;\ndata = data2struct(data,T,train);\n% if train.standardise\n%     disp('Option standardise should be zero in hmmdual.')\n%     disp('Standardization should be done separately and using the entire data set.')\n% end\n% Standardise data and control for ackward trials\nvalid_dims = computeValidDimensions(data,train);\ndata = standardisedata(data,T,train.standardise,valid_dims);\n% Filtering\nif ~isempty(train.filter)\n    data = filterdata(data,T,train.Fs,train.filter);\nend\n% Detrend data\nif train.detrend\n    data = detrenddata(data,T);\nend\n% Leakage correction\nif train.leakagecorr ~= 0\n    data = leakcorr(data,T,train.leakagecorr);\nend\n% Hilbert envelope\nif train.onpower\n    data = rawsignal2power(data,T);\nend\n% Leading Phase Eigenvectors\nif train.leida\n    data = leadingPhEigenvector(data,T);\nend\n% pre-embedded  PCA transform\nif length(train.pca_spatial) > 1 || train.pca_spatial > 0\n    if isfield(train,'As')\n        data.X = bsxfun(@minus,data.X,mean(data.X));\n        data.X = data.X * train.As;\n    else\n        [train.As,data.X] = highdim_pca(data.X,T,train.pca_spatial);\n    end\nend\n% Embedding\nif length(train.embeddedlags) > 1\n    [data,T] = embeddata(data,T,train.embeddedlags);\nend\n% PCA transform\nif length(train.pca) > 1 || train.pca > 0\n    if isfield(train,'A')\n        data.X = bsxfun(@minus,data.X,mean(data.X));\n        data.X = data.X * train.A;\n    else\n        error('PCA cannot be recomputed within hmmdual, use parameter A instead')\n        %[train.A,data.X] = highdim_pca(data.X,T,train.pca,0,0,0,train.varimax);\n    end\n    % Standardise principal components and control for ackward trials\n    data = standardisedata(data,T,train.standardise_pc);\n    train.ndim = size(train.A,2);\n    train.S = ones(train.ndim);\n    orders = formorders(train.order,train.orderoffset,train.timelag,train.exptimelag);\n    train.Sind = formindexes(orders,train.S) == 1;\nend\n% Downsampling\nif train.downsample > 0\n    [data,T] = downsampledata(data,T,train.downsample,train.Fs);\nend\n\nif isempty(residuals) && ~do_HMM_pca\n    if ~isfield(hmm.train,'Sind')\n        orders = formorders(hmm.train.order,hmm.train.orderoffset,hmm.train.timelag,hmm.train.exptimelag);\n        hmm.train.Sind = formindexes(orders,hmm.train.S) == 1;\n    end\n    residuals =  getresiduals(data.X,T,hmm.train.S,hmm.train.maxorder,hmm.train.order,...\n        hmm.train.orderoffset,hmm.train.timelag,hmm.train.exptimelag,hmm.train.zeromean);\nend\n\nif isempty(Gamma)   \n    [Gamma,~,Xi,LL] = hsinference(data,T,hmm,residuals); \nelseif isempty(Xi) \n    Xi = approximateXi(Gamma,T,hmm);\nend\nsetxx;\n\nhmm = obsupdate(Gamma,hmm,residuals,XX,XXGXX);\nhmm = hsupdate(Xi,Gamma,T,hmm);\n\nif nargout > 1\n    Gamma = hsinference(data,T,hmm,residuals);\nend\nif nargout > 2\n    vpath = hmmdecode(data,T,hmm,1,residuals,0);\nend\ndatat = data;\n\nend\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/hmmdual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2295306919200221}}
{"text": "function [gKern, gVarmeans, gVarcovars, gInd] = rbfardjitVardistPsi2Gradient(rbfardKern, vardist, Z, covGrad, learnInducing)\n\n% RBFARDJITVARDISTPSI2GRADIENT description.\n  \n% VARGPLVM\n  \nif nargin < 5\n    learnInducing = 1;\nend\n\n[gKern, gVarmeans, gVarcovars, gInd] = rbfard2VardistPsi2Gradient(rbfardKern, vardist, Z, covGrad, learnInducing);\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/rbfardjitVardistPsi2Gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22945854377344055}}
{"text": "function [freq] = ft_datatype_freq(freq, varargin)\n\n% FT_DATATYPE_FREQ describes the FieldTrip MATLAB structure for freq data\n%\n% The freq data structure represents frequency or time-frequency decomposed\n% channel-level data. This data structure is usually generated with the\n% FT_FREQANALYSIS function.\n%\n% An example of a freq data structure containing the powerspectrum for 306 channels\n% and 120 frequencies is\n%\n%       dimord: 'chan_freq'          defines how the numeric data should be interpreted\n%    powspctrm: [306x120 double]     the power spectum\n%        label: {306x1 cell}         the channel labels\n%         freq: [1x120 double]       the frequencies expressed in Hz\n%          cfg: [1x1 struct]         the configuration used by the function that generated this data structure\n%\n% An example of a freq data structure containing the time-frequency resolved\n% spectral estimates of power (i.e. TFR) for 306 channels, 120 frequencies\n% and 60 timepoints is\n%\n%       dimord: 'chan_freq_time'     defines how the numeric data should be interpreted\n%    powspctrm: [306x120x60 double]  the power spectum\n%        label: {306x1 cell}         the channel labels\n%         freq: [1x120 double]       the frequencies, expressed in Hz\n%         time: [1x60 double]        the time, expressed in seconds\n%          cfg: [1x1 struct]         the configuration used by the function that generated this data structure\n%\n% Required fields:\n%   - freq, dimord, label or labelcmb\n%\n% Optional fields:\n%   - powspctrm, fouriesspctrm, csdspctrm, cohspctrm, time, grad, elec, cumsumcnt, cumtapcnt, trialinfo\n%\n% Deprecated fields:\n%   - <none>\n%\n% Obsoleted fields:\n%   - <none>\n%\n% Revision history:\n%\n% (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS\n% for further information.\n%\n% (2008) The presence of labelcmb in case of crsspctrm became optional,\n% from now on the crsspctrm can also be represented as Nchan * Nchan.\n%\n% (2006) The fourierspctrm field was added as alternative to powspctrm and\n% crsspctrm. The fields foi and toi were renamed to freq and time.\n%\n% (2003v2) The fields sgn and sgncmb were renamed into label and labelcmb.\n%\n% (2003v1) The initial version was defined.\n%\n% See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ,\n% FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE,\n% FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME\n\n% Copyright (C) 2011, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% get the optional input arguments, which should be specified as key-value pairs\nversion = ft_getopt(varargin, 'version', 'latest');\n\nif strcmp(version, 'latest')\n  version = '2011';\nend\n\nif isempty(freq)\n  return;\nend\n\n% do some sanity checks\nassert(isfield(freq, 'freq') && (isfield(freq, 'label') || isfield(freq, 'labelcmb')), 'inconsistent freq data structure, some field is missing');\nif isfield(freq, 'label')\n  % it could also be that it has labelcmb instead of label\n  assert(length(unique(freq.label))==length(freq.label), 'channel labels must be unique');\nend\n\n% ensure consistency between the dimord string and the axes that describe the data dimensions\nfreq = fixdimord(freq);\n\nif ~isrow(freq.freq)\n  freq.freq = freq.freq';\nend\nif isfield(freq, 'label') && ~iscolumn(freq.label)\n  % this is not present if the dimord is chancmb_freq or chancmb_freq_time\n  freq.label = freq.label';\nend\nif isfield(freq, 'time') && ~isrow(freq.time)\n  freq.time = freq.time';\nend\nif ~isfield(freq, 'label') && ~isfield(freq, 'labelcmb')\n  ft_warning('data structure is incorrect since it has no channel labels');\nend\n\nswitch version\n  case '2011'\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % ensure that the sensor structures are up to date\n    if isfield(freq, 'grad')\n      freq.grad = ft_datatype_sens(freq.grad);\n    end\n    if isfield(freq, 'elec')\n      freq.elec = ft_datatype_sens(freq.elec);\n    end\n    if isfield(freq, 'opto')\n      freq.opto = ft_datatype_sens(freq.opto);\n    end\n\n    if isfield(freq, 'foi') && ~isfield(freq, 'freq')\n      % this was still the case in early 2006\n      freq.freq = freq.foi;\n      freq = rmfield(freq, 'foi');\n    end\n\n    if isfield(freq, 'toi') && ~isfield(freq, 'time')\n      % this was still the case in early 2006\n      freq.time = freq.toi;\n      freq = rmfield(freq, 'toi');\n    end\n\n    if isfield(freq, 'cumtapcnt') && isvector(freq.cumtapcnt)\n      % ensure that it is a column vector\n      freq.cumtapcnt = freq.cumtapcnt(:);\n    end\n\n    if isfield(freq, 'cumsumcnt') && isvector(freq.cumsumcnt)\n      % ensure that it is a column vector\n      freq.cumsumcnt = freq.cumsumcnt(:);\n    end\n\n    % ensure that the structure has all required fields\n    % note that dimord is listed as required field, but it might also be xxxdimord, or dynamically determined with GETDIMORD\n    for required={'freq'}\n      assert(isfield(freq, required), 'required field \"%s\" is missing', required{:});\n    end\n    % either label or labelcmb should be present\n    assert(any(ismember({'label', 'labelcmb'}, fieldnames(freq))), 'required field \"label\" or \"labelcmb\" is missing');\n\n  case '2008'\n    % there are no known conversions for backward or forward compatibility support\n\n  case '2006'\n    % there are no known conversions for backward or forward compatibility support\n\n  case '2003v2'\n    % there are no known conversions for backward or forward compatibility support\n\n  case '2003v1'\n    % there are no known conversions for backward or forward compatibility support\n\n  otherwise\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    ft_error('unsupported version \"%s\" for freq datatype', version);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/utilities/ft_datatype_freq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22945854377344055}}
{"text": "function [mimgR,mimgG] = red_channel_mean3(ops)\n\n% numPlanes = length(ops.planesToProcess);\n\n% build file list with red channel\n\nif (isfield(ops, 'SubDirsRed') && ~isempty(ops.SubDirsRed))\n    subDirsRed = ops.SubDirsRed;\nelse\n    if (isfield(ops, 'expred') && ~isempty(ops.expred))\n        for i = 1:length(ops.expred)\n            subDirsRed{i} = sprintf('%d', ops.expred(i));\n        end\n    else\n        warning('could not find red channel info, returning...')\n        return;\n    end\nend\n%\n% build file list\nfsRED = dir(fullfile(ops.RootDir, subDirsRed{1}, '*.tif'));\nfor k = 1:length(fsRED)\n    fsRED(k).name = fullfile(ops.RootDir, subDirsRed{1}, fsRED(k).name);\nend\n\nroot = ops.ResultsSavePath;\nfregops =  sprintf('regops_%s_%s.mat', ops.mouse_name, ops.date);\nif exist(fullfile(root, fregops), 'file')\n    load(fullfile(root, fregops))\nelse\n    ops1 = cell(ops.nplanes, 1);\n    for j = 1:ops.nplanes\n        \n        fname = sprintf('regops_%s_%s_plane%d.mat', ops.mouse_name, ops.date, j);\n        dat = load(fullfile(root, fname));\n        ops1{j} = dat.ops;\n        ops1{j}.useGPU = ops.useGPU;\n    end\nend\n\n%\nntf0 = 0;\nnumPlanes = ops.nplanes;\n%iplane0 = 1:1:ops.nplanes;\n\ntotFrames=0;\nfor k = 1:length(fsRED)\n    %iplane0 = mod(iplane0-1, numPlanes) + 1;\n    startPlane=((mod(totFrames+1,ops.nplanes*2)-1)/2)+1;\n    \n    nFr = nFramesTiff(fsRED(k).name);\n    totFrames=totFrames+nFr;\n    data = loadFramesBuff(fsRED(k).name, 1, nFr, 1, ops.temp_tiff);\n    \n    if ~exist('mimgR', 'var')\n        [Ly, Lx, ~] = size(data);\n        mimgR = zeros(Ly, Lx, ops.nplanes);\n    end\n    if ~exist('mimgG', 'var')\n        [Ly, Lx, ~] = size(data);\n        mimgG = zeros(Ly, Lx, ops.nplanes);\n    end\n    %\n    \n    \n    for iPlane=1:ops.nplanes\n      \n        idx0=mod((ops.nplanes-startPlane+iPlane)*2,ops.nplanes*2);\n        planesG=(idx0+1):(2*ops.nplanes):nFr;\n        planesR=(idx0+2):(2*ops.nplanes):nFr;\n        dataG0=data(:,:,planesG);\n        dataR0=data(:,:,planesR);\n        \n        BiDiPhase = ops1{iPlane}.BiDiPhase;\n        if abs(BiDiPhase) > 0\n            yrange = 2:2:Ly;\n            if BiDiPhase>0\n                dataG0(yrange,(1+BiDiPhase):Lx,:,:) = dataG0(yrange, 1:(Lx-BiDiPhase),:,:);\n                dataR0(yrange,(1+BiDiPhase):Lx,:,:) = dataR0(yrange, 1:(Lx-BiDiPhase),:,:);\n            else\n                dataG0(yrange,1:Lx+BiDiPhase,:,:)   = dataG0(yrange, 1-BiDiPhase:Lx,:,:);\n                dataR0(yrange,1:Lx+BiDiPhase,:,:)   = dataR0(yrange, 1-BiDiPhase:Lx,:,:);\n            end\n        end\n        \n        [ds, ~]  = regoffKriging(dataG0, ops1{iPlane}, 0);\n        %[ds, ~]  = registration_offsets(dataG0, ops1{iPlane}, 0);\n        \n        if k==1\n            ds(1,:) = 0;\n        end\n        dataR       = ...\n            register_movie(dataR0, ops1{iPlane}, ds);\n        dataG     = ...\n            register_movie(dataG0, ops1{iPlane}, ds);\n        \n        \n        mimgR(:,:,iPlane) = mimgR(:,:,iPlane) + mean(dataR, 3);\n        mimgG(:,:,iPlane) = mimgG(:,:,iPlane) + mean(dataG, 3);\n        \n    end\n    \n    ntf0 = ntf0 + 1;\n    \n    %iplane0 = iplane0 - nFr/ops.nchannels_red;\n    fprintf('processing tiff %d/%d\\n',k,length(fsRED))\nend\n\nmimgR = mimgR/ntf0;\nmimgG = mimgG/ntf0;", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/redChannel/red_channel_mean3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22945854377344047}}
{"text": "function L = co_reggui(action,varargin)\n% GUI for Manual co-registration of different image modalities to go with\n% CERR\n% - Detailed Description: this is a manual co-registration routine for two\n% set of images (2d/3d) assuming that a possible resmapling and affine\n% transformation are sufficient for alignment. The quality of registration is measured by\n% using the mutual information criterion (MI)\n%\n% Written By: Issam El Naqa    Date: 08/28/03\n% Revised by:                  Date:\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n\nif nargin<1,\n    action='Initializeco_reggui';\nend;\n\nswitch action\n\n    case 'Initializeco_reggui'   %Initialization\n        Initializeco_reggui;                             \n        \n    case 'RegisterMode'\n        mode = get(findobj('Tag', 'dispregpopupmenu'),'Value');\n        switch mode\n            case 1 %manual\n            case 2 %ctrl points  \n            case 3 %auto control points\n        end\n               \n    case 'LoadRefImage'\n        set(findobj(gcbf, 'Tag', 'StatusText'), 'String', 'Loading images...');\n        h = get(gcbf,'Userdata');\n        pathname \t= h.pathname;\n        [filename, pathname] = uigetfile('*.*', 'Load reference image');\n        load([pathname,filename]);\n        x = cropImage(x);\n        h.refimage=min_maxnorm(x, 0:255);\n        set(gcbf,'Userdata',h);\n        DispImage('axref',x);\n        drawnow\n        \n    case 'LoadPlanCUnregImage'\n        \n    case 'LoadPlanCRefImage'\n        \n    case 'LoadUnregImage'\n        set(findobj(gcbf, 'Tag', 'StatusText'), 'String', 'Loading images...');\n        h = get(gcbf,'Userdata');\n        pathname \t= h.pathname;\n        [filename, pathname] = uigetfile('*.*', 'Load unregistered image');\n        load([pathname,filename]);\n        x = cropImage(x);\n        h.unregimage=min_maxnorm(x, 0:255);\n        h.regimage=h.unregimage; % initailize registered image to unregistered one!\n        set(gcbf,'Userdata',h);\n        DispImage('axunreg',x);\n        drawnow\n        set(findobj(gcbf, 'Tag', 'StatusText'), 'String', 'Set registration parameters...');\n    case 'EditRegParam'\n        h = get(gcbf,'Userdata');\n        h.Tx=str2num(get(findobj(gcbf,'Tag','TXed'),'String'));\n        h.Ty=str2num(get(findobj(gcbf,'Tag','TYed'),'String'));\n        h.Tz=str2num(get(findobj(gcbf,'Tag','TZed'),'String'));\n        h.rot=str2num(get(findobj(gcbf,'Tag','Roted'),'String'));\n        h.Sx=str2num(get(findobj(gcbf,'Tag','SXed'),'String'));\n        h.Sy=str2num(get(findobj(gcbf,'Tag','SYed'),'String'));\n        h.Sz=str2num(get(findobj(gcbf,'Tag','SZed'),'String'));\n        h.samp=str2num(get(findobj(gcbf,'Tag','Resamped'),'String'));\n        set(findobj(gcbf, 'Tag', 'regpushbutton'), 'Enable', 'on');\n        set(findobj(gcbf, 'Tag', 'dispmodepopupmenu'), 'Enable', 'on');\n        set(findobj(gcbf, 'Tag', 'StatusText'), 'String', 'Press register button for processing...');\n        set(gcbf,'UserData',h);\n    case 'DisplayMode'\n        setDisplayMode;\n\n    case 'enlargeOverlay'\n        h = get(gcbf,'Userdata');\n        displayOverlays(h.refimage, h.regimage);\n        \n    case 'ApplyRegistration'\n        h = get(gcbf,'Userdata');\n             \n        mode = get(findobj('Tag', 'dispregpopupmenu'),'Value');\n        switch mode\n            case 1 %manual\n                tempimage=imtranslate2d(h.unregimage,h.Tx,h.Ty);\n                tempimage=imrotate2d(tempimage,h.rot);\n                tempimage=imscale2d(tempimage,h.Sx,h.Sy);\n                tempimage=imresample2d(tempimage,h.samp);\n                h.regimage=tempimage;\n            case 2 %ctrl points  \n                getControlPoints('init');\n                getControlPoints('load', h.refimage, h.unregimage);\n                waitfor(findobj('Tag', 'RegGui'), 'Tag', 'RegGuiDone');                \n                [ref_pts, target_pts] = getControlPoints('getpoints', h.refimage, h.unregimage);\n                delete(findobj('Tag', 'RegGuiDone'));\n                [tempimage,A]=compute_aff_transform(h.unregimage, ref_pts, target_pts);\n                h.regimage=tempimage;                \n            case 3\n                getControlPoints('init');\n                getControlPoints('load', h.refimage, h.unregimage);\n                waitfor(findobj('Tag', 'RegGui'), 'Tag', 'RegGuiDone');                \n                [ref_pts, target_pts] = getControlPoints('getpoints', h.refimage, h.unregimage);\n                delete(findobj('Tag', 'RegGuiDone'));\n                [tempimage,A]=compute_perspect_transform(h.unregimage, ref_pts, target_pts);\n                h.regimage=tempimage;               \n            case 4 %auto control points\n                numPoints = 20;\n                sigma = 1;\n                get_control_points(h.unregimage, h.refimage, numPoints, sigma);\n                \n        end\n        \n\n        % make joint histogram plot\n        [h.mi, h.jhist]=get_mutualinfo(h.refimage,h.regimage);\n        %set(findobj(gcbf, 'Tag', 'mitext'), 'Visible', 'on');\n        %set(findobj(gcbf, 'Tag', 'mivalue'), 'Visible', 'on');\n        % make a cross-correlation image\n        h.xcorr=fxcorr(h.refimage,h.regimage);\n        % save current data\n        set(gcbf,'UserData',h);\n        % display images\n        setDisplayMode;\n        DisplayJHist(h.jhist);\n        set(findobj(gcbf, 'Tag', 'mivalue'), 'String', num2str(h.mi));\n        DispImage('axcorr',h.xcorr);\n        drawnow\n    case 'info'\n        helpwin co_reggui;\n    case 'close'\n        close(gcbf);\nend\n\nreturn\n\n% supplmentary routines\n\nfunction setDisplayMode() % set display mode for registration\nh = get(gcbf,'Userdata');\nh.displaymode = get(findobj(gcbf,'Tag','dispmodepopupmenu'),'Value');\nswitch h.displaymode\n    case 1  % Single registered\n        DispImage('axreg',h.regimage);\n    case 2  % Overlayed images\n        alpha=0.8; % transperancy factor\n        alternate_time=0.5; % refresh time\n        AlternateOverlayed(h.refimage,h.regimage,'axreg',alpha,alternate_time);\n    case 3  % Sliceomatic\nend\nset(gcbf,'UserData',h);\nreturn\n\n% image display function\nfunction DispImage(imTag,x)\nset(gcbf,'CurrentAxes',findobj(gcbf,'Tag',imTag));\ncla, h=imagesc(x), axis image, colormap('hot'), axis ij, axis off\nset(h, 'ButtonDownFcn', ['co_reggui(''Ctrl_' imTag ''');']);\nreturn\n\n% image translation function\nfunction fh=imtranslate2d(f,xoff,yoff)\n[h,w]=size(f);\n[x,y]=meshgrid([1:1:h],[1:1:w]);\nxd=x(:)+xoff; yd=y(:)+yoff;\nfh=reshape(bilinear_interpolation(f,xd,yd),w,h)';\nreturn\n\n% image rotation function around the middle of the image\nfunction fh=imrotate2d(f,ang)\n[h,w]=size(f);\nphi = ang*pi/180; % Convert to radians\nvx=[-floor(h/2):ceil(h/2)-1]; % center around the middle\nvy=[-floor(w/2):ceil(w/2)-1];\n\n\n\n[x,y]=meshgrid(vx,vy);\nx=x(:); y=y(:);\nxd=x*cos(phi)+y*sin(phi)+floor(h/2)+1;\nyd=-x*sin(phi)+y*cos(phi)+floor(w/2)+1;\nfh=reshape(bilinear_interpolation(f,xd,yd),w,h)';\nreturn\n\n% image scaling function (exapnsion/shrinking)\nfunction fh=imscale2d(f,Sx,Sy)\n[h,w]=size(f);\n[x,y]=meshgrid([1:1:h],[1:1:w]);\nxd=x(:)*Sx; yd=y(:)*Sy;\nfh=reshape(bilinear_interpolation(f,xd,yd),w,h)';\nreturn\n\n% image resampling function\nfunction fh=imresample2d(f,q)\n[h,w]=size(f);\n% use a binomial filter of order 5 for smoothing\nd=[1 4 6 4 1]/16; B=d'*d;\nfh=f;\nif q==1\n    return\nelseif q>1 % upsample\n    N=round(q);\n    y = zeros(N*h,N*w);\n    y(1:N:end,1:N:end)=fh;\n    fh=conv2(y,B,'same');\nelseif (q<1 & q>0) % downsample\n    D=round(1/q);\n    fh=conv2(fh,B,'same');\n    fh=fh(1:D:end,1:D:end);\nelse\n    errordlg('The resampling factor should a positive number!', 'co_reggui Error', 'replace');\nend\n\n% perform fast cross-correlation in frequency domain\nfunction c=fxcorr(x,y)\nFsize=size(x)+size(y)-1;\nFx = fft2(rot90(x,2),Fsize(1),Fsize(2));\nFy = fft2(y,Fsize(1),Fsize(2));\nc = real(ifft2(Fx .* Fy));\nreturn\n\n% compute the mutual information using the joint histogram\nfunction [mi, histxy]=get_mutualinfo(x,y)\n% x, y : the two images,\nsiz=min([size(x);size(y)]); % if sizes are different\nnbits=8; ngray=2^nbits; % assume 256 levels is sufficient approximation!\nx=double(uint8(double(x)+1)); y=double(uint8(double(y)+1)); % convert to 8 bits\nhistxy=zeros(ngray,ngray);\n\n[iM,jM] = meshgrid(1:siz(1),1:siz(2));\n\nindV = (jM(:) - 1) * siz(1) + iM(:);\n\nxV =double(x(indV));\nyV = double(y(indV));\n\nind2V = (yV - 1) * ngray + xV;\n\nfor i=1:length(ind2V)\n    histxy(ind2V(i)) = histxy(ind2V(i)) + 1;\nend\n\n%for i=1:siz(1)\n%    for j=1:siz(2)\n%        histxy(x(i,j),y(i,j))= histxy(x(i,j),y(i,j))+1;\n%    end\n%end\n\n\nhistxy=histxy/sum(histxy(:)); % normalize\n% compute marginal distributions\nhistx=sum(histxy,2); histy=sum(histxy,1); % by integrating out the joint\nmi=sum(sum(histxy.*log2(histxy./(histx*histy+eps)+eps)));\nreturn\n\n% joint histogram display\nfunction DisplayJHist(jhist)\nset(gcbf,'CurrentAxes',findobj(gcbf,'Tag','axjhist'));\nset(findobj(gcbf,'Tag','axjhist'),'Box','off');\ncla, view(-37.5,30), colormap('hot'), mesh(jhist);\nreturn\n\n\n% display transparent in a cyclic fashion\nfunction DisplayOverlayed(x,y,imTag,alpha)\n% try alphas, or linear combinations...\n%mask = ones(size(y));\n%mask(find(y<1)) = alpha;\nset(gcbf,'CurrentAxes',findobj(gcbf,'Tag',imTag));\nsx=size(x); sy=size(y); % linear combination\nsiz=max([sx;sy]);\nxa=zeros(siz); xa(1:sx(1),1:sx(2))=x;\nya=zeros(siz); ya(1:sy(1),1:sy(2))=y;\ncla, imagesc(double(xa)+0.75*double(ya), 'ButtonDownFcn', 'co_reggui(''enlargeOverlay'');'), axis image, colormap('hot'), axis ij, axis off\n% hold on\n% hi=imagesc();\n% axis image, colormap('hot'), axis ij, axis off;\n%set(hi,'AlphaData',mask);\nreturn\n\nfunction AlternateOverlayed(x,y,imTag,alpha, atime)\nDisplayOverlayed(x,y,imTag,alpha);\n% pause(atime);\n% DisplayOverlayed(y,x,imTag,alpha);\nreturn   \n\nfunction x = cropImage(x)\n    minCol = 1, minRow = 1;\n    [maxCol, maxRow] = size(x);\n    rows = find(~max(x'));\n    cols = find(~max(x));\n    for i=1:length(rows)\n        if rows(i) ~= i\n            minRow = rows(i-1)+1;\n            maxRow = rows(i)-1;\n            break;\n        end\n    end\n    for i=1:length(cols)\n        if cols(i) ~= i\n            minCol = cols(i-1)+1;\n            maxCol = cols(i)-1;\n            break;\n        end\n    end\n    x = imcrop(x,[minCol, minRow,  maxCol-minCol, maxRow-minRow]);\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/co_reggui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.2294175734193912}}
{"text": "function g = lmcKernGradient(kern, X, X2, covGrad)\n\n% LMCKERNGRADIENT Gradient of LMC kernel's parameters.\n% FORMAT\n% DESC computes the gradient of parameters associated to the LMC kernel.\n% As well as the kernel structure and the input positions, the user\n% provides a matrix COVGRAD which gives the partial derivatives of the\n% function with respect to the relevant elements of the kernel matrix.\n% RETURN g:  gradients of the function of interest with respect to the\n% kernel parameters. The ordering of the vector should match that\n% provided by the function kernExtractParam.\n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG X : the input locations for which the gradients are being computed.\n% ARG covGrad : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The argument takes the\n% form of a square matrix of dimension  numData, where numData is the\n% number of rows in X.\n%\n% FORMAT\n% DESC  computes the derivatives as above, but input locations are now\n% provided in two matrices associated with rows and columns of the kernel\n% matrix.\n% RETURN g : gradients of the function of interest with respect to the\n% kernel parameters.\n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG X : the input locations associated with the rows of the kernel matrix.\n% ARG X2 : the input locations associated with the columns of the kernel\n% matrix.\n% ARG covGrad : matrix of partial derivatives of the function of interest\n% with respect to the kernel matrix. The matrix should have the same number\n% of rows as X1 and the same number of columns as X2 has rows.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010.\n\n% KERN\n\nfhandle = str2func([kern.basicKernelType 'KernCompute']);\nfhandleGrad = str2func([kern.basicKernelType 'KernGradient']);\ngBK = zeros(1, kern.nParamsBK);\ngPartialB = zeros(kern.nout);\n\nif iscell(X)\n    if nargin>3 && ~iscell(X2)\n        error('Time course information is not matched in Cell format!');\n    end\n    % Collate arguments.\n    dim1 = zeros(1, kern.nout);\n    dim2 = zeros(1, kern.nout);\n    for i=1:kern.nout\n        dim1(i) = size(X{i}, 1);\n        if nargin > 3\n            dim2(i) = size(X2{i}, 1);\n        else\n            dim2(i) = dim1(i);\n            covGrad = X2;\n        end\n    end\n    for i = 1:kern.nout\n        startOne = sum(dim1(1:(i-1)))+1;\n        endOne = sum(dim1(1:i));\n        startThree = sum(dim2(1:(i-1))) + 1;\n        endThree = sum(dim2(1:i));\n        if nargin > 3\n            gBK = gBK + kern.B(i,i)*fhandleGrad(kern, X{i}, X2{i}, covGrad(startOne:endOne, ...\n                startThree:endThree));\n            basicK = fhandle(kern, X{i}, X2{i});\n        else\n            gBK = gBK + kern.B(i,i)*fhandleGrad(kern, X{i}, covGrad(startOne:endOne,...\n                startThree:endThree));\n            basicK = fhandle(kern, X{i});\n        end\n        gPartialB(i,i) = sum(sum(covGrad(startOne:endOne, startThree:endThree).*basicK));\n        for j = 1:i-1\n            startTwo = sum(dim2(1:(j-1))) + 1;\n            endTwo =  sum(dim2(1:j));\n            if nargin > 3\n                g2  = kern.B(i,j)*fhandleGrad(kern, X{i}, X2{j}, covGrad(startOne:endOne, ...\n                    startTwo:endTwo));\n                basicK = fhandle(kern, X{i}, X2{j});\n            else\n                g2  = kern.B(i,j)*fhandleGrad(kern, X{i}, X{j}, covGrad(startOne:endOne, ...\n                    startTwo:endTwo));\n                basicK = fhandle(kern, X{i}, X{j});\n            end\n            gBK = gBK + 2*g2;\n            gPartialB(i,j) = sum(sum(covGrad(startOne:endOne, startTwo:endTwo).*basicK));\n            gPartialB(j,i) = gPartialB(i,j);\n        end\n    end\nelse\n    if nargin < 4\n        covGrad = X2;\n        X2 = X;\n    end\n    basicK = fhandle(kern, X, X2);\n    startOne = 1;\n    endOne = 0;\n    startThree = 1;\n    endThree = 0;\n    for i=1:kern.nout\n        endOne = endOne + size(X,1);\n        endThree = endThree + size(X2,1);\n        gBK = gBK + kern.B(i,i)*fhandleGrad(kern, X, X2, ...\n            covGrad(startOne:endOne, startThree:endThree));\n        gPartialB(i,i) = sum(sum(covGrad(startOne:endOne, startThree:endThree).*basicK));\n        startTwo = 1;\n        endTwo = 0;\n        startFour = 1;\n        endFour = 0;\n        for j=1:i-1\n            endTwo = endTwo + size(X2,1);\n            g2  = kern.B(i,j)*fhandleGrad(kern, X, X2, covGrad(startOne:endOne, ...\n                startTwo:endTwo));\n            gBK = gBK + g2;\n            gPartialB(i,j) = sum(sum(covGrad(startOne:endOne, startTwo:endTwo).*basicK));\n            if nargin < 3\n                gBK = gBK + g2;\n                gPartialB(j,i) = gPartialB(i,j);\n            else\n                endFour = endFour + size(X,1);\n                g3 = kern.B(j,i)*fhandleGrad(kern, X, X2, covGrad(startFour:endFour, ...\n                    startThree:endThree));\n                gBK = gBK + g3;\n                gPartialB(j,i) = sum(sum(covGrad(startFour:endFour, startThree:endThree).*basicK));\n                startFour = endFour + 1;\n            end\n            startTwo = endTwo + 1;\n        end\n        startOne = endOne + 1;\n        startThree = endThree + 1;\n    end\nend\n\nJij = zeros(kern.nout, kern.rankCorregMatrix);\nJji = zeros(kern.rankCorregMatrix, kern.nout);\ngB = zeros(kern.nout, kern.rankCorregMatrix);\nfor i=1:kern.nout\n    for j=1:kern.rankCorregMatrix\n        Jij(i,j) = 1; Jji(j,i) = 1;\n        gB(i,j) = sum(sum((kern.A*Jij' + Jji'*kern.A').*gPartialB));\n        Jij(i,j) = 0; Jji(j,i) = 0;\n    end\nend\n\ng = [gBK gB(:)'];\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lmcKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22936331116887343}}
{"text": "\n\n\nfunction batch_data=batch_do_data_crop(train_opts, imdb, work_info_epoch, batch_data, work_info_batch, work_info)\n\n\ndata_crop_config=train_opts.data_crop_config;\n\nif work_info.ref.run_eva || ~data_crop_config.do_crop\n    batch_data.crop_info=[];\n    return;\nend\n\n\nimg_data=batch_data.img_data;\nmask_data=batch_data.label_data;\nimg_size=size(img_data);\nimg_size=img_size(1:2);\n\nif any(size(mask_data)~=img_size)\n    mask_data=imresize(mask_data, img_size, 'nearest');\nend\n\n\nmin_edge_size=min(img_size);\nneed_changed_flags=mod(min_edge_size,2)~=0;\nmin_edge_size(need_changed_flags)=min_edge_size(need_changed_flags)-1;\n\ncrop_box_size=data_crop_config.crop_box_size;\ncrop_box_size=min(min_edge_size, crop_box_size);\n\n\ngen_crop_point_type=data_crop_config.gen_crop_point_type;\n\nstart_point=[];\n\nif strcmp(gen_crop_point_type, 'random')\n    start_point=gen_crop_point_random(data_crop_config, imdb, work_info_batch, mask_data, crop_box_size);\n\nelseif strcmp(gen_crop_point_type, 'class_sample')\n    \n    start_point=gen_crop_point_class_sample(data_crop_config, imdb, work_info_batch, mask_data, crop_box_size);\n    if isempty(start_point)\n        start_point=gen_crop_point_random(data_crop_config, imdb, work_info_batch, mask_data, crop_box_size);\n    end\n\nelse\n\t\n\terror('gen_crop_point_type not support!');\nend\n\nassert(~isempty(start_point));\n\nstop_point1=start_point(1)+crop_box_size-1;\nif stop_point1>img_size(1)\n    stop_point1=img_size(1);\n    start_point(1)=stop_point1-crop_box_size+1;\nend\n    \nstop_point2=start_point(2)+crop_box_size-1;\nif stop_point2>img_size(2)\n    stop_point2=img_size(2);\n    start_point(2)=stop_point2-crop_box_size+1;\nend\n\nrow_idxes=start_point(1):stop_point1;\ncol_idxes=start_point(2):stop_point2;\n\n\ncrop_img_data=img_data(row_idxes, col_idxes, :);\ncrop_mask_data=mask_data(row_idxes, col_idxes);\n\n\ncrop_info=[];\ncrop_info.img_size=img_size;\ncrop_info.row_idxes=row_idxes;\ncrop_info.col_idxes=col_idxes;\ncrop_info.crop_mask_data=crop_mask_data;\ncrop_info.crop_img_data=crop_img_data;\ncrop_info.mask_data=mask_data;\ncrop_info.img_data=img_data;\ncrop_info.do_crop=true;\n\n\nbatch_data.crop_info=crop_info;\n\nbatch_data.img_data=crop_img_data;\nbatch_data.label_data=crop_mask_data;\n\ncrop_img_size=size(crop_img_data);\ncrop_img_size=crop_img_size(1:2);\nbatch_data.img_size=crop_img_size;\n\n\nend\n\n\n\n\nfunction start_point=gen_crop_point_random(data_crop_config, imdb, work_info_batch, mask_data, crop_box_size)\n\n\nimg_size=size(mask_data);\n\ncrop_box_step_ratio=data_crop_config.crop_box_step_ratio;\nif ~isempty(crop_box_step_ratio)\n    step_size=round(crop_box_size*crop_box_step_ratio);    \n    step_size=max(step_size, 1);\nelse\n    step_size=1;\nend\n\nmax_range=img_size-crop_box_size+1;\n\n\ncan_row_points=[1:step_size:max_range(1) max_range(1)];\ncan_col_points=[1:step_size:max_range(2) max_range(2)];\nstart_point=[my_random_sample(can_row_points, 1) my_random_sample(can_col_points, 1)];\n\nend\n\n\n\n\nfunction start_point=gen_crop_point_class_sample(data_crop_config, imdb, work_info_batch, mask_data, crop_box_size)\n\n\nif ~isfield(imdb.ref, 'crop_cache_info') || isempty(imdb.ref.crop_cache_info)\n    imdb.ref.crop_cache_info=gen_crop_cache_info(work_info_batch.ref.train_opts, imdb.ref.ds_info);\nend\n\n\ncrop_cache_info=imdb.ref.crop_cache_info;\ntask_idx=work_info_batch.ref.task_idxes;\nclass_idxes=crop_cache_info.class_idxes_imgs{task_idx};\n\nstart_point=[];\n\nif isempty(class_idxes)\n    disp('################# class_sample crop: empty class_idxes!');\n    return;\nend\n\n\none_class_idx=my_random_sample(class_idxes, 1);\nvalid_flags=mask_data==one_class_idx;\n\nvalid_idxes=find(valid_flags);\n\nif isempty(valid_idxes)\n    disp('################# class_sample crop: no points with the selected class label are found!');\n    return;\nend\n\ntmp_point_idx=my_random_sample(valid_idxes, 1);\n[start_point(1), start_point(2)]=ind2sub(size(valid_flags), tmp_point_idx);\n\n\nassert(~isempty(start_point));\n\n\nstart_point=round(start_point-crop_box_size./2);\nstart_point=max(start_point, 1);\n\n\n\nend\n\n\n\nfunction crop_cache_info=gen_crop_cache_info(train_opts, ds_info)\n\n\ndisp('gen_crop_cache_info...');\nclass_idxes_imgs=ds_info.class_idxes_imgs;\n\nvoid_class_idxes=ds_info.class_info.void_class_idxes;\nfor img_idx=1:length(class_idxes_imgs)\n    class_idxes=class_idxes_imgs{img_idx};\n    assert(max(class_idxes)<256);\n    if ~isempty(void_class_idxes)\n        class_idxes=class_idxes(class_idxes~=void_class_idxes);\n    end\n    class_idxes_imgs{img_idx}=uint8(class_idxes);\nend\n\ncrop_cache_info=[];\ncrop_cache_info.class_idxes_imgs=class_idxes_imgs;\n\nend\n\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/batch_do_data_crop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22936330534058058}}
{"text": "function poseRefPoint = getPoseRefPoint(keypointsAll,pidxsHead)\n\nposeRefPoint = zeros(size(keypointsAll,2),2);\nfor clusidx = 1:size(keypointsAll,2)\n    pp = [];\n    % reference point is head center\n%     pidxHC = 8; % head center\n%     pidxN = 15; % neck\n%     pidxHT = 16; % head top\n    for pidx = pidxsHead\n        pp = [pp; keypointsAll{pidx,clusidx}];\n    end\n    if (isempty(pp))\n        pp = [-inf -inf];\n    end\n    poseRefPoint(clusidx,:) = mean(pp,1);\nend\n\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/multicut/getPoseRefPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22936330534058053}}
{"text": "function [m, symbol, filterind] = model_add_terminal(m, varargin)\n% Add a filter to the model.  \n%   [m, symbol, filterind] = model_add_terminal(m, varargin)\n%\n% Return values\n%   m         Updated model\n%   symbol    Newly created terminal symbol \n%   filterind Index of the newly created filter associated with the terminal\n%\n% Arguments\n%   m         Model to update\n%   varargin  (key, value) pairs that can specify the following:\n%   key                         value\n%   ---                         -----\n%   w                           Filter coefficients\n%   flip                        True or false (default)\n%   blocklabel                  model.blocks index\n%   mirror_terminal             Terminal symbol to horizontally mirror\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nvalid_opts = {'w', 'blocklabel', 'flip', 'mirror_terminal'};\nopts = getopts(varargin, valid_opts);\n\nif opts.isKey('mirror_terminal')\n  src_terminal = opts('mirror_terminal');\n  fi = m.symbols(src_terminal).filter;\n  opts('blocklabel') = m.filters(fi).blocklabel;\n  opts('w')          = flipfeat(model_get_block(m, m.filters(fi)));\n  opts('flip')       = ~m.filters(fi).flip;\nend\n\nif opts.isKey('w')\n  w = opts('w');\nelse\n  error('argument ''w'' is required');\nend\n\nif opts.isKey('blocklabel')\n  blocklabel = opts('blocklabel');\nelse\n  [m, blocklabel] = model_add_block(m, ...\n                                    'type', block_types.Filter, ...\n                                    'w', w);\nend\n\nif opts.isKey('flip')\n  flip = opts('flip');\nelse\n  flip = false;\nend\n\n% get index for new filter\nj = m.numfilters + 1;\nm.numfilters = j;\n\nm.filters(j).blocklabel = blocklabel;\nm.filters(j).size       = [size(w, 1) size(w, 2)];\nm.filters(j).flip       = flip;\n\n% new symbol for terminal associated with filter f\n[m, i] = model_add_symbol(m, 'T');\nm.symbols(i).filter = j;\nm.filters(j).symbol = i;\n\nfilterind = j;\nsymbol = i;\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/model/model_add_terminal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22936224696128907}}
{"text": "function vis_grammar(model)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% visualize random derivations...forever\nwhile true\n  f = vis_grammar_rand(model);\n  visualizeHOG(max(0, f));\n  pause;\nend\n\n\nfunction f = vis_grammar_rand(model, s, p, f)\n\nconf = voc_config();\n\nif nargin < 2\n  s = model.start;\n  p = [0 0 0];\n  f = zeros([0 0 conf.features.dim]);\nend\n\nif model.symbols(s).type == 'T'\n  w = model_get_block(model, model.filters(model.symbols(s).filter));\n  wsz = size(w);\n  fsz = size(f);\n  req_fsz = [p(2) + wsz(1), p(1) + wsz(2), wsz(3)];\n  pad = max(0, req_fsz - fsz);\n  f = padarray(f, pad, 0, 'post');\n  f(1+p(2):1+p(2)+wsz(1)-1, 1+p(1):1+p(1)+wsz(2)-1, :) = ...\n    f(1+p(2):1+p(2)+wsz(1)-1, 1+p(1):1+p(1)+wsz(2)-1, :) + w;\nelse\n  % sample a rule weighted by production score\n  len = length(model.rules{s});\n  z = zeros(len,1);\n  for i = 1:len\n    z(i) = model_get_block(model, model.rules{s}(i).offset);\n  end\n  z = exp(z);\n  Z = sum(z);\n  if Z ~= 0\n    r = find(mnrnd(1, z./Z) == 1);\n  else\n    r = ceil(rand*length(model.rules{s}));\n  end\n\n  if model.rules{s}(r).type == 'D'\n    cs = model.rules{s}(r).rhs(1);\n    f = vis_grammar_rand(model, cs, p, f);\n  else\n    for i = 1:length(model.rules{s}(r).rhs)\n      cs = model.rules{s}(r).rhs(i);\n      anchor = model.rules{s}(r).anchor{i};\n      f = vis_grammar_rand(model, cs, p + anchor, f);\n    end\n  end\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/vis/vis_grammar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22899327150761628}}
{"text": "function corrderived_plot_swarm_history(c,varargin)\n\n%CORRDERIVED_PLOT_SWARM_HISTORY plots relevent details of seismic swarms\n% CORRDERIVED_PLOT_SWARM_HISTORY(C)reads correlation object C and plots various\n% parameters to characterize the swarm. Typical input will be a correlation\n% object containing waveforms from a single station for numerous events. \n% This function requires that the CLUST and WAVEFORM fields of the\n% correlation object be filled. The heavily lifting will have already been\n% done by the LINKAGE and CLUSTER functions. This is predominantly a\n% plotting function. Plots include:\n%    - A histogram of all events and clustered events\n%    - An amplitude measure of all events\n%    - A plot showing the \"lifespan\" of each cluster\n%\n% CORRDERIVED_PLOT_SWARM_HISTORY(C,CLUSTERSIZE) specifies the minimum number of\n% events to be counted as a cluster. The default is 5. Note that the\n% clusters defined in the correaltion object may have a few as 1 event. For\n% analysis purposes however, the user will often want to set a minimum\n% size for significant clusters. CLUSTERSIZE is this value.\n%\n% The trace amplitude plot is based on the maximum value of the hilbert\n% transform of the input data. The user may wish to narrow the window of\n% data to a portion of the input trace by using the cop function. Example\n%     c1 = crop(c,-1,3)\n%     corrderived_plot_swarm_history(c1,10)\n%\n% See also correlation/linkage correlation/cluster\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\n% CHECK INPUTS\nif nargin>2\n    error('Incorrect number of inputs');\nend\nif ~isa(c,'correlation')\n    error('First argument must be a correlation object');\nend\n\nif isempty(get(c,'CLUST'))\n    error('CLUSTER field must be filled in input argument. See HELP CLUSTER');\nend\n\nif numel(varargin)==1\n    clusterSize = varargin{1};\nelse\n    clusterSize = 5;\nend\n\n\n% FIND EVENTS IN/OUT OF CLUSTERS\ninMult = find(c,'BIG',clusterSize);\n% find non-multiplets\nfor n = 1:get(c,'TRACES')\n    if numel(find(inMult==n))==0\n        notInMult(n) = 1;\n    else\n        notInMult(n) = 0;\n    end\nend\nnotInMult = find(notInMult)';\ninMult = sort(inMult);\n\n\n% GET STA_CHAN\nif ~check(c,'STA') | ~check(c,'CHAN')\n   warning('This function was written assuming data from a single sta_chan'); \nend\nwtmp = waveform(c);\nwtmp = wtmp(1);\nnscl = [ get(wtmp,'NETWORK') '_' get(wtmp,'STATION') '_' get(wtmp,'CHANNEL') '_' get(wtmp,'LOCATION') ];\n\n\n\n\n% PLOT IT\nfigure('Color','w','Position',[0 0 1100 850]);\nbox on; hold on;\nset(gcf,'DefaultLineLineWidth',0.1);\nset(gcf,'DefaultAxesFontSize',12);\n\n% PLOT EVENT RATES\nsubplot(3,1,1)\ndisp('Preparing event rate histograms ...');\nc1 = subset(c,inMult);\nc1 = sort(c1);\ntrigMult = get(c1,'TRIG');\ntrigAll = get(c,'TRIG');\nedges = [floor(min(trigAll)):1/24:ceil(max(trigAll))];\nnMult = histc(trigMult,edges);\nnAll = histc(trigAll,edges);\n%\nbar(edges,nAll,'y');\n%h = findobj(gca,'Type','patch');\n%set(h,'FaceColor',[.7 .7 .7])\nhold on;\nbar(edges,nMult,'r');\nh = findobj(gca,'Type','patch');\nset(h,'EdgeColor',[0 0 0],'LineWidth',0.1)\nxlim([[min(trigAll)-1/24 max(trigAll)+1/24]]);\ndatetick('x','KeepLimits');\nlegend('All events','Clustered events');\n\ntitle('Event rates');\nylabel('Events per hour');\n\n\n\n% AMPLITUDE PLOT\ndisp('Preparing amplitude measures ...');\nsubplot(3,1,2)\nc1 = crop(c,-1,4);\nw = waveform(c1);\nw = hilbert(w);\namp = max(double(w));\ntrig = get(c1,'TRIG');\nplot(trig(notInMult),amp(notInMult),'ko','MarkerFaceColor','y','MarkerSize',4);\nhold on;\nplot(trig(inMult),amp(inMult),'ko','MarkerFaceColor','r','MarkerSize',4);\nset(gca,'YScale','log');\nxlim([[min(trigAll)-1/24 max(trigAll)+1/24]]);\nylim([min(amp) max(amp)]);\ndatetick('x','KeepLimits');\n%set(gca,'YGrid','on')\nylabel('amplitude (nm/s)')\nlegend('All events','Clustered events');\ntitle(['Event amplitudes    (derived from  ' nscl ')'],'Interpreter','none');\n\n\n\n% PLOT EVENT RATES\nsubplot(3,1,3)\ndisp('Preparing cluster lifespan plot ...');\nfamily = getclusterstat(c);\nindex = find(family.numel>=clusterSize);\n[tmp,index] = sort(family.begin(index));\n\nbox on; hold on;\nfor n = 1:numel(index)\n    plot([ family.begin(index(n)) family.finish(index(n)) ],[n n],'-','Color',[0.7 0.7 0.7],'LineWidth',1);\n    plot(family.trig{index(n)},repmat(n,family.numel(index(n)),1),'o','Color',[0 0 0],'MarkerFaceColor','r','MarkerSize',4);\n\nend\nxlim([[min(trigAll)-1/24 max(trigAll)+1/24]]);\nylim([0 numel(index)+1]);\ndatetick('x','KeepLimits');\nset(gca,'YTick',[1:numel(index)]);\nset(gca,'YTickLabel',index);\nylabel('cluster rank')\ntitle(['Cluster lifespan  (clusters of ' num2str(clusterSize) ' or more events)']);\n\n\n%PRINT OUT FIGURE\nset(gcf, 'paperorientation', 'portrait');\nset(gcf, 'paperposition', [.25 .25 8 10.5] );\nprint(gcf,'-dpsc2','FIG_SWARM_HISTORY.ps');\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/contributed/correlation_derived/corrderived_plot_swarm_history.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22899327150761623}}
{"text": "% std_plottf() - plot ERSP/ITC images a component\n%              or channel cluster in a STUDY. Also allows plotting scalp\n%              maps.\n% Usage:\n%          >> std_plottf( times, freqs, data, 'key', 'val', ...)\n% Inputs:\n%  times - [vector] latencies in ms of the data points.\n%  freqs - [vector] frequencies in Hz of the data points.\n%  data  -  [cell array] mean data for each subject group and/or data\n%           condition. For example, to plot mean ERPs from a STUDY \n%           for epochs of 800 frames in two conditions from three groups \n%           of 12 subjects:\n%\n%           >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n%                       [800x12] [800x12] [800x12] };  % 3 groups, cond 2\n%           >> std_plottf(erp_ms,data);\n%\n%           By default, parametric statistics are computed across subjects \n%           in the three groups. (group,condition) ERP averages are plotted. \n%           See below and >> help statcond \n%           for more information about the statistical computations.\n%\n% Optional display parameters:\n%  'datatype'    - ['ersp'|'itc'] data type {default: 'ersp'}\n%  'titles'      - [cell array of string] titles for each of the subplots. \n%                  { default: none}\n%\n% Statistics options:\n%  'groupstats'  - ['on'|'off'] Compute (or not) statistics across groups.\n%                  {default: 'off'}\n%  'condstats'   - ['on'|'off'] Compute (or not) statistics across groups.\n%                  {default: 'off'}\n\n%  'threshold'   - [NaN|real<<1] Significance threshold. NaN -> plot the \n%                  p-values themselves on a different figure. When possible, \n%                  significance regions are indicated below the data.\n%                  {default: NaN}\n%  'maskdata'    - ['on'|'off'] when threshold is non-NaN and not both \n%                  condition and group statistics are computed, the user \n%                  has the option to mask the data for significance.\n%                  {defualt: 'off'}\n%\n% Other plotting options:\n%  'plotmode'    - ['normal'|'condensed'] statistics plotting mode:\n%                  'condensed' -> plot statistics under the curves \n%                  (when possible); 'normal' -> plot them in separate \n%                  axes {default: 'normal'}\n%  'freqscale'   - ['log'|'linear'|'auto'] frequency plotting scale.\n%                  {default: 'auto'}\n%  'ylim'        - [min max] ordinate limits for ERP and spectrum plots\n%                  {default: all available data}\n%\n% ITC/ERSP image plotting options:\n%  'tftopoopt'   - [cell array] tftopo() plotting options (ERSP and ITC)\n%  'caxis'       - [min max] color axis (ERSP, ITC, scalp maps)\n%\n% Scalp map plotting options:\n%  'chanlocs'    - [struct] channel location structure\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n%\n% See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond()\n\n% Copyright (C) 2006 Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [pgroup, pcond, pinter] = std_plottf(timevals, freqs, data, varargin)\n\npgroup = [];\npcond  = [];\npinter = [];\nif nargin < 2\n    help std_plottf;\n    return;\nend;\n\nopt = finputcheck( varargin, { 'titles'         'cell'   []              cell(20,20);\n                               'caxis'          'real'   []              [];\n                               'ersplim'        'real'   []              []; % same as above\n                               'itclim'         'real'   []              []; % same as above\n                               'ylim'           'real'   []              [];\n                               'tftopoopt'      'cell'   []              {};\n                               'threshold'      'real'   []              NaN;\n                               'unitx'          'string' []              'ms'; % just for titles\n                               'chanlocs'       'struct' []              struct('labels', {});\n                               'freqscale'      'string' { 'log' 'linear' 'auto' }  'auto';\n                               'groupstats'     'cell'   []              {};\n                               'condstats'      'cell'   []              {};\n                               'interstats'     'cell'   []              {};                               \n                               'maskdata'       'string' { 'on' 'off' }   'off';\n                               'datatype'       'string' { 'ersp' 'itc' }    'ersp';\n                               'plotmode'       'string' { 'normal' 'condensed' }  'normal' }, 'std_plottf');\nif isstr(opt), error(opt); end;\nif all(all(cellfun('size', data, 3)==1))               opt.singlesubject = 'on'; end;\n\n% remove empty entries\ndatapresent = ~cellfun(@isempty, data);\nfor c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; opt.titles(c,:) = []; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end;\nfor g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; opt.titles(:,g) = []; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end;\n\nif ~isempty(opt.groupstats) & ~isempty(opt.condstats) & strcmpi(opt.maskdata, 'on')\n    disp('Cannot use ''maskdata'' option with both condition stat. and group stat. on');\n    disp('Disabling statistics');\n    opt.groupstats = {}; opt.condstats = {}; opt.maskdata = 'off'; \nend;\nif ~isempty(opt.ersplim), opt.caxis = opt.ersplim; end;\nif ~isempty(opt.itclim), opt.caxis = opt.itclim; end;\nonecol  = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' };\nmanycol = { 'b' 'r' 'g' 'k' 'c' 'y' };\n\nnc = size(data,1);\nng = size(data,2);\nif nc >= ng, opt.transpose = 'on';\nelse         opt.transpose = 'off';\nend;\n\n% test log frequencies\n% --------------------\nif length(freqs) > 2 & strcmpi(opt.freqscale, 'auto')\n    midfreq = (freqs(3)+freqs(1))/2;\n    if midfreq*.9999 < freqs(2) & midfreq*1.0001 > freqs(2), opt.freqscale = 'linear';\n    else                                                     opt.freqscale = 'log';\n    end;\nend;\n\n% condensed plot\n% --------------\nif strcmpi(opt.plotmode, 'condensed') \n    meanplot = zeros(size(data{1},1), size(data{1},2));\n    count = 0;\n    for c = 1:nc\n        for g = 1:ng\n            if ~isempty(data{c,g})\n                meanplot = meanplot + mean(data{c,g},3);\n                count = count+1;\n            end;\n        end;\n    end;\n    meanplot = meanplot/count;\n    options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'on', ...\n            'cmode', 'separate', opt.tftopoopt{:} };       \n        \n    if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end;\n    tftopo( meanplot', timevals, freqs, 'title', opt.titles{1}, options{:}); \n    currentHangle = gca;\n    if ~isempty( opt.caxis )\n        caxis( currentHangle, opt.caxis )\n    end\n    colorbarHandle = cbar;\n    title(colorbarHandle,'dB');\n    axes(currentHangle); \n    return; \nend;\n\n% plotting paramters\n% ------------------\nif ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end;\nif nc > 1 && ~isempty(opt.condstats  ), addr = 1; else addr = 0; end;\n\n% compute significance mask\n% --------------------------\nif ~isempty(opt.interstats), pinter = opt.interstats{3}; end;\n\nif ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) )    \n    pcondplot  = opt.condstats;\n    pgroupplot = opt.groupstats;\n    pinterplot = pinter;\n    maxplot = 1;\nelse\n    warning off;\n    for ind = 1:length(opt.condstats),  pcondplot{ind}  = -log10(opt.condstats{ind}); end;\n    for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end;\n    if ~isempty(pinter), pinterplot = -log10(pinter); end;\n    maxplot = 3;\n    warning on;\nend;\n\n% -------------------------------\n% masking for significance of not\n% -------------------------------\nstatmask = 0;\nif strcmpi(opt.maskdata, 'on') && ~isnan(opt.threshold) && ...\n        (~isempty(opt.condstats) || ~isempty(opt.condstats))\n    addc = 0; addr = 0; statmask = 1;\nend;\n\n% -------------------------\n% plot time/frequency image\n% -------------------------\noptions = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'off', ...\n            'cmode', 'separate', opt.tftopoopt{:} };\nif strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end;\n\n% adjust figure size\n% ------------------\nfig = figure('color', 'w');\npos = get(fig, 'position');\nset(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/2.5*(nc+addr), pos(4)/2*(ng+addc) ]);\npos = get(fig, 'position');\nif strcmpi(opt.transpose, 'off'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);\nelse                              set(gcf, 'position', pos);\nend;\n\ntmpc = [inf -inf];\nfor c = 1:nc\n    for g = 1:ng\n        hdl(c,g) = mysubplot(nc+addr, ng+addc, g + (c-1)*(ng+addc), opt.transpose);\n        if ~isempty(data{c,g})\n            tmpplot = mean(data{c,g},3);\n            if ~isreal(tmpplot(1)), tmpplot = abs(tmpplot); end;\n            if statmask, \n                if ~isempty(opt.condstats), tmpplot(find(pcondplot{g}(:) == 0)) = 0;\n                else                        tmpplot(find(pgroupplot{c}(:) == 0)) = 0;\n                end;\n            end;\n\n            tftopo( tmpplot', timevals, freqs, 'title', opt.titles{c,g}, options{:}); \n                \n            if isempty(opt.caxis) && ~isempty(tmpc)\n                warning off;\n                tmpc = [ min(min(tmpplot(:)), tmpc(1)) max(max(tmpplot(:)), tmpc(2)) ];\n                warning on;\n            else \n                if ~isempty(opt.caxis)\n                    caxis(opt.caxis);\n                end;\n            end;\n\n            if c > 1\n                ylabel(''); \n            end;\n        end;\n    \n        % statistics accross groups\n        % -------------------------\n        if g == ng && ng > 1 && ~isempty(opt.groupstats) && ~isinf(pgroupplot{c}(1)) && ~statmask\n            hdl(c,g+1) = mysubplot(nc+addr, ng+addc, g + 1 + (c-1)*(ng+addc), opt.transpose);\n            tftopo( pgroupplot{c}', timevals, freqs, 'title', opt.titles{c,g+1}, options{:});\n            caxis([-maxplot maxplot]);\n        end;\n    end;\nend;\n\nfor g = 1:ng\n    % statistics accross conditions\n    % -----------------------------\n    if ~isempty(opt.condstats) && ~isinf(pcondplot{g}(1)) && ~statmask && nc > 1\n        hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, g + c*(ng+addc), opt.transpose);\n        tftopo( pcondplot{g}', timevals, freqs, 'title', opt.titles{nc+1,g}, options{:});\n        caxis([-maxplot maxplot]);\n    end;\nend;\n\n% color scale\n% -----------\nif isempty(opt.caxis)\n    tmpc = [-max(abs(tmpc)) max(abs(tmpc))];\n    for c = 1:nc\n        for g = 1:ng\n            axes(hdl(c,g));\n            if ~isempty(tmpc)\n                caxis(tmpc);\n            end;\n        end;\n    end;\nend;\n\n% statistics accross group and conditions\n% ---------------------------------------\nif ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1\n    hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, g + 1 + c*(ng+addr), opt.transpose);\n    tftopo( pinterplot',  timevals, freqs, 'title', opt.titles{nc+1,ng+1}, options{:});\n    caxis([-maxplot maxplot]);\n    ylabel('');\nend;    \n\n% color bars\n% ----------\naxes(hdl(nc,ng)); \ncbar_standard(opt.datatype, ng); \nif isnan(opt.threshold) && (nc ~= size(hdl,1) || ng ~= size(hdl,2))\n    ind = find(hdl(end:-1:1));\n    axes(hdl(end-ind(1)+1));\n    cbar_signif(ng, maxplot);\nend;\n\n% mysubplot (allow to transpose if necessary)\n% -------------------------------------------\nfunction hdl = mysubplot(nr,nc,ind,transp);\n\n    r = ceil(ind/nc);\n    c = ind -(r-1)*nc;\n    if strcmpi(transp, 'on'), hdl = subplot(nc,nr,(c-1)*nr+r);\n    else                      hdl = subplot(nr,nc,(r-1)*nc+c);\n    end;\n\n% colorbar for ERSP and scalp plot\n% --------------------------------\nfunction cbar_standard(datatype, ng);\n    pos = get(gca, 'position');\n    tmpc = caxis;\n    fact = fastif(ng == 1, 40, 20);\n    tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]);  \n    set(gca, 'unit', 'normalized');\n    if strcmpi(datatype, 'itc')\n         cbar(tmp, 0, tmpc, 10); ylim([0.5 1]);\n         title('ITC');\n    else cbar(tmp, 0, tmpc, 5);title('dB');\n    end;\n    \n\n% colorbar for significance\n% -------------------------\nfunction cbar_signif(ng, maxplot);\n    pos = get(gca, 'position');\n    tmpc = caxis;\n    fact = fastif(ng == 1, 40, 20);\n    tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]);  \n    map = colormap;\n    n = size(map,1);\n    cols = [ceil(n/2):n]';\n    image([0 1],linspace(0,maxplot,length(cols)),[cols cols]);\n    %cbar(tmp, 0, tmpc, 5);\n    tick = linspace(0, maxplot, maxplot+1);\n    set(gca, 'ytickmode', 'manual', 'YAxisLocation', 'right', 'xtick', [], ...\n        'ytick', tick, 'yticklabel', round(10.^-tick*1000)/1000);\n    xlabel('');\n\n% rapid filtering for ERP\n% -----------------------\nfunction tmpdata2 = myfilt(tmpdata, lowpass, highpass, factor, filtertype)\n\n    tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));\n    tmpdata2 = eegfiltfft(tmpdata2',lowpass, highpass, factor, filtertype)';\n    tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_plottf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.22899326553173602}}
{"text": "% [succeeded,outmatname,trx] = cadabra2ctrax(featname,roiname,moviename,[outmatname],[doflipup],[dofliplr],[rot])\n% inputs cadabra mat file output names, loads in the trajectories, and\n% converts to ctrax trx format. these trx will be saved to the file\n% outmatname (user will be prompted for this name if none given). \n% inputs:\n% featname: [optional] \"feat\" output by cadabra. if not input, user will be\n% prompted for file. \n% roiname: [optional] \"roi\" output by cadabra. if not input, user will be\n% prompted for file.\n% moviename: name of movie tracked\n% outmatname: [optional] mat file to save trx trajectories to. user will be\n% prompted for file name if none given\n% doflipud: [optional] whether to flip the trajectories vertically across\n% the middle of the video. Default: false.\n% dofliplr: [optional] whether to flip the trajectories horizontally across\n% the center of the video. Default: false.\n% rot: [optional] degrees to rotate the trajectories by around the center\n% of the video. Default: 0. \n\nfunction [succeeded,outmatname,trx] = cadabra2ctrax(featname,roiname,moviename,outmatname,doflipud,dofliplr,rot,movieinfo)\n\n% initialize outputs\nsucceeded = false;\nif ~exist('outmatname','var'),\n  outmatname = '';\nend\ntrx = [];\n\nif ~exist('featname','var') || isempty(featname),\n  helpmsg = 'Choose CADABRA feat mat file';\n  [featname,featpath] = uigetfilehelp('*.mat','Choose feat file','','helpmsg',helpmsg);\n  if ~ischar(featname),\n    return;\n  end\n  featname = fullfile(featpath,featname);\nend\n\nif ~exist('roiname','var') || isempty(roiname),\n  helpmsg = sprintf('Choose CADABRA roi mat file corresponding to feat file %s',featname);\n  roiname = strrep(featname,'feat','roi');\n  [roiname,roipath] = uigetfilehelp('*.mat','Choose feat file',roiname,'helpmsg',helpmsg);\n  if ~ischar(roiname),\n    return;\n  end\n  roiname = fullfile(roipath,roiname);\nend\n\nif ~exist('moviename','var') || isempty(moviename),\n  helpmsg = sprintf('Choose movie file corresponding to feat file %s',featname);\n  moviename = strrep(featname,'_feat.mat','.avi');\n  [moviename,moviepath] = uigetfilehelp('*.avi','Choose movie file',moviename,'helpmsg',helpmsg);\n  if ~ischar(moviename),\n    return;\n  end\n  moviename = fullfile(moviepath,moviename);\nend\n\nif ~exist('doflipud','var'),\n  doflipud = false;\nend\n\nif ~exist('dofliplr','var'),\n  dofliplr = false;\nend\n\nif ~exist('rot','var'),\n  rot = 0;\nend\n\nif rot ~= 0,\n  phi = rot*pi/180;\n  R = [cos(rot),sin(rot);-sin(rot),cos(rot)];\nend\n\n\n% load in data\nfeat = load(featname);\nroi = load(roiname);\n\nif ~exist('movieinfo','var') || isempty(movieinfo),\n\n  % read fps, frame size, moviename is either the name of the movie or an mmreader object\n  if ~ischar(moviename),\n    readerobj = moviename;\n    moviename = fullfile(get(readerobj,'Path'),get(readerobj,'Name'));\n  else\n    readerobj = mmreader(moviename);\n  end\n  fps = get(readerobj,'FrameRate')+0;\n  movieheight = get(readerobj,'Height')+0;\n  moviewidth = get(readerobj,'Width')+0;\nelse\n  fps = movieinfo.fps;\n  movieheight = movieinfo.height;\n  moviewidth = movieinfo.width;\nend\nmovieheight_mm = movieheight * roi.scale.y;\nmoviewidth_mm = moviewidth * roi.scale.x;\n\n% scale, pxpermm\npxpermm = 1/mean([roi.scale.x,roi.scale.y]);\n\n% allocate\nc = cell(1,2);\ntrx = struct('x',c,'y',c,'theta',c,'a',c,'b',c,...\n  'id',c,'moviename',c,'firstframe',c,'arena',c,...\n  'nframes',c,'endframe',c,'pxpermm',c,'fps',c,'x_mm',c,...\n  'y_mm',c,'a_mm',c,'b_mm',c,'dt',c);\nobj = [feat.fly_feat.obj1,feat.fly_feat.obj2];\nfirstframeoff = feat.fly_feat.frame(1) - 1;\narena = struct('x',nan,'y',nan,'r',nan);\nfor fly = 1:2,\n  \n  % frames for which fly is tracked\n  \n  % (x,y) = (0,0) for untracked frames\n  badframes = obj(fly).pos_x == 0 & obj(fly).pos_y == 0;\n  lastframe = find(~badframes,1,'last');\n  firstframe = find(~badframes,1);\n  if isempty(lastframe), \n    firstframe = 1;\n    lastframe = 0;\n  end\n  nframes = lastframe - firstframe + 1;\n  \n  % allocate\n  trx(fly).x = nan(1,nframes);\n  trx(fly).y = nan(1,nframes);\n  trx(fly).theta = nan(1,nframes);\n  trx(fly).a = nan(1,nframes);\n  trx(fly).b = nan(1,nframes);\n  trx(fly).xwingl = nan(1,nframes);\n  trx(fly).ywingl = nan(1,nframes);\n  trx(fly).xwingr = nan(1,nframes);\n  trx(fly).ywingr = nan(1,nframes);\n  trx(fly).x_mm = nan(1,nframes);\n  trx(fly).y_mm = nan(1,nframes);\n  trx(fly).a_mm = nan(1,nframes);\n  trx(fly).b_mm = nan(1,nframes);\n  trx(fly).dt = nan(1,nframes-1);\n  \n  % store parameters\n  trx(fly).moviename = moviename;\n  trx(fly).firstframe = firstframe + firstframeoff;\n  trx(fly).endframe = lastframe + firstframeoff;\n  trx(fly).nframes = nframes;\n  trx(fly).pxpermm = pxpermm;\n  trx(fly).fps = fps;\n  trx(fly).id = fly;\n  trx(fly).arena = arena;\n  %trx(fly).f2i = @(f) f - trx(fly).firstframe + 1;\n  \n  % store data\n  idx = feat.fly_feat.frame(firstframe:lastframe)-trx(fly).firstframe + 1;\n  % we use the quarter major, minor axis length\n  trx(fly).a_mm(idx) = obj(fly).FLength/4;\n  % maybe area is major/2 * minor/2 * pi, store quarter minor axis length\n  trx(fly).b_mm(idx) = (obj(fly).FArea./(obj(fly).FLength/2)/pi)/2;\n  % convert degrees to radians\n  trx(fly).theta(idx) = obj(fly).headdir*pi/180;\n  \n  % convert mm to px, incorporate offset\n  trx(fly).x(idx) = obj(fly).pos_x*pxpermm + roi.ROI.cols(1) - 1;\n  trx(fly).y(idx) = obj(fly).pos_y*pxpermm + roi.ROI.rows(1) - 1 - 1;\n  trx(fly).x_mm = trx(fly).x / pxpermm;\n  trx(fly).y_mm = trx(fly).y / pxpermm;\n  trx(fly).a = trx(fly).a_mm*pxpermm;\n  trx(fly).b = trx(fly).b_mm*pxpermm;\n    \n  phil = obj(fly).phil*pi/180;\n  wingll = obj(fly).wingll*pxpermm;\n  xwl = trx(fly).x(idx) + wingll.*cos(-phil-trx(fly).theta(idx)-pi);\n  ywl = trx(fly).y(idx) + wingll.*sin(-phil-trx(fly).theta(idx));\n  phir = obj(fly).phir*pi/180;\n  winglr = obj(fly).winglr*pxpermm;\n  xwr = trx(fly).x(idx) + winglr.*cos(phir-trx(fly).theta(idx)-pi);\n  ywr = trx(fly).y(idx) + winglr.*sin(phir-trx(fly).theta(idx));\n  trx(fly).xwingl(idx) = xwl;\n  trx(fly).ywingl(idx) = ywl;\n  trx(fly).xwingr(idx) = xwr;\n  trx(fly).ywingr(idx) = ywr;\n  trx(fly).xwingl_mm = trx(fly).xwingl / pxpermm;\n  trx(fly).ywingl_mm = trx(fly).ywingl / pxpermm;\n  trx(fly).xwingr_mm = trx(fly).xwingr / pxpermm;\n  trx(fly).ywingr_mm = trx(fly).ywingr / pxpermm;\n  \n  \n  trx(fly).dt(idx(1:end-1)) = diff(feat.fly_feat.time(firstframe:lastframe));\n  \n  % flipud if necessary\n  if doflipud,\n    trx(fly).y_mm = movieheight_mm - trx(fly).y_mm;\n    trx(fly).y = movieheight - trx(fly).y;\n    trx(fly).theta = -trx(fly).theta;\n  end\n\n  % fliplr if necessary\n  if dofliplr,\n    trx(fly).x_mm = moviewidth_mm - trx(fly).x_mm;\n    trx(fly).x = moviewidth - trx(fly).x;\n    trx(fly).theta = modrange(pi-trx(fly).theta,-pi,pi);\n  end\n  \n  % rotate if necessary\n  if rot ~= 0,\n    trx(fly).x_mm = (trx(fly).x_mm - moviewidth_mm/2)*R + moviewidth_mm/2;\n    trx(fly).y_mm = (trx(fly).y_mm - movieheight_mm/2)*R + movieheight_mm/2;\n    trx(fly).x = (trx(fly).x - moviewidth/2)*R + moviewidth/2;\n    trx(fly).y = (trx(fly).y - movieheight/2)*R + movieheight/2;\n    trx(fly).theta = modrange(trx(fly).theta + phi,-pi,pi);\n  end\n  \nend\n\nif ~exist('outmatname','var') || isempty(outmatname),\n  [pathstr,name] = fileparts(featname);\n  outname = strrep(name,'_feat','');\n  outmatname = fullfile(pathstr,[outname,'_trx.mat']);\n  helpmsg = {};\n  helpmsg{1} = 'Choose mat file to save Ctrax version of trajectories loaded from:';\n  helpmsg{2} = sprintf('CADABRA feat file: %s',featname);\n  helpmsg{3} = sprintf('CADABRA roi file: %s',roiname);\n  [outmatname,outmatpath] = uiputfilehelp('*.mat',sprintf('Save ctrax version of %s',name),outmatname,'helpmsg',helpmsg);\n  if ~ischar(outmatname),\n    outmatname = '';\n    return;\n  end\n  outmatname = fullfile(outmatpath,outmatname);\n  fprintf('Saving to %s...\\n',outmatname);\nend\n\nsave(outmatname,'trx');\nsucceeded = true;", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/filehandling/cadabra2ctrax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22891757446279754}}
{"text": "function plotPredictionResults_LGG(pathResults,nameOutcome,fSetNames,metric,maxOrder,pathFig)\n% -------------------------------------------------------------------------\n% function plotPredictionResults_LGG(pathResults,nameOutcome,fSetNames,metrics,maxOrder)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function plots prediction performance estimation results for all the\n% different feature set types entered as inputs in the LGG study.\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathResults: Full path to the 'RESULTS' folder where prediction results\n%                 are saved.\n%                 --> Ex: '/myProject/WORKSPACE/LOGISTIC_REGRESSION/RESULTS'\n% 2. nameOutcome: String specifying the name of the outcome being displayed\n%                 --> Ex: 'progression'\n% 3. fSetNames: Cell of strings specifying the name of the type of feature \n%               set analyzed.\n%               --> Ex: {'T1W_T2W','T1W_T2F','T1CE_T2W','T1CE_T2F'}\n% 4. metric: String specifying the metric to display.\n%            --> 'AUC632'\n% 5. maxOrder: Integer specifying the maximal multivariable model order.\n%              --> Ex: 10\n% 6. pathFig: (optional).  Full path to where figure is saved without\n%             displaying it. Put '' for displaying the figure and not \n%             saving it to 'pathFig' (default).\n%             --> Ex: ''\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nif nargin < 6\n    pathFig = '';\nend\n\nstartpath = pwd;\ncd(pathResults)\n\nsigns = {'-r',':b','--g','-.y'};\nnFSET = numel(fSetNames);\n\nmaxOrderChosen = maxOrder;\n\nif isempty(pathFig)\n    figure\nelse\n    h = figure('visible','off');\nend\nfor i = 1:nFSET\n    fSET = fSetNames{i};\n    results = load(['RESULTS_',fSET,'_',nameOutcome]); results = struct2cell(results); results = results{1};\n    nOrders = numel(fieldnames(results));\n    if nOrders < maxOrderChosen\n        maxOrder = nOrders;\n    else\n        maxOrder = maxOrderChosen;\n    end\n    val = zeros(maxOrder,1);\n    val_SE = zeros(maxOrder,1);\n    for j = 1:maxOrder\n        orderName = ['Order',num2str(j)];\n        val(j,1) = results.(orderName).(metric);\n        val_SE(j,1) = results.(orderName).(['SE_',metric]);\n    end\n    errorbar(1:maxOrder,val(:,1),val_SE(:,1),signs{i},'LineWidth',3,'MarkerFaceColor',signs{i}(end),'MarkerSize',6)\n    hold on\nend\nset(gca,'FontSize',20)\nxlabel('Model Order','FontSize',24)\nylabel('Prediction performance','FontSize',24)\nind = strfind(metric,'632');\nif ~isempty(ind)\n    metric = [metric,'+'];\nend\nmetric = [metric(1:ind-1),'_{',metric(ind:end),'}'];\nind = strfind(nameOutcome,'Death');\nif ~isempty(ind)\n    nameOutcome(ind:ind+4) = [];\n    nameOutcome = ['Survival',nameOutcome];\nend\ntitleName = [nameOutcome,' -- ',metric];\ntitle(titleName,'FontSize',30,'FontWeight','bold')\nlegend(fSetNames,'Location','SouthEast')\naxis([0 maxOrderChosen+1 0.5 1])\nset(gca,'XTick',[1 2 3 4 5 6 7 8 9 10])\n\nif ~isempty(pathFig)\n    cd(pathFig)\n    saveas(h,titleName,'fig')\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/plotPredictionResults_LGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2288455972315638}}
{"text": "function [ResultsMaleFemale] = compareMaleFemale(male,female)\n% This function compares basic features of the male and female whole-body\n% metabolic models\n%\n% [ResultsMaleFemale] = compareMaleFemale(male,female)\n%\n% INPUT\n% male                  model structure (male whole-body metabolic model)\n% female                model structure (female whole-body metabolic model)\n%\n% OUTPUT\n% ResultsMaleFemale     structure containing the basic differences and\n%                       commenalities between male and female model\n%\n% Ines Thiele 2017\n\n% reactions unique to male\nResultsMaleFemale.MaleOnly = setdiff(male.rxns,female.rxns);\nResultsMaleFemale.FemaleOnly = setdiff(female.rxns,male.rxns);\nResultsMaleFemale.BothGender = intersect(female.rxns,male.rxns);\n\n[maleOrgans]=unique(strtok(male.rxns,'_'));\n[femaleOrgans]=unique(strtok(female.rxns,'_'));\n\nfor i = 1 : length(maleOrgans)\n    ResultsMaleFemale.OrgansNumRxnMale(i,1) = length(strmatch(maleOrgans(i),male.rxns));   \n    ResultsMaleFemale.OrgansNumRxnMale(i,2) = length(strmatch(maleOrgans(i),ResultsMaleFemale.MaleOnly));\n    % fraction\n    ResultsMaleFemale.OrgansNumRxnMale(i,3) = ResultsMaleFemale.OrgansNumRxnMale(i,2)/ResultsMaleFemale.OrgansNumRxnMale(i,1); \nend\n\nfor i = 1 : length(femaleOrgans)\n    ResultsMaleFemale.OrgansNumRxnFemale(i,1) = length(strmatch(femaleOrgans(i),female.rxns));   \n    ResultsMaleFemale.OrgansNumRxnFemale(i,2) = length(strmatch(femaleOrgans(i),ResultsMaleFemale.FemaleOnly));\n    % fraction\n    ResultsMaleFemale.OrgansNumRxnFemale(i,3) = ResultsMaleFemale.OrgansNumRxnFemale(i,2)/ResultsMaleFemale.OrgansNumRxnFemale(i,1); \nend\n\nResultsMaleFemale.maleOrgans = maleOrgans;\nResultsMaleFemale.femaleOrgans = femaleOrgans;\n\n%get subsystems for gall rxns\nFemaleSS = female.subSystems(find(ismember(female.rxns,ResultsMaleFemale.FemaleOnly(strmatch('Gall_',ResultsMaleFemale.FemaleOnly)))));\nResultsMaleFemale.FemaleGallSSEnrich = unique(FemaleSS);\nfor i = 1 : length(ResultsMaleFemale.FemaleGallSSEnrich)\n    ResultsMaleFemale.FemaleGallSSEnrich{i,2} = num2str(length(strmatch(ResultsMaleFemale.FemaleGallSSEnrich{i},FemaleSS,'exact')));\nend\nMaleSS = male.subSystems(find(ismember(male.rxns,ResultsMaleFemale.MaleOnly(strmatch('Gall_',ResultsMaleFemale.MaleOnly)))));\nResultsMaleFemale.MaleGallSSEnrich = unique(MaleSS);\nfor i = 1 : length(ResultsMaleFemale.MaleGallSSEnrich)\n    ResultsMaleFemale.MaleGallSSEnrich{i,2} = num2str(length(strmatch(ResultsMaleFemale.MaleGallSSEnrich{i},MaleSS,'exact')));\nend\n\n% unique biofluid exchange reactions\n\nResultsMaleFemale.MaleOnlyBiofluid = ResultsMaleFemale.MaleOnly(find(~cellfun(@isempty,strfind(ResultsMaleFemale.MaleOnly,'_EX_'))));\nResultsMaleFemale.FemaleOnlyBiofluid = ResultsMaleFemale.FemaleOnly(find(~cellfun(@isempty,strfind(ResultsMaleFemale.FemaleOnly,'_EX_'))));\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/wholeBody/PSCMToolbox/compareMaleFemale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.22884559723156378}}
{"text": "function mrInit_updateSessiontSeries()\n%\n% USAGE: Takes a session that has already been initialized with an older\n% version of mrInit and update it to the newest version. This version\n% is of 2013-05-05 and it no longer uses tSeries data in the form of\n% matrices, instead saving tSeries data to a nifti and using that.\n%\n% INPUT: N/A, no input is used. As long as the user is in the directory of\n% the session to be migrated, this should work correctly.\n%\n% OUTPUT: N/A, no output is given. The error handling has been upgraded to\n% use built in matlab try-catch blocks.\n%\n% This migration tool takes a series of folders of tSeries*.mat files and\n% makes some assumptions about their orientation. Specifically, it is assumed\n% that these are already in the normal display format.\n% All of the tSeries data is loaded and the migration tool creates\n% a nifti structure around this data, saves it to the filesystem and writes\n% the information about its location in the session and datatype global\n% variables, before saving these to mrSESSION.mat as well.\n\ntry\n    loadSession;\n    mrGlobals;\n    \n    %Before we reset mrSESSION, let's save a backup\n    copyfile('mrSESSION.mat','mrSESSION_tSeriesMigrationBackup.mat');\n    \n    %Now that we have the number of scans, we know how many tSeries nifti\n    %files we will need to create\n    \n    % Use local paths, not absolute paths\n    % inplaneBasePath = fullfile(pwd,'Inplane');\n    inplaneBasePath = 'Inplane';\n    \n    \n    for dtNum = 1:numel(dataTYPES)\n        fprintf('Starting dataTYPE number %d\\n', dtNum);\n        tSeriesOutPath = fullfile(inplaneBasePath, dtGet(dataTYPES(dtNum),'Name'));\n        tSeriesInBasePath = fullfile(tSeriesOutPath,'TSeries');\n        \n        if exist(fullfile(tSeriesInBasePath,'Scan1','tSeries1.mat'),'file')\n            %Checks to see if there is any inplane tSeries data in this\n            %dataTYPE if there is, then does all of the processing\n            \n            numScans = dtGet(dataTYPES(dtNum),'N Scans');\n            \n            keepFrames = zeros(numScans,2);\n            \n            for scan = 1:numScans\n                fprintf('Starting scan number %d\\n', scan);\n                % For each scan, go through each scan directory, read in all of the\n                % matrix files and then build the data for a nifti from them.\n                numSlices = dtGet(dataTYPES(dtNum),'N Slices', scan);\n                tSeriesInFolder = fullfile(tSeriesInBasePath,['Scan' num2str(scan)]);\n                dimSize = [dtGet(dataTYPES(dtNum),'N Frames', scan) dtGet(dataTYPES(dtNum),'Func Size', scan) dtGet(dataTYPES(dtNum),'N Slices', scan)];\n                tSeries = zeros(dimSize);\n                for slice = 1:numSlices\n                    tSeriesInFile = fullfile(HOMEDIR, tSeriesInFolder,['tSeries' num2str(slice) '.mat']);\n                    tSeriesIn = load(tSeriesInFile);\n                    tSeriesIn = reshape(tSeriesIn.tSeries, dimSize(1:3));\n                    tSeries(:,:,:,slice) = tSeriesIn;\n                end %for\n                \n                % The following transform will preserve the orientation of the data\n                % across the migration, such that inplane to vAnatomy xforms do not\n                % need to change, nor do parameter maps, ROIs, etc. The permute([2 1])\n                % followed by flipdim(2) effectively converts from x/y coordinates to\n                % row/column coordinates. The reason we do this is that the old\n                % vistasoft (prior to the move to NIFTIs) did this transform when\n                % showing the slices as images, whereas the current code simply pulls\n                % the data array from a nifti (after applying a standard xform to the\n                % nifti), and uses an image tool such as imagesc slice by slice without\n                % re-orienting the array. Since we no longer do this xform each time we\n                % show the data, we must do it here as part of the migration if want\n                % the migrated data to appear the same way as the pre-migrated data.\n                % See also mrInit_updateInplaneSession.m.\n                tSeries = permute(tSeries,[3 2 4 1]); %Standard format: freq phase slice time\n                tSeries = flip(tSeries, 2);\n                %Note: this needed to be changed to reflect the fact that\n                %MATLAB stores values row, column, etc. and not column,\n                %row,\n                \n                %Create the freq, phase and slice dimensions, assuming that we are in\n                %standard format\n                freqPhaseSliceDims = [1 2 3];\n                \n                %Create the slice information\n                % We are assuming that the voxels are the same size in all\n                % of the dataTYPES\n                funcVoxel = sessionGet(mrSESSION,'Functional Voxel Size',scan);\n                \n                xform = [[diag(1./funcVoxel); 0 0 0], size(tSeries)'/2];\n                \n                funcVoxel(4) = dtGet(dataTYPES(dtNum),'Frame Period',scan);\n                \n                sliceInfo = [3 0 dtGet(dataTYPES(dtNum),'N Slices',scan)-1 funcVoxel(4)];\n                \n                %Build the nifti from the components above\n                nii = niftiCreate('data',tSeries,'qto_xyz',xform,'freq_dim',freqPhaseSliceDims,'slice_code',sliceInfo);\n                \n                %However, this does not create the proper pix dims, so let's fix that\n                nii = niftiSet(nii,'Pix dim',funcVoxel);\n                \n                keepFrames(scan, 1) = 0;\n                keepFrames(scan, 2) = -1;\n                \n                mrSESSION = sessionSet(mrSESSION,'Keep Frames',keepFrames, scan);\n                \n                tSeriesOut = fullfile(tSeriesInBasePath,['tSeriesScan' num2str(scan) '.nii.gz']);\n                \n                nii = niftiSet(nii,'File Path',tSeriesOut);\n                \n                dataTYPES(dtNum) = dtSet(dataTYPES(dtNum),'Inplane Path',tSeriesOut,scan);\n                dataTYPES(dtNum) = dtSet(dataTYPES(dtNum),'Keep Frames', keepFrames, scan);\n                \n                niftiWrite(nii,tSeriesOut);\n                \n                mrSESSION = sessionSet(mrSESSION,'Version','2.1');\n                \n                %Update the session variables\n                save('mrSESSION.mat', 'mrSESSION','-append');\n                save('mrSESSION.mat', 'dataTYPES','-append');\n                \n                % we already wrote the nifti 4 lines above. this is\n                % redundant.\n                %   writeFileNifti(nii);\n                \n                fprintf('Finished scan number %d\\n', scan)\n            end %for\n            \n        end %if\n        fprintf('Finished dataTYPE number %d\\n', dtNum)\n    end %for\n    \ncatch err\n    warning(['There was an error when attempting to update your session.',...\n        'No changes have been made to your system. Please run the update code again.']);\n    rethrow(err);\nend %try\n\nreturn", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Init/mrInit_updateSessiontSeries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.22880354053663277}}
{"text": "%yuv2yuv can change the resolution and format of YUV-Files.\n%\tyuv2yuv('Filename_old',width_old,height_old,format_old,'Filename_new',w\n%\tidth_new,height_new,format_new) read one YUV-File with the\n%\tspecified resolution and format and write it to a second YUV-File with\n%\tthe specified resolution and format.\n%\t\n%\tFilename_old --> Name of original File (e.g. 'Test_old.yuv')\n%   width_old    --> width of original frame  (e.g. 352) \n%   height_old   --> height of original frame (e.g. 280)\n%   format_old   --> subsampling rate of original YUV-File('400','411','420','422' or '444')\n%\tFilename_new --> Name of new File (e.g. 'Test_new.yuv')\n%   width_new    --> width of new frame  (e.g. 704) \n%   height_new   --> height of new frame (e.g. 560)\n%   format_new   --> subsampling rate of new YUV-File('400','411','420','422' or '444')\n%example: yuv2yuv('Test_old.yuv',352,288,'420','Test_new.yuv',704,560,'400')\n\nfunction yuv2yuv(File_old,width_old,height_old,format_old,File_new,width_new,height_new,format_new)\n\n    %set factor for UV-sampling\n    [fwidth_old,fheight_old] = getformatfactor(format_old);\n    [fwidth_new,fheight_new] = getformatfactor(format_new);\n    %get Filesize and Framenumber of original File\n    filep = dir(File_old); \n    fileBytes = filep.bytes; %Filesize\n    clear filep\n    framenumber = fileBytes/(width_old*height_old*(1+2*fheight_old*fwidth_old)); %Framenumber\n    if mod(framenumber,1) ~= 0\n        display('Error: wrong resolution, format or filesize');\n    else\n        fclose(fopen(File_new,'w')); %Init File\n        h = waitbar(0,'Please wait ... ');\n        %read YUV-Frames\n        for cntf = 1:1:framenumber\n            waitbar(cntf/framenumber,h);\n            YUV     = loadFileYUV(width_old,height_old,cntf,File_old,fheight_old,fwidth_old);\n            YUV_new = imresize(YUV,[height_new width_new],'bicubic');\n            save_yuv(YUV_new,File_new,width_new,height_new,fheight_new,fwidth_new);\n        end\n        close(h);\n    end\n    \n    \n    \n%get factor for YUV-subsampling\nfunction [fwidth,fheight] = getformatfactor(format)\n    fwidth = 0.5;\n    fheight= 0.5;\n    if strcmp(format,'400')\n        fwidth = 0;\n        fheight= 0;\n    elseif strcmp(format,'411')\n        fwidth = 0.25;\n        fheight= 1;\n    elseif strcmp(format,'420')\n        fwidth = 0.5;\n        fheight= 0.5;\n    elseif strcmp(format,'422')\n        fwidth = 0.5;\n        fheight= 1;\n    elseif strcmp(format,'444')\n        fwidth = 1;\n        fheight= 1;\n    else\n        display('Error: wrong format');\n    end\n\n    \n% read YUV-data from file\nfunction YUV = loadFileYUV(width,heigth,Frame,fileName,Teil_h,Teil_b)\n    % get size of U and V\n    fileId = fopen(fileName,'r');\n    width_h = width*Teil_b;\n    heigth_h = heigth*Teil_h;\n    % compute factor for framesize\n    factor = 1+(Teil_h*Teil_b)*2;\n    % compute framesize\n    framesize = width*heigth;\n      \n    fseek(fileId,(Frame-1)*factor*framesize, 'bof');\n    % create Y-Matrix\n    YMatrix = fread(fileId, width * heigth, 'uchar');\n    YMatrix = int16(reshape(YMatrix,width,heigth)');\n    % create U- and V- Matrix\n    if Teil_h == 0\n        UMatrix = 0;\n        VMatrix = 0;\n    else\n        UMatrix = fread(fileId,width_h * heigth_h, 'uchar');\n        UMatrix = int16(UMatrix);\n        UMatrix = reshape(UMatrix,width_h, heigth_h).';\n        \n        VMatrix = fread(fileId,width_h * heigth_h, 'uchar');\n        VMatrix = int16(VMatrix);\n        VMatrix = reshape(VMatrix,width_h, heigth_h).';       \n    end\n    % compose the YUV-matrix:\n    YUV(1:heigth,1:width,1) = YMatrix;\n    \n    if Teil_h == 0\n        YUV(:,:,2) = 127;\n        YUV(:,:,3) = 127;\n    end\n    % consideration of the subsampling of U and V\n    if Teil_b == 1\n        UMatrix1(:,:) = UMatrix(:,:);\n        VMatrix1(:,:) = VMatrix(:,:);\n    \n    elseif Teil_b == 0.5        \n        UMatrix1(1:heigth_h,1:width) = int16(0);\n        UMatrix1(1:heigth_h,1:2:end) = UMatrix(:,1:1:end);\n        UMatrix1(1:heigth_h,2:2:end) = UMatrix(:,1:1:end);\n \n        VMatrix1(1:heigth_h,1:width) = int16(0);\n        VMatrix1(1:heigth_h,1:2:end) = VMatrix(:,1:1:end);\n        VMatrix1(1:heigth_h,2:2:end) = VMatrix(:,1:1:end);\n    \n    elseif Teil_b == 0.25\n        UMatrix1(1:heigth_h,1:width) = int16(0);\n        UMatrix1(1:heigth_h,1:4:end) = UMatrix(:,1:1:end);\n        UMatrix1(1:heigth_h,2:4:end) = UMatrix(:,1:1:end);\n        UMatrix1(1:heigth_h,3:4:end) = UMatrix(:,1:1:end);\n        UMatrix1(1:heigth_h,4:4:end) = UMatrix(:,1:1:end);\n        \n        VMatrix1(1:heigth_h,1:width) = int16(0);\n        VMatrix1(1:heigth_h,1:4:end) = VMatrix(:,1:1:end);\n        VMatrix1(1:heigth_h,2:4:end) = VMatrix(:,1:1:end);\n        VMatrix1(1:heigth_h,3:4:end) = VMatrix(:,1:1:end);\n        VMatrix1(1:heigth_h,4:4:end) = VMatrix(:,1:1:end);\n    end\n    \n    if Teil_h == 1\n        YUV(:,:,2) = UMatrix1(:,:);\n        YUV(:,:,3) = VMatrix1(:,:);\n        \n    elseif Teil_h == 0.5        \n        YUV(1:heigth,1:width,2) = int16(0);\n        YUV(1:2:end,:,2) = UMatrix1(:,:);\n        YUV(2:2:end,:,2) = UMatrix1(:,:);\n        \n        YUV(1:heigth,1:width,3) = int16(0);\n        YUV(1:2:end,:,3) = VMatrix1(:,:);\n        YUV(2:2:end,:,3) = VMatrix1(:,:);\n        \n    elseif Teil_h == 0.25\n        YUV(1:heigth,1:width,2) = int16(0);\n        YUV(1:4:end,:,2) = UMatrix1(:,:);\n        YUV(2:4:end,:,2) = UMatrix1(:,:);\n        YUV(3:4:end,:,2) = UMatrix1(:,:);\n        YUV(4:4:end,:,2) = UMatrix1(:,:);\n        \n        YUV(1:heigth,1:width) = int16(0);\n        YUV(1:4:end,:,3) = VMatrix1(:,:);\n        YUV(2:4:end,:,3) = VMatrix1(:,:);\n        YUV(3:4:end,:,3) = VMatrix1(:,:);\n        YUV(4:4:end,:,3) = VMatrix1(:,:);\n    end\n    YUV = uint8(YUV);\n    fclose(fileId);\n    \n%Save YUV-Data to File\nfunction save_yuv(data,video_file,BreiteV,HoeheV,HoehenteilerV,BreitenteilerV)\n\n    %get Resolution od Data\n    datasize = size(data);\n    datasizelength = length(datasize);\n\n    %open File\n    fid = fopen(video_file,'a');\n\n    %subsampling of U and V\n    if datasizelength == 2 | HoehenteilerV == 0\n        %4:0:0\n        y(1:HoeheV,1:BreiteV) = data(:,:,1);\n    elseif datasizelength == 3\n        y(1:HoeheV,1:BreiteV) = double(data(:,:,1));\n        u(1:HoeheV,1:BreiteV) = double(data(:,:,2));\n        v(1:HoeheV,1:BreiteV) = double(data(:,:,3));\n        if BreitenteilerV == 1\n            %4:1:1\n            u2 = u;\n            v2 = v;\n        elseif HoehenteilerV == 0.5\n            %4:2:0\n            u2(1:HoeheV/2,1:BreiteV/2) = u(1:2:end,1:2:end)+u(2:2:end,1:2:end)+u(1:2:end,2:2:end)+u(2:2:end,2:2:end);\n            u2                         = u2/4;\n            v2(1:HoeheV/2,1:BreiteV/2) = v(1:2:end,1:2:end)+v(2:2:end,1:2:end)+v(1:2:end,2:2:end)+v(2:2:end,2:2:end);\n            v2                         = v2/4;\n        elseif BreitenteilerV == 0.25\n            %4:1:1\n            u2(1:HoeheV,1:BreiteV/4) = u(:,1:4:end)+u(:,2:4:end)+u(:,3:4:end)+u(:,4:4:end);\n            u2                       = u2/4;\n            v2(1:HoeheV,1:BreiteV/4) = v(:,1:4:end)+v(:,2:4:end)+v(:,3:4:end)+v(:,4:4:end);\n            v2                       = v2/4;\n        elseif BreitenteilerV == 0.5 & HoehenteilerV == 1\n            %4:2:2\n            u2(1:HoeheV,1:BreiteV/2) = u(:,1:2:end)+u(:,2:2:end);\n            u2                       = u2/2;\n            v2(1:HoeheV,1:BreiteV/2) = v(:,1:2:end)+v(:,2:2:end);\n            v2                       = v2/2;\n        end\n    end\n\n    fwrite(fid,uint8(y'),'uchar'); %writes Y-Data\n\n    if HoehenteilerV ~= 0\n        %writes U- and V-Data if no 4:0:0 format\n        fwrite(fid,uint8(u2'),'uchar');\n        fwrite(fid,uint8(v2'),'uchar');\n    end\n\n    fclose(fid);\n ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11318-transform-yuv-file/yuv2yuv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22858095211847498}}
{"text": "function [charData] = srcCharLayerForward(W_rnn, W_emb, input, mask, charMap, vocabSize, params, isTest)\n% Running char layer forward to compute word representations\n% Input:\n%   W_rnn: recurrent connections of multiple layers, e.g., W_rnn{ll}.\n%   input: indices for the current batch\n%   isTest: 1 -- don't store intermediate results in each state\n%   isDecoder: 0 -- encoder, 1 -- decoder\n% Output:\n%   charData\n%\n% Thang Luong @ 2015, <lmthang@stanford.edu>\n\n  charData.params = params;\n  charData.params.numLayers = params.charNumLayers;\n\n  % find rare words\n  charData.rareFlags = input > params.srcCharShortList;\n  charData.rareWords = unique(input(charData.rareFlags));\n  \n  % sample from frequent words\n  if isTest == 0 && params.charSrcSample > 0\n    % select by types: not masked and not unk\n    freqWords = unique(input(~charData.rareFlags & mask & (input ~= params.srcUnk)));\n    numSelect = floor(length(freqWords)*params.charSrcSample);\n    perm = randperm(length(freqWords));\n    selectFreqWords = freqWords(perm(1:numSelect));\n    \n    % assert\n    if params.assert\n      assert(isempty(intersect(charData.rareWords, selectFreqWords)) == 1);\n      assert(ismember(params.srcSos, selectFreqWords) == 0);\n    end\n    \n    % update rare words and flags\n    charData.rareWords = union(charData.rareWords, selectFreqWords);\n    charData.rareFlags = ismember(input, charData.rareWords);\n    \n    if params.assert\n      assert(isempty(find(charData.rareWords == params.srcUnk, 1)));\n    end\n  end\n  \n  charData.numRareWords = length(charData.rareWords);\n  charSeqs = charMap(charData.rareWords);\n  seqLens = cellfun(@(x) length(x), charSeqs);\n  \n  if charData.numRareWords > 0\n    charData.params.curBatchSize = charData.numRareWords;\n    [charData.batch, charData.mask, charData.maxLen, charData.numSeqs] = leftPad(charMap(charData.rareWords), seqLens, params.srcCharSos, params.srcCharEos);\n    \n    charData.rnnFlags = struct('decode', 0, 'test', isTest, 'attn', 0, 'feedInput', 0, 'charSrcRep', 0, 'charTgtGen', 0);\n    zeroState = createZeroState(charData.params);\n    [charData.states, ~, ~] = rnnLayerForward(W_rnn, W_emb, zeroState, charData.batch, charData.mask, charData.params, charData.rnnFlags, [], [], []);\n    charData.rareWordReps = charData.states{end}{end}.h_t;\n    charData.rareWordMap = zeros(vocabSize, 1);\n    charData.rareWordMap(charData.rareWords) = 1:charData.numRareWords;\n  end\nend\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/layers/srcCharLayerForward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22849830988539047}}
{"text": "% POP_SELECT - given an input EEG dataset structure, output a new EEG data structure \n%                retaining and/or excluding specified time/latency, data point, channel, \n%                and/or epoch range(s).\n% Usage:\n%   >> OUTEEG = pop_select(INEEG, 'key1', value1, 'key2', value2 ...);\n%\n% Graphic interface:\n%   \"Time range\" - [edit box] RETAIN only the indicated epoch latency or continuous data \n%                  time range: [low high] in ms, inclusive. For continuous data, several \n%                  time ranges may be specified, separated by semicolons. \n%                  Example: \"5 10; 12 EEG.xmax\" will retain the indicated\n%                  stretches of continuous data, and remove data portions outside\n%                  the indicated ranges, e.g. from 0 s to 5 s and from 10 s to 12 s. \n%                  Command line equivalent: 'time' (or 'notime' - see below)\n%   \"Time range\" - [checkbox] EXCLUDE the indicated latency range(s) from the data.\n%                  For epoched data, it is not possible to remove a range of latencies \n%                  from the middle of the epoch, so either the low and/or the high values \n%                  in the specified latency range (see above) must be at an epoch boundary \n%                  (EEG.xmin, EEGxmax).  Command line equivalent: [if checked] 'notime' \n%   \"Point range\" - [edit box] RETAIN the indicated data point range(s). \n%                  Same options as for the \"Time range\" features (above).\n%                  Command line equivalent: 'point' (or 'nopoint' - see below).\n%   \"Point range\" - [checkbox] EXCLUDE the indicated point range(s).\n%                  Command line equivalent: [if checked] 'nopoint' \n%   \"Epoch range\" - [edit box] RETAIN the indicated data epoch indices in the dataset.\n%                  This checkbox is only visible for epoched datasets. \n%                  Command line equivalent: 'trial' (or 'notrial' - see below)\n%   \"Epoch range\" - [checkbox] EXCLUDE the specified data epochs. \n%                   Command line equivalent: [if checked] 'notrial' \n%   \"Channel range\" - [edit box] RETAIN the indicated vector of data channels \n%                  Command line equivalent: 'channel' (or 'nochannel' - see below)\n%   \"Channel range\" - [checkbox] EXCLUDE the indicated channels.\n%                  Command line equivalent: [if checked] 'nochannel' \n%   \"...\" - [button] select channels by name.\n%   \"Scroll dataset\" - [button] call the EEGPLOT function to scroll the\n%                  channel activities in a new window for visual inspection.\n%                  Commandline equivalent: EEGPLOT - see its help for details.\n% Inputs:\n%   INEEG         - input EEG dataset structure\n%\n% Optional inputs\n%   'time'        - [min max] in seconds. Epoch latency or continuous data time range \n%                   to retain in the new dataset, (Note: not ms, as in the GUI text entry \n%                   above). For continuous data (only), several time ranges can be specified, \n%                   separated by semicolons. Example: \"5 10; 12 EEG.xmax\" will retain \n%                   the indicated times ranges, removing data  outside the indicated ranges \n%                   e.g. here from 0 to 5 s and from 10 s to 12 s. (See also, 'notime')\n%   'rmtime'      - [min max] in seconds. Epoch latency or continuous dataset time range \n%                   to exclude from the new dataset. For continuous data, may be \n%                   [min1 max1; min2 max2; ...] to exclude several time ranges. For epoched \n%                   data, the latency range must include an epoch boundary, as latency \n%                   ranges in the middle of epochs cannot be removed from epoched data.\n%   'point'       - [min max] epoch or continuous data point range to retain in the new \n%                   dataset. For continuous datasets, this may be [min1 max1; min2 max2; ...] \n%                   to retain several point ranges. (Notes: If both 'point'/'nopoint' and \n%                   'time' | 'notime' are specified, the 'point' limit values take precedence. \n%                   The 'point' argument was originally a point vector, now deprecated).\n%   'rmpoint'     - [min max] epoch or continuous data point range to exclude in the new dataset. \n%                   For epoched data, the point range must include either the first (0) \n%                   or the last point (EEG.pnts), as a central point range cannot be removed. \n%   'trial'       - [integer array] array of trial indices to retain in the new dataset\n%   'rmtrial'     - [integer array] array of trial indices to exclude from the new dataset\n%   'sorttrial'   - ['on'|'off'] sort trial indices before extracting them (default: 'on').\n%   'checkchans'  - ['on'|'off'] check that channels are present before\n%                   rejecting them (default: 'on')\n%   'channel'     - vector of channel indices to retain in the new \n%                   dataset. Can also be a cell array of channel names.\n%   'rmchannel'   - vector of channel indices to exclude from the new\n%                   dataset. Can also be a cell array of channel names.\n%   'chantype'    - [string|cell] list of channel types to keep\n%   'rmchantype'  - [string|cell] list of channel types to remove\n%\n% Outputs:\n%   OUTEEG        - new EEG dataset structure\n%\n% Note: This function performs a conjunction (AND) of all its optional inputs.\n%       Using negative counterparts of all options, any logical combination is\n%       possible. Legacy input 'notrial', 'notime', 'nochannel', 'nopoint'\n%       are still supported.\n% \n% Author: Arnaud Delorme, CNL/Salk Institute, 2001; SCCN/INC/UCSD, 2002-\n% \n% see also: EEGLAB\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 01-25-02 reformated help & license -ad \n% 01-26-02 changed the format for events and trial conditions -ad\n% 02-04-02 changed display format and allow for negation of inputs -ad \n% 02-17-02 removed the event removal -ad \n% 03-17-02 added channel info subsets selection -ad \n% 03-21-02 added event latency recalculation -ad \n\nfunction [EEG, com] = pop_select( EEG, varargin)\n\ncom = '';\nif nargin < 1\n    help pop_select;\n    return;\nend\nif isempty(EEG(1).data)\n    disp('Pop_select error: cannot process empty dataset'); return;\nend\n    \nif nargin < 2\n   geometry = { [1 1 1] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] ...\n           [1 1 0.25 0.23 0.51] [1] [1 1 1]};\n   enabletype = ~isempty(EEG(1).chanlocs) && isfield(EEG(1).chanlocs, 'type') && ~isempty(EEG(1).chanlocs(1).type);\n   uilist = { ...\n         { 'Style', 'text', 'string', 'Select data in:', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'Input desired range', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'on->remove these', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'Time range [min max] (s)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', 'on' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', 'on' },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Point range (ex: [1 10])', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', 'on' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', 'on' },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Epoch range (ex: 3:2:10)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', 'on' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', 'on' },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Channel(s)' }, ...\n         { 'Style', 'edit', 'string', '', 'tag', 'chans' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ' }, ...\n         { 'style' 'pushbutton' 'string'  '...', 'enable' fastif(isempty(EEG(1).chanlocs), 'off', 'on') ...\n           'callback' 'pop_chansel(get(gcbf, ''userdata''), ''field'', ''labels'',   ''handle'', findobj(''parent'', gcbf, ''tag'', ''chans''));' }, ...\n           ...\n         { 'Style', 'text', 'string', 'Channel type(s)' }, ...\n         { 'Style', 'edit', 'string', '', 'tag', 'chantype' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ' }, ...\n         { 'style' 'pushbutton' 'string'  '...', 'enable' fastif(enabletype, 'on', 'off') ...\n           'callback'  'pop_chansel(get(gcbf, ''userdata''), ''field'', ''type'',   ''handle'', findobj(''parent'', gcbf, ''tag'', ''chantype''));' }, ...\n         ...\n           { }, { }, { 'Style', 'pushbutton', 'string', 'Scroll dataset', 'enable', fastif(length(EEG)>1, 'off', 'on'), 'callback', ...\n                          'eegplot(EEG.data, ''srate'', EEG.srate, ''winlength'', 5, ''limits'', [EEG.xmin EEG.xmax]*1000, ''position'', [100 300 800 500], ''xgrid'', ''off'', ''eloc_file'', EEG.chanlocs);' } {}};\n%           'callback' 'tmplabels = get(gcbf, ''userdata''); [~, tmpvalchan] = pop_chansel(tmplabels, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''chans''), ''string'',tmpvalchan); clear tmplabels tmpvalchan' }, ...\n   chanlocs = eeg_mergelocs(EEG.chanlocs);\n   results = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', 'pophelp(''pop_select'');', 'title', 'Select data -- pop_select()', 'userdata', chanlocs );\n   if isempty(results), return; end\n   \n   % decode inputs\n   % -------------\n   args = {};\n   if ~isempty( results{1} )\n       if ~results{2}, args = { args{:}, 'time', eval( [ '[' results{1} ']' ] ) };\n       else            args = { args{:}, 'rmtime', eval( [ '[' results{1} ']' ] ) }; end\n   end\n\n   if ~isempty( results{3} )\n       if ~results{4}, args = { args{:}, 'point', eval( [ '[' results{3} ']' ] ) };\n       else            args = { args{:}, 'rmpoint', eval( [ '[' results{3} ']' ] ) }; end\n   end\n\n   if ~isempty( results{5} )\n       if ~results{6}, args = { args{:}, 'trial', eval( [ '[' results{5} ']' ] ) };\n       else            args = { args{:}, 'rmtrial', eval( [ '[' results{5} ']' ] ) }; end\n   end\n\n   if ~isempty( results{7} )\n       [ chaninds, chanlist ] = eeg_decodechan(chanlocs, results{7});\n       if isempty(chanlist)\n           if length(EEG) > 1 && length(unique([EEG.nbchan])) > 1\n               error([ 'Cannot use channel indices when processing multiple datasets' 10 ...\n                   'with some channels already removed' ])\n           end\n           chanlist = chaninds; \n       end\n       if ~results{8}, args = { args{:}, 'channel'  , chanlist };\n       else            args = { args{:}, 'rmchannel', chanlist }; end\n   end\n\n   if ~isempty( results{9} )\n       [ ~, chantypes ] = eeg_decodechan(chanlocs, results{9}, 'type');\n       if ~results{10}, args = { args{:}, 'chantype'  , unique(chantypes) };\n       else             args = { args{:}, 'rmchantype', unique(chantypes) }; end\n   end\n\nelse\n    args = varargin;\nend\n\n% process multiple datasets\n% -------------------------\nif length(EEG) > 1\n    if nargin < 2\n        [ EEG, com ] = eeg_eval( 'pop_select', EEG, 'warning', 'on', 'params', args);\n    else\n        [ EEG, com ] = eeg_eval( 'pop_select', EEG, 'warning', 'off', 'params',args);\n    end\n    return;\nend\n\n%----------------------------AMICA---------------------------------\nif isfield(EEG.etc,'amica') && isfield(EEG.etc.amica,'prob_added')\n    for index = 1:2:length(args)\n       if strcmpi(args{index}, 'channel')\n           args{index+1} = [ args{index+1} EEG.nbchan-(0:2*EEG.etc.amica.num_models-1)];\n       end\n    end\nend\n%--------------------------------------------------------------------\n        \ng = finputcheck(args, { 'time'    'real'      []         []; ...\n                        'notime'  'real'      []         []; ...\n                        'rmtime'  'real'      []         []; ...\n                        'trial'   'integer'   []         [1:EEG.trials]; ...\n                        'notrial' 'integer'   []         []; ...\n                        'rmtrial' 'integer'   []         []; ...\n                        'point'   'integer'   []         []; ...\n                        'nopoint' 'integer'   []         []; ...\n                        'rmpoint' 'integer'   []         []; ...\n                        'channel'   { 'integer','cell' }  []   [];\n                        'nochannel' { 'integer','cell' }   []  [];\n                        'rmchannel' { 'integer','cell' }   []  [];\n                        'chantype'    { 'string','cell' }    []  {};\n                        'rmchantype'  { 'string','cell' }    []  {};\n                        'trialcond'   'integer'   []         []; ...\n                        'notrialcond' 'integer'   []         []; ...\n                        'sort'        'integer'   []         []; ...\n                        'sorttrial'   'string'    { 'on','off' } 'on' }, 'pop_select');\nif ischar(g), error(g); end\nif ~isempty(g.sort)\n    if g.sort, g.sorttrial = 'on';\n    else       g.sorttrial = 'off';\n    end\nend\nif strcmpi(g.sorttrial, 'on')\n    g.trial = sort(setdiff( g.trial, g.notrial ));\n    if isempty(g.trial), error('Error: dataset %s is empty',EEG.filename); end\nelse\n    g.trial(ismember(g.trial,g.notrial)) = [];\n    % still warn about & remove duplicate trials (may be removed in the future)\n    [p,q] = unique_bc(g.trial);\n    if length(p) ~= length(g.trial)\n        disp('Warning: trial selection contained duplicated elements, which were removed.'); \n    end    \n    g.trial = g.trial(sort(q));\nend\n\n% rename parameters\n% -----------------\nif ~isempty(g.rmtime)    g.notime    = g.rmtime; end\nif ~isempty(g.rmpoint)   g.nopoint   = g.rmpoint; end\nif ~isempty(g.rmtrial)   g.notrial   = g.rmtrial; end\nif ~isempty(g.rmchannel) g.nochannel = g.rmchannel; end\n\n% decode channels\n% ---------------\nif ~isempty(g.channel) || ~isempty(g.nochannel)\n    % find channels by name\n    if ~isempty(g.channel)\n        if ~isempty(g.chantype) || ~isempty(g.rmchantype)\n            error('You can select channels by name or by type but not both');\n        end\n        inds = eeg_decodechan(EEG, g.channel, 'labels', true);\n        chanFlag = zeros(1, EEG.nbchan);\n        chanFlag(inds) = 1;\n    else\n        chanFlag = ones(1, EEG.nbchan);\n    end\n    if ~isempty(g.nochannel)\n        if ~isempty(g.chantype) || ~isempty(g.rmchantype)\n            error('You can select channels by name or by type but not both');\n        end\n        inds = eeg_decodechan(EEG, g.nochannel, 'labels', true);\n        chanFlag(inds) = 0;\n    end\nelse\n    % find channels by type\n    if ~isempty(g.chantype)\n        inds = eeg_decodechan(EEG, g.chantype, 'type', true);\n        chanFlag = zeros(1, EEG.nbchan);\n        chanFlag(inds) = 1;\n    else\n        chanFlag = ones(1, EEG.nbchan);\n    end\n    if ~isempty(g.rmchantype)\n        inds = eeg_decodechan(EEG, g.rmchantype, 'type', true);\n        chanFlag(inds) = 0;\n    end\nend\ng.channel = find(chanFlag);\n\n% time selection\n% --------------\nif ~isempty(g.time) && (g.time(1) < EEG.xmin*1000) && (g.time(2) > EEG.xmax*1000)\n   error('Wrong time range');\nend\nif min(g.trial) < 1 || max( g.trial ) > EEG.trials  \n   error('Wrong trial range');\nend\nif size(g.point,2) > 2\n    g.point = [g.point(1) g.point(end)];\n    disp('Warning: vector format for point range is deprecated');\nend\nif size(g.nopoint,2) > 2\n    g.nopoint = [g.nopoint(1) g.nopoint(end)];\n    disp('Warning: vector format for point range is deprecated');\nend\nif ~isempty( g.point )\n    g.time = zeros(size(g.point));\n    for index = 1:length(g.point(:))\n        g.time(index) = eeg_point2lat(g.point(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);\n    end\n    g.notime = [];\nend\nif ~isempty( g.nopoint )\n    g.notime = zeros(size(g.nopoint));\n    for index = 1:length(g.nopoint(:))\n        g.notime(index) = eeg_point2lat(g.nopoint(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);\n    end\n    g.time = [];\nend\nif ~isempty( g.notime )\n    if size(g.notime,2) ~= 2\n        error('Time/point range must contain 2 columns exactly');\n    end\n    if g.notime(2) == EEG.xmax\n        g.time = [EEG.xmin g.notime(1)];\n    else\n        if g.notime(1) == EEG.xmin\n            g.time = [g.notime(2) EEG.xmax];\n        elseif EEG.trials > 1\n            error('Wrong notime range. Remember that it is not possible to remove a slice of time for data epochs.');\n        end\n    end\n    if g.notime(end) > EEG.xmax, g.notime(end) = EEG.xmax; end\n    if g.notime(1)   < EEG.xmin, g.notime(1)   = EEG.xmin; end\n    if floor(max(g.notime(:))) > EEG.xmax \n        error('Time/point range exceed upper data limits');\n    end\n    if min(g.notime(:)) < EEG.xmin\n        error('Time/point range exceed lower data limits');\n    end\nend\nif ~isempty(g.time)\n    if size(g.time,2) ~= 2\n        error('Time/point range must contain 2 columns exactly');\n    end\n    for index = 1:length(g.time)\n        if g.time(index) > EEG.xmax\n            g.time(index) = EEG.xmax;\n            disp('Upper time limits exceed data, corrected');\n        elseif g.time(index) < EEG.xmin\n            g.time(index) = EEG.xmin;\n            disp('Lower time limits exceed data, corrected');\n        end\n    end\nend\n\n% select trial values\n%--------------------\nif ~isempty(g.trialcond)\n   try \n        tt = struct( g.trialcond{:} ); catch\n        error('Trial conditions format error');\n   end\n   ttfields = fieldnames (tt);\n   for index = 1:length(ttfields)\n        if ~isfield( EEG.epoch, ttfields{index} )\n            error([ ttfields{index} 'is not a field of EEG.epoch' ]);\n        end    \n        tmpepoch = EEG.epoch;\n\t    eval( [ 'Itriallow  = find( [ tmpepoch(:).' ttfields{index} ' ] >= tt.' ttfields{index} '(1) );' ] );\n\t    eval( [ 'Itrialhigh = find( [ tmpepoch(:).' ttfields{index} ' ] <= tt.' ttfields{index} '(end) );' ] );\n\t    Itrialtmp = intersect_bc(Itriallow, Itrialhigh);\n\t    g.trial = intersect_bc( g.trial(:)', Itrialtmp(:)');\n   end\nend\n\nif isempty(g.trial)\n   error('Empty dataset, no trial');\nend\nif length(g.trial) ~= EEG.trials\n\tfprintf('Removing %d trial(s)...\\n', EEG.trials - length(g.trial));\nend\nif length(g.channel) ~= EEG.nbchan\n\tfprintf('Removing %d channel(s)...\\n', EEG.nbchan - length(g.channel));\nend\n\ntry\n    % For AMICA probabilities...\n    %-----------------------------------------------------\n    if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')\n        if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)\n            if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models\n\n                EEG = eeg_formatamica(EEG);\n\n                %-------------------------------------------\n\n                [EEG, com] = pop_select(EEG,args{:});\n\n                %-------------------------------------------\n\n                EEG = eeg_reformatamica(EEG);\n                EEG = eeg_checkamica(EEG);\n                return;\n            else\n                disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected')\n\n                disp('Resuming rejection...')\n            end\n        end\n\n    end\n    % ------------------------------------------------------\ncatch\n    warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed.  Continuing and ignoring amica information.');\n    warning(warnmsg)\nend\n\n\n% recompute latency and epoch number for events\n% ---------------------------------------------\nif length(g.trial) ~= EEG.trials && ~isempty(EEG.event)\n    if ~isfield(EEG.event, 'epoch')\n        disp('Pop_epoch warning: bad event format with epoch dataset, removing events');\n        EEG.event = [];\n    else\n        if isfield(EEG.event, 'epoch')\n            keepevent = [];\n            for indexevent = 1:length(EEG.event)\n                newindex = find( EEG.event(indexevent).epoch == g.trial );% For AMICA probabilities...\n                %-----------------------------------------------------\n                try\n                    if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')\n                        if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)\n                            if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models\n                                \n                                EEG = eeg_formatamica(EEG);\n                                \n                                %-------------------------------------------\n                                \n                                [EEG, com] = pop_select(EEG,args{:});\n                                \n                                %-------------------------------------------\n                                \n                                EEG = eeg_reformatamica(EEG);\n                                EEG = eeg_checkamica(EEG);\n                                return;\n                            else\n                                disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected')\n                                \n                                disp('Resuming rejection...')\n                            end\n                        end\n                        \n                    end\n                catch\n                    warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed.  Continuing and ignoring amica information.');\n                    warning(warnmsg)\n                end;                \n                % ------------------------------------------------------\n                \n                if ~isempty(newindex)\n                    keepevent = [keepevent indexevent];\n                    if isfield(EEG.event, 'latency')\n                        EEG.event(indexevent).latency = EEG.event(indexevent).latency - (EEG.event(indexevent).epoch-1)*EEG.pnts + (newindex-1)*EEG.pnts;\n                    end\n                    EEG.event(indexevent).epoch = newindex;\n                end\n            end\n            diffevent = setdiff_bc([1:length(EEG.event)], keepevent);\n            if ~isempty(diffevent)\n                disp(['Pop_select: removing ' int2str(length(diffevent)) ' unreferenced events']);\n                EEG.event(diffevent) = [];\n            end\n        end\n    end\nend\n\n\n% performing removal\n% ------------------\nif ~isempty(g.time) || ~isempty(g.notime)\n    if EEG.trials > 1\n        % select new time window\n        % ----------------------    \n        try,   tmpevent = EEG.event;\n               tmpeventlatency = [ tmpevent.latency ];\n        catch, tmpeventlatency = [];\n        end\n        alllatencies = 1-(EEG.xmin*EEG.srate); % time 0 point\n        alllatencies = linspace( alllatencies, EEG.pnts*(EEG.trials-1)+alllatencies, EEG.trials);\n        [EEG.data, tmptime, indices, epochevent]= epoch(EEG.data, alllatencies, ...\n                                                     [g.time(1) g.time(2)]*EEG.srate, 'allevents', tmpeventlatency);\n        tmptime = tmptime/EEG.srate;\n        if g.time(1) ~= tmptime(1) && g.time(2)-1/EEG.srate ~= tmptime(2)\n            fprintf('pop_select(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\\n', tmptime(1), tmptime(2)+1/EEG.srate);\n        end\n        EEG.xmin = tmptime(1);\n        EEG.xmax = tmptime(2);\n        EEG.pnts = size(EEG.data,2);\n        alllatencies = alllatencies(indices);\n        \n        % modify the event structure accordingly (latencies and add epoch field)\n        % ----------------------------------------------------------------------\n        allevents = [];\n        newevent = [];\n        count = 1;\n        if ~isempty(epochevent)\n            newevent = EEG.event(1);\n            for index=1:EEG.trials\n                for indexevent = epochevent{index}\n                    newevent(count)         = EEG.event(indexevent);\n                    newevent(count).epoch   = index;\n                    newevent(count).latency = newevent(count).latency - alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1);\n                    count = count + 1;\n                end\n            end\n        end\n        EEG.event = newevent;\n        \n        % erase event-related fields from the epochs\n        % ------------------------------------------\n        if ~isempty(EEG.epoch)\n            fn = fieldnames(EEG.epoch);\n            EEG.epoch = rmfield(EEG.epoch,{fn{strmatch('event',fn)}});\n        end\n    else\n        if isempty(g.notime)\n            if length(g.time) == 2 && EEG.xmin < 0\n                disp('Warning: negative minimum time; unchanged to ensure correct latency of initial boundary event');\n            end\n            g.notime = g.time';\n            g.notime = g.notime(:);\n            if g.notime(1) ~= 0, g.notime = [EEG.xmin g.notime(:)'];\n            else                 g.notime = [g.notime(2:end)'];\n            end\n            if g.time(end) == EEG.xmax, g.notime(end) = [];\n            else                        g.notime(end+1) = EEG.xmax;\n            end\n            \n            for index = 1:length(g.notime)\n                if g.notime(index) ~= 0  && g.notime(index) ~= EEG.xmax\n                    if mod(index,2), g.notime(index) = g.notime(index) + 1/EEG.srate;\n                    else             g.notime(index) = g.notime(index) - 1/EEG.srate;\n                    end\n                end\n            end \n            g.notime = reshape(g.notime, 2, length(g.notime)/2)';\n        end\n        \n        nbtimes = length(g.notime(:));\n        [points,flag] = eeg_lat2point(g.notime(:)', ones(1,nbtimes), EEG.srate, [EEG.xmin EEG.xmax]);\n        points = reshape(points, size(g.notime));\n        \n        % fixing if last region is the same\n        if flag\n            if ~isempty(find((points(end,1)-points(end,2))== 0)), points(end,:) = []; end\n        end\n        \n        EEG = eeg_eegrej(EEG, points);\n    end\nend\n\n% performing removal\n% ------------------\nif ~isequal(g.channel,1:size(EEG.data,1)) || ~isequal(g.trial,1:size(EEG.data,3))\n    eeglab_options;\n    if option_memmapdata\n        % this code below is preferred for memory mapped files\n        diff1 = setdiff_bc([1:size(EEG.data,1)], g.channel);\n        diff2 = setdiff_bc([1:size(EEG.data,3)], g.trial);\n        if ~isempty(diff1)\n            EEG.data(diff1, :, :) = [];\n        end\n        if ~isempty(diff2)\n            EEG.data(:, :, diff2) = [];\n        end\n    else\n        EEG.data  = EEG.data(g.channel, :, g.trial);\n    end\nend\nif ~isempty(EEG.icaact), EEG.icaact = EEG.icaact(:,:,g.trial); end\nif ~isempty(EEG.chanlocs)\n    if ~isfield(EEG.chaninfo, 'removedchans')\n        EEG.chaninfo.removedchans = [];\n    end\n    try \n        diff1 = setdiff_bc([1:EEG.nbchan], g.channel);\n        fields = fieldnames(EEG.chanlocs);\n        for iChan = diff1(:)'\n            EEG.chaninfo.removedchans(end+1).(fields{1}) = EEG.chanlocs(iChan).(fields{1});\n            for iField = 1:length(fields)\n                EEG.chaninfo.removedchans(end).(fields{iField}) = EEG.chanlocs(iChan).(fields{iField});\n            end\n        end\n    catch\n        disp('There was an issue storing removed channels in pop_select');\n    end\n    EEG.chanlocs = EEG.chanlocs(g.channel);\nend\nEEG.trials    = length(g.trial);\nEEG.pnts      = size(EEG.data,2);\nEEG.nbchan    = length(g.channel);\nif ~isempty(EEG.epoch)\n   EEG.epoch = EEG.epoch( g.trial );\nend\nif ~isempty(EEG.specdata)\n\tif length(g.point) == EEG.pnts\n   \t\tEEG.specdata = EEG.specdata(g.channel, :, g.trial);\n   \telse\n   \t\tEEG.specdata = [];\n   \t\tfprintf('Warning: spectral data were removed because of the change in the number of points\\n');\n    end\nend\n\n% ica specific\n% ------------\nif ~isempty(EEG.icachansind)\n    \n    rmchans = setdiff_bc( EEG.icachansind, g.channel ); % channels to remove\n    \n    % channel sub-indices\n    % -------------------\n    icachans = 1:length(EEG.icachansind);\n    for index = length(rmchans):-1:1\n        chanind           = find(EEG.icachansind == rmchans(index));\n        icachans(chanind) = [];\n    end\n        \n    % new channels indices\n    % --------------------\n    count   = 1;\n    newinds = [];\n    for index = 1:length(g.channel)\n        if any(EEG.icachansind == g.channel(index))\n            newinds(count) = index;\n            count          = count+1;\n        end\n    end\n    EEG.icachansind = newinds;\n    \nelse\n    icachans = 1:size(EEG.icasphere,2);\nend\n\nif ~isempty(EEG.icawinv)\n    flag_rmchan = (length(icachans) ~= size(EEG.icawinv,1));\n    if  isempty(EEG.icaweights) || flag_rmchan\n        EEG.icawinv    = EEG.icawinv(icachans,:);\n        EEG.icaweights = pinv(EEG.icawinv);\n        EEG.icasphere  = eye(size(EEG.icaweights,2));\n    end\nend\nif ~isempty(EEG.specicaact)\n    if length(g.point) == EEG.pnts\n        EEG.specicaact = EEG.specicaact(icachans, :, g.trial);\n    else\n        EEG.specicaact = [];\n        fprintf('Warning: spectral ICA data were removed because of the change in the number of points\\n');\n    end\nend\n\n% check if only one epoch\n% -----------------------\nif EEG.trials == 1\n    if isfield(EEG.event, 'epoch')\n        EEG.event = rmfield(EEG.event, 'epoch');\n    end\n    EEG.epoch = [];\nend\nif isfield(EEG.reject, 'gcompreject') && isequal(g.channel,1:size(EEG.data,1))\n    tmpgcompreject = EEG.reject.gcompreject;\n    EEG.reject = [];\n    EEG.reject.gcompreject = tmpgcompreject;\nelse\n    EEG.reject = [];\nend\nEEG.stats  = [];\nEEG.reject.rejmanual = [];\n% for stats, can adapt remove the selected trials and electrodes\n% in the future to gain time -----------------------------------  \nEEG.stats.jp = [];\nEEG = eeg_checkset(EEG, 'eventconsistency');\n\n% generate command\n% ----------------\nif nargout > 1\n    com = sprintf('EEG = pop_select( EEG, %s);', vararg2str(args));\nend\n\nreturn;\n\n% ********* OLD, do not remove any event any more\n% ********* in the future maybe do a pack event to remove events not in the time range of any epoch\n\nif ~isempty(EEG.event)\n    % go to array format if necessary\n    if isstruct(EEG.event), format = 'struct';\n    else                     format = 'array';\n    end\n    switch format, case 'struct', EEG = eventsformat(EEG, 'array'); end\n    \n    % keep only events related to the selected trials\n    Indexes = [];\n    Ievent  = [];\n    for index = 1:length( g.trial )\n        currentevents = find( EEG.event(:,2) == g.trial(index));\n        Indexes = [ Indexes ones(1, length(currentevents))*index ];\n        Ievent  = union_bc( Ievent, currentevents );\n    end\n    EEG.event = EEG.event( Ievent,: );\n    EEG.event(:,2) = Indexes(:);\n    \n    switch format, case 'struct', EEG = eventsformat(EEG, 'struct'); end\nend\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/popfunc/pop_select.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.22844636044777086}}
{"text": "%kPlot3D '3D Plot Object Menuform'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Plot3D.pane file\n%\n% Parameters: \n% MultiChoice: plot3DXOrientation 'X Orientation', default: 1: 'x orientation'\n%    Choices are:\n%   1: 'Width'\n%   2: 'Height'\n%   3: 'Depth'\n%   4: 'Time'\n%   5: 'Elements'\n% MultiChoice: plot3DYOrientation 'Y Orientation', default: 2: 'y orientation'\n%    Choices are:\n%   1: 'Width'\n%   2: 'Height'\n%   3: 'Depth'\n%   4: 'Time'\n%   5: 'Elements'\n% Integer: plot3DWidthOffset 'Width Offset', default: 0: 'width offset'\n% Integer: plot3DHeightOffset 'Height Offset', default: 0: 'height offset'\n% Integer: plot3DDepthOffset 'Depth Offset', default: 0: 'depth offset'\n% Integer: plot3DTimeOffset 'Time Offset', default: 0: 'time offset'\n% Integer: plot3DElementsOffset 'Elements Offset', default: 0: 'elements offset'\n%\n% Example: kPlot3D( {'plot3DXOrientation',1;'plot3DYOrientation',2;'plot3DWidthOffset',0;'plot3DHeightOffset',0;'plot3DDepthOffset',0;'plot3DTimeOffset',0;'plot3DElementsOffset',0})\n%\n% Khoros helpfile follows below:\n% \n% The 3D plot object supports the display of a 3D plot.\n% .begin tagged\n% .item \"Plot Type\"\n% This list selection lets you set the plot type that is used by the\n% 3D plot object.  Choices include: \"Line Plot,\" \"Wireframe,\" \"Mesh,\" \n% \"Horizon,\" \"Scatter,\" \"Impulse,\" \"Contour 3D,\" \"Contour 2D,\"  or \n% \"Constant Shade.\n% .item \"Line Type\"\n% There are seven line types available: \"Solid,\" \"Dotted,\" \"Dot Dash,\" \n% \"Short Dash,\" \"Long Dash,\" \"Odd Dash,\" and \"Grid Dotted.\"  The line type\n% is not used with scatter plots or shaded plots.\n% .item \"Marker Type\"\n% This attribute only applies to plots that use a marker, ie, scatter plots.\n% There is a wide variety of marker types that may be used with scatter plots.\n% .item \"Surface Shade Type\"\n% This attribute only applies to the constant shade plot type.\n% It specifies what part of the data is to dictate the shading.  \n% \"Imagery\" specifies that shading is to be done on imagery (or color)\n% ie, using the \"d\" value of each data point as defined by its C\n% oord structure.  \"Elevation\" specifies that shading is to be done on \n% elevation, ie, using the \"z\" value of each data point as defined\n% by its Coord structure.  When \"Normals\" is used, the normal to each \n% data point is computed, and shading is done using the normals.\n% .item \"Color Origination\"\n% When this attribute is set to \"Use Foreground Color,\" the plot is colored in \n% the foreground color.   When set to \"Use Data Values,\" the plot is colored\n% according to the plot data (see manual for more details).  \n% .item \"Foreground Color\"\n% This stringlist selection lets you set the foreground color of the 3D\n% plot, using the color name.  It is only used when \"Color Origination\"\n% is set to \"Use Foreground Color.\"\n% .item \"Fill Color\"\n% This stringlist selection lets you set the color that is used with \n% filled plots.  The only filled plots are the mesh and the horizon plots.\n% .item \"X and Y Orientation\"\n% These toggles only take effect when the plot data input is provided via a\n% data object (as opposed to an array of Coords).  Furthermore, they only apply\n% when the plot data is stored in the value segment of the data object (as\n% opposed to the location segment of the data object).  They dictate how the\n% 3D plot data is to be extracted from the value segment of the data object.\n% The 3D plot data is always extracted as a surface, but that surface may be \n% defined over any two of the dimensions supported by the value segment. For\n% example, the default surface orientation is (width x height), but you might\n% specify it to be (height x depth),  (width x time), or any other combination\n% of the 5 supported dimensions.\n% .item \"Width, Height, Depth, Time, And Elements Offsets\"\n% These integer selections may be set in conjunction with the \"X and Y \n% Orientation\" toggles.  When neither the X or Y orientation\" set to \"Width,\" \n% the \"Width Offset\" may be used to specify the width offset at which the \n% surface of plot data is to be extracted.  Similarly, \"Height Offset,\" \n% \"Depth Offset,\" \"Time Offset\" and \"Elements Offset\" may be used to specify \n% offsets into height, depth, time, and elements whenever that dimension is\n% \"not\" being plotted.  Note that an offset may only be used when that \n% dimension of the value data is greater than 1.\n% .item \"Rotation About X\"\n% This parameter allows you to rotate the camera (the eye) about the X axis.\n% Values are given in degrees, from 0 to 360.  \n% .item \"Rotation About Y\"\n% This parameter allows you to rotate the camera (the eye) about the Y axis.\n% Values are given in degrees, from 0 to 360.  \n% .item \"Rotation About Z\"\n% This parameter allows you to rotate the camera (the eye) about the Z axis.\n% Values are given in degrees, from 0 to 360.  \n% .item \"Eye Distance\"\n% This parameter specifies the distance between the plot and the eye.\n% The default value of 0 is right up against the bounding box of the\n% plot.\n% .end tagged\n\n\nfunction varargout = kPlot3D(varargin)\nInputs={};\nif nargin ==0\n  arglist={'',''};\nelseif nargin ==1\n  arglist=varargin{1};\nelse error('Usage: [out1,..] = kPlot3D(arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'plot3DXOrientation', 1;'plot3DYOrientation', 2;'plot3DWidthOffset', 0;'plot3DHeightOffset', 0;'plot3DDepthOffset', 0;'plot3DTimeOffset', 0;'plot3DElementsOffset', 0};\nmaxval={0,0,1,1,1,1,1};\nminval={0,0,1,1,1,1,1};\nistoggle=[0,0,0,0,0,0,0];\nwas_set=istoggle * 0;\nparamtype={'MultiChoice','MultiChoice','Integer','Integer','Integer','Integer','Integer'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=0; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(0);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\ncallKhoros([w 'Plot3D\" '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kPlot3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22844636044777084}}
{"text": "% ----------------------------------------------------------------------------\n% function hfssCylinder(fid, Name, Axis, Center, Radius, Height, Units)\n% \n% Description :\n% -------------\n% Creates the VB script necessary to model a cylinder in HFSS.\n%\n% Parameters :\n% ------------\n% fid     - file identifier of the HFSS script file.\n% Name    - name of the cylinder (in HFSS).\n% Center  - center of the cylinder (specify as [x, y, z]). This is also the \n%           starting point of the cylinder.\n% Axis    - axis of the cylinder (specify as 'X', 'Y', or 'Z').\n% Radius  - radius of the cylinder (scalar).\n% Height  - height of the cylidner (from the point specified by Center).\n% Units   - specify as 'in', 'mm', 'meter' or anything else defined in HFSS.\n% \n% Note :\n% ------\n%\n% Example :\n% ---------\n% fid = fopen('myantenna.vbs', 'wt');\n% ... \n% hfssCylinder(fid, 'Cyl1', 'Z', [0, 0, 0], 0.1, 10, 'in');\n% ----------------------------------------------------------------------------\n\n% ----------------------------------------------------------------------------\n% This file is part of HFSS-MATLAB-API.\n%\n% HFSS-MATLAB-API is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the Free \n% Software Foundation; either version 2 of the License, or (at your option) \n% any later version.\n%\n% HFSS-MATLAB-API is distributed in the hope that it will be useful, but \n% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \n% or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License \n% for more details.\n%\n% You should have received a copy of the GNU General Public License along with\n% Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple \n% Place, Suite 330, Boston, MA  02111-1307  USA\n%\n% Copyright 2004, Vijay Ramasami (rvc@ku.edu)\n% ----------------------------------------------------------------------------\nfunction hfssCylinder(fid, Name, Axis, Center, Radius, Height, Units)\n\n% Cylinder Parameters.\nfprintf(fid, '\\n');\nfprintf(fid, 'oEditor.CreateCylinder _\\n');\nfprintf(fid, 'Array(\"NAME:CylinderParameters\", _\\n');\nfprintf(fid, '\"XCenter:=\", \"%f%s\", _\\n', Center(1), Units);\nfprintf(fid, '\"YCenter:=\", \"%f%s\", _\\n', Center(2), Units);\nfprintf(fid, '\"ZCenter:=\", \"%f%s\", _\\n', Center(3), Units);\nfprintf(fid, '\"Radius:=\", \"%f%s\", _\\n', Radius, Units);\nfprintf(fid, '\"Height:=\", \"%f%s\", _\\n', Height, Units);\nfprintf(fid, '\"WhichAxis:=\", \"%s\"), _\\n', upper(Axis));\n\n% Cylinder Properties.\nfprintf(fid, 'Array(\"NAME:Attributes\", _\\n'); \nfprintf(fid, '\"Name:=\", \"%s\", _\\n', Name);\nfprintf(fid, '\"Flags:=\", \"\", _\\n');\nfprintf(fid, '\"Color:=\", \"(132 132 193)\", _\\n');\nfprintf(fid, '\"Transparency:=\", 0, _\\n');\nfprintf(fid, '\"PartCoordinateSystem:=\", \"Global\", _\\n');\nfprintf(fid, '\"MaterialName:=\", \"vacuum\", _\\n');\nfprintf(fid, '\"SolveInside:=\", true)\\n');\nfprintf(fid, '\\n');", "meta": {"author": "yuip", "repo": "hfss-api", "sha": "93ac0700830f473f1438f335a7fa964383b07abb", "save_path": "github-repos/MATLAB/yuip-hfss-api", "path": "github-repos/MATLAB/yuip-hfss-api/hfss-api-93ac0700830f473f1438f335a7fa964383b07abb/3dmodeler/hfssCylinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22842631940499605}}
{"text": "function test_bug1607\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_channelrepair ft_topoplotER\n\n% During preprocessing I lost some channels which I got back through\n% ft_channelrepair after which the channel order changed per subject.\n% I realigned the channel order and the associated data structure of each subject\n% to one reference order after which the topoplots look completely different.\n% They look even worse than before realignment. Anybody got a clue where the\n% confusion arises?\n% Attached a script and two data files, one with reference data and one with the\n% to be aligned data.\n\n% solution\n% was not a bug, instead jonas was indexing the wrong way around:\n%\n%     nERPdata_nD_left{isubject}.avg(:,:) = ERPdata_nD_left{isubject}.avg(loc,:);     % realign data to ref channel order\n% instead of\n%     nERPdata_nD_left{isubject}.avg(loc,:) = ERPdata_nD_left{isubject}.avg(:,:);     % realign data to ref channel order\n\nERPdata_nD_left = [];\nreference_labels = [];\n\n%load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug1607/06_control_ICA_clean.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug1607/ERPdata.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug1607/reference.mat'));\n\n% reference_labels = ICA_clean.label;\n\nnERPdata_nD_left = ERPdata_nD_left;\n% nERPdata_D_left = ERPdata_D_left;\n% nERPdata_nD_right = ERPdata_nD_right;\n% nERPdata_D_right = ERPdata_D_right;\n\nfor isubject = 1:1%length(ERPdata_nD_left)\n%     disp(num2str(isubject))\n    [a loc] = ismember(ERPdata_nD_left{isubject}.label, reference_labels);  % compare the channel labeling of each subject with a reference\n%     for isens = 1 : 64\n%         if loc(isens) ~= isens\n%             disp(['changing subj ' num2str(isubject) ' sensnr ' num2str(isens)]);\n%             break;\n%         end\n%     end\n%     disp(num2str(any(find((ERPdata_nD_left{isubject}.avg == ERPdata_nD_left{isubject}.avg(loc,:))==0))));    \n    nERPdata_nD_left{isubject}.label = reference_labels;    % relabel the channels according to the reference\n%     nERPdata_nD_left{isubject}.avg(:,:) = ERPdata_nD_left{isubject}.avg(loc,:);     % realign data to ref channel order\n    nERPdata_nD_left{isubject}.avg(loc,:) = ERPdata_nD_left{isubject}.avg(:,:);     % realign data to ref channel order\n    nERPdata_nD_left{isubject}.dof(:,:) = ERPdata_nD_left{isubject}.dof(loc,:);     % realign data to ref channel order\n\nend\n% after realigning the data the plots look completely different, compare\n% old and new data\n\ncfg = [];\ncfg.layout      = 'biosemi64.lay';\ncfg.xlim        = [.04 .06];\ncfg.channel     = 'all';\ncfg.interactive = 'no';\ncfg.highlight   = 'yes';\ncfg.highlightchannel = reference_labels(end-6:end);\n\nfigure; ft_topoplotER(cfg,ERPdata_nD_left{1});      % plot original data \nfigure; ft_topoplotER(cfg,nERPdata_nD_left{1});     % plot corrected data\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1607.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22842631940499605}}
{"text": "fplot('Afun1',[-3,3])", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/17\u9644\u5f55A/exA_1_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.22840144208036736}}
{"text": "any(cellfun(@exist,{'mdwt', 'midwt', 'mirdwt', 'mrdwt'})==3)", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/rwt-3.0/mex/build-computing-0-10.local/env_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2284014420803673}}
{"text": "% [HEIGHT] = lpyrHt(INDICES)\n%\n% Compute height of Laplacian pyramid with given its INDICES matrix.\n% See buildLpyr.m\n\n% Eero Simoncelli, 6/96.\n\nfunction [ht] =  lpyrHt(pind)\n\n% Don't count lowpass residual band\nht = size(pind,1)-1;\n", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/quant_eval/ifcvec_release/matlabPyrTools/lpyrHt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2284014420803673}}
{"text": "function [tt]=tt_elem_reverse(tt)\n% Elementwise reverse of a tensor train vector\n% NOT tested on a multidimensional case\n%\n% use tt_qutrtoepl(core(tt_shf(d)'*tt_elem_reverse(tt))) - to build\n% upper-toeplitz matrix in \"normal\", blin, indexing, i.e. second element\n% goes to S^{+1}, usw.\n\nd = tt.d;\ntt = core2cell(tt);\n\nfor i=1:d\n    n = size(tt{i}, 2);\n    tt{i} = tt{i}(:,(n:-1:1),:);\nend;\n\ntt = cell2core(tt_tensor, tt);\n\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_elem_reverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2282069115008927}}
{"text": "% SPM5 UPDATE 14/11/06\n% UPDATE 27/01/05\n% Sets the default values for the FieldMap toolbox\n%\n% FORMAT pm_defaults_Sonata\n%_______________________________________________________________________\n%\n% This file is intended for use with the Siemens fieldmap sequence\n% on the Sonata scanner at the FIL with the being phased out sequence\n% ralf_epi_tbr and nw_mepi_silent_v1a.\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Chloe Hutton and Jesper Andersson\n% $Id: pm_defaults_Sonata.m 5015 2012-10-24 13:40:07Z guillaume $\n\nglobal pm_def\n\n% Defaults for creating field map. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.INPUT_DATA_FORMAT = 'PM';      % 'RI' = load two real and \n                                      % imaginary image pairs\n                                      % 'PM' = load one or two\n                                      % phase and magnitude image\n                                      % pairs.\npm_def.SHORT_ECHO_TIME = 10.0;        % Short echo time in ms for Sonata\npm_def.LONG_ECHO_TIME = 14.76;        % Long echo time in ms for Sonata\npm_def.MASKBRAIN = 1;                 % Do brain masking (1 or 0,\n                      % 0 for EPI fieldmaps)\n\n% Defaults for unwrapping options. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.UNWRAPPING_METHOD = 'Mark3D';  % Unwrapping options are:\n                                      % 'Huttonish', 'Mark3D' or 'Mark2D'\npm_def.FWHM = 10;                     % FWHM of Gaussian filter used to \n                                      % implement weighted smoothing of\n                                      % unwrapped maps.\npm_def.PAD = 0;                       % Size of padding kernel if required.\npm_def.WS = 1;                        % Weighted or normal smoothing.\n\n% Flags for brain extraction\n%=======================================================================\npm_def.MFLAGS.TEMPLATE = fullfile(spm('Dir'),'toolbox','FieldMap','T1.nii');\npm_def.MFLAGS.FWHM = 5; % In mm\npm_def.MFLAGS.NERODE = 2;% In voxels\npm_def.MFLAGS.NDILATE = 4; % In voxels\npm_def.MFLAGS.THRESH = 0.5;\npm_def.MFLAGS.REG = 0.02; % A larger value helps segmentation to converge\npm_def.MFLAGS.GRAPHICS = 0; % A larger value helps segmentation to converge\n\n% Defaults for converting field map to voxel displacement map.\n%=======================================================================\npm_def.EPI_BASED_FIELDMAPS = 0;         % EPI=1, other=0.\npm_def.K_SPACE_TRAVERSAL_BLIP_DIR = -1; % +ve k-space = 1, -ve = -1.\npm_def.TOTAL_EPI_READOUT_TIME = 32;     % Sonata EPI RO time (500E-6*64)\n\n% Defaults for Unwarping.\n%=======================================================================\npm_def.DO_JACOBIAN_MODULATION = 0;    % Do jacobian modulation to adjust \n                                      % for compression or stretching\n                                      % No = 0, Yes = 1\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/FieldMap/FIL/pm_defaults_Sonata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.2281871986164689}}
{"text": "function [N info energy V] = ibr_fuse_depths(D1, D2, vals)\n%IBR_FUSE_DEPTHS  Fuse two disparity images using QPBO\n%\n%   [N info energy V] = ibr_fuse_depths(D0, D1, vals)\n%\n% Given two disparity maps and input data (image sequence, projection\n% matrices and configuration parameters) this function will fuse the two\n% maps into a single, lower energy disparity map, using QPBO.\n%\n%IN:\n%   D0 - MxN disparity map to splice, assumed to be current best solution.\n%   D1 - MxN disparity map to splice, assumed to be new proposal.\n%   vals - structure containing the following input data and parameters:\n%      R - MxNxC reference image.\n%      I - Lx1 cell array of input images.\n%      P - 4x3xL array of transposed projection matrices from reference to\n%          input images.\n%      SEI - (O+1)xV matrix of indices for smoothness cliques (columns),\n%            where O is the order of the smoothness prior (1 or 2).\n%      ephoto - handle to function which, when given TxC colour\n%               differences, returns Tx1 values for Ephoto.\n%      esmooth - handle to function which, when given Sx1 disparity\n%                derivatives, returns Sx1 values for Esmooth.\n%      d_min - scalar giving the minimum disparity in the scene.\n%      d_step - scalar giving the range of disparities in the scene.\n%      visibility - boolean indicating whether visibility constraints are\n%                   to be used.\n%      occl_val - scalar value for occluded pixels in the graph.\n%      improve - method to use on unlabelled pixels: 0, fix to D0; 1, use\n%                QPBOI; 2, use optimal splice on independent regions; 3,\n%                fix to whichever of D0, D1 gives the lowest energy; 4,\n%                transform labelling of method 2 using QPBOI.\n%      contract - iterations of QPBOP to do.\n%      independent - boolean indicating whether to use independent, or\n%                    merely strongly-connected, regions for improve methods\n%                    2 & 4.\n%      show_output - figure handle to display output to, otherwise 0.\n%\n%OUT:\n%   N - MxN logical array indicating fusing of D0 and D1.\n%   info - structure containing the following useful info on the\n%          optimization:\n%      timings - 4x1 vector of cumulative times for [data_term_eval;\n%                smoothness_term_eval; qpbo_fuse_time; finish_time]; \n%      numbers - 3x1 vector of values for [disps_set2D1; num_unlabelled_by_\n%                qpbo; independent_unlabelled_regions];\n%   energy - scalar value for the energy of the output disparity.\n%   V - (M*N)xL logical array of visibilities of the input pixels, given\n%       output disparity.\n\n% $Id: ibr_fuse_depths.m,v 1.3 2008/11/17 11:27:35 ojw Exp $\nt_start = cputime;\n\n% Initialize values\nKinf = int32(0);\nscale_factor = 1e5 / vals.ephoto(1e6);\noccl_cost = cast(scale_factor * vals.occl_val, class(Kinf));\nKinf = occl_cost + 1; % Smaller value seems to avoid errors in QPBO\ninfo.timings = zeros(3, 1, numel(vals.improve));\ninfo.numbers = zeros(4, 1, numel(vals.improve), 'uint32');\nenergy = zeros(1, numel(vals.improve));\nnum_in = numel(vals.I);\nsp = size(D1);\ntp = numel(D1);\nplanar = size(vals.SEI, 1) == 3;\noobv = cast(-1000, class(vals.R));\nout_unlabel = vals.improve(end) < 0;\n\n% Calculate the homogenous coordinates of our two labellings\nX = repmat(1:sp(2), [sp(1) 1]);\nY = repmat((1:sp(1))', [1 sp(2)]); % Faster than meshgrid\nWC = [repmat([X(:) Y(:)], [2 1]) ones(2*tp, 1) [D1(:); D2(:)]];\nclear X Y\n\n% Initialise arrays for the data terms\nif vals.visibility\n    EI = reshape(repmat(uint32(tp+(0:num_in-1)*2*tp), [2*tp 1]), 1, []);\n    EI = [repmat(uint32(1:tp), [1 2*num_in]); EI+repmat(uint32(1:2*tp), [1 num_in])];\n    E = repmat(cat(3, [occl_cost 0 0 0], [0 0 occl_cost 0]), [tp 1 1 num_in]);\nelse\n    % Data edges are not needed\n    EI = zeros(2, 0, 'uint32');\n    E = zeros(4, 0, class(Kinf));\nend\nU = zeros(tp, 2, class(Kinf));\nTEI = zeros(2, 0, 'uint32');\nTE = zeros(4, 0, class(Kinf));\n\n% For each input image...\nfor a = 1:num_in\n    % Calculate the coordinates in the input image\n    T = WC * vals.P(:,:,a);\n    N = 1 ./ T(:,3);\n    T(:,1) = T(:,1) .* N;\n    T(:,2) = T(:,2) .* N;\n\n    % Calculate photoconsistency\n    M = vgg_interp2(vals.I{a}, T(:,1), T(:,2), 'linear', oobv);\n    M = squeeze(M) - vals.R;\n    IA = reshape(cast(scale_factor * vals.ephoto(M), class(Kinf)), tp, 2);\n    clear M N\n\n    % Find interactions\n    T(:,3) = T(:,3) ./ WC(:,4);\n    [T M] = sortrows(T);\n    N = find_interactions(T, 0.5); % Optimized version\n    N = M(N); % Unsort\n    N = uint32(N(:,abs(diff(N))~=tp)); % Remove interactions between the same node\n\n    % Add the pixel interactions to the graph\n    M = N(1,:) > tp;\n    TEI = [TEI [N(1,:)-uint32(tp*M); (tp*2*a-tp)+N(2,:)]];\n    T = zeros(4, numel(M));\n    T(2,~M) = Kinf;\n    T(4,M) = Kinf;\n    TE = [TE T];\n\n    if vals.visibility\n        % Set up photoconsistency edges\n        E(:,2,1,a) = IA(:,1);\n        E(:,4,2,a) = IA(:,2);\n        \n        if vals.compress_graph\n            % Determine the photoconsistency nodes which have no interactions\n            M = ones(tp, 2, class(Kinf));\n            M(N(2,:)) = 0;\n\n            % Add those photoconsistency terms to the unaries\n            U = U + M .* IA;\n        end\n    else\n        % Add the photoconsistency terms to the unaries\n        U = U + IA;\n    end\n    clear T M N\nend\nclear WC IA\n\nEI_ = EI;\nif vals.visibility\n    E = reshape(permute(E, [2 1 3 4]), 4, []);\n    if vals.compress_graph\n        % The unary and pairwise energies as they stand are entirely\n        % correct, i.e. will give the correct labelling. However, it can be\n        % compressed into a smaller but equivalent graph, which will be\n        % faster to solve, by removing superfluous nodes and edges.\n        [U EI EI_ E N T] = compress_graph(U', EI, E, TEI, TE, tp, num_in);\n    else\n        U = zeros(2, tp+tp*2*num_in, class(Kinf));\n        T = TE;\n        N = TEI;\n    end\n    % Concatenate data and visibility edges\n    E = [E T];\n    EI_ = [EI_ N];\n    clear T N\nelse\n    U = U';\nend\nTE = TE(2,:) ~= 0;\ninfo.timings(1,:) = cputime - t_start; % Time data term evaluation\n\n% Add surface smoothness constraints\nSE = (double([D1(:)'; D2(:)']) - vals.d_min) / vals.d_step;\nSE = SE(:,vals.SEI);\nif planar\n    % Planar prior - Finite differences 2nd derivative of disparity\n    SE = reshape(SE, 6, []);\n    SE = reshape(SE([1 3 5; 1 3 6; 1 4 5; 1 4 6; 2 3 5; 2 3 6; 2 4 5; 2 4 6]',:), 3, 8, []);\n    SE = diff(SE, 2);\nelse\n    % Fronto-parallel prior - Finite differences 1st derivative of\n    % disparity\n    SE = reshape(SE, 4, []);\n    SE = diff(reshape(SE([1 3; 1 4; 2 3; 2 4]',:), 2, 4, []));\nend\n% Apply our smoothness weighting\nSE = reshape(cast(scale_factor * vals.esmooth(SE(:)), class(E)), [], size(vals.SEI, 2));\nif ~planar\n    E = [E SE];\n    EI_ = [EI_ vals.SEI];\nend\ninfo.timings(2,:) = cputime - t_start; % Time smoothness term evaluation\n\nfor a = 1:numel(vals.improve)\n    t_start = cputime;\n    % Fuse the two labellings, using contract and/or improve if desired\n    qpbo_params = int32([tp ((vals.improve(a)==1)+(vals.improve(a)==4)*2) vals.contract(a) vals.contract(a)>0]);\n    if vals.improve(a) == 4\n        % Add callback function handle\n        qpbo_params = {qpbo_params, @(L) (choose_labels(L, U, E, EI, SE, vals.SEI, TE, TEI, num_in, vals.visibility, 2, vals.independent) > 0)};\n    end\n    try\n        if planar\n            [M stats] = vgg_qpbo(U, EI_, E, vals.SEI, SE, qpbo_params);\n        else\n            [M stats] = vgg_qpbo(U, EI_, E, qpbo_params);\n        end\n    catch\n        % Error probably due to probe failure\n        stats = [0 0 Inf];\n        M = false(tp, 1);\n    end\n    clear qpbo_params\n    info.numbers(2:4,a) = stats;\n\n    if stats(1) && vals.improve(a) >= 2 && vals.improve(a) <= 3\n        if nargout > 2 || vals.show_output\n            [M info.numbers(3,a) U_ E_ SE_ V] = choose_labels(M, U, E(:,1:size(EI, 2)), EI, SE, vals.SEI, TE, TEI, num_in, vals.visibility, vals.improve(a), vals.independent);\n            energy(a) = sum(U_) + sum(E_) + sum(SE_);\n        else\n            [M info.numbers(3,a)] = choose_labels(M, U, E(:,1:size(EI, 2)), EI, SE, vals.SEI, TE, TEI, num_in, vals.visibility, vals.improve(a), vals.independent);\n        end\n        N = M > 0;\n    elseif nargout > 2 || vals.show_output\n        N = M > 0;\n        [U_ E_ SE_ V] = calc_vis_energy(N, U, E(:,1:size(EI, 2)), EI, SE, vals.SEI, TE, TEI, num_in);\n        energy(a) = sum(U_) + sum(E_) + sum(SE_);\n    end\n    info.numbers(1,a) = sum(N);\n    info.timings(3,a) = cputime - t_start + info.timings(2,a); % Time optimization\nend\nclear TEI TE U E SE EI_\n\nif nargout > 3 || vals.show_output\n    % Generate output visibilities\n    T = (tp * N) + (1:tp)';\n    for b = 1:num_in\n        V(1:tp,b) = V(T);\n        T = T + 2*tp;\n    end\n    V(tp+1:end,:) = [];\nend\n\nif vals.show_output\n    % Display the output figures\n    U_ = double(U_) + accum(EI(1,:)', E_, [tp 1]);\n    U_ = reshape(U_, sp(1), sp(2));\n    if vals.visibility\n        % Take off the occlusion costs and normalize\n        EI = reshape(sum(V(1:tp,:), 2), sp(1), sp(2));\n        U_ = U_ - (num_in - EI) * double(occl_cost);\n        E_ = EI ~= 0;\n        U_(E_) = U_(E_) ./ EI(E_);\n    end\n    set(0, 'CurrentFigure', vals.show_output);\n    subplot('Position', [1/3 0.5 1/3 0.5]);\n    D1(N) = D2(N);\n    sc(D1, 'contrast', vals.d_min+[0 vals.d_step]);\n    subplot('Position', [2/3 0.5 1/3 0.5]);\n    sc(U_, 'jet');\n    subplot('Position', [0 0 1/3 0.5]);\n    T = reshape(sc(reshape(M, sp(1), sp(2)), 'prism'), [], 3);\n    I = M < 0;\n    T(I,:) = 1 - (1 - T(I,:)) * 0.3; % Lighten unlabelled pixels set to 0\n    I = M > 1;\n    T(I,:) = T(I,:) .* 0.3; % Darken unlabelled pixels set to 1 by optimal splice\n    T(M==0,:) = 1;\n    T(M==1,:) = 0;\n    sc(reshape(T, sp(1), sp(2), 3), [0 1]);\n    subplot('Position', [1/3 0 1/3 0.5]);\n    sc(reshape(sum(V, 2), sp(1), sp(2)), [0 num_in], 'contrast');\n    subplot('Position', [2/3 0 1/3 0.5]);\n    U_ = -accum(vals.SEI(2,:)', SE_, [tp 1]);\n    sc(reshape(U_, sp(1), sp(2)));\n    drawnow;\nend\nif out_unlabel\n    N = M; % Output unlabelled pixels\nend\nreturn\n\nfunction [M num_regions U_ E_ SE_ V] = choose_labels(M, U, E, EI, SE, SEI, TE, TEI, num_in, visibility, improve, independent)\n% Calculate visibilities and regions assuming unlabelled pixels are set\n% to 0 then 1.\n[U_ E_ SE_ V] = calc_vis_energy(M==1, U, E, EI, SE, SEI, TE, TEI, num_in);\n[U2 E2 SE2 V2] = calc_vis_energy(M~=0, U, E, EI, SE, SEI, TE, TEI, num_in);\nnum_regions = double(-min(M(:)));\n\nif improve == 2\n    % We want to do optimal splice.\n    sz = [num_regions 1];\n    % Merge strongly connected regions that are connected by smoothness\n    % cliques\n    SEI2 = M(SEI);\n    SEI2 = SEI2(:,any(SEI2 < 0));\n    SEI2 = SEI2(:,~all(SEI2 >= 0 | ojw_bsxfun(@eq, SEI2, min(SEI2))));\n    while independent && ~isempty(SEI2)\n        num_regions = num_regions - 1;\n        T = SEI2(:,1);\n        N = min(T);\n        T = T(T < 0 & T ~= N);\n        M(M==T(1)) = N;\n        SEI2(SEI2==T(1)) = N;\n        SEI2 = SEI2(:,~all(SEI2 >= 0 | ojw_bsxfun(@eq, SEI2, min(SEI2))));\n    end\n    if visibility\n        % Merge strongly connected regions that are connected by visibility\n        % cliques\n        TEI2 = TEI(:,M(TEI(1,:))<0);\n        tp = numel(M);\n        M = repmat(M, [1+2*num_in 1]);\n        M(TEI2(2,:)) = M(TEI2(1,:));\n        SEI2 = M(TEI);\n        SEI2 = SEI2(:,any(SEI2 < 0));\n        SEI2 = SEI2(:,~all(SEI2 >= 0 | ojw_bsxfun(@eq, SEI2, min(SEI2))));\n        while independent && ~isempty(SEI2)\n            num_regions = num_regions - 1;\n            T = SEI2(:,1);\n            N = min(T);\n            T = T(T < 0 & T ~= N);\n            M(M==T(1)) = N;\n            SEI2(SEI2==T(1)) = N;\n            SEI2 = SEI2(:,~all(SEI2 >= 0 | ojw_bsxfun(@eq, SEI2, min(SEI2))));\n        end\n        % Go through each region and determine whether a labelling of 1 or 0\n        % gives a lower energy, starting with the visibility edges\n        EI2 = min(M(EI))';\n        T = EI2 < 0;\n        E2 = E2(T) - E_(T);\n        engy = accum(-EI2(T), E2, sz);\n        M = M(1:tp);\n    else\n        engy = zeros(sz);\n    end\n    % Go through each region and determine whether a labelling of 1 or 0\n    % gives a lower energy\n    SEI2 = M(SEI);\n    T = any(SEI2 < 0);\n    SEI2 = SEI2(:,T);\n    SE2 = SE2(T) - SE_(T);\n    T = -min(SEI2);\n    engy = engy + accum(T(:), SE2, sz);\n    T = M < 0;\n    U2 = U2(T) - U_(T);\n    engy = engy + accum(-M(T), U2, sz);\n    update = false;\n    for b = 1:sz(1)\n        if engy(b) < 0\n            M(M==-b) = b + 1;\n            update = true;\n        end\n    end\n    if update && nargout > 2\n        % Recalculate the visibilities and energies\n        [U_ E_ SE_ V] = calc_vis_energy(M > 0, U, E, EI, SE, SEI, TE, TEI, num_in);\n    end\nelse\n    % Just choose the label which gives the lowest energy\n    if (sum(U_) + sum(E_) + sum(SE_)) >= (sum(U2) + sum(E2) + sum(SE2))\n        % Update the labelling\n        T = M < 0;\n        M(T) = 1 - M(T);\n        % Update the energy and visibility\n        U_ = U2;\n        E_ = E2;\n        SE_ = SE2;\n        V = V2;\n    end\nend\nreturn\n\nfunction [U E SE V] = calc_vis_energy(L, U, E, EI, SE, SEI, TE, TEI, num_in)\n% Generate visibility maps\ntp = numel(L);\nV = true(2*tp, num_in);\nV(TEI(2,L(TEI(1,:))~=TE')-tp) = false;\n\n% Calculate energies\nU = U((0:tp-1)'*2+L+1);\nL = [L; V(:)];\nE = E((0:size(EI, 2)-1)'*4+L(EI(1,:))*2+L(EI(2,:))+1);\nif size(SEI, 1) == 3\n    SE = SE((0:size(SEI, 2)-1)'*8+L(SEI(1,:))*4+L(SEI(2,:))*2+L(SEI(3,:))+1);\nelse\n    SE = SE((0:size(SEI, 2)-1)'*4+L(SEI(1,:))*2+L(SEI(2,:))+1);\nend\nreturn\n\nfunction [U EI EI_ E TEI TE] = compress_graph(U, EI, E, TEI, TE, tp, num_in)\n% Count the number of interactions per input sample\nSE = accum(TEI(2,:)', (1:size(TEI, 2))', [tp+tp*2*num_in 1], @num_first);\nSE = SE(tp+1:end);\n\n% Remove single interactions, attaching the photoconsitency edge\n% directly to the interacting pixel\nM = find(SE > 0);\nL = SE(M);\nEI(2,M) = TEI(1,L);\nM = M(TE(4,L)~=0);\nE(:,M) = E([2 1 4 3],M);\nTEI(:,L) = [];\nTE(:,L) = [];\n\n% Remove the superfluous edges - photoconsistency edges with no\n% interactions, that have already been incorporated into the unary term\nM = SE ~= 0;\nE = E(:,M);\nEI = EI(:,M);\n\n% Compress the node indices\nM = zeros(tp+2*tp*num_in, 1, 'uint32');\nSE = SE < 0;\nL = sum(SE);\nM([true(tp, 1); SE]) = uint32(1):uint32(L+tp);\nEI_ = EI;\nEI_(2,:) = M(EI(2,:));\nTEI(2,:) = M(TEI(2,:));\nU = [U zeros(2, L, class(U))];\nreturn\n\nfunction B = accum(I, A, sz, varargin)\n% Older versions of Matlab can't accumulate integer arrays!\ntry\n    B = accumarray(I, A, sz, varargin{:});\ncatch\n    if isempty(I)\n        B = zeros(sz);\n    else\n        B = accumarray(double(I), double(A), sz, varargin{:});\n    end\nend\nreturn\n\nfunction B = num_first(A)\n% Return:        A  if numel(A) == 1\n%         -numel(A) otherwise\nB = -numel(A);\nif B == -1\n    B = A;\nend\nreturn\n", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/external/imrender/ojw/ibr_fuse_depths.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.2281556827503234}}
{"text": "function SO3F = sqrt(SO3F, varargin)\n% square root of a SO3Fun\n% \n% Syntax\n%   SO3F = sqrt(SO3F)\n%\n% Input\n%  SO3F - @SO3FunHarmonic\n%\n% Output\n%  SO3F - @SO3FunHarmonic\n%\n\nSO3F = SO3F.^(1/2);\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3Fun/sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2281240142617566}}
{"text": "function obj = D_func_hand_eye_new(in1,in2,in3,in4)\ncoef_f0_q_sym1 = in1(:,1);\ncoef_f0_q_sym2 = in1(:,2);\ncoef_f0_q_sym3 = in1(:,3);\ncoef_f0_q_sym4 = in1(:,4);\ncoef_f0_q_sym5 = in1(:,5);\ncoef_f0_q_sym6 = in1(:,6);\ncoef_f0_q_sym7 = in1(:,7);\ncoef_f0_q_sym8 = in1(:,8);\ncoef_f0_q_sym9 = in1(:,9);\ncoef_f0_q_sym10 = in1(:,10);\ncoef_f1_q_sym1 = in2(:,1);\ncoef_f0_q_sym12 = in1(:,12);\ncoef_f1_q_sym2 = in2(:,2);\ncoef_f0_q_sym13 = in1(:,13);\ncoef_f1_q_sym3 = in2(:,3);\ncoef_f0_q_sym14 = in1(:,14);\ncoef_f1_q_sym4 = in2(:,4);\ncoef_f0_q_sym15 = in1(:,15);\ncoef_f1_q_sym5 = in2(:,5);\ncoef_f0_q_sym16 = in1(:,16);\ncoef_f1_q_sym6 = in2(:,6);\ncoef_f0_q_sym17 = in1(:,17);\ncoef_f1_q_sym7 = in2(:,7);\ncoef_f1_q_sym8 = in2(:,8);\ncoef_f0_q_sym19 = in1(:,19);\ncoef_f1_q_sym9 = in2(:,9);\ncoef_f0_q_sym20 = in1(:,20);\ncoef_f0_q_sym21 = in1(:,21);\ncoef_f2_q_sym1 = in3(:,1);\ncoef_f2_q_sym2 = in3(:,2);\ncoef_f0_q_sym23 = in1(:,23);\ncoef_f2_q_sym3 = in3(:,3);\ncoef_f2_q_sym4 = in3(:,4);\ncoef_f2_q_sym5 = in3(:,5);\ncoef_f2_q_sym6 = in3(:,6);\ncoef_f2_q_sym7 = in3(:,7);\ncoef_f2_q_sym8 = in3(:,8);\ncoef_f2_q_sym9 = in3(:,9);\ncoef_f3_q_sym1 = in4(:,1);\ncoef_f3_q_sym2 = in4(:,2);\ncoef_f3_q_sym3 = in4(:,3);\ncoef_f3_q_sym4 = in4(:,4);\ncoef_f3_q_sym5 = in4(:,5);\ncoef_f3_q_sym6 = in4(:,6);\ncoef_f3_q_sym7 = in4(:,7);\ncoef_f3_q_sym8 = in4(:,8);\ncoef_f3_q_sym9 = in4(:,9);\ncoef_f1_q_sym10 = in2(:,10);\ncoef_f1_q_sym12 = in2(:,12);\ncoef_f1_q_sym13 = in2(:,13);\ncoef_f1_q_sym14 = in2(:,14);\ncoef_f1_q_sym15 = in2(:,15);\ncoef_f1_q_sym16 = in2(:,16);\ncoef_f1_q_sym17 = in2(:,17);\ncoef_f1_q_sym19 = in2(:,19);\ncoef_f1_q_sym20 = in2(:,20);\ncoef_f1_q_sym21 = in2(:,21);\ncoef_f1_q_sym23 = in2(:,23);\ncoef_f2_q_sym10 = in3(:,10);\ncoef_f2_q_sym12 = in3(:,12);\ncoef_f2_q_sym13 = in3(:,13);\ncoef_f2_q_sym14 = in3(:,14);\ncoef_f2_q_sym15 = in3(:,15);\ncoef_f2_q_sym16 = in3(:,16);\ncoef_f2_q_sym17 = in3(:,17);\ncoef_f2_q_sym19 = in3(:,19);\ncoef_f2_q_sym20 = in3(:,20);\ncoef_f2_q_sym21 = in3(:,21);\ncoef_f2_q_sym23 = in3(:,23);\ncoef_f3_q_sym10 = in4(:,10);\ncoef_f3_q_sym12 = in4(:,12);\ncoef_f3_q_sym13 = in4(:,13);\ncoef_f3_q_sym14 = in4(:,14);\ncoef_f3_q_sym15 = in4(:,15);\ncoef_f3_q_sym16 = in4(:,16);\ncoef_f3_q_sym17 = in4(:,17);\ncoef_f3_q_sym19 = in4(:,19);\ncoef_f3_q_sym20 = in4(:,20);\ncoef_f3_q_sym21 = in4(:,21);\ncoef_f3_q_sym23 = in4(:,23);\nt2 = coef_f1_q_sym1.*2.0;\nt3 = coef_f2_q_sym1.*2.0;\nt4 = coef_f3_q_sym1.*2.0;\nt5 = -coef_f0_q_sym2;\nt6 = -coef_f0_q_sym3;\nt7 = -coef_f0_q_sym4;\nt8 = -coef_f1_q_sym1;\nt10 = -coef_f2_q_sym1;\nt12 = -coef_f3_q_sym1;\nt9 = -t2;\nt11 = -t3;\nt13 = -t4;\nobj = reshape([coef_f0_q_sym1-coef_f1_q_sym2,-coef_f2_q_sym2,-coef_f3_q_sym2,-coef_f1_q_sym3,coef_f0_q_sym1-coef_f2_q_sym3,-coef_f3_q_sym3,-coef_f1_q_sym4,-coef_f2_q_sym4,coef_f0_q_sym1-coef_f3_q_sym4,coef_f0_q_sym5-coef_f1_q_sym12,-coef_f2_q_sym12,-coef_f3_q_sym12,coef_f0_q_sym6-coef_f1_q_sym13,coef_f0_q_sym5-coef_f2_q_sym13,-coef_f3_q_sym13,coef_f0_q_sym7-coef_f1_q_sym14,-coef_f2_q_sym14,coef_f0_q_sym5-coef_f3_q_sym14,coef_f0_q_sym8-coef_f1_q_sym15,coef_f0_q_sym6-coef_f2_q_sym15,-coef_f3_q_sym15,coef_f0_q_sym9-coef_f1_q_sym16,coef_f0_q_sym7-coef_f2_q_sym16,coef_f0_q_sym6-coef_f3_q_sym16,coef_f0_q_sym10-coef_f1_q_sym17,-coef_f2_q_sym17,coef_f0_q_sym7-coef_f3_q_sym17,-coef_f1_q_sym19,coef_f0_q_sym8-coef_f2_q_sym19,-coef_f3_q_sym19,-coef_f1_q_sym20,coef_f0_q_sym9-coef_f2_q_sym20,coef_f0_q_sym8-coef_f3_q_sym20,-coef_f1_q_sym21,coef_f0_q_sym10-coef_f2_q_sym21,coef_f0_q_sym9-coef_f3_q_sym21,-coef_f1_q_sym23,-coef_f2_q_sym23,coef_f0_q_sym10-coef_f3_q_sym23,coef_f0_q_sym12+coef_f1_q_sym5+t5+t8,coef_f2_q_sym5+t10,coef_f3_q_sym5+t12,coef_f0_q_sym13+coef_f1_q_sym6+t6,coef_f0_q_sym12+coef_f2_q_sym6+t5,coef_f3_q_sym6,coef_f0_q_sym14+coef_f1_q_sym7+t7,coef_f2_q_sym7,coef_f0_q_sym12+coef_f3_q_sym7+t5,coef_f0_q_sym15+coef_f1_q_sym5+coef_f1_q_sym8+t5+t9,coef_f0_q_sym13+coef_f2_q_sym5+coef_f2_q_sym8+t6+t11,coef_f3_q_sym5+coef_f3_q_sym8+t13,coef_f0_q_sym16+coef_f1_q_sym9,coef_f0_q_sym14+coef_f2_q_sym9+t7,coef_f0_q_sym13+coef_f3_q_sym9+t6,coef_f1_q_sym5+coef_f0_q_sym17+coef_f1_q_sym10+t5+t9,coef_f2_q_sym5+coef_f2_q_sym10+t11,coef_f0_q_sym14+coef_f3_q_sym5+coef_f3_q_sym10+t7+t13,coef_f1_q_sym6+coef_f0_q_sym19+t6,coef_f0_q_sym15+coef_f2_q_sym6+t5,coef_f3_q_sym6,coef_f1_q_sym7+coef_f0_q_sym20+t7,coef_f0_q_sym16+coef_f2_q_sym7,coef_f0_q_sym15+coef_f3_q_sym7+t5,coef_f1_q_sym6+coef_f0_q_sym21+t6,coef_f0_q_sym17+coef_f2_q_sym6+t5,coef_f0_q_sym16+coef_f3_q_sym6,coef_f1_q_sym7+coef_f0_q_sym23+t7,coef_f2_q_sym7,coef_f0_q_sym17+coef_f3_q_sym7+t5,coef_f1_q_sym8+t8,coef_f0_q_sym19+coef_f2_q_sym8+t6+t10,coef_f3_q_sym8+t12,coef_f1_q_sym9,coef_f0_q_sym20+coef_f2_q_sym9+t7,coef_f0_q_sym19+coef_f3_q_sym9+t6,coef_f1_q_sym8+coef_f1_q_sym10+t9,coef_f0_q_sym21+coef_f2_q_sym8+coef_f2_q_sym10+t6+t11,coef_f0_q_sym20+coef_f3_q_sym8+coef_f3_q_sym10+t7+t13,coef_f1_q_sym9,coef_f0_q_sym23+coef_f2_q_sym9+t7,coef_f0_q_sym21+coef_f3_q_sym9+t6,coef_f1_q_sym10+t8,coef_f2_q_sym10+t10,coef_f0_q_sym23+coef_f3_q_sym10+t7+t12],[3,28]);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/func_files/D_func_hand_eye_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22806661764142752}}
{"text": "function rtk=udstate_pppins(rtk,obs,nav)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% update the state parameters (PPP/INS mode)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nglobal glc\n\n% update positon \nrtk=udpos_pppins(rtk);\n\n% update clock(include GLONASS icb)\nrtk=udclk_pppins(rtk);\n\n% update tropospheric parameters\nif rtk.opt.tropopt==glc.TROPOPT_EST||rtk.opt.tropopt==glc.TROPOPT_ESTG\n    rtk=udtrop_pppins(rtk);\nend\n\n% update ionospheric parameters\nif rtk.opt.ionoopt==glc.IONOOPT_EST\n    rtk=udiono_pppins(rtk,obs,nav);\nend\n\n% update L5-receiver-dcb parameters\nif rtk.opt.nf>=3\n    rtk=uddcb_pppins(rtk);\nend\n\n% update ambiguity\nrtk=udamb_pppins(rtk,obs,nav);\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss_ins_tc/pppins/udstate_pppins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22806661194973316}}
{"text": "function ApToolupdatePHD_axesLabels(handles)\n%update PHD axes labels\n\nxlim = get(handles.phd,'xlim');\nylim = get(handles.phd,'ylim');\n\n%setup axes labels\nif isfield(handles,'phdXaxis')\n    dxlim = diff(xlim);\n    xticks = round(xlim(1))+[0 ceil(dxlim/4-1) ceil(dxlim/2-1) ...\n        ceil(dxlim/4*3-1) dxlim];\n    xticks(xticks < xlim(1)) = ceil(xlim(1));\n    xticks(xticks > xlim(2)) = floor(xlim(2));\n    xticklabels = cellfun(@(x) sprintf('%0.2g',x),num2cell(handles.phdXaxis(xticks)),'uniformoutput',false);\n    xticklabels{3} = '0'; % Should be very close to zero, so this makes display cleaner.\n    set(handles.phd,'xtick',xticks,'xticklabel',xticklabels);\n    xlabel(handles.phd,'Polar Angle (degrees)','fontweight','bold')\nelse\n    set(handles.phd, 'xtick', []);\nend\nif isfield(handles,'phdYaxis')\n    dylim = diff(ylim);\n    yticks = round(ylim(1))+[0 ceil(dylim/4-1) ceil(dylim/2-1) ...\n        ceil(dylim/4*3-1) dylim];\n    yticks(yticks < ylim(1)) = ceil(ylim(1));\n    yticks(yticks > ylim(2)) = floor(ylim(2));\n    set(handles.phd,'ytick',yticks,'yticklabel',...\n        cellfun(@(x) sprintf('%0.4g',x),num2cell(handles.phdYaxis(yticks)),'uniformoutput',false));\n    ylabel(handles.phd,sprintf('Frequency (%s)',handles.freqUnits),'fontweight','bold')\nelse\n    set(handles.phd, 'ytick', []);\nend\n\n", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Tools/ApertureTool/ApToolupdatePHD_axesLabels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2279848609658756}}
{"text": "%% NISwGSP-parrington\n% %{\nimfolder = 'images\\NISwGSP-parrington';\nim_n = 18;\nimfile = cell(im_n,1);\nfor ii = 1:im_n\n    imfile{ii} = sprintf('%s\\\\prtn%02d.jpg', imfolder, ii-1);\nend\n\nim = cell(im_n,1);\nfor ii = 1:im_n\n    im{ii} = imread(imfile{ii});\nend\n\nedge_list = zeros(im_n,2);\nei = 0;\nfor ii = 1:im_n-1\n    ei = ei + 1;\n    edge_list(ei,:) = [ii,ii+1];\nend\nedge_list(im_n,:) = [im_n,1];\n\nimsize = zeros(im_n,3);\n\nfor ii = 1:im_n\n    imsize(ii,:) = size(im{ii});\n    if imsize(ii,1) > 720\n        scale = 720/size(im{ii}, 1);\n        im{ii} = imresize(im{ii}, scale);\n\n        imsize(ii,:) = size(im{ii});\n    end\nend\n\nmosaic = REW_mosaic( im, edge_list, 0, 'equi', 0.02, imfolder );\n%}", "meta": {"author": "gain2217", "repo": "Robust_Elastic_Warping", "sha": "36ad3cb2f709fbea17225642ea1fa7b083924fd9", "save_path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping", "path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping/Robust_Elastic_Warping-36ad3cb2f709fbea17225642ea1fa7b083924fd9/multiple_views/examples/NISwGSP_parrington.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22798486096587556}}
{"text": "%PNTSET Set Dirichlet point constraints.\n%\n%   [ F, INDROW, AMAT, T ] = PNTSET( PROB, F, AMAT, ISYMM, SET_NULL )\n%   Sets Dirichlet point constraints conditions in the right hand side\n%   load vector F and global matrix AMAT with the information in the finite\n%   element problem struct PROB.\n%\n%       Input       Value/(Size)           Description\n%       -----------------------------------------------------------------------------------\n%       prob        struct                 Finite element problem struct\n%       f           (neq,1)                Right hand side/load vector\n%       amat        (n_a,n_a)              System matrix (sparse or triplet format)\n%       isymm       scalar/{0}             Symmetrize BCs if applicable.\n%       set_null    scalar/{0}             Set zeros in f vector.\n%                                                                                         .\n%       Output      Value/(Size)           Description\n%       -----------------------------------------------------------------------------------\n%       f           (neq,1)                Modified right hand side/load vector\n%       indrow      (neq,1)                Index to rows (dofs) in rhs which were set\n%       amat        (n_a,n_a)              Modified system matrix\n%       t           scalar                 Time spent in function\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/core/pntset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22794884086677045}}
{"text": "function [ChannelLabels, Time, Frequency, Data, Info] = read_besa_tfc(FILENAME)\n\n% READ_BESA_TFC imports data from a BESA *.tfc file\n%\n% Use as\n%   [DataType, ConditionName, Channels, Time, Frequency, Data] = read_besa_tfc(FILENAME)\n%\n% This reads data from the BESA Time-Frequency-Coherence output data file\n% FILENAME and returns the following data:\n%   ConditionName: name of analyzed condition\n%   ChannelLabels: character array of channel labels\n%   Time: array of sampled time instants\n%   Frequency: array of sampled frequencies\n%   Data: 3D data matrix with indices (channel,time,frequency)\n%   Info: Struct containing additional information:\n%       DataType: type of the exported data\n%       ConditionName: name of analyzed condition\n%       NumbeOfTrials: Number of trials on which the data is based\n%       StatisticsCorrection: Type of statistics correction for multiple testing\n%       EvokedSignalSubtraction: Type of evoked signal subtraction\n\n% Copyright (C) 2005, Vladimir Litvak\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nfp = fopen(FILENAME);\n\nVersionNumber = fscanf(fp,'VersionNumber=%s ',1);\nDataType = fscanf(fp,'DataType=%s ',1);\nConditionName = fscanf(fp,'ConditionName=%s ',1);\ntry\n    if ConditionName == 'Condition'\n        ConditionName = [ConditionName,' ',fscanf(fp,'%s ',1)];\n    end\ncatch\nend\nNumberTrials = fscanf(fp,'NumberTrials=%i ',1);\nNumberTimeSamples = fscanf(fp,'NumberTimeSamples=%i ');\nTimeStartInMS = fscanf(fp,'TimeStartInMS=%f ',1);\nTimeIntervalInMS = fscanf(fp,'IntervalInMS=%f ',1);\nNumberFrequencies = fscanf(fp,'NumberFrequencies=%i ');\nFreqStartInHZ = fscanf(fp,'FreqStartInHz=%f ',1);\nFreqIntervalInHZ = fscanf(fp,'FreqIntervalInHz=%f ',1);\nNumberChannels = fscanf(fp,'NumberChannels=%i ');\n\n% New file versions (BESA 5.0.8 and higher) include more information in the .tfc file header; skip that\nvers=0;                 % new tfc file format\ntry\n    StatisticsCorrection = fscanf(fp,'StatisticsCorrection=%s ',1);\n    EvokedSignalSubtraction = fscanf(fp,'EvokedSignalSubtraction=%s',1);\ncatch\n    vers=1;             % old tfc file format\nend\n\n% Handle possible future extensions of the tfc file header\ni=1;\nwhile i<1000\n    a = fscanf(fp,'%c',1);\n    if strcmp(a,sprintf('\\n'))\n        i=1000;\n    end\n    i=i+1;\nend\n\n% Generate return values\n% FIXME the following statement does not work for MATLAB 7.2 on XP (see mail from Stephan Bickel)\nTime = [TimeStartInMS:TimeIntervalInMS:(NumberTimeSamples-1)*TimeIntervalInMS+TimeStartInMS];\nFrequency = [FreqStartInHZ:FreqIntervalInHZ:(NumberFrequencies-1)*FreqIntervalInHZ+FreqStartInHZ];\nif vers == 1\n    Info = struct('DataType',{DataType},'ConditionName',{ConditionName},'NumberOfTrials',{NumberTrials});\nelse\n    Info = struct('DataType',{DataType},'ConditionName',{ConditionName},'NumberOfTrials',{NumberTrials},...\n        'StatisticsCorrection',{StatisticsCorrection},'EvokedSignalSubtraction',{EvokedSignalSubtraction});\nend\n\nif ~contains(DataType,'COH')\n    for Channel=1:NumberChannels\n        ChannelLabels(Channel) = cellstr(fscanf(fp,'%s ',1));\n    end\nelse\n    for Channel=1:NumberChannels\n        ChannelLabels(Channel) = cellstr(fscanf(fp,'%s ',3));\n    end\nend\n\nChannelLabels=char(ChannelLabels);\n\nData = zeros(NumberChannels,NumberTimeSamples,NumberFrequencies);\nfor Channel=1:NumberChannels\n    Data(Channel,:,:) = fscanf(fp,'%f',[NumberTimeSamples,NumberFrequencies]);\nend\nfclose(fp);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/read_besa_tfc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22794884086677045}}
{"text": "function writeInfluenceMatrixBixel(IM, structNum, planC, outFile)\n%\"writeInfluenceMatrixBixel\"\n%   Write the bixel information to binary file.\n%\n%   All beams in one file, for each beam:\n%       float    a_g, a_t, a_c  - gantry, table and collimator angles\n%       float    dx_b, dy_b     - bixel dimensions \n%       float    dx, dy, dz     - voxel dimensions   \n%       int      Nx, Ny, Nz     - dose cube dimensions (number of voxels)\n%       int      Npb            - number of pencil beams (bixels) used for this field\n%       float    DoseScalefactor- conversion factor to the absolute dose, for the best resolution, this will be max(Dij_entry)/max(short) = max(Dij_entry)/(2^15-1)\n% \n%       For each of Npb bixels:\n%           PB header:  \n%           float    energy         - energy\n%           float    spot_x, spot_y - position of the bixel w/ respect to the central axis of the field\n%           int      Nvox           - number of voxels with non-zero dose from this beamlet\n%\n%           For each of Nvox voxels:\n%               int      VoxelNumber    - voxel ID in the cube (between 1 and Nx*Ny*Nz)\n%               short    Value          - multiply this by DoseScalefactor to get the dose deposited by this beamlet to the voxel VoxelNumber, assuming the beamlet weight of 1\n%\n% Repeat for each beam.\n%\n% JRA 3/11/04\n%\n%Usage:\n%   function writeInfluenceMatrixBixel(IM, structNum, planC, outFile)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nindexS = planC{end};\n\n%Open file\nif nargin < 4   %default\n    outFile = 'c:\\tmp\\default.txt'\nelse\n    outFile\nend\nfid = fopen(outFile,'w+');\n\n%Rows of inflM are voxels, columns are PBs.\ndisp('Constructing influence matrix...')\n[inflM] = getGlobalInfluenceM(IM, structNum);\ndisp('Done.')\n\n%Find indices of voxels with nonzero dose.\nindexV = find(any(inflM,2));\n\n%Get total number of non zero voxels for each bixel.\nnnzVoxelsPerBixel = full(sum(inflM ~= 0, 1));\n\n%Get beamNumber for each beamlet.\nbeamN = [IM.beamlets(structNum, :).beamNum];\n\n%Index map from influence beamlets to beam style beamlets\nfor i = 1:length(IM.beams)\n    beamletsPerBeam([IM.beamlets(structNum, :).beamNum] == i) = find([IM.beamlets(structNum, :).beamNum] == i);\nend\n\n%For each beam...\nfor beamNum = 1:length(IM.beams)\n\t%Generate header info.\n\ta_g = IM.beams(beamNum).gantryAngle;\n\ta_t = IM.beams(beamNum).couchAngle;\n    if isempty(a_t), a_t = 0; end\n\ta_c = IM.beams(beamNum).collimatorAngle;\n    if isempty(a_c), a_c = 0; end\n\t\n\tdx_b = IM.beams(beamNum).beamletDelta_x;\n\tdy_b = IM.beams(beamNum).beamletDelta_y;\n\t\n\tdx = planC{indexS.scan}.uniformScanInfo.grid2Units;\n\tdy = planC{indexS.scan}.uniformScanInfo.grid1Units;\n\tdz = planC{indexS.scan}.uniformScanInfo.sliceThickness;\n\t\n\tsiz = getUniformizedSize(planC)\n\tNx = siz(1);\n\tNy = siz(2);\n\tNz = siz(3);\n\t\n\tNpb = length(find([IM.beamlets(structNum, :).beamNum] == beamNum));\n\t\n    %Find bixels belonging to this beam.\n    myBixels = find([IM.beamlets(structNum, :).beamNum] == beamNum);\n\n    %Scale determined by maximum value contributed to influence matrix from all bixels belonging to this beam. \n  \tdScale = max(max(inflM(:, myBixels)))/(2^15-1);\n    \n\t%Write header info:\n\tfwrite(fid, [a_g a_t a_c dx_b dy_b dx dy dz],'float32');\n\tfwrite(fid, [Nx Ny Nz Npb], 'int32');\n    fwrite(fid, dScale, 'float32');\n    \n\t%For every beamlet in this beam...\n\tfor i = myBixels\n        %Prepare data that will be written.\n        bE     = IM.beams(beamNum).beamEnergy;\n        spot_x = IM.beams(beamNum).xPBPosV(beamletsPerBeam(i));\n        spot_y = IM.beams(beamNum).yPBPosV(beamletsPerBeam(i));\n        nVox   = nnzVoxelsPerBixel(i);\n        voxNum = find(inflM(:,i));\n        %Convert to KonRad Cube.\n        voxI = KonRadCube(voxNum, siz);\n        doses = full(inflM(voxNum, i)) / dScale;      \n\n        %Write it.                \n        write  = fwrite(fid, bE,'float32');\n        write  = fwrite(fid, spot_x,'float32');    \n        write  = fwrite(fid, spot_y,'float32');    \n        write  = fwrite(fid, nVox,'uint32');    \n                  \n        %Use seeking+skips to interleave values.\n        pos = ftell(fid);\n        fseek(fid, -2, 'cof');\n        write = fwrite(fid, voxI,'int32', 2);\n        fseek(fid, pos, 'bof');\n        write = fwrite(fid, doses,'ushort', 4);\n        \n        if mod(i,200) == 0\n            disp(['Processed ' num2str(i) ' bixels for beam ' num2str(beamNum) '.']);\n        end\n    end\nend\t\nclear inflM;\n\ndisp('Done.');\nfclose(fid);", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/fileInterface/writeInfluenceMatrixBixel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22794883481344563}}
{"text": "function [label] = atlas_lookup(atlas, pos, varargin)\n\n% ATLAS_LOOKUP determines the anatomical label of a location in the given atlas.\n%\n% Use as\n%   label = atlas_lookup(atlas, pos, ...);\n%\n% Optinal input arguments should come in key-value pairs and can include\n%   'method'       = 'sphere' (default) searches surrounding voxels in a sphere\n%                    'cube' searches surrounding voxels in a cube\n%   'queryrange'   = number, should be 1, 3, 5, 7, 9 or 11 (default = 3)\n%   'coordsys'     = 'mni' or 'tal' (default = [])\n%\n% Dependent on the coordinates if the input points and the coordinates of the atlas,\n% the input positions are transformed betweem MNI and Talairach-Tournoux coordinates.\n% See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details.\n\n% Copyright (C) 2005-2020, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% get the optional input arguments\nmethod      = ft_getopt(varargin, 'method', 'sphere');\nqueryrange  = ft_getopt(varargin, 'queryrange', 3);\ncoordsys    = ft_getopt(varargin, 'coordsys');\n\nif isempty(coordsys)\n  ft_error('you must specify coordsys');\nend\n\nif isempty(intersect(queryrange, 1:2:queryrange))\n  ft_error('incorrect query range, should be an odd number');\nend\n\nif size(pos,1)==3 && size(pos,2)~=3\n  % transpose the input positions to get Nx3\n  pos = pos';\nend\n\n% determine which field(s) to use to look up the labels,\n% and whether these are boolean or indexed\nfn = fieldnames(atlas);\nisboolean = false(numel(fn),1);\nisindexed = false(numel(fn),1);\nfor i=1:length(fn)\n  if islogical(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim)\n    isboolean(i) = true;\n  elseif isnumeric(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim)\n    isindexed(i) = true;\n  end\nend\nif any(isindexed)\n  % let the indexed prevail\n  fn = fn(isindexed);\n  isindexed = 1;\nelseif any(isboolean)\n  % use the boolean\n  fn = fn(isboolean);\n  isindexed = 0;\nend\n\n% convert between MNI head coordinates and TAL head coordinates\n% coordinates should be expressed compatible with the atlas\nif     strcmp(coordsys, 'mni') && strcmp(atlas.coordsys, 'tal')\n  pos = mni2tal(pos')'; % this function likes 3xN\nelseif strcmp(coordsys, 'mni') && strcmp(atlas.coordsys, 'mni')\n  % nothing to do\nelseif strcmp(coordsys, 'tal') && strcmp(atlas.coordsys, 'tal')\n  % nothing to do\nelseif strcmp(coordsys, 'tal') && strcmp(atlas.coordsys, 'mni')\n  pos = tal2mni(pos')'; % this function likes 3xN\nelseif ~strcmp(coordsys, atlas.coordsys)\n  ft_error('the mismatch between the coordinate system in the atlas and the coordinate system in the data cannot be resolved');\nend\n\nnum = size(pos,1);\nsel = cell(1,numel(fn));\nlabel = {};\n\n% convert the atlas head coordinates into voxel coordinates\nvox  = ft_warp_apply(inv(atlas.transform), pos);\n\nfor i=1:num\n  \n  % this is the center voxel\n  ijk_center = vox(i,:);\n  \n  if isindexed\n    if strcmp(method, 'sphere')\n      % search in a sphere around the center voxel\n      \n      % first, identify the voxels (x,y,z) in a sphere around the center voxel\n      [x, y, z] = sphere(1000);\n      ori = [0 0 0];\n      ptswithinq = [];\n      for r = 0:(queryrange/2 - 0.5)\n        xs = round(r*x(:));\n        ys = round(r*y(:));\n        zs = round(r*z(:));\n        pts = unique([xs ys zs], 'rows');\n        \n        spherepts = [];\n        for a = 1:size(pts,1)\n          d2ori = sqrt(sum((pts(a, :)-ori).^2));\n          if d2ori <= r\n            spherepts = [spherepts; pts(a, :)];\n          end\n        end\n        \n        ptswithinr = []; % voxels located at a radius of r voxels from the center voxel\n        for n = 1:size(spherepts,1)\n          ptswithinr = [ptswithinr; spherepts(n, 1)+ijk_center(1), spherepts(n, 2)+ijk_center(2), spherepts(n,3)+ijk_center(3)];\n        end\n        \n        ptswithinq = [ptswithinq; ptswithinr]; % voxels within a radius of queryrange from the center voxel\n      end\n      ptswithinq = unique(round(ptswithinq), 'rows');\n      \n      for n = 1:size(ptswithinq,1)\n        ijk = ptswithinq(n, :);\n        if ijk(1)>=1 && ijk(1)<=atlas.dim(1) && ...\n            ijk(2)>=1 && ijk(2)<=atlas.dim(2) && ...\n            ijk(3)>=1 && ijk(3)<=atlas.dim(3)\n          for k=1:numel(fn)\n            sel{k} = [sel{k}; atlas.(fn{k})(ijk(1), ijk(2), ijk(3))];\n          end\n        else\n          ft_warning('location is outside atlas volume');\n        end\n      end\n      \n    elseif strcmp(method, 'cube')\n      % search in a cube around the center voxel\n      for di=(-(queryrange-1)/2):1:((queryrange-1)/2)\n        for dj=(-(queryrange-1)/2):1:((queryrange-1)/2)\n          for dk=(-(queryrange-1)/2):1:((queryrange-1)/2)\n            \n            % search in a cube around the center voxel\n            ijk = round(ijk_center + [di dj dk]);\n            \n            if ijk(1)>=1 && ijk(1)<=atlas.dim(1) && ...\n                ijk(2)>=1 && ijk(2)<=atlas.dim(2) && ...\n                ijk(3)>=1 && ijk(3)<=atlas.dim(3)\n              for k=1:numel(fn)\n                sel{k} = [sel{k}; atlas.(fn{k})(ijk(1), ijk(2), ijk(3))];\n              end\n              %brick0_val = atlas.brick0(ijk(1), ijk(2), ijk(3));\n              %brick1_val = atlas.brick1(ijk(1), ijk(2), ijk(3));\n              %sel = [sel; find(atlas.descr.brick==0 & atlas.descr.value==brick0_val)];\n              %sel = [sel; find(atlas.descr.brick==1 & atlas.descr.value==brick1_val)];\n            else\n              ft_warning('location is outside atlas volume');\n            end % k\n            %FIXME the three loops can probably be easily vectorized\n          end % dk\n        end % dj\n      end % di\n    end\n    \n    for k = 1:numel(fn)\n      if ~isempty(sel{k})\n        % Get rid of zeros in sel{k}\n        for t = numel(sel{k}):-1:1\n          if sel{k}(t) == 0\n            sel{k}(t) = [];\n          end\n        end\n        label = [label; atlas.([fn{k} 'label'])(sel{k})]; % by using setdiff and/or unique, the count for each label is lost, and ft_volumelookup cannot provide an accurate number for labels.count\n      end\n    end\n  else\n    ft_error('support for atlases that have a probabilistic segmentationstyle is not supported yet');\n  end\nend\n\n\n%label = unique(atlas.descr.name(sel));\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/atlas_lookup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.22792215741264787}}
{"text": "% example_radar.m\n% ====================================================>\n% The following seem to be descent parameters:\n%   - ProbOfDetection = 0.8\n%   - ProbOfDeath = 0.2\n%   - VelocityErrVariance = 2\n%   - ObsErrVariance = 50\n%   - ProbOfConfirm = 0.9\n%   - PHD.BirthScheme = {'Expansion', 5000}\n%\n\n%% Radar specific settings\nRadarName = 'staddon';\nswitch(RadarName)\n    case('staddon')\n        % Surveillance region parameters\n        V_bounds = [-8154.72944624983;... % X-min | \n                    -212.289393440959;... % X-max | Surveillance region bounding\n                    -7548.44272179096;... % Y-min | box coordinates (m)\n                    4355.32645897434]';   % Y-max |\n        RadarCoords.lat = 50.33933333;\n        RadarCoords.lon = -4.12527778;\n%         RadarCoords.lat = 50.346069;\n%         RadarCoords.lon = -4.113670;\n    case('longroom')\n        % Surveillance region parameters\n        V_bounds = [-8154.72944624983;... % X-min | \n                    3000;...              % X-max | Surveillance region bounding\n                    -7548.44272179096;... % Y-min | box coordinates (m)\n                    4355.32645897434]';   % Y-max |\n        RadarCoords.lat = 50.36286670714617;\n        RadarCoords.lon = -4.156833300366998;\nend\n\n% Load dataset\nload(strcat(RadarName,'_old.mat'));\nN = size(DataList,2); % Simulation length\n\n%% Plot & Recording settings\n% Plot settings\nShowPlots = 1;              % Set to 0 to prevent showing any plots\nShowUpdate = 1;             % Set to 0 to skip showing update plots\nShowTrackInfo = 0;\nNumPersistFrames = 50;           \n\n% Recording settings\nRecord = 1;                 % Set to (0|1) to turn video recording (off|on)\nFrameRate = 0.5;            % Number of frames per second\nVideoQuality = 100;         % Set to desired quality percentage\nVideoPathName = strcat(RadarName,'.avi'); % Set to the desired path and name of produced recording\n%% Instantiation of necessary components\n\n% Instantiate a Dynamic model (CV model with q = 1 m/s^2)\ndyn = ConstantVelocityModelX_2D('VelocityErrVariance',0.3);\ndyn.TimeVariant = 2;\n\n% Instantiate an Observation model (Variance of 50m^2 on each coordinate)\nobs = LinGaussObsModelX_2D('NumStateDims',4,'ObsErrVariance',50,'Mapping',[1 3]);\n\n% Compile the State-Space model\nssm = StateSpaceModelX(dyn,obs);\n\nV = (abs(V_bounds(2)-V_bounds(1))*abs(V_bounds(4)-V_bounds(3))); % Total area of surveillance region\n\n% Assign PHD parameter values\nconfig.NumParticles = 100000;\nconfig.Model = ssm;\nconfig.BirthIntFcn = @(Np)[abs(V_bounds(2)-V_bounds(1))*rand(1,Np)+V_bounds(1);... % Uniform position across the surveillance \n                           5*rand(1,Np);...                                      % region.                         \n                           abs(V_bounds(4)-V_bounds(3))*rand(1,Np)+V_bounds(3);... % Uniform speed between 0-9 m/s in both\n                           5*rand(1,Np)];                                        % X and Y.\nconfig.PriorDistFcn = @ (Np) deal(config.BirthIntFcn(Np), repmat(1/Np, Np, 1)');   % Uniform position and weights.\nconfig.BirthScheme = {'Expansion', 0.1*config.NumParticles};\nconfig.ProbOfDeath = 0.005;                                                        % Probability of death = 0.5%\nconfig.ProbOfDetection = 0.6;                                                      % Probability of detection = 70%\nconfig.ResamplingScheme = 'Multinomial';                                           % Use Multinomial Resampling\n\n% Instantiate PHD filter\nmyphd = SMC_PHDFilterX(config);\n\n% Instantiate PF filter\nmypf = ParticleFilterX(ssm);\n\n% Initiate PDAF parameters\nParams_pdaf.Clusterer = NaiveClustererX();\nParams_pdaf.Gater = EllipsoidalGaterX(2,'ProbOfGating',0.99)';\nParams_pdaf.ProbOfDetect = 0.6;\nParams_pdaf.Hypothesiser = LoopyBeliefPropagationX('ConvergeThreshold',10^(-3));\nmypdaf = JointIntegratedProbabilisticDataAssocX(Params_pdaf);\n\n% Initiate Track Initiator\nconfig_ti.Filter = mypf;\nconfig_ti.PHDFilter = myphd;\nconfig_ti.ProbOfGating = 0.99;\nconfig_ti.ProbOfConfirm = 0.9;\nmyti = PhdExistProbTrackInitiatorX(config_ti);\n\nTrackList = [];\n\n%% Create plot windows\nif(ShowPlots)\n    \n    % Map plot\n    figure('units','normalized','outerposition',[0 0 .5 1])\n    ax(1) = gca;\n    plot_google_map('Axis',ax(1),'APIKey','AIzaSyBXKujdtXRZiqya1soVS9pxBzYR4g7aGvM','Resize',3,'Scale',2,'MapType','satellite');\n    %axis(ax(1),V_bounds)\n    axis(ax(1),[-4.195 -4.11 50.31 50.375])\n    \n    % PHD Intensity plot\n    figure('units','normalized','outerposition',[.5 0 .5 1])\n    ax(2) = gca;\n    \n    plots = [];\nend\n\n%% START OF SIMULATION\n% ===================>\nfor k=1:N\n    fprintf('Iteration = %d/%d\\n================>\\n',k,N);\n\n    % Extract DataList at time k\n    tempDataList = DataList{k}(1:2,:);\n    tempDataList( :, ~any(tempDataList,1) ) = [];\n    \n    % Process JPDAF\n    mypdaf.MeasurementList = tempDataList;\n    mypdaf.TrackList = TrackList;\n    for j=1:numel(TrackList)\n        mypdaf.TrackList{j}.Filter.predict();\n    end\n    mypdaf.associate();    \n    mypdaf.updateTracks();\n    \n    tic;\n    \n    % Append state to target trajectories\n    for j=1:numel(TrackList)\n        if(isempty(TrackList{j}.Trajectory))\n            TrackList{j}.Trajectory = TrackList{j}.Filter.StateMean;\n        else\n            TrackList{j}.Trajectory = [TrackList{j}.Trajectory, TrackList{j}.Filter.StateMean];\n        end\n    end\n    \n    % Plot update step results\n    if(ShowPlots && ShowUpdate)\n        \n        % Delete all plots (other than map)\n        for i = 1:numel(plots)\n            delete(plots(i))\n        end\n        plots = [];\n        hold on;\n        \n        if(size(DataList{k},2)>0)\n            % Convert measurements to LLA and plot them\n            [lat,lon,~] = ned2geodetic(DataList{k}(2,:),...\n                                       DataList{k}(1,:),...\n                                       0,...\n                                       RadarCoords.lat,...\n                                       RadarCoords.lon,...\n                                       0,...\n                                       referenceEllipsoid('wgs84'));\n    %         lat = DataList{k}(3,:);\n    %         lon = DataList{k}(4,:);\n            plots(end+1) = plot(ax(1), lon,lat,'y*','MarkerSize', 10);\n            plot(ax(1), RadarCoords.lon,RadarCoords.lat,...\n                               '-s','MarkerSize',20,...\n                               'MarkerEdgeColor','red',...\n                               'MarkerFaceColor',[1 .6 .6]);\n        end\n        \n        % Plot all existing tracks\n        for j=1:numel(TrackList)\n            \n            % Convert track trajectory to LLA and plot it\n            [lat,lon,~] = ned2geodetic(TrackList{j}.Trajectory(3,:),...\n                                       TrackList{j}.Trajectory(1,:),...\n                                       0,...\n                                       RadarCoords.lat,...\n                                       RadarCoords.lon,...\n                                       0,...\n                                       referenceEllipsoid('wgs84'));\n            traj_length = size(lon,2);\n            if(traj_length>NumPersistFrames)\n                start = traj_length-NumPersistFrames;\n            else\n                start = 1;\n            end\n            plots(end+1) = plot(ax(1), lon(:,start:end),lat(:,start:end),'-.w','LineWidth',2);\n            plots(end+1) = plot(ax(1), lon(:,end),lat(:,end),'ws','MarkerSize',15);\n            \n            % Convert track velocity to LLA and plot it\n            [lat_vel,lon_vel,~] = ned2geodetic(TrackList{j}.Trajectory(4,end),...\n                                       TrackList{j}.Trajectory(2,end),...\n                                       0,...\n                                       lat(:,end),...\n                                       lon(:,end),...\n                                       0,...\n                                       referenceEllipsoid('wgs84'));\n            lat_vel = lat_vel-lat(:,end);\n            lon_vel = lon_vel-lon(:,end);\n            \n            plots(end+1) = quiver(ax(1), lon(:,end),lat(:,end),20*lon_vel,20*lat_vel,'r','LineWidth',1.5);\n            speed_kmph = sqrt(TrackList{j}.Trajectory(4,end)^2+TrackList{j}.Trajectory(2,end)^2)*3.6;\n            speed_knot = speed_kmph/1.852;\n            \n            if(ShowTrackInfo)\n                plots(end+1) = text(ax(1), lon(:,end)+0.001,lat(:,end)+0.00027,strcat(\"Sog:\",num2str(speed_knot,2),\" kt\"),'FontSize',8,'Color','w');\n                plots(end+1) = text(ax(1), lon(:,end)+0.001,lat(:,end)-0.00027,strcat(\"PoE:\",num2str(TrackList{j}.ProbOfExist*100,3),\" %\"),'FontSize',8,'Color','w');\n            end\n            % TODO: Convert heading and state covariance to LLA and plot them\n            % [lat,lon,h] = ned2geodetic(North,East,0,50.346069,-4.113670,0,referenceEllipsoid('wgs84'));\n            % h2 = plot_gaussian_ellipsoid(TrackList{j}.Filter.StateMean([1 3]), TrackList{j}.Filter.StateCovar([1 3],[1 3]),1,20,ax(1));\n            % plots(end+1) = h2;\n            % plots(end+1) = text(ax(1),TrackList{j}.Filter.StateMean(1)+20,TrackList{j}.Filter.StateMean(3)-5,int2str(TrackList{j}.TrackID));\n            % plots(end+1) = text(ax(1),TrackList{j}.Filter.StateMean(1)+20,TrackList{j}.Filter.StateMean(3)-130,num2str(TrackList{j}.ProbOfExist,2));\n        end\n        \n        % Add axis labels\n        xlabel('Longitude')\n        ylabel('Latitude')\n        \n        % Plot PHD Intensity\n%         cla(ax(2), 'reset');\n%         [bandwidth,density,X,Y]=kde2d(myphd.Particles([1,3],:)');\n%         h = surf(ax(2),X,Y,density);        \n%         shading interp\n%         colormap(ax(2), jet(3000))\n%         hold on;\n%         plot(ax(2), myphd.Particles(1,:), myphd.Particles(3,:), '.',...\n%                     myphd.MeasurementList(1,:), myphd.MeasurementList(2,:), 'y*');\n%         axis(ax(2), [V_bounds]);\n%         str = sprintf('PHD intensity (Update)');\n%         xlabel(ax(2),'X position (m)')\n%         ylabel(ax(2),'Y position (m)')\n%         zlabel(ax(2),'Intensity')\n%         title(ax(2),str)\n%         pause(0.01)\n        \n        % Store video frame\n        if(Record)\n            F(k) = getframe(ax(1));\n        end\n    end\n    \n    % Perform Track initiation\n    myti.MeasurementList = tempDataList; % New observations\n    myti.PHDFilter.ClutterRate = size(myti.MeasurementList,2)/V;\n    myti.TrackList = TrackList;\n    myti.AssocWeightsMatrix = mypdaf.AssocWeightsMatrix;\n    TrackList = myti.initiateTracks();\nend\n\n% Create video file and write to it\nif(Record)\n    %F = F(2:end);\n    vidObj = VideoWriter(char(VideoPathName));\n    vidObj.Quality = VideoQuality;\n    vidObj.FrameRate = FrameRate;\n    open(vidObj);\n    writeVideo(vidObj, F);\n    close(vidObj);\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/TrackInitiators/PhdTrackInitiatorX/Example/Not-Working/example_radar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.22792215303667826}}
{"text": "function [nScoutProj, destSurfMat, sAtlasProj] = bst_project_scouts( srcSurfFile, destSurfFile, sAtlas, isSingleHemi, isSave )\n% BST_PROJECT_SCOUTS: Project scouts on a different surface (need the FreeSurfer registered spheres).\n%\n% USAGE:  [nScoutProj, destSurfMat, sAtlasProj] = bst_project_scouts( srcSurfFile, destSurfFile, sAtlas=[all], isSingleHemi=0, isSave=1 )\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2015-2023\n\n% ===== PARSE INPUTS ======\nif (nargin < 5) || isempty(isSave)\n    isSave = 1;\nend\nif (nargin < 4) || isempty(isSingleHemi)\n    isSingleHemi = 0;\nend\nif (nargin < 3) || isempty(sAtlas)\n    sAtlas = [];\nend\nnScoutProj = 0;\ndestSurfMat = [];\nsAtlasProj = sAtlas;\n\n% ===== GET INTERPOLATION =====\n% Make sure files are different\nif file_compare(srcSurfFile, destSurfFile)\n    disp('BST> Error: Source and destination surfaces are the same.');\n    return;\nend\n% Compute interpolation  \n[Wmat, sSrcSubj, sDestSubj, srcSurfMat, destSurfMat] = tess_interp_tess2tess(srcSurfFile, destSurfFile, 1, [], isSingleHemi);\n% Source subject and destination subject are the same\nisSameSubject = file_compare(sSrcSubj.FileName, sDestSubj.FileName);\n% If no scouts in input, project everything\nif isempty(sAtlas)\n    sAtlas = srcSurfMat.Atlas;\nend\n% Check if there are things to project\nif isempty(sAtlas)\n    disp('BST> Error: No scouts to project.');\n    return;\nend\n% Ratio of vertex number\nratio = size(destSurfMat.Vertices,1) ./ size(srcSurfMat.Vertices,1);\n\n% ===== PROCESS ATLAS/SCOUTS =====\nfor iAtlas = 1:length(sAtlas)\n    % Initialize probability maps\n    scoutIndex = zeros(size(destSurfMat.Vertices,1),1);\n    scoutProba = zeros(size(destSurfMat.Vertices,1),1);\n    % Project scouts one by one and keep for each vertex only the maximum probability\n    for iScout = 1:length(sAtlas(iAtlas).Scouts)\n        % Vertex map on the original surface\n        vMap = zeros(size(srcSurfMat.Vertices,1),1);\n        vMap(sAtlas(iAtlas).Scouts(iScout).Vertices) = 1;\n        % Project to destination surface\n        vMapProj = full(Wmat * vMap);\n        % Keep only the projections that have a higher probability than the previous scouts\n        isHigherProba = vMapProj > scoutProba;\n        scoutProba(isHigherProba) = vMapProj(isHigherProba);\n        scoutIndex(isHigherProba) = iScout;\n    end\n        \n% DISABLED 2018\n%         % If the number of vertices does not decrease: force the selection of the closest vertex to each input vertex\n%         if (ratio > 0.9)\n%             for iVert = 1:length(sScout.Vertices)\n%                 % Get the closest projected vertex for iVert\n%                 [tmp, iVertClosest] = max(Wmat(:, sScout.Vertices(iVert)));\n%                 % Force the selection by setting the interpolated value higher than 1\n%                 vMapProj(iVertClosest) = 2;\n%             end\n%         end\n    \n    % Create all the scouts in the destination surface\n    for iScout = 1:length(sAtlas(iAtlas).Scouts)\n        % Current scout\n        sScout = sAtlas(iAtlas).Scouts(iScout);\n        \n        % Get vertices identified in this scout\n        iVertices = find(scoutIndex == iScout);\n        if isempty(iVertices)\n            sAtlasProj(iAtlas).Scouts(iScout).Vertices = [];\n            sAtlasProj(iAtlas).Scouts(iScout).Seed     = [];\n            continue;\n        end\n        % Limit the growth to extra vertices when not projecting an entire atlas\n        if (length(sAtlas(iAtlas).Scouts) < 10)\n            % Sort the projected values and keep the highest ones, up to desired number of vertices\n            [tmp,I] = sort(scoutProba(iVertices), 1, 'descend');\n            % Keep the highest values\n            nVertices = round(ratio * length(sScout.Vertices));\n            iVertices = iVertices(I(1:min(nVertices,length(I))));\n        end\n        \n        % Identify seed (closest point to the center of mass of the scout)\n        c = mean(destSurfMat.Vertices(iVertices,:),1);\n        distC = sqrt((destSurfMat.Vertices(iVertices,1)-c(1)).^2 + (destSurfMat.Vertices(iVertices,2)-c(2)).^2 + (destSurfMat.Vertices(iVertices,3)-c(3)).^2);\n        [distMin,iMin] = min(distC);\n        iSeed = iVertices(iMin);\n        \n        % Get destination atlas\n        iAtlasDest = find(strcmpi({destSurfMat.Atlas.Name}, sAtlas(iAtlas).Name));\n        if isempty(iAtlasDest)\n            iAtlasDest = length(destSurfMat.Atlas) + 1;\n            destSurfMat.Atlas(iAtlasDest).Name = sAtlas(iAtlas).Name;\n        end\n        % Destination scout name\n        if ~isSave\n            ScoutLabel = sScout.Label;\n        elseif isSameSubject\n            ScoutLabel = sScout.Label;\n        else\n            ScoutLabel = [sSrcSubj.Name '_' sScout.Label];\n            ScoutLabel = strrep(ScoutLabel, '@default_subject', 'Default');\n        end\n        if ~isempty(destSurfMat.Atlas(iAtlasDest).Scouts)\n            ScoutLabel = file_unique(ScoutLabel, {destSurfMat.Atlas(iAtlasDest).Scouts.Label});\n        end\n        % Create new scout\n        iScoutDest = length(destSurfMat.Atlas(iAtlasDest).Scouts) + 1;\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Vertices = iVertices(:)';\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Seed     = iSeed;\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Color    = sScout.Color;\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Label    = ScoutLabel;\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Function = sScout.Function;\n        destSurfMat.Atlas(iAtlasDest).Scouts(iScoutDest).Region   = sScout.Region;\n        % Report projected scouts\n        nScoutProj = nScoutProj + 1;\n        sAtlasProj(iAtlas).Scouts(iScout).Vertices = iVertices(:)';\n        sAtlasProj(iAtlas).Scouts(iScout).Seed     = iSeed;\n    end\nend\n\n% Save destination surface (append the atlas to existing file)\nif isSave && (nScoutProj > 0)\n    s.Atlas = destSurfMat.Atlas;\n    bst_save(file_fullpath(destSurfFile), s, 'v7', 1);\nend\n\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_project_scouts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.22792214916677958}}
{"text": "function [K] = ku0u0(x, y, xp, yp, hyp, ubar, vbar, ubarp, vbarp, dt, i)\n\nlogsigma = hyp(1);\nlogthetax = hyp(2);\nlogthetay = hyp(3);\n\na1 = hyp(4);\na2 = hyp(5);\n\nlogsigmap = hyp(6);\nlogthetaxp = hyp(7);\nlogthetayp = hyp(8);\n\nn_x = size(x,1);\nn_y = size(y,1);\nn_xp = size(xp,1);\nn_yp = size(yp,1);\n\nx = repmat(x,1,n_xp);\ny = repmat(y,1,n_yp);\nxp = repmat(xp',n_x,1);\nyp = repmat(yp',n_y,1);\n\nubar = repmat(ubar,1,n_xp);\nvbar = repmat(vbar,1,n_yp);\nubarp = repmat(ubarp',n_x,1);\nvbarp = repmat(vbarp',n_y,1);\n\nswitch i\n\n\ncase 0\n\nK=dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1/2).*exp(1).^((-1).* ...\n  logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+(-1) ...\n  .*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp).^2)+a1.*dt.*exp(1).^( ...\n  logsigma+(-5).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+(-1).*xp) ...\n  .^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp(1).^((-2) ...\n  .*logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*(x+(-1).*xp).*( ...\n  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...\n  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...\n  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...\n  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...\n  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^( ...\n  logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...\n  .^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.*dt.* ...\n  exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay) ...\n  .*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...\n  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...\n  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...\n  .*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).* ...\n  (y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^( ...\n  2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+ ...\n  (-1).*yp)))+exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).* ...\n  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...\n  yp).^2).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...\n  .^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-1) ...\n  .*dt.*exp(1).^(a2+logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).* ...\n  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...\n  yp).^2).*((-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*( ...\n  logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1) ...\n  .^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.* ...\n  a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1) ...\n  .^(a2+2.*logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.* ...\n  logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...\n  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...\n  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1) ...\n  .^(a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...\n  yp).^2)+(-2).*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...\n  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1).^logthetay+(y+(-1).*yp).^2) ...\n  +(-2).*exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...\n  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...\n  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...\n  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...\n  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...\n  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp)); ...\n  \n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...\n  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(a1.* ...\n  dt.*exp(1).^logthetay.*(exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1) ...\n  .*exp(1).^logthetax.*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^(logthetax+2.*logthetay).* ...\n  ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+ ...\n  2.*logthetay).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2))+ ...\n  vbar.*(exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...\n  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...\n  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...\n  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...\n  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...\n  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^( ...\n  2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1) ...\n  .^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).* ...\n  xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+ ...\n  exp(1).^(2.*logthetay).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1) ...\n  .*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1) ...\n  .^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-1) ...\n  .*dt.*exp(1).^a2.*((-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1) ...\n  .^(2.*(logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay) ...\n  +exp(1).^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1) ...\n  .*xp).^2+3.*a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+( ...\n  -6).*exp(1).^(a2+2.*logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).* ...\n  logthetax+2.*logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*( ...\n  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...\n  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...\n  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...\n  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...\n  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1) ...\n  .^(a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...\n  yp).^2)+(-2).*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...\n  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1).^logthetay+(y+(-1).*yp).^2) ...\n  +(-2).*exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...\n  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...\n  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...\n  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...\n  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...\n  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp))); ...\n  \n\n\ncase 2 % logthetax\n\nK=(1/2).*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).* ...\n  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...\n  yp).^2).*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(x+(-1).*xp).^2.* ...\n  (exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*( ...\n  x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...\n  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.* ...\n  dt.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*( ...\n  y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...\n  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...\n  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...\n  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...\n  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...\n  -1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+exp(1).^((-1).*logthetax+ ...\n  2.*logthetay).*(x+(-1).*xp).^2.*(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4))+(-2).*a1.*dt.*exp(1).^((-3).*logthetax+2.* ...\n  logthetay).*((-1).*exp(1).^(2.*(logthetax+logthetay)).*ubar.*(x+(-1).* ...\n  xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^( ...\n  logthetax+logthetay).*(exp(1).^(logthetax+2.*logthetay).*ubar.*ubarp+( ...\n  -2).*exp(1).^(2.*logthetay).*ubar.*ubarp.*(x+(-1).*xp).^2+(-1).*exp(1) ...\n  .^(logthetax+logthetay).*(3.*ubar.*vbarp.*(x+(-1).*xp)+ubarp.*(3.*vbar.* ...\n  (x+(-1).*xp)+ubar.*(y+(-1).*yp))).*(y+(-1).*yp)+2.*exp(1).^logthetay.* ...\n  ubar.*ubarp.*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^logthetax.*( ...\n  ubarp.*vbar+ubar.*vbarp).*(x+(-1).*xp).*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^a2.*((-6).*exp(1).^(logthetax+3.*logthetay).*ubar.*(x+(-1).*xp)+3.* ...\n  exp(1).^(3.*logthetay).*ubar.*(x+(-1).*xp).^3+(-3).*exp(1).^(2.*( ...\n  logthetax+logthetay)).*(ubar.*(x+(-1).*xp)+vbar.*(y+(-1).*yp))+6.*exp(1) ...\n  .^(logthetax+2.*logthetay).*(x+(-1).*xp).*(vbar.*(x+(-1).*xp)+ubar.*(y+( ...\n  -1).*yp)).*(y+(-1).*yp)+(-3).*exp(1).^(2.*logthetay).*ubar.*(x+(-1).*xp) ...\n  .^3.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax+logthetay).*(6.*ubar.*(x+(-1) ...\n  .*xp)+vbar.*(y+(-1).*yp)).*(y+(-1).*yp).^2+(-2).*exp(1).^(logthetax+ ...\n  logthetay).*vbar.*(x+(-1).*xp).^2.*(y+(-1).*yp).^3+(-1).*exp(1).^(2.* ...\n  logthetax).*ubar.*(x+(-1).*xp).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+ ...\n  (-4).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+logthetay)).*( ...\n  exp(1).^logthetax+(-2).*(x+(-1).*xp).^2).*(exp(1).^logthetay+(-1).*(y+( ...\n  -1).*yp).^2)+dt.*(6.*exp(1).^(a2+3.*logthetax+2.*logthetay)+6.*exp(1).^( ...\n  a2+2.*logthetax+3.*logthetay)+6.*a1.*exp(1).^(2.*logthetax+3.*logthetay) ...\n  .*ubarp.*(x+(-1).*xp)+(-18).*exp(1).^(a2+logthetax+3.*logthetay).*(x+( ...\n  -1).*xp).^2+(-3).*a1.*exp(1).^(logthetax+3.*logthetay).*ubarp.*(x+(-1).* ...\n  xp).^3+4.*exp(1).^(a2+3.*logthetay).*(x+(-1).*xp).^4+3.*a1.*exp(1).^(3.* ...\n  logthetax+2.*logthetay).*(ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp))+(-6) ...\n  .*exp(1).^(a2+2.*(logthetax+logthetay)).*(2.*x.^2+(-4).*x.*xp+2.*xp.^2+( ...\n  y+(-1).*yp).^2)+(-6).*a1.*exp(1).^(2.*(logthetax+logthetay)).*(x+(-1).* ...\n  xp).*(vbarp.*(x+(-1).*xp)+ubarp.*(y+(-1).*yp)).*(y+(-1).*yp)+(-12).*exp( ...\n  1).^(a2+3.*logthetax+logthetay).*(y+(-1).*yp).^2+24.*exp(1).^(a2+2.* ...\n  logthetax+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+18.*exp(1).^(a2+ ...\n  logthetax+2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+3.*a1.*exp(1) ...\n  .^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp).^3.*(y+(-1).*yp).^2+(-4) ...\n  .*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^4.*(y+(-1).*yp).^2+(-1).*a1.* ...\n  exp(1).^(3.*logthetax+logthetay).*(6.*ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1) ...\n  .*yp)).*(y+(-1).*yp).^2+2.*a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.* ...\n  (x+(-1).*xp).^2.*(y+(-1).*yp).^3+2.*exp(1).^(a2+3.*logthetax).*(y+(-1).* ...\n  yp).^4+a1.*exp(1).^(3.*logthetax).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^4+ ...\n  (-4).*exp(1).^(a2+2.*logthetax).*(x+(-1).*xp).^2.*(y+(-1).*yp).^4))+(-1) ...\n  .*dt.*exp(1).^(a2+(-1).*logthetax).*(x+(-1).*xp).^2.*((-2).*exp(1).^(( ...\n  -2).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+logthetay))+dt.*( ...\n  6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1).^(a2+logthetax+2.* ...\n  logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp)+( ...\n  -1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.*a1.*exp(1).^(2.* ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.* ...\n  logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.*logthetay).*(( ...\n  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+(-2).*logthetax+4.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1) ...\n  .^((-3).*logthetax+4.*logthetay).*(a1.*exp(1).^logthetax.*ubarp+(-2).* ...\n  exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+( ...\n  -1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...\n  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...\n  -1).*exp(1).^logthetay+(y+(-1).*yp).^2)+(-2).*exp(1).^logthetay.*(a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...\n  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...\n  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...\n  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...\n  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...\n  -1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp))+(-2).*dt.*exp(1).^((-2).* ...\n  logthetax+4.*logthetay).*(exp(1).^(a2+logthetax)+a1.*exp(1).^logthetax.* ...\n  ubarp.*(x+(-1).*xp)+(-2).*exp(1).^a2.*(x+(-1).*xp).^2).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2));\n\n\ncase 3 % logthetay\n\nK=exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...\n  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp( ...\n  1).^((-2).*logthetax+3.*logthetay).*(exp(1).^(2.*logthetax+logthetay).*( ...\n  3.*exp(1).^logthetay+(-2).*(y+(-1).*yp).^2)+dt.*(6.*exp(1).^(a2+2.* ...\n  logthetax+logthetay)+3.*exp(1).^(a2+logthetax+2.*logthetay)+3.*a1.*exp( ...\n  1).^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp)+(-3).*exp(1).^(a2+2.* ...\n  logthetay).*(x+(-1).*xp).^2+6.*a1.*exp(1).^(2.*logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.*logthetax).*(y+(-1).*yp).^2+( ...\n  -2).*exp(1).^(a2+logthetax+logthetay).*(y+(-1).*yp).^2+(-2).*a1.*exp(1) ...\n  .^(logthetax+logthetay).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+2.*exp(1) ...\n  .^(a2+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+(-1).*a1.*exp(1).^( ...\n  2.*logthetax).*vbarp.*(y+(-1).*yp).^3))+a1.*dt.*exp(1).^((-3).* ...\n  logthetax+2.*logthetay).*(exp(1).^(2.*logthetax+logthetay).*((-4).*exp( ...\n  1).^(2.*logthetay).*ubar.*(x+(-1).*xp)+(-9).*exp(1).^(logthetax+ ...\n  logthetay).*vbar.*(y+(-1).*yp)+3.*exp(1).^logthetay.*ubar.*(x+(-1).*xp) ...\n  .*(y+(-1).*yp).^2+2.*exp(1).^logthetax.*vbar.*(y+(-1).*yp).^3)+a1.*dt.* ...\n  exp(1).^logthetax.*(4.*exp(1).^(logthetax+3.*logthetay).*ubar.*ubarp+9.* ...\n  exp(1).^(2.*(logthetax+logthetay)).*vbar.*vbarp+(-4).*exp(1).^(3.* ...\n  logthetay).*ubar.*ubarp.*(x+(-1).*xp).^2+(-3).*exp(1).^(logthetax+2.* ...\n  logthetay).*(3.*ubar.*vbarp.*(x+(-1).*xp)+ubarp.*(3.*vbar.*(x+(-1).*xp)+ ...\n  ubar.*(y+(-1).*yp))).*(y+(-1).*yp)+(-12).*exp(1).^(2.*logthetax+ ...\n  logthetay).*vbar.*vbarp.*(y+(-1).*yp).^2+3.*exp(1).^(2.*logthetay).* ...\n  ubar.*ubarp.*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+2.*exp(1).^(logthetax+ ...\n  logthetay).*(ubarp.*vbar+ubar.*vbarp).*(x+(-1).*xp).*(y+(-1).*yp).^3+ ...\n  exp(1).^(2.*logthetax).*vbar.*vbarp.*(y+(-1).*yp).^4)+dt.*exp(1).^a2.*(( ...\n  -12).*exp(1).^(logthetax+3.*logthetay).*ubar.*(x+(-1).*xp)+4.*exp(1).^( ...\n  3.*logthetay).*ubar.*(x+(-1).*xp).^3+(-9).*exp(1).^(2.*(logthetax+ ...\n  logthetay)).*(ubar.*(x+(-1).*xp)+vbar.*(y+(-1).*yp))+(-30).*exp(1).^(3.* ...\n  logthetax+logthetay).*vbar.*(y+(-1).*yp)+9.*exp(1).^(logthetax+2.* ...\n  logthetay).*(x+(-1).*xp).*(vbar.*(x+(-1).*xp)+ubar.*(y+(-1).*yp)).*(y+( ...\n  -1).*yp)+(-3).*exp(1).^(2.*logthetay).*ubar.*(x+(-1).*xp).^3.*(y+(-1).* ...\n  yp).^2+2.*exp(1).^(2.*logthetax+logthetay).*(6.*ubar.*(x+(-1).*xp)+ ...\n  vbar.*(y+(-1).*yp)).*(y+(-1).*yp).^2+10.*exp(1).^(3.*logthetax).*vbar.*( ...\n  y+(-1).*yp).^3+(-2).*exp(1).^(logthetax+logthetay).*vbar.*(x+(-1).*xp) ...\n  .^2.*(y+(-1).*yp).^3+(-1).*exp(1).^(2.*logthetax).*ubar.*(x+(-1).*xp).*( ...\n  y+(-1).*yp).^4))+dt.*exp(1).^(a2+(-4).*logthetax+logthetay).*(exp(1).^( ...\n  2.*logthetax+logthetay).*(12.*exp(1).^(2.*(logthetax+logthetay))+5.*exp( ...\n  1).^(logthetax+3.*logthetay)+(-5).*exp(1).^(3.*logthetay).*(x+(-1).*xp) ...\n  .^2+(-18).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-4).*exp( ...\n  1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+4.*exp(1).^(2.*logthetay) ...\n  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).* ...\n  yp).^4)+dt.*(45.*exp(1).^(a2+4.*logthetax+2.*logthetay)+15.*exp(1).^(a2+ ...\n  2.*logthetax+4.*logthetay)+24.*exp(1).^(a2+3.*(logthetax+logthetay))+ ...\n  15.*a1.*exp(1).^(2.*logthetax+4.*logthetay).*ubarp.*(x+(-1).*xp)+(-30).* ...\n  exp(1).^(a2+logthetax+4.*logthetay).*(x+(-1).*xp).^2+(-5).*a1.*exp(1).^( ...\n  logthetax+4.*logthetay).*ubarp.*(x+(-1).*xp).^3+5.*exp(1).^(a2+4.* ...\n  logthetay).*(x+(-1).*xp).^4+12.*a1.*exp(1).^(3.*(logthetax+logthetay)).* ...\n  (ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp))+(-12).*exp(1).^(a2+2.* ...\n  logthetax+3.*logthetay).*(2.*x.^2+(-4).*x.*xp+2.*xp.^2+(y+(-1).*yp).^2)+ ...\n  45.*a1.*exp(1).^(4.*logthetax+2.*logthetay).*vbarp.*(y+(-1).*yp)+(-12).* ...\n  a1.*exp(1).^(2.*logthetax+3.*logthetay).*(x+(-1).*xp).*(vbarp.*(x+(-1).* ...\n  xp)+ubarp.*(y+(-1).*yp)).*(y+(-1).*yp)+(-90).*exp(1).^(a2+4.*logthetax+ ...\n  logthetay).*(y+(-1).*yp).^2+(-36).*exp(1).^(a2+3.*logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+24.*exp(1).^(a2+logthetax+3.*logthetay).*(x+ ...\n  (-1).*xp).^2.*(y+(-1).*yp).^2+36.*exp(1).^(a2+2.*(logthetax+logthetay)) ...\n  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+4.*a1.*exp(1).^(logthetax+3.* ...\n  logthetay).*ubarp.*(x+(-1).*xp).^3.*(y+(-1).*yp).^2+(-4).*exp(1).^(a2+ ...\n  3.*logthetay).*(x+(-1).*xp).^4.*(y+(-1).*yp).^2+(-3).*a1.*exp(1).^(3.* ...\n  logthetax+2.*logthetay).*(6.*ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp)).*( ...\n  y+(-1).*yp).^2+(-20).*a1.*exp(1).^(4.*logthetax+logthetay).*vbarp.*(y+( ...\n  -1).*yp).^3+3.*a1.*exp(1).^(2.*(logthetax+logthetay)).*vbarp.*(x+(-1).* ...\n  xp).^2.*(y+(-1).*yp).^3+15.*exp(1).^(a2+4.*logthetax).*(y+(-1).*yp).^4+ ...\n  4.*exp(1).^(a2+3.*logthetax+logthetay).*(y+(-1).*yp).^4+2.*a1.*exp(1).^( ...\n  3.*logthetax+logthetay).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^4+(-4).*exp( ...\n  1).^(a2+2.*logthetax+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^4+a1.* ...\n  exp(1).^(4.*logthetax).*vbarp.*(y+(-1).*yp).^5))+(-1).*dt.*exp(1).^a2.*( ...\n  (-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+ ...\n  logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1).^(a2+ ...\n  logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(x+ ...\n  (-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.*a1.*exp(1) ...\n  .^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.* ...\n  logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.*logthetay).*(( ...\n  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+(-2).*logthetax+4.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1) ...\n  .^((-3).*logthetax+4.*logthetay).*(a1.*exp(1).^logthetax.*ubarp+(-2).* ...\n  exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+( ...\n  -1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...\n  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...\n  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...\n  -1).*exp(1).^logthetay+(y+(-1).*yp).^2)+(-2).*exp(1).^logthetay.*(a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...\n  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...\n  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...\n  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...\n  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...\n  -1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp)).*((-6)+(1/2).*exp(1).^((-1).* ...\n  logthetay).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^logthetay.*(exp(1).^((-2).* ...\n  logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*(x+(-1).*xp).*( ...\n  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...\n  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...\n  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...\n  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...\n  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...\n  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^( ...\n  logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...\n  .^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.*dt.* ...\n  exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay) ...\n  .*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...\n  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...\n  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...\n  .*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).* ...\n  (y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^( ...\n  2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+ ...\n  (-1).*yp))).*((-5)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2)+ ...\n  exp(1).^(2.*logthetay).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1) ...\n  .*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1) ...\n  .^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...\n  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...\n  -4)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2));\n\n\ncase 4 % a1\n\nK=dt.*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax) ...\n  .*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*( ...\n  exp(1).^logthetay.*(exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1).* ...\n  exp(1).^logthetax.*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...\n  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...\n  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...\n  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...\n  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^(logthetax+2.*logthetay).* ...\n  ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+ ...\n  2.*logthetay).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2))+ ...\n  vbar.*(exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...\n  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...\n  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...\n  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...\n  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...\n  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^( ...\n  2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1) ...\n  .^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).* ...\n  xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+ ...\n  a1.*dt.*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^logthetay.* ...\n  ubar.*(exp(1).^(logthetax+logthetay).*ubarp.*(exp(1).^logthetay+(-1).*( ...\n  y+(-1).*yp).^2)+(-1).*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*ubarp.*(x+( ...\n  -1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...\n  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3))+exp(1).^logthetax.*vbar.*(3.*exp( ...\n  1).^(logthetax+2.*logthetay).*vbarp+(-3).*exp(1).^(2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-6).*exp(1).^(logthetax+logthetay).* ...\n  vbarp.*(y+(-1).*yp).^2+exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).* ...\n  yp).^3+exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^4))+(-1).*dt.*exp(1).^( ...\n  a2+(-3).*logthetax+logthetay).*((-2).*exp(1).^(2.*(logthetax+logthetay)) ...\n  .*(exp(1).^logthetay.*ubarp.*(x+(-1).*xp)+3.*exp(1).^logthetax.*vbarp.*( ...\n  y+(-1).*yp))+(-2).*exp(1).^(logthetax+3.*logthetay).*ubarp.*(x+(-1).*xp) ...\n  .*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+exp(1).^(2.*logthetay).*(( ...\n  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...\n  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...\n  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+exp(1).^(2.*logthetax).*((-1) ...\n  .*exp(1).^logthetay+(y+(-1).*yp).^2).*(exp(1).^(2.*logthetay).*ubarp.*( ...\n  x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...\n  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+(-2).*exp(1).^(2.*logthetax+ ...\n  logthetay).*(3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.* ...\n  vbarp.*(y+(-1).*yp).^2).*(y+(-1).*yp))+exp(1).^((-1).*logthetax+3.* ...\n  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...\n  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...\n  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...\n  (-1).*yp).^3));\n\n\ncase 5 % a2\n\nK=dt.*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax) ...\n  .*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*( ...\n  exp(1).^a2.*(2.*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*( ...\n  logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1) ...\n  .^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).* ...\n  ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.* ...\n  a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1) ...\n  .^(a2+2.*logthetax).*(y+(-1).*yp).^2))+(-1).*exp(1).^((-2).*logthetax+ ...\n  2.*logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...\n  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...\n  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+2.*dt.*exp(1).^( ...\n  a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...\n  .^2)+2.*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...\n  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...\n  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-1).*(exp(1).^(2.*logthetay).*( ...\n  exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).* ...\n  logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.* ...\n  exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...\n  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...\n  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...\n  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...\n  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1) ...\n  .^logthetay+(y+(-1).*yp).^2)+2.*exp(1).^logthetay.*(a1.*dt.*exp(1).^(( ...\n  -1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).*vbarp+(-2) ...\n  .*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1) ...\n  .^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+( ...\n  -1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...\n  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...\n  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...\n  .*(y+(-1).*yp)).*(y+(-1).*yp))+a1.*dt.*exp(1).^(a2+(-2).*logthetax+ ...\n  logthetay).*(exp(1).^logthetay.*ubar.*(x+(-1).*xp).*((-2).*exp(1).^(2.* ...\n  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-1).*exp(1).^(( ...\n  -1).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...\n  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...\n  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...\n  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...\n  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+ ...\n  vbar.*((-15).*exp(1).^(2.*(logthetax+logthetay))+(-3).*exp(1).^( ...\n  logthetax+3.*logthetay)+3.*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+10.* ...\n  exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(2.*logthetay).*(x+(-1).*xp) ...\n  .^2.*(y+(-1).*yp).^2+(-1).*exp(1).^(2.*logthetax).*(y+(-1).*yp).^4).*(y+ ...\n  (-1).*yp))+(-1).*dt.*exp(1).^(a2+(-4).*logthetax).*((-2).*exp(1).^(a2+ ...\n  2.*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+ ...\n  4.*exp(1).^(a2+logthetax+4.*logthetay).*(x+(-1).*xp).^2.*(exp(1) ...\n  .^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*exp(1).^(a2+2.*(logthetax+ ...\n  logthetay)).*(6.*exp(1).^(2.*logthetax+logthetay)+exp(1).^(logthetax+2.* ...\n  logthetay)+(-1).*exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^( ...\n  2.*logthetax).*(y+(-1).*yp).^2)+exp(1).^(a2+2.*logthetay).*((-1).*exp(1) ...\n  .^logthetax+(x+(-1).*xp).^2).*(3.*exp(1).^(2.*(logthetax+logthetay))+ ...\n  exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).* ...\n  xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).* ...\n  exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay) ...\n  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp) ...\n  .^4)+exp(1).^(a2+2.*logthetax).*((-1).*exp(1).^logthetay+(y+(-1).*yp) ...\n  .^2).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.* ...\n  logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^( ...\n  2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...\n  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...\n  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)+(-4).*exp(1).^(a2+ ...\n  2.*logthetax+logthetay).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).* ...\n  exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp) ...\n  .^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp).^2)+exp(1) ...\n  .^(a2+(-2).*logthetax+2.*logthetay).*(3.*exp(1).^(2.*(logthetax+ ...\n  logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^(3.* ...\n  logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*(y+( ...\n  -1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp( ...\n  1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...\n  logthetax).*(y+(-1).*yp).^4));\n\n\ncase 6 % logsigmap\n\nK=dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1/2).*exp(1).^((-1).* ...\n  logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+(-1) ...\n  .*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp).^2);\n\n\ncase 7 % logthetaxp\n\nK=(-1/2).*dt.^2.*exp(1).^(logsigmap+(-3).*logthetaxp+(-1/2).*exp(1).^((-1) ...\n  .*logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+( ...\n  -1).*yp).^2).*(2.*exp(1).^(2.*logthetaxp)+(-5).*exp(1).^logthetaxp.*(x+( ...\n  -1).*xp).^2+(x+(-1).*xp).^4);\n\n\ncase 8 % logthetayp\n\nK=(1/2).*dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1).*logthetayp+( ...\n  -1/2).*exp(1).^((-1).*logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1) ...\n  .*logthetayp).*(y+(-1).*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp) ...\n  .^2).*(y+(-1).*yp).^2;\n\n\notherwise\n        \n        K = zeros(n_x, n_xp);\nend\n\nend\n", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Kernels/Navier_Stokes/+k00/ku0u0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.2845760102840561, "lm_q1q2_score": 0.22785773542281978}}
{"text": "%\n%  Context-Aware Correlation Filters\n%\n%  Written by Luca Bertinetto, 2016\n%  Adapted by Matthias Mueller, 2016\n%\n%  This function takes care of setting up parameters, loading video\n%  information and computing precisions. For the actual tracking code,\n%  check out the TRACKERMAIN.m function.\n%\n\nfunction run_tracker(video, start_frame)\n% RUN_TRACKER  is the external function of the tracker - does initialization and calls trackerMain\n\n\t%path to the videos (you'll be able to choose one with the GUI).\n\tbase_path = 'sequences/';\n    \n\t%default settings\n\tif nargin < 1, video = 'Skiing'; end\n\tif nargin < 2, start_frame = 1; end\n    if nargin < 3, show_plots = 1; end\n    \n    %% Read params.txt\n    params = readParams('params.txt');\n\t%% load video info\n    sequence_path = fullfile(base_path,video);\n    img_path = fullfile(sequence_path, 'img');\n    %% Read files\n    text_files = dir([sequence_path '*_frames.txt']);\n    if(~isempty(text_files))\n        f = fopen([sequence_path text_files(1).name]);\n        frames = textscan(f, '%f,%f');\n        fclose(f);\n    else\n        frames = {};\n    end\n    if exist('start_frame')\n        frames{1} = start_frame;\n    else\n        frames{1} = 1;\n    end\n    \n   \n    params.bb_VOT = csvread(fullfile(sequence_path, 'groundtruth_rect.txt'));\n    region = params.bb_VOT(frames{1},:);\n    %%%%%%%%%%%%%%%%%%%%%%%%%\n    % read all the frames in the 'imgs' subfolder\n    dir_content = dir(fullfile(sequence_path, 'img'));\n    % skip '.' and '..' from the count\n    n_imgs = length(dir_content) - 2;\n    img_files = cell(n_imgs, 1);\n    for ii = 1:n_imgs\n        img_files{ii} = dir_content(ii+2).name;\n    end\n       \n    img_files(1:start_frame-1)=[];\n\n    im = imread(fullfile(img_path, img_files{1}));\n    % is a grayscale sequence ?\n    if(size(im,3)==1)\n        params.grayscale_sequence = true;\n    end\n\n    params.img_files = img_files;\n    params.img_path = img_path;\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(numel(region)==8)\n        % polygon format\n        [cx, cy, w, h] = getAxisAlignedBB(region);\n    else\n        x = region(1);\n        y = region(2);\n        w = region(3);\n        h = region(4);\n        cx = x+w/2;\n        cy = y+h/2;\n    end\n\n    % init_pos is the centre of the initial bounding box\n    params.init_pos = [cy cx];\n    params.target_sz = round([h w]);\n    [params, bg_area, fg_area, area_resize_factor] = initializeAllAreas(im, params);\n\tif params.visualization\n\t\tparams.videoPlayer = vision.VideoPlayer('Position', [100 100 [size(im,2), size(im,1)]+30]);\n\tend\n    % in runTracker we do not output anything\n\tparams.fout = -1;\n\t% start the actual tracking\n\tresults = trackerMain(params, im, bg_area, fg_area, area_resize_factor);\n    \n    %calculate and show precision plot, as well as frames-per-second\n    precisions = precision_plot(results.res, params.bb_VOT, video, show_plots);\n    fprintf('%12s - Precision (20px):% 1.3f, FPS:% 4.2f\\n', video, precisions(20), results.fps)\n    fclose('all');\n    \nend\n", "meta": {"author": "thias15", "repo": "Context-Aware-CF-Tracking", "sha": "2b1198a24aea6420d28987f68622f50a2970ffac", "save_path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking", "path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking/Context-Aware-CF-Tracking-2b1198a24aea6420d28987f68622f50a2970ffac/STAPLE_CA/run_tracker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.22783372938319535}}
{"text": "function [maps,stats] = SurveyFiringMaps(units,varargin)\n\n%SurveyFiringMaps - Compute and plot firing maps for all subsessions.\n%\n%  USAGE\n%\n%    [maps,stats] = SurveyFiringMaps(units,<options>)\n%\n%    units          optional list of units, i.e. [electrode group, cluster]\n%                   pairs; set cluster to -1 to process all clusters\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'minv'        minimum instantaneous velocity (default = 0)\n%     'pixel'       size of the video pixel in cm (no default value)\n%     'show'        set to 'off' to compute but not plot data (default = 'on')\n%    =========================================================================\n%\n%  OUTPUT\n%\n%    The outputs are the same as for <a href=\"matlab:help MapStats\">MapStats</a>, except for map.z which is\n%    replaced by map.rate.\n%\n%  SEE\n%\n%    See also FiringMap, PlotColorMap.\n\n% Copyright (C) 2009-2013 by Anne Cei, Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Default values\nminv = [];\npixel = [];\nshow = 'on';\n\n% No unit list provided?\nif ~(nargin >= 1 && isimatrix(units)),\n\tunits = GetUnits;\n\tvarargin = {units,varargin{:}};\nelse\n\tall = units(:,2) == -1;\n\tgroups = unique(units(all,1));\n\tunits(all,:) = [];\n\tunits = unique([units;GetUnits(groups)],'rows');\nend\nnUnits = size(units,1);\n\nif mod(length(varargin),2) ~= 0,\n\terror('Incorrect number of parameters (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).');\nend\n\n% Parse options\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\terror(['Parameter ' num2str(i+1) ' is not a property (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'minv',\n\t\t\tminv = varargin{i+1};\n\t\t\tif ~isdscalar(minv,'>=0'),\n\t\t\t\terror('Incorrect value for property ''minv'' (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).');\n\t\t\tend\n\t\tcase 'pixel',\n\t\t\tpixel = varargin{i+1};\n\t\t\tif ~isdscalar(pixel,'>0'),\n\t\t\t\terror('Incorrect value for property ''pixel'' (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).');\n\t\t\tend\n\t\tcase 'show',\n\t\t\tshow = varargin{i+1};\n\t\t\tif ~isstring_FMAT(show,'on','off'),\n\t\t\t\terror('Incorrect value for property ''show'' (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).');\n\t\t\tend\n\t\totherwise,\n\t\t\terror(['Unknown property ''' num2str(varargin{i}) ''' (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).']);\n\tend\nend\n\n% Get positions\npositions = GetPositions;\nif isempty(positions), warning('No positions found for current subsession'); return; end\nif ~isempty(minv),\n\tif isempty(pixel),\n\t\terror(['Missing pixel size for minimum velocity (type ''help <a href=\"matlab:help SurveyFiringMaps\">SurveyFiringMaps</a>'' for details).']);\n\tend\n\tx = GetPositions('coordinates','real','pixel',pixel);\n\tv = LinearVelocity(x,30);\n\t[~,in] = Threshold(v,'>',minv,'min',10,'max',2);\n\tpositions = positions(in,:);\nend\n\n% Get start/stop events for each subsession\nstart = GetEvents('beginning of .*');\nstop = GetEvents('end of .*');\nnSubsessions = length(start);\n\nif strcmp(show,'on'),\n\ttitles = GetEventTypes('beginning of .*');\n\tstatus = Hide('status');\n\tHide('on');\n\tfigureList = [];\nend\n\ntry\n\tn = 0;\n\t% Loop through units\n\tfor j = 1:nUnits,\n\t\tif strcmp(show,'on'), figureList = [figureList figure]; end\n\t\tspikes = GetSpikes(units(j,:));\n\t\t% Loop through subsessions\n\t\tfor i = 1:nSubsessions,\n\t\t\tp = Restrict(positions,[start(i) stop(i)]);\n\t\t\ts = Restrict(spikes,[start(i) stop(i)]);\n\t\t\tif nargin == 0,\n\t\t\t\tmap = FiringMap(p(:,1:3),s,'nbins',[250 250],'smooth',5,'mintime',0);\n\t\t\telse\n\t\t\t\t[map,st] = FiringMap(p(:,1:3),s,'nbins',[250 250],'smooth',5,'mintime',0);\n\t\t\t\tst.unit = units(j,:);\n\t\t\t\tst.subsession = i;\n\t\t\t\tn = n + 1;\n\t\t\t\tstats(n) = st;\n\t\t\t\tmaps(n) = map;\n\t\t\tend\n\t\t\tif strcmp(show,'on'),\n\t\t\t\tSquareSubplot(nSubsessions,i);\n\t\t\t\tPlotColorMap(map.rate,map.time,'ydir','reverse','bar','off','cutoffs',[0 10],'gamma',2);\n\t\t\t\ttitle = titles{i}(14:end);\n\t\t\t\tSplitTitle([title ' (' int2str(units(j,1)) '-' int2str(units(j,2)) ')'],round(150/sqrt(nSubsessions)));\n\t\t\tend\n\t\tend\n\tend\ncatch err\n\tif strcmp(show,'on'),\n\t\tHide(status);\n\t\tHide(figureList,status);\n\tend\n\terr.rethrow;\nend\n\nif strcmp(show,'on'),\n\tHide(status);\n\tHide(figureList,status);\nend", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Analyses/SurveyFiringMaps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.22783372354181666}}
{"text": "%% Example 1 Overview\n%\n% GLMsingle is new tool that provides efficient, scalable, and accurate\n% single-trial fMRI response estimates.\n%\n% The purpose of this Example 1 notebook is to guide the user through basic\n% calls to GLMsingle, using a representative, small-scale test dataset (in\n% this case, an example session from a rapid event-related visual fMRI\n% dataset - the Natural Scenes Dataset core experiment).\n%\n% The goal is to examine the effect of GLMsingle on the reliability of\n% single-trial fMRI response estimates. By default, the tool implements a\n% set of optimizations that improve upon generic GLM approaches by: (1)\n% identifying an optimal hemodynamic response function (HRF) at each voxel,\n% (2) deriving a set of useful GLM nuisance regressors via \"GLMdenoise\" and\n% picking an optimal number to include in the final GLM, and (3) applying a\n% custom amount of ridge regularization at each voxel using an efficient\n% technique called \"fracridge\". The output of GLMsingle are GLM betas\n% reflecting the estimated percent signal change in each voxel in response\n% to each experimental stimulus or condition being modeled.\n%\n% Beyond directly improving the reliability of neural responses to repeated\n% stimuli, these optimized techniques for signal estimation can have a\n% range of desirable downstream effects such as: improving cross-subject\n% representational similarity within and between datasets; improving the\n% single-image decodability of evoked neural patterns via MVPA; and,\n% decreasing the correlation in spatial patterns observed at neighboring\n% timepoints in analysis of fMRI GLM outputs. See our video presentation at\n% V-VSS 2020 for a summary of these phenomena as observed in recent\n% massive-scale fMRI datasets (the Natural Scenes Dataset and BOLD5000):\n% https://www.youtube.com/watch?v=yb3Nn7Han8o\n%\n% Example 1 contains a full walkthrough of the process of loading an\n% example dataset and design matrix, estimating neural responses using\n% GLMsingle, estimating the reliability of responses at each voxel, and\n% comparing those achieved via GLMsingle to those achieved using a baseline\n% GLM. After loading and visualizing formatted fMRI time-series and their\n% corresponding design matrices, we will describe the default behavior of\n% GLMsingle and show how to modify hyperparameters if the user desires.\n% Throughout the notebook we will highlight important metrics and outputs\n% using figures, print statements, and comments.\n%\n% Users encountering bugs, unexpected outputs, or other issues regarding\n% GLMsingle shouldn't hesitate to raise an issue on GitHub:\n% https://github.com/kendrickkay/GLMsingle/issues\n\n%% Add dependencies and download the example dataset\n\n% Start fresh\nclear\nclc\nclose all\n\nthis_dir    = fileparts(which('example1.m'));\n\n% Add path to GLMsingle\nrun(fullfile(this_dir, '..', '..', 'setup.m'));\n\n% Name of directory to which outputs will be saved\noutputdir = fullfile(this_dir, 'example1outputs');\n\n% Download files to data directory\ninput_dir = fullfile(this_dir, 'data');\nif ~exist(input_dir, 'dir')\n    mkdir('data')\nend\n\ninput_file = fullfile(input_dir, 'nsdcoreexampledataset.mat');\nURL = 'https://osf.io/k89b2/download';\n\ndownload_data(URL, input_file);\n\nload(input_file)\n\n% Data comes from the NSD dataset (subj01, nsd01 scan session).\n% https://www.biorxiv.org/content/10.1101/2021.02.22.432340v1.full.pdf\n\n%% Data overview\nclc\nwhos\n\n% data -> consists of several runs of 4D volume files (x,y,z,t)  where\n% (t)ime is the 4th dimention. In this example, data consists of only a\n% single slice and has been prepared with a TR = 1s\n\n% ROI -> manually defined region in the occipital cortex. It is a binary\n% matrix where (x,y,z) = 1 corresponds to the cortical area that responded\n% to visual stimuli used in the NSD project.\n\nfprintf('There are %d runs in total.\\n',length(design));\nfprintf('The dimensions of the data for the first run are %s.\\n',mat2str(size(data{1})));\nfprintf('The stimulus duration is %.3f seconds.\\n',stimdur);\nfprintf('The sampling rate (TR) is %.3f seconds.\\n',tr);\n\n%%\n\nfigure(1);clf\n\n%Show example design matrix.\nfor d = 1\n    imagesc(design{d}); colormap gray; drawnow\n    xlabel('Conditions')\n    ylabel('TRs')\n    title(sprintf('Design matrix for run%i',d))\n    axis image\nend\n\nxticks(0:53:length(design{d}))\nset(gcf,'Position',[418   412   782   605])\n\n%%\n% design -> Each run has a corresponding design matrix where each column\n% describes a single condition (conditions are repeated across runs). Each\n% design matrix is binary with 1 specfing the time (TR) when the stimulus\n% is presented on the screen.\n%\n% In this NSD scan session, there are a total of 750 trials, in which a\n% total of 583 distinct images are shown. (Thus, some images were presented\n% more than once.) In the design matrix shown, there are 583 predictor\n% columns/conditions, one per distinct image. Notice that white rectangles\n% are pseudo randomized and they indicate when the presentation of each\n% image occurs. Note that in some runs not all images are shown; if a\n% column does not have a white rectangle it means that this image is shown\n% in a different run within the session.\n\n%%\n\n% Show an example slice of the first fMRI volume.\nfigure(2);clf\nimagesc(data{1}(:,:,:,1));\ncolormap(gray);\naxis equal tight;\nc=colorbar;\ntitle('fMRI data (first volume)');\nset(gcf,'Position',[418   412   782   605])\naxis off\nc.Label.String = 'T2*w intensity';\nset(gca,'FontSize',15)\n\n%% Call GLMestimatesingletrial with default parameters\n\n% Outputs and figures will be stored in a folder (you can specify its name\n% as the 5th input to GLMestimatesingletrial). Model estimates can be also\n% saved to the 'results' variable which is the only output of\n% GLMestimatesingletrial.\n\n% Optional parameters below can be assigned to a structure, i.e., opt =\n% struct('wantlibrary',1,'wantglmdenoise',1); Options are the 6th input to\n% GLMestimatesingletrial.\n\n% There are many options that can be specified; here, we comment on the\n% main options that one might want to modify/set. Defaults for the options\n% are indicated below.\n\n% wantlibrary = 1 -> Fit HRF to each voxel \n% wantglmdenoise = 1 -> Use GLMdenoise \n% wantfracridge = 1  -> Use ridge regression to improve beta estimates\n% chunknum = 50000 -> is the number of voxels that we will\n%     process at the same time. For setups with lower memory, you may need to \n%     decrease this number.\n\n% wantmemoryoutputs is a logical vector [A B C D] indicating which of the\n%     four model types to return in the output <results>. The user must be\n%     careful with this, as large datasets can require a lot of RAM. If you\n%     do not request the various model types, they will be cleared from\n%     memory (but still potentially saved to disk). Default: [0 0 0 1]\n%     which means return only the final type-D model.\n\n% wantfileoutputs is a logical vector [A B C D] indicating which of the\n%     four model types to save to disk (assuming that they are computed). A\n%     = 0/1 for saving the results of the ONOFF model, B = 0/1 for saving\n%     the results of the FITHRF model, C = 0/1 for saving the results of the\n%     FITHRF_GLMdenoise model, D = 0/1 for saving the results of the\n%     FITHRF_GLMdenoise_RR model. Default: [1 1 1 1] which means save all\n%     computed results to disk.\n\n% numpcstotry (optional) is a non-negative integer indicating the maximum\n%     number of GLMdenoise PCs to enter into the model. Default: 10.\n\n% fracs (optional) is a vector of fractions that are greater than 0\n%     and less than or equal to 1. We automatically sort in descending\n%     order and ensure the fractions are unique. These fractions indicate\n%     the regularization levels to evaluate using fractional ridge\n%     regression (fracridge) and cross-validation. Default:\n%     fliplr(.05:.05:1). A special case is when <fracs> is specified as a\n%     single scalar value. In this case, cross-validation is NOT performed\n%     for the type-D model, and we instead blindly use the supplied\n%     fractional value for the type-D model.\n\n% For the purpose of this example, we will keep all outputs in the memory.\nopt = struct('wantmemoryoutputs',[1 1 1 1]);\n\n% This example saves output .mat files to the folder\n% \"example1outputs/GLMsingle\". If these outputs don't already exist, we\n% will perform the time-consuming call to GLMestimatesingletrial.m;\n% otherwise, we will just load from disk.\nif ~exist(fullfile(outputdir, 'GLMsingle', 'TYPEB_FITHRF.mat'),'file') || ...\n   ~exist(fullfile(outputdir, 'GLMsingle', 'TYPEC_FITHRF_GLMDENOISE.mat'),'file') || ...\n   ~exist(fullfile(outputdir, 'GLMsingle', 'TYPED_FITHRF_GLMDENOISE_RR.mat'),'file')\n    \n    [results designSINGLE] = GLMestimatesingletrial(design,data,stimdur,tr,[outputdir '/GLMsingle'],opt);\n    \n    % We assign outputs of GLMestimatesingletrial to \"models\" structure.\n    % Note that results{1} contains GLM estimates from an ONOFF model,\n    % where all images are treated as the same condition. These estimates\n    % could be potentially used to find cortical areas that respond to\n    % visual stimuli. We want to compare beta weights between conditions\n    % therefore we are not going to store the ONOFF GLM results.\n    \n    clear models;\n    models.FIT_HRF = results{2};\n    models.FIT_HRF_GLMdenoise = results{3};\n    models.FIT_HRF_GLMdenoise_RR = results{4};\n    \nelse\n    % Load existing file outputs if they exist\n    results = load([outputdir '/GLMsingle/TYPEB_FITHRF.mat']);\n    models.FIT_HRF = results;\n    results = load([outputdir '/GLMsingle/TYPEC_FITHRF_GLMDENOISE.mat']);\n    models.FIT_HRF_GLMdenoise = results;\n    results = load([outputdir '/GLMsingle/TYPED_FITHRF_GLMDENOISE_RR.mat']);\n    models.FIT_HRF_GLMdenoise_RR = results;\n    \nend\n\n%% Summary of important outputs\n\n% The outputs of GLMestimatesingletrial.m are formally documented in its\n% header. Here, we highlight a few of the more important outputs:\n%\n% R2 -> is model accuracy expressed in terms of R^2 (percentage).\n%\n% modelmd -> is the full set of single-trial beta weights (X x Y x Z x\n% TRIALS). Beta weights are arranged in chronological order.\n%\n% HRFindex -> is the 1-index of the best fit HRF. HRFs can be recovered\n% with getcanonicalHRFlibrary(stimdur,tr)\n%\n% FRACvalue -> is the fractional ridge regression regularization level\n% chosen for each voxel. Values closer to 1 mean less regularization.\n\n%% Plot a slice of brain showing GLMsingle outputs\n\n% We are going to plot several outputs from the FIT_HRF_GLMdenoise_RR GLM,\n% which contains the full set of GLMsingle optimizations.\n\nslice = 1;\n\n% we will plot betas, R2, optimal HRF indices, and the voxel frac values\nval2plot = {'modelmd';'R2';'HRFindex';'FRACvalue'};\ncmaps = {cmapsign2;hot;jet;copper};\n\nfigure(3);clf\n\nfor v = 1 : length(val2plot)\n    \n    f=subplot(2,2,v);\n    \n    if contains('modelmd',val2plot{v})\n        % When plotting betas, for simplicity just average across all image\n        % presentations This will yield a summary of whether voxels tend to\n        % increase or decrease their activity in response to the\n        % experimental stimuli (similar to outputs from an ONOFF GLM)\n        imagesc(nanmean(models.FIT_HRF_GLMdenoise_RR.(val2plot{v})(:,:,slice),4),[-5 5]); axis off image;\n        title('Average GLM betas (750 stimuli)')\n   \n    else\n        % Plot all other voxel-wise metrics as outputted from GLMsingle\n        imagesc(models.FIT_HRF_GLMdenoise_RR.(val2plot{v})(:,:,slice)); axis off image;\n        title(val2plot{v})\n        \n    end\n    \n    colormap(f,cmaps{v})\n    colorbar\n    set(gca,'FontSize',15)\nend\n\nset(gcf,'Position',[418   412   782   605])\n\n%% Run a baseline GLM to compare with GLMsingle\n\n% Additionally, for comparison purposes we are going to run a standard GLM\n% without HRF fitting, GLMdenoise, or ridge regression regularization. We\n% will change the default settings by using the \"opt\" structure.\nopt.wantlibrary = 0; % switch off HRF fitting\nopt.wantglmdenoise = 0; % switch off GLMdenoise\nopt.wantfracridge = 0; % switch off ridge regression\nopt.wantfileoutputs = [0 1 0 0];\nopt.wantmemoryoutputs = [0 1 0 0];\n\n% If these outputs don't already exist, we will perform the call to\n% GLMestimatesingletrial.m; otherwise, we will just load from disk.\nif ~exist(fullfile(outputdir, 'GLMbaseline', 'TYPEB_FITHRF.mat'),'file')\n    \n    [ASSUME_HRF] = GLMestimatesingletrial(design,data,stimdur,tr,[outputdir '/GLMbaseline'],opt);\n    models.ASSUME_HRF = ASSUME_HRF{2};\n    \nelse\n    \n    % Note that even though we are loading TYPEB_FITHRF betas, HRF fitting\n    % has been turned off and this struct field will thus contain the\n    % outputs of a GLM fit using the canonical HRF.\n    results = load([outputdir '/GLMbaseline/TYPEB_FITHRF.mat']);\n    models.ASSUME_HRF = results;\n    \nend\n\n% We assign outputs from GLMestimatesingletrial to \"models\" structure.\n% Again, results{1} contains GLM estimates from an ONOFF model so we are\n% not going to extract it.\n\n%%\n\n% Now, \"models\" variable holds solutions for 4 GLM models\ndisp(fieldnames(models))\n\n%% Get indices of repeated conditions to use for reliability calculations\n\n% To compare the results of different GLMs we are going to calculate the\n% voxel-wise split-half reliablity for each model. Reliability values\n% reflect a correlation between beta weights for repeated presentations of\n% the same conditions. In short, we are going to check how\n% reliable/reproducible are the single trial responses to repeated\n% conditions estimated with each GLM type.\n\n% This NSD scan session has a large number of images that are just shown\n% once during the session, some images that are shown twice, and a few that\n% are shown three times. In the code below, we are attempting to locate the\n% indices in the beta weight GLMsingle outputs modelmd(x,y,z,trials) that\n% correspond to repeated images. Here we only consider stimuli that have\n% been presented at least twice. For the purpose of the example we ignore\n% the 3rd repetition of the stimulus.\n\n% Consolidate design matrices\ndesignALL = cat(1,design{:});\n\n% Construct a vector containing 1-indexed condition numbers in\n% chronological order.\n\ncorder = [];\nfor p=1:size(designALL,1)\n    if any(designALL(p,:))\n        corder = [corder find(designALL(p,:))];\n    end\nend\n\n%%\n\n% Let's take a look at the first few entries\ncorder(1:3)\n\n% Note that [375 497 8] means that the first stimulus trial involved\n% presentation of the 375th condition, the second stimulus trial involved\n% presentation of the 497th condition, and so on.\n\n%%\n\n% In order to compute split-half reliability, we have to do some indexing.\n% we want to find images with least two repetitions and then prepare a\n% useful matrix of indices that refer to when these occur.\nrepindices = [];  % 2 x images containing stimulus trial indices.\n\n% The first row refers to the first presentation; the second row refers to\n% the second presentation.\nfor p=1:size(designALL,2)  % loop over every condition\n    temp = find(corder==p);\n    if length(temp) >= 2\n        repindices = cat(2,repindices,[temp(1); temp(2)]);  % note that for images with 3 presentations, we are simply ignoring the third trial\n    end\nend\n\n% Let's take a look at a few entries\nrepindices(:,1:3)\n\n% Notice that the first condition is presented on the 217th stimulus trial\n% and the 486th stimulus trial, the second condition is presented on the\n% 218th and 621st stimulus trials, and so on.\n\nfprintf('There are %i repeated images in the experiment \\n',length(repindices))\n\n% Now, for each voxel we are going to correlate beta weights describing the\n% response to images presented for the first time with beta weights\n% describing the response from the repetition of the same image. With 136\n% repeated conditions, the correlation for each voxel will reflect the\n% relationship between two vectors with 136 beta weights each.\n\n%% Compute median split-half reliability for each GLM version\n\n% Finally, let's compute split-half reliability. We are going to loop\n% through our 4 models and calculate split-half reliability for each of\n% them.\n\n% We first arrange models from least to most sophisticated (for\n% visualization purposes)\nmodel_names = fieldnames(models);\nmodel_names = model_names([4 1 2 3]);\n\n% Create output variable for reliability values\nvox_reliabilities = cell(1,length(models));\n\n% For each GLM...\nfor m = 1 : length(model_names)\n    \n    % Get the GLM betas\n    betas = models.(model_names{m}).modelmd(:,:,:,repindices);  % use indexing to pull out the trials we want\n    betas_reshaped = reshape(betas,size(betas,1),size(betas,2),size(betas,3),2,[]);  % reshape to X x Y x Z x 2 x CONDITIONS\n    \n    % compute reliabilities using an efficient (vectorized) utility\n    % function\n    vox_reliabilities{m} = calccorrelation(betas_reshaped(:,:,:,1,:),betas_reshaped(:,:,:,2,:),5);\n    \n    % Note that calccorrelation.m is a utility function that computes\n    % correlations in a vectorized fashion (for optimal speed).\n    \nend\n\n%% Compare visual voxel reliabilities between beta versions\n\nfigure(4);clf\nsubplot(1,2,1);\ncmap = [0.2314    0.6039    0.6980\n    0.8615    0.7890    0.2457\n    0.8824    0.6863         0\n    0.9490    0.1020         0];\n\n% For each GLM type we calculate median reliability for voxels within the\n% visual ROI and plot it as a bar plot.\nfor m = 1 : 4\n    bar(m,nanmedian(vox_reliabilities{m}(ROI==1)),'FaceColor','None','Linewidth',3,'EdgeColor',cmap(m,:)); hold on\nend\nylabel('Median reliability')\nlegend(model_names,'Interpreter','None','Location','NorthWest')\nset(gca,'Fontsize',16)\nset(gca,'TickLabelInterpreter','none')\nxtickangle(0)\nxticks([])\nylim([0.1 0.2])\nset(gcf,'Position',[418   412   782   605])\ntitle('Median voxel split-half reliability of GLM models')\n\nsubplot(1,2,1);\n\n% Comparison is the final output (FIT_HRF_GLMDENOISE_RR) vs. the baseline\n% GLM (ASSUME_HRF)\nvox_reliability = vox_reliabilities{4} - vox_reliabilities{1};\nunderlay = data{1}(:,:,:,1);\nROI(ROI~=1) = NaN;\noverlay = vox_reliability;\n\nunderlay_im = cmaplookup(underlay,min(underlay(:)),max(underlay(:)),[],gray(256));\noverlay_im = cmaplookup(overlay,-0.3,0.3,[],cmapsign2);\n\nmask = ROI==1;\n\nsubplot(1,2,2);\nhold on\nimagesc(underlay_im);\nimagesc(overlay_im, 'AlphaData', mask);\nhold off\naxis image\ncolormap(cmapsign2)\nc = colorbar;\nc.Ticks = [0 0.5 1];\nc.TickLabels = {'-0.3';'0';'0.3'};\ntitle('change in nsdgeneral voxel reliability** due to GLMsingle (\\Delta{\\itr})')\nset(gca,'Fontsize',16)\nxlabel('**plotting (FITHRF_GLMDENOISE_RR - ASSUMEHRF) reliabilities','Interpreter','none','FontSize',12);\nxticks([])\nyticks([])\n\nset(gcf,'Position',[36 343 1116 674])\n\n% Notice that there is systematic increase in reliability moving from the\n% first to the second to the third to the final fourth version of the GLM\n% results. These increases reflect, respectively, the addition of HRF\n% fitting, the derivation and use of data-driven nuisance regressors, and\n% the use of ridge regression as a way to regularize the instability of\n% closely spaced experimental trials. Depending on one's experimental\n% goals, it is possible with setting of option flags to activate a subset\n% of these analysis features.\n%\n% Also, keep in mind that in the above figure, we are simply showing the\n% median as a metric of the central tendency (you may want to peruse\n% individual voxels in scatter plots, for example).\n", "meta": {"author": "cvnlab", "repo": "GLMsingle", "sha": "e37bbc9f26362094e3a574f8d6c2156f5fa92077", "save_path": "github-repos/MATLAB/cvnlab-GLMsingle", "path": "github-repos/MATLAB/cvnlab-GLMsingle/GLMsingle-e37bbc9f26362094e3a574f8d6c2156f5fa92077/matlab/examples/example1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22773539795792522}}
{"text": "% Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich, \n%   Switzerland\n%   You can contact the author at <titus at ifi dot uzh dot ch>\n% Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing,\n%   Georgia Institute of Technology, Atlanta, GA, USA\n% Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich, \n%   Switzerland\n%\n% This file is part of dslam_open.\n%\n% dslam_open is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% dslam_open is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with dslam_open. If not, see <http://www.gnu.org/licenses/>.\n\nfunction [decentr_state, dgs_stats, final_increments, ...\n    final_increment_times, opt_handle, final_accuracy_measurements] = ...\n    wrapUpOptimization(...\n    decentr_state, opt_handle, distributed_mapper_location, params, ...\n    final_time)\n\nt = tic;\n% Collect data from still running optimization and launch last one.\n[decentr_state, opt_handle, dgs_stats, opt_increment] = ...\n    manageAsyncGaussSeidel(...\n    decentr_state, opt_handle, distributed_mapper_location, true, ...\n    params.opt_max_iters, true);\nt0 = toc(t);\nfor i = 1:numel(dgs_stats)\n    dgs_stats{i}.end_time = final_time + t0;\nend\nfinal_increments = ...\n    {cat(3, opt_increment, zeros(size(opt_increment)), ...\n    zeros(size(opt_increment)))};\nfinal_increment_times = [final_time + t0];\n[accuracy_measurement, decentr_state] = ...\n    evalAccuracy(...\n    decentr_state, opt_handle, final_time + t0);\nfinal_accuracy_measurements = {accuracy_measurement};\nplotDecentrState(decentr_state);\npause(0.0001);\n\n% Collect last one (final launch will be ignored).\n[decentr_state, ~, last_dgs_stats, opt_increment] = ...\n    manageAsyncGaussSeidel(...\n    decentr_state, opt_handle, distributed_mapper_location, true, ...\n    params.opt_max_iters, false);\nt1 = toc(t);\nfor i = 1:numel(last_dgs_stats)\n    last_dgs_stats{i}.end_time = final_time + t1;\nend\ndgs_stats = [dgs_stats; last_dgs_stats];\nfinal_increments = [final_increments;\n    cat(3, opt_increment, zeros(size(opt_increment)), ...\n    zeros(size(opt_increment)))];\nfinal_increment_times = [final_increment_times; final_time + t1];\n[accuracy_measurement, decentr_state] = ...\n    evalAccuracy(decentr_state, opt_handle, final_time + t1);\nfinal_accuracy_measurements = [final_accuracy_measurements; ...\n    accuracy_measurement];\nplotDecentrState(decentr_state);\npause(0.0001);\n\nend\n\n", "meta": {"author": "uzh-rpg", "repo": "dslam_open", "sha": "3428893cffa5e832e8d51a6f3e18213b47205a83", "save_path": "github-repos/MATLAB/uzh-rpg-dslam_open", "path": "github-repos/MATLAB/uzh-rpg-dslam_open/dslam_open-3428893cffa5e832e8d51a6f3e18213b47205a83/dslam/matlab/wrapUpOptimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2277353913829076}}
{"text": "%CODEGENERATOR.GENSLBLOCKINERTIA Generate Simulink block for inertia matrix\n%\n% cGen.genslbgenslblockinertia() generates a robot-specific Simulink block to compute\n% robot inertia matrix.\n%\n% Notes::\n% - Is called by CodeGenerator.geninertia if cGen has active flag genslblock\n% - The Inertia matrix is stored row by row to avoid memory issues.\n% - The Simulink block recombines the the individual blocks for each row.\n% - The Simulink blocks are generated and stored in a robot specific block \n%   library cGen.slib in the directory cGen.basepath.\n%\n% Author::\n%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)\n%\n% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia.\n\n% Copyright (C) 2012-2014, by Joern Malzahn\n%\n% This file is part of The Robotics Toolbox for Matlab (RTB).\n%\n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n%\n% The code generation module emerged during the work on a project funded by\n% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully \n% acknowledge the financial support.\n\nfunction genslblockinertia(CGen)\n\n%% Open or create block library\nbdclose('all')                                                              % avoid problems with previously loaded libraries\nload_system('simulink');\nif ~(exist([CGen.slibpath,simulinkext]) == 2)                                  % Create new block library if none exists\n CGen.createnewblocklibrary;\nend\nopen_system(CGen.slibpath);\nset_param(CGen.slib,'lock','off');\n\nq = CGen.rob.gencoords;\n\n%% Generate Inertia Block\nCGen.logmsg([datestr(now),'\\tGenerating Simulink Block for the robot inertia matrix\\n']);\nnJoints = CGen.rob.n;\n\nCGen.logmsg([datestr(now),'\\t\\t... enclosing subsystem ']);\nsymname = 'inertia';\nInertiaBlock = [CGen.slib,'/',symname];\n    if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname))                    % Delete previously generated inertia matrix block\n        delete_block(InertiaBlock);\n        save_system;\n    end\n% Subsystem in which individual rows are concatenated\nadd_block('built-in/SubSystem',InertiaBlock);                               % Add new inertia matrix block\nadd_block('simulink/Math Operations/Matrix Concatenate'...\n    , [InertiaBlock,'/inertia']...\n    , 'NumInputs',num2str(nJoints)...\n    , 'ConcatenateDimension','1');\nadd_block('simulink/Sinks/Out1',[InertiaBlock,'/out']);\nadd_block('simulink/Sources/In1',[InertiaBlock,'/q']);\nadd_line(InertiaBlock,'inertia/1','out/1');\nCGen.logmsg('\\t%s\\n',' done!');\n\nfor kJoints = 1:nJoints\n    CGen.logmsg([datestr(now),'\\t\\t... Embedded Matlab Function Block for joint ',num2str(kJoints),': ']);\n    \n    % Generate Embedded Matlab Function block for each row\n    symname = ['inertia_row_',num2str(kJoints)];\n    fname = fullfile(CGen.sympath,[symname,'.mat']);\n    \n    if exist(fname,'file')\n        tmpStruct = load(fname);\n    else\n        error ('genslblockinertia:SymbolicsNotFound','Save symbolic expressions to disk first!')\n    end\n    \n    blockaddress = [InertiaBlock,'/',symname];\n    if doesblockexist(CGen.slib,symname)\n        delete_block(blockaddress);\n        save_system;\n    end\n    \n    CGen.logmsg('%s',' block creation');\n    symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q});\n    \n    \n    % connect output\n    CGen.logmsg('%s',', output wiring');\n    if ( verLessThan('matlab','7.11.0.584') ) && ( isequal(tmpStruct.(symname),zeros(1,nJoints)) )\n        % There is a bug in earlier Matlab versions. If the symbolic\n        % vector is a zero vector, then the Simulink Embedded Matlab\n        % Function block outputs a scalar zero. We need to concatenate\n        % a row vector of zeros here, which we have to construct on our\n        % own.\n        add_block('simulink/Math Operations/Matrix Concatenate'...              % Use a matrix concatenation block ...\n            , [InertiaBlock,'/DimCorrection',num2str(kJoints)]...               % ... named with the current row number ...\n            , 'NumInputs',num2str(nJoints),'ConcatenateDimension','2');         % ... intended to concatenate zero values for each joint ...\n        % ... columnwise. This will circumvent the bug.\n        \n        for iJoints = 1:nJoints                                                 % Connect signal lines from the created block (which outputs\n            add_line(InertiaBlock...                                            % a scalar zero in this case) with the bugfix block.\n                , [symname,'/1']...\n                , ['DimCorrection',num2str(kJoints),'/', num2str(iJoints)]);\n        end\n        \n        add_line(InertiaBlock,['DimCorrection',num2str(kJoints)...              % Connect the fixed row with other rows.\n            , '/1'],['inertia/', num2str(kJoints)]);\n        \n    else\n        add_line(InertiaBlock,[symname,'/1']...          % In case that no bug occurs, we can just connect the rows.\n            , ['inertia/', num2str(kJoints)]);\n    end\n    \n    % Connect inputs\n    CGen.logmsg('%s',', input wiring');\n    add_line(InertiaBlock,'q/1',[symname,'/1']);\n    CGen.logmsg('\\t%s\\n','row complete!');\nend\naddterms(InertiaBlock); % Add terminators where needed\ndistributeblocks(InertiaBlock);\nCGen.logmsg([datestr(now),'\\tInertia matrix block complete\\n']);\n\n\n%% Built inverse Inertia matrix block\nCGen.logmsg([datestr(now),'\\tGenerating Simulink Block for the inverse robot inertia matrix\\n']);\nCGen.logmsg([datestr(now),'\\t\\t... enclosing subsystem ']);\n% block address\nsymname = 'invinertia';\ninvInertiaBlock = [CGen.slib,'/',symname];\n% remove any existing blocks\n    if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname))                    % Delete previously generated block\n        delete_block(invInertiaBlock);\n        save_system;\n    end\nadd_block('built-in/SubSystem',invInertiaBlock);\nCGen.logmsg('\\t%s\\n',' done!');\n\n% matrix inversion\nCGen.logmsg([datestr(now),'\\t\\t... matrix inversion block ']);\nadd_block('simulink/Math Operations/Product',[invInertiaBlock,'/inverse']); % Use a product block...\nset_param([invInertiaBlock,'/inverse'],'Inputs','/');                       % ... with single input '/'...\nset_param([invInertiaBlock,'/inverse'],'Multiplication','Matrix(*)');       % ... and matrix multiplication\nCGen.logmsg('\\t%s\\n',' done!');\n\n% wire the input and output\nCGen.logmsg([datestr(now),'\\t\\t... input and output ']);\nadd_block(InertiaBlock,[invInertiaBlock,'/inertiaMatrix']);\nadd_block('simulink/Sources/In1',[invInertiaBlock,'/q']);\nadd_block('simulink/Sinks/Out1',[invInertiaBlock,'/out']);\n\n\n% wire the blocks among each other\nCGen.logmsg('and internal wiring');\nadd_line(invInertiaBlock,'q/1','inertiaMatrix/1');\nadd_line(invInertiaBlock,'inertiaMatrix/1','inverse/1');\nadd_line(invInertiaBlock,'inverse/1','out/1');\nCGen.logmsg('\\t%s\\n',' done!');\n\n% add terminators where necessary\naddterms(invInertiaBlock);\ndistributeblocks(invInertiaBlock);\nCGen.logmsg([datestr(now),'\\tInverse inertia matrix block complete.\\n']);\n\n%% Cleanup\n% Arrange blocks\ndistributeblocks(CGen.slib);\n\n% Lock, save and close library\nset_param(CGen.slib,'lock','on');\nsave_system(CGen.slib,CGen.slibpath);\nclose_system(CGen.slib);\n\nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/@CodeGenerator/genslblockinertia.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22772290882762503}}
{"text": "function ConvHDRvtoLDRv(hdrv, filenameOutput, fstops, ldrv_gamma, ldrv_quality, ldrv_video_profile)\n%\n%\n%        ConvHDRvtoLDRv(hdrv, filenameOutput, fstops, ldrv_gamma, ldrv_quality, ldrv_video_profile)\n%\n%        \n%\n%        Input:\n%           -hdrv:\n%           -filenameOutput:\n%           -fstops:\n%           -ftops:\n%           -ldrv_gamma:\n%           -ldrv_quality:\n%           -ldrv_video_profile:\n%\n%\n%     Copyright (C) 2016  Francesco Banterle\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n\nif(~exist('ldrv_gamma', 'var'))\n    ldrv_gamma = 2.2;\nend\n\nif(~exist('ldrv_quality', 'var'))\n    ldrv_quality = 95;\nend\n\nif(~exist('ldrv_video_profile', 'var'))\n    ldrv_video_profile = 'MPEG-4';\nend\n\nif(ldrv_gamma < 0)\n    bsRGB = 1;\nelse\n    bsRGB = 0;\nend\n\nif(isempty(fstops))\n    errir('ConvHDRvtoLDRv: fstops cannot be empty!');\nend\n\nname = RemoveExt(filenameOutput);\next = fileExtension(filenameOutput);\n\nbVideo = 0;\nwriterObj = 0;\n\nif(strcmp(ext, 'avi') == 1 | strcmp(ext, 'mp4') == 1)\n    bVideo = 1;\n    writerObj = VideoWriter(filenameOutput, ldrv_video_profile);\n    writerObj.FrameRate = hdrv.FrameRate;\n    writerObj.Quality = ldrv_quality;\n    open(writerObj);\nend\n\nif(bVideo == 0)\n    mkdir([name,'_img']);\nend\n\nhdrv = hdrvopen(hdrv, 'r');\n\nn = length(fstops);\n\nfor i=1:hdrv.totalFrames\n    disp(['Processing frame ', num2str(i)]);\n    [frame, hdrv] = hdrvGetFrame(hdrv, i);\n        \n    frame(frame < 0) = 0;\n       \n    j = mod(i, n) + 1;\n   \n    frameOut = frame * 2^fstops(j);\n    \n    %Gamma/sRGB encoding\n    if(bsRGB)\n        frameOut = ClampImg(ConvertRGBtosRGB(frameOut, 0), 0, 1);\n    else\n        frameOut = ClampImg(GammaTMO(frameOut, ldrv_gamma, 0, 0), 0, 1);\n    end\n      \n    %Storing \n    if(bVideo)\n        writeVideo(writerObj, frameOut);\n    else\n        nameOut = [name, '_img/frame_', sprintf('%.10d',i), '.', ext];\n        imwrite(frameOut, nameOut);\n\n        nameOut = [name, '_img/frame_', sprintf('%.10d',i), '.exr'];\n        hdrimwrite(frame, nameOut);\n    end    \nend\n\nhdrvclose(hdrv);\n    \nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/BatchFunctions/ConvHDRvtoLDRv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.22772114278921313}}
{"text": "\n\n        \n\nfunction extra_data_info=my_net_forward(net_info, work_info_batch, data_info, net_run_config, extra_output_layer_idxes)\n\n           \n    gpu_mode=net_run_config.use_gpu;\n    if gpu_mode\n      if ~net_info.ref.net_on_gpu\n           my_move_net(net_info, 'gpu') ;\n      end\n      data_info.ref.output_info_layers{1}=...\n          move_output_info_gpu(data_info.ref.output_info_layers{1});\n    else\n      assert(~net_info.ref.net_on_gpu);\n      data_info.ref.output_info_layers{1}=...\n          move_output_info_cpu(data_info.ref.output_info_layers{1});\n    end\n    \n    extra_data_info=do_forward(net_info, work_info_batch, data_info, net_run_config, extra_output_layer_idxes);\n    \n    if gpu_mode\n        if ~net_info.ref.net_stay_on_gpu\n            my_move_net(net_info, 'cpu') ;\n        end\n    end\n    \n       \nend\n\n\n\nfunction extra_data_info=do_forward(net_info, work_info_batch, data_info, net_run_config, extra_output_layer_idxes)\n\n\nlayer_num = numel(net_info.ref.layers) ;\ngpu_mode = net_run_config.use_gpu;\n\n\nif gpu_mode && net_run_config.sync\n    wait(gpuDevice) ;\nend\n\n    \n\nassert(check_valid_net_output(data_info.ref.output_info_layers{1}));\n\n\nbp_turn_on_layer=-1;\ndisableDropout=true;\nkeep_layer_output=false;\n\n\n\ndo_bp_current_net=check_do_bp_current_net(work_info_batch, net_run_config, net_info);\nif do_bp_current_net\n    bp_start_layer=net_info.ref.bp_start_layer;\n    bp_turn_on_layer=bp_start_layer;\nend\n\ndata_info.ref.need_bp=do_bp_current_net;\n\n\n\nextra_output_layer_flags=false(layer_num, 1);\nif ~isempty(extra_output_layer_idxes)\n    extra_output_layers=cell(layer_num, 1);\n    extra_output_layer_flags(extra_output_layer_idxes)=true;\nelse\n    extra_output_layers=[];\nend\n\n\n\n\nfor layer_idx=1:layer_num\n        \n    input_info=data_info.ref.output_info_layers{layer_idx};\n    l = net_info.ref.layers{layer_idx} ;\n    is_simple_layer= ~strcmp(l.type, 'my_custom');\n   \n   \n    if bp_turn_on_layer==layer_idx\n        disableDropout=false;\n        keep_layer_output=true;\n    end\n    \n  \n      \n\n        if is_simple_layer\n            output_info=data_info.ref.output_info_layers{layer_idx+1};\n            assert(~input_info.is_group_data);\n            assert(~output_info.is_group_data);\n            switch l.type\n                case 'conv'\n                    input_size=size(input_info.x);\n                    filter_size=size(l.filters);\n                    if filter_size(3)~=input_size(3)\n                        \n                        disp('filter_size:');\n                        disp(filter_size);\n                        disp('input_size:');\n                        disp(input_size);\n                        error('filter size not match input size!');\n                    end\n                    if any(filter_size(1:2)>input_size(1:2))\n                        error('filter size larger than the input size!');\n                    end\n                  output_info.x = vl_nnconv(input_info.x, l.filters, l.biases, 'pad', l.pad, 'stride', l.stride) ;\n                case 'pool'\n                    input_size=size(input_info.x);\n                    pool_size=l.pool;\n                    if any(pool_size(1:2)>input_size(1:2))\n                        error('pool size larger than the input size!');\n                    end\n                    output_info.x = vl_nnpool(input_info.x, l.pool, 'pad', l.pad, 'stride', l.stride, 'method', l.method) ;\n                case 'normalize'\n                  output_info.x = vl_nnnormalize(input_info.x, l.param) ;\n                case 'softmax'\n                  output_info.x = vl_nnsoftmax(input_info.x) ;\n                case 'relu'\n                  output_info.x = vl_nnrelu(input_info.x) ;\n                case 'noffset'\n                  output_info.x = vl_nnnoffset(input_info.x, l.param) ;\n                case 'dropout'\n                  \n                  if disableDropout\n                    output_info.x = input_info.x ;\n                  else\n                    [output_info.x, output_info.aux] = vl_nndropout(input_info.x, 'rate', l.rate) ;\n                  end\n\n                otherwise\n                    error('Unknown layer type %s', l.type) ;\n            end\n        else\n            \n            output_info= l.forward_fn(input_info, l, work_info_batch) ;\n                       \n            \n        end\n\n        if isempty(output_info)\n            break;\n        end\n        output_info.forward_finished=true;\n\n        \n    if ~keep_layer_output && layer_idx < layer_num - 1\n      data_info.ref.output_info_layers{layer_idx}=[];\n      input_info=[];\n    end\n\n    if gpu_mode\n        if ~net_info.ref.data_stay_on_gpu\n            if ~isempty(input_info)\n                input_info=move_output_info_cpu(input_info);\n                data_info.ref.output_info_layers{layer_idx}=input_info;\n            end\n        end\n    end\n      \n    if gpu_mode && net_run_config.sync\n        wait(gpuDevice) ;\n    end\n\n    data_info.ref.output_info_layers{layer_idx+1}=output_info;\n     \n    if extra_output_layer_flags(layer_idx)\n        extra_output_layers{layer_idx}=output_info;\n    end\n    \nend\n\n\nif gpu_mode && ~net_info.ref.data_stay_on_gpu\n    output_info=data_info.ref.output_info_layers{end};\n    output_info=move_output_info_cpu(output_info);\n    data_info.ref.output_info_layers{end}=output_info;\nend\n       \n\nextra_data_info=[];\nextra_data_info.output_layers=extra_output_layers;\n\n\nend\n\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/my_net_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.22762493794222177}}
{"text": "% :Usage:\n% ::\n%\n%    [c, alld] = getVertexColors(xyz, v, actcolor, [basecolor], [mind], 'vert', [xyz2], [actcolor2], 'vert', [xyz3], [actcolor3])\n%\n% given a point list of XYZ mm coordinates (3 columns)\n% and a list of vertices in an isosurface, \n% returns FaceVertexCData color values for brain near points and brain not near points.\n% c is vertex color specification, 3 columns indicating RGB values\n%\n% Inputs:\n% xyz   a 3-vol list of vertices to color\n% v     can be a matrix of vertices\n%       or a handle to a patch object containing vertices\n%       if it's a handle, this function sets the color to interp\n%       and the FaceVertexCData to the color matrix c\n% actcolor\n%       [r g b] activation color\n% basecolor\n%       [r g b] baseline color - optional.\n% mind  optional - min distance to color vertex\n%       Vertices within mind of an xyz coordinate will be colored\n% colorscale\n%       optional.  followed by vector of values by which to multiply input\n%       color\n%       these are scaled to be between .3 and one.\n%       if entered, this will make the colors vary by, for example, Z score\n%       so Z-scores are an acceptable input.\n%       cscale should be in the same coordinate order as xyz\n%       for ADDITIONAL clusters, repeat the 'colorscale', Z argument pair in the function call\n%\n%       YOU CAN ALSO pass true RGB values for each xyz coordinate in: 'colorscale', rgblist, \n%       IF cscale is a 3-vector, it specifies the ACTUAL colors, and is not scaled to .3 - 1\n%\n%\n% following basecolor and mind:\n% additional xyz coordinate lists, with syntax:\n% 'vert', xyz2 [your xyz input], [r g b] color for xyz plot\n%\n% also, you can enter 'ovlcolor' followed by [r g b] for overlaps between xyz sets\n%   colors will ONLY appear in the overlap color if they share actual coordinates in common, \n%   not necessarily if surface vertices are within the specified distance from both sets of coords.\n%\n% to get a good brain surface, try this:\n%figure\n%p = patch('Faces', faces, 'Vertices', vertices, 'FaceColor', [.5 .5 .5], ...\n% 'EdgeColor', 'none', 'SpecularStrength', .2, 'FaceAlpha', 1, 'SpecularExponent', 200);\n%lighting gouraud;camlight right\n%axis image; myLight = camlight(0, 0);set(myLight, 'Tag', 'myLight');\n%set(gcf, 'WindowButtonUpFcn', 'lightFollowView');lightfollowview\n%drawnow\n%\n% ..\n% by Tor Wager  August 25, 2002\n% ..\n\n\nfunction [c, alld] = getVertexColors_old_backup(xyz, v, actcolor, varargin)\n\n    mind = 3;\n    basecolor = [.5 .5 .5];\n    alld = [];\n    xyza = xyz;\n    cscale = [];\n    allda = [];\n    vv = [];\n\n    % -----------------------------------------------------------------------\n    % * set up input arguments\n    % -----------------------------------------------------------------------\n    doalph = 0; cscale = [];\n    if ~isempty(varargin), basecolor = varargin{1}; end\n    if length(varargin) > 1, mind = varargin{2}; end\n    ind = 1;\n    for i = 3:length(varargin)\n        if strcmp(varargin{i}, 'vert')\n            vv{ind} = varargin{i+1};\n\n            % intersections\n            xyzb{ind, 1} = intersect(xyz, vv{ind}, 'rows');\n            for j = ind-1:-1:1\n                xyzb{ind, j} = intersect(vv{j}, vv{ind}, 'rows');\n                xyza = intersect(xyza, xyzb{ind, j}, 'rows');\n            end\n\n            cc{ind} = varargin{i+2};\n            ind = ind+1;\n        elseif strcmp(varargin{i}, 'ovlcolor')\n            ocol = varargin{i+1};\n        elseif strcmp(varargin{i}, 'alphaone')\n            doalph = 1;\n        elseif strcmp(varargin{i}, 'allcolor')\n            acol = varargin{i+1};\n        elseif strcmp(varargin{i}, 'colorscale')\n            cscale{end+1} = varargin{i+1};\n            if min(size(cscale{end})) == 1\n                % scale colors (may be necessary) - only if single vector, not RGB values\n                cscale{end} = cscale{end} ./ max(cscale{end});\n            end\n            if any(cscale{end} < 0), error('Some color scale values are less than zero.'), end\n\n        end\n    end\n\n    if isempty(cscale)\n        cscale{1} = ones(size(xyz, 1), 1);\n        for i = 1:length(vv)    % additional vertices\n            cscale{end+1} = ones(size(vv{i}, 1), 1);\n        end\n    end\n\n    %if ~isempty(cscale) don't need this.\n    %    if length(cscale) < length(vv)\n    %        cscale{length(vv)} = [];\n    %    end\n    %end\n\n\n    if ishandle(v)\n        p = v;\n        v = get(p, 'Vertices');\n        c = get(p, 'FaceVertexCData');   % get existing colors from surface\n    else\n        % uh-oh, not a handle!\n        warning('Figure handle missing: Figure was closed?')\n        p = findobj('Type', 'patch');\n        v = get(p(1), 'Vertices');\n        c = get(p, 'FaceVertexCData');   % get existing colors from surface\n    end\n\n    bad = any(size(c) - size(v));\n    if bad\n        c = repmat(basecolor, size(v, 1), 1);\n    end\n\n\n\n\n    % -----------------------------------------------------------------------\n    % * main xyz color change\n    % -----------------------------------------------------------------------\n\n    t1 = clock;\n    fprintf('Main color vertices: ')\n\n    c = change_colors(c, xyz, v, mind, cscale, actcolor, p);\n    drawnow();\n\n\n\n    % -----------------------------------------------------------------------\n    % * additional optional vertices\n    % -----------------------------------------------------------------------\n    if exist('vv', 'var')\n        for j = 1:length(vv)\n            fprintf('\\nAdditional vertices: ')\n\n            % cscale:\n            % pass in vector of ones length coords for solid color\n            % or scalar vals for color mapping\n            % pass in cell array\n\n            % cc{j} is color, cscale{j+1} is scaling vals for coords\n            c = change_colors(c, vv{j}, v, mind, cscale(j+1), cc{j}, p);\n        end\n        drawnow();\n    end\n\n\n    % -----------------------------------------------------------------------\n    % * figure out which vertices should be colored with ocol (overlap color)\n    % -----------------------------------------------------------------------\n\n    if exist('ocol', 'var') && exist('xyzb', 'var') && ~isempty(cat(1, xyzb{:}))\n\n        alld = zeros(size(v, 1), 1);  % keeps track of overlap vertices\n        xyzb = cat(1, xyzb{:});\n\n        t1 = clock;\n        fprintf('\\nOverlap vertices: ')\n\n        cscaletmp = {ones(size(xyzb, 1), 1)};\n        c = change_colors(c, xyzb, v, mind, cscaletmp, ocol, p);\n        drawnow();\n\n        fprintf('%3.0f.done in %3.0f s\\n', i, etime(clock, t1))\n    end\n\n\n    % -----------------------------------------------------------------------\n    % * figure out which vertices should be colored with acol (all color)\n    % -----------------------------------------------------------------------\n    if exist('acol', 'var') && ~isempty(xyza) && length(vv)>1\n\n        xyzall = xyza;\n        for i = 2:length(vv)\n            xyzall = intersect(xyzall, vv{i}, 'rows');\n        end\n\n        t1 = clock;\n        fprintf('\\nAll overlap vertices: ')\n\n        cscaletmp = {ones(size(xyzall, 1), 1)};\n        c = change_colors(c, xyzall, v, mind, cscaletmp, acol, p);\n        drawnow();\n\n        fprintf('%3.0f.done in %3.0f s\\n', i, etime(clock, t1))\n\n    end\n\n\n    % -----------------------------------------------------------------------\n    % * final color change\n    % -----------------------------------------------------------------------\n\n\n    if exist('p', 'var')\n        set(p, 'FaceColor', 'interp')\n        set(p, 'FaceVertexCData', c)\n        drawnow()\n    end\n\n    %lightFollowView\nend\n\n\n\n\n\n\n% -----------------------------------------------------------------------\n% * SUB-FUNCTIONS\n% -----------------------------------------------------------------------\n\n\n\nfunction c = change_colors(c, coords, v, mind, cscale, actcolor, p)\n\n    if isempty(coords), disp('Coords is empty. Nothing to plot.'), return, end\n\n    % select vertices that are even close\n    cmax = max(coords, [], 1);\n    cmin = min(coords, [], 1);\n    fprintf('%3.0f vertices.  selecting: ', size(v, 1));\n    wh = any(v - repmat(cmax, size(v, 1), 1) > mind, 2);\n    wh2 = any(repmat(cmin, size(v, 1), 1) - v > mind, 2);\n\n    % list vertices to test and possibly change color\n    whverts = (1:size(v, 1))';\n    whverts(wh | wh2) = [];     % vertex indices in big list\n    smallv = v;\n    smallv(wh | wh2,:) = [];     % vertices--restricted list\n\n    fprintf('%3.0f\\n', size(whverts, 1));\n\n    if isempty(smallv), return, end\n\n    % select coords that are even close\n    % ----------------------------------\n    cmax = max(smallv, [], 1);\n    cmin = min(smallv, [], 1);\n    fprintf('%3.0f coords.  selecting: ', size(coords, 1));\n    wh = any(coords - repmat(cmax, size(coords, 1), 1) > mind, 2);\n    wh2 = any(repmat(cmin, size(coords, 1), 1) - coords > mind, 2);\n    \n    \n    % if cscale is matrix, must select these values of cscale as well!\n    if size(cscale{1}, 1) == size(coords, 1)\n        cscale{1}(wh | wh2,:) = [];\n    end\n    \n    coords(wh | wh2,:) = [];\n    \n\n    if isempty(coords), return, end\n\n    nc = size(coords, 1);\n    fprintf('%3.0f\\n', nc);\n\n    % break up coords into list and run\n    % ----------------------------------\n    \n    % break up coords into list\n    xyz2 = {}; indx = 1;\n    for kk = 1:1000:nc\n        setwh{indx} = (kk:min(nc, kk + 1000 - 1))';\n        xyz2{indx} = coords(setwh{indx},:);\n\n        indx = indx + 1;\n    end\n\n    fprintf('Running %3.0f sets of coordinates: 000', length(xyz2));\n\n    indxval = 1;\n    wh_coords_near_surface = false(size(coords, 1), 1);\n    \n    for setno = 1:length(xyz2)\n        fprintf('\\b\\b\\b%03d', setno);\n\n        for i = 1:size(xyz2{setno}, 1)\n            % find vertices that are within range of point i in set  setno\n            vertex_indices = find_in_radius(xyz2, setno, i, smallv, mind, whverts);\n\n            % two modes: if cscale{1} is a matrix, treats as rgb values, and put in\n            % color stored in cscale.  if cscale{1} is a vector, treat it as a scaling value for actcolor\n            % In either case, indxval should index location of coordinate in FULL\n            % list (corresponding to full list in cscale)\n            \n            c = color_change_vertices(c, mind, indxval, cscale, actcolor, vertex_indices);\n\n            if ~isempty(vertex_indices), wh_coords_near_surface(indxval) = 1; end\n            \n            indxval = indxval + 1;\n        end\n\n        if exist('p', 'var')\n            set(p, 'FaceColor', 'interp')\n            set(p, 'FaceVertexCData', c)\n        end\n    end\nend\n\n\n\n\n\n\nfunction z = dist_tmp(w, p)\n\n    %\n    % if isstr(w)\n    %   switch (w)\n    %     case 'deriv', \n    %       z = '';\n    %     otherwise\n    %       error('Unrecognized code.')\n    %   end\n    %   return\n    % end\n\n    % CALCULATION\n    if nargin == 1\n        p = w;\n        w = w';\n    end\n\n    [S, R] = size(w);\n    [R2, Q] = size(p);\n    if (R ~= R2), error('Inner matrix dimensions do not match.'), end\n\n    z = zeros(S, Q);\n    if (Q<S)\n        p = p';\n        copies = zeros(1, S);\n        for q=1:Q\n            z(:,q) = sum((w-p(q+copies,:)).^2, 2);\n        end\n    else\n        w = w';\n        copies = zeros(1, Q);\n        for i=1:S\n            z(i,:) = sum((w(:,i+copies)-p).^2, 1);\n        end\n    end\n    z = sqrt(z);\n\nend\n\n\n\n\n\n\nfunction [vertex_indices, d] = find_in_radius(xyz2, setno, i, smallv, mind, whverts)\n    % output: indices of vertices in BIG list, and distances\n    \n    % get vertices v within box -- fast method\n    wh = find(all(abs(bsxfun(@minus, xyz2{setno}(i,:), smallv)) <= mind, 2));\n    d = dist_tmp(smallv(wh,:), xyz2{setno}(i,:)');\n\n    % convert back to big list\n    vertex_indices = whverts(wh(d < mind));\nend\n\n\n\n\nfunction c = color_change_vertices(c, mind, i, cscale, actcolor, vertex_indices)\n\n    % two modes: if cscale{1} is a matrix, treats as rgb values, and put in\n    % color stored in cscale\n    % if cscale{1} is a vector, treat it as a scaling value for actcolor\n    % In either case, the ith index point should correspond to the\n    % coordinate being worked on.\n\n    n = length(vertex_indices);\n\n    if n\n        if min(size(cscale{1})) > 1  % if we have rgb values rather than scaling values\n            % this occurs if heatmap = yes and colorscale = no, we pass in rgb values\n            c(vertex_indices,:) = repmat(cscale{1}(i,:), n, 1);\n        else\n            c(vertex_indices,:) = repmat(actcolor.*cscale{1}(i,:), n, 1);\n        end\n    end\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/getVertexColors_old_backup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22745864304150118}}
{"text": "%Help file for INTLAB Version 5.1\n%\n% - corrections in long toolbox (thanks to Nobito Yamamoto and Nozomu Matsuda)\n% - new function 'isspd': verify positive definiteness\n% - revision of verifylss for sparse matrices (omit eigs etc.)\n% - warning when defining complex by infsup(zinf,zsup) [overestimation, use midrad]\n% - abss replaced by mag (thanks to Arnold for proposing better naming)\n% - generation of extremely ill-conditioned matrices (randmat) improved\n% - norm delivers interval result\n% - rounding unchanged after call of any INTLAB routine\n%\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/INTLAB_Version_5_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22745863652736745}}
{"text": "function dx = f_Wrapper(u,x,p,parIdx)\n% dx = f(u,x,p)\n    if coder.target('MATLAB') \n        % Specify your own f(u,x,p) function for normal excution\n    else \n        % Specify your own f(u,x,p) function for code generation\n        coder.cinclude('iiwa14.h');\n        q = x(1:7,1);\n        qd = x(8:end,1);\n        qdd = zeros(7,1);\n        tau = u(1:7,1);\n        coder.ceval('qdd_cal',  coder.ref(q),...\n                                coder.ref(qd),...\n                                coder.ref(qdd),...\n                                coder.ref(tau),...\n                                parIdx);\n        dx  = [qd;qdd];\n    end\n    \nend", "meta": {"author": "deng-haoyang", "repo": "ParNMPC", "sha": "ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b", "save_path": "github-repos/MATLAB/deng-haoyang-ParNMPC", "path": "github-repos/MATLAB/deng-haoyang-ParNMPC/ParNMPC-ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b/RobotManipulator/f_Wrapper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22742523294005293}}
{"text": "% dtiEpilepsy\n%\n% This script is applied to compare a single subject with epilepsy (an\n% adult) with the template of comparable adults without epilepsy.  We are\n% using the SIRL20 template for the moment.\n%\n% To run this script you will need the statistics toolbox on your path.\n% This toolbox is part of our normal lab Matlab and it is part of the Unix\n% side.  We don't have it yet for license 11723 version.  We should get it.\n% \n\n% Specify and load the subject data and the atlas data\n%\n%  Does the subject need to be spatially aligned with the template? Usually\n%  this is done once for each dti scan.  If you haven't done it, you can\n%  get it done here.\ndoSpatialNorm = true;\n\n% Is there a warping needed for the B0 field?  Radiation necrosis needed\n% this, but normally we don't.  See paragraph below.  The b0Norm is only\n% invoked during the doSpatialNorm operation.\nb0Norm = false;\n\n% There are several possible templates.  They should be listed here.\ntemplateName = 'SIRL20adult';\n\n% Set up the files and directories.  We have had trouble reading across the\n% network from time to time.  So on PCs, we copy the key files locally.  On\n% Linux boxes, everything works in place.\nif(ispc)\n    dataDir = '\\\\white.stanford.edu\\biac2-wandell2\\data\\Epilepsy';\n    templateDir = '\\\\white.stanford.edu\\biac2-wandell2\\data\\templates\\adult';   \nelse\n    dataDir = '/biac2/wandell2/data/Epilepsy';\n    templateDir = '/biac2/wandell2/data/templates/adult';\nend\navgdir = fullfile(templateDir,[templateName 'warp3_averageDataset']);\n% Full path to the file\n%subjectDt6 = epiSubjectFile(dataDir, 1,'postictal');   \nsubjectDt6 = epiSubjectFile(dataDir, 1,'control');   \n\n% This normalization operation should be a integrated script, we think.  It\n% requires SPM2.  It requires comments.\nif(doSpatialNorm)\n    if(ispc)\n        % To avoid a memory paging error in windows, we copy the templates to a\n        % local directory.\n        copyfile(fullfile(templateDir,[templateName '_brain.img']), fullfile(tempdir,[templateName '_brain.img']));\n        copyfile(fullfile(templateDir,[templateName '_brain.hdr']), fullfile(tempdir,[templateName '_brain.hdr']));\n        copyfile(fullfile(templateDir,[templateName '_EPI.img']), fullfile(tempdir,[templateName '_EPI.img']));\n        copyfile(fullfile(templateDir,[templateName '_EPI.hdr']), fullfile(tempdir,[templateName '_EPI.hdr']));\n        copyfile(fullfile(templateDir,[templateName 'warp3_averageDataset'],'tensorSummary.mat'), fullfile(tempdir,['tensorSummary.mat']));\n        copyfile(fullfile(templateDir,[templateName 'warp3_averageDataset'],'average_dt6.mat'), fullfile(tempdir,['average_dt6.mat']));\n\n        % On the PC, we put all the files in one directory, the temp\n        % directory for this user.\n        templateDir = tempdir;\n        avgdir = templateDir;\n    end\n    dtiSpatialNormalize;\nelse\n    % No normalization needed\n    subjectDt6 = [subjectDt6 '_' templateName '.mat'];\nend\n\n% Needs further definition.\ntensorSumFile = fullfile(avgdir,'tensorSummary.mat');\n\n% VOXELWISE ANALYSIS\n% We are not sure about the difference between the template, the\n% average and the tensor summary.\n% We think that the \nif(exist(tensorSumFile,'file'))\n    disp(['Loading control group tensor summary (' tensorSumFile ')']);\n    % This loads various summary structures such as md, fa, logTensor,\n    % meanB0 and notes.\n    load(tensorSumFile);\nelse\n    % Compute the tensor summary.  \n    dtiTensorSummary;\nend\n\n% Load the atlas information\ntemplate = load(fullfile(avgdir,'average_dt6'));\nxformDtToAcpc = template.xformToAcPc;\n\n% Directory containing this subject's data\nsubDir = fileparts(subjectDt6);\n\n% Single subject DTI data, spatially normalized\ndisp(['Loading dt6 file (' subjectDt6 ')']);\nssDt_sn = load(subjectDt6);\n%mask = mask&ssDt_sn.dt6(:,:,:,1)>0;\n\n%figure; imagesc(makeMontage(template.b0)); axis image; colormap gray;\n%figure; imagesc(makeMontage(ssDt_sn.b0)); axis image; colormap gray;\n\n%------------------------\n% At this point the atlas data and the subject are loaded.\n% We begin statistical analysis.  We begin with FA and MD analyses in this\n% section. Then we move on to the full tensor analyses in the following\n% section.\n\n% The mask is the valid data mask computed  within dtiTensorSummary.\nssDt_ind = dtiImgToInd(ssDt_sn.dt6, mask);\n[eigVec, eigVal] = dtiEig(ssDt_ind);\n\n% Compute a test comparing FA in this subject with the atlas. This is done\n% by a t-test implemented in dtiTTest.\n[ss_fa, ss_md]   = dtiComputeFA(eigVal);\n\n% Create the T-test images and related data for FA\n[Tfa, DISTR, df] = dtiTTest(fa.mean, fa.stdev, fa.n, ss_fa);\n[TfaImg, tFDRfa, n_signif,index_signif, pvals] = dtiTTestImage(Tfa, DISTR, df, mask);\n\n% showSlices = [15:62]; \n% figure; imagesc(makeMontage(TfaImg,showSlices)); axis image; colormap cool; colorbar;\n% set(gcf,'Name','FA test'); title(sprintf('tthresh, no FDR (p<10^-^4) = %0.1f',tThresh));\n\n% Save out images that can be viewed in dtiFiberUI\ndtiWriteNiftiWrapper(TfaImg, xformDtToAcpc, fullfile(subDir,['fa_' DISTR '-test_' num2str(df(1)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(-1*TfaImg, xformDtToAcpc, fullfile(subDir,['negfa_' DISTR '-test_' num2str(df(1)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(dtiIndToImg(fa.stdev,mask), xformDtToAcpc, fullfile(subDir,'fa_variance.nii.gz'));\n\n% Repeat the process for mean diffusivity\n[Tmd, DISTR, df] = dtiTTest(md.mean, md.stdev, md.n, ss_md);\n[TmdImg, tFDRmd, n_signif,index_signif, pvals] = dtiTTestImage(Tmd, DISTR, df, mask);\n\n% showSlices = [15:62]; \n% figure; imagesc(makeMontage(TmdImg,showSlices)); axis image; colormap cool; colorbar;\n% set(gcf,'Name','MD test'); title(sprintf('tthresh, no FDR (p<10^-^4) = %0.1f',tThresh));\n\n% Save out images that can be viewed in dtiFiberUI.  Until we fix the\n% dtiFiberUI, we can't really select out the negative values.  So we write\n% the data out both positive and negative for the moment.  We need to\n% amend dtiFiberUI so that it \ndtiWriteNiftiWrapper(TmdImg, xformDtToAcpc, fullfile(subDir,['md_' DISTR '-test_' num2str(df(1)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(-1*TmdImg, xformDtToAcpc, fullfile(subDir,['negmd_' DISTR '-test_' num2str(df(1)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(dtiIndToImg(md.stdev,mask), xformDtToAcpc, fullfile(subDir,'md_variance.nii.gz'));\n\n% To view the locations of the significantly different voxels, use\n% dtiFiberUI.  Load the file, say, fa_t-test_19df.nii.gz as a NIFTI image\n% overlay into the program.  You can adjust the cutoff in the user\n% interface.  You can use, say, the fdr threshold (tFDRxx) as the p < 0.05\n% cutoff.\n\n% clear TmdImg TfaImg Tmd Tfa\n\n%--------------------------------------\n% The next two analyses require log-space tensors.\n\n% Log-transform the single subject data\neigVal(eigVal<0) = 0;\neigVal = log(eigVal);\nssDt_ind = dtiEigComp(eigVec, eigVal);\n\n% Test for VECTOR differences\n[T, DISTR, df] = dtiLogTensorTest('vec', logTensor.mean, logTensor.stdev, logTensor.n, ssDt_ind);\n\nTimg = dtiIndToImg(T, mask);\nfThresh = finv(1-10^-4, df(1), df(2));\nfMax = finv(1-10^-12, df(1), df(2));\nTimg(Timg>fMax) = fMax;\nfMax = max(Timg(:));\nSimg = dtiIndToImg(logTensor.stdev,mask);\n\n% figure; imagesc(makeMontage(Timg,showSlices)); axis image; colormap hot; colorbar; \n% set(gcf,'Name','Vec test'); title(sprintf('fthresh (p<10^-^4) = %0.1f',fThresh));\n%\n% figure; imagesc(makeMontage(Simg,showSlices)); axis image; colormap hot; colorbar; \n% set(gcf,'Name','Vec test variance'); \n\n%\ndtiWriteNiftiWrapper(Timg, xformDtToAcpc, fullfile(subDir,['vec_' DISTR '-test_' num2str(df(1)) ',' num2str(df(2)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(Simg, xformDtToAcpc, fullfile(subDir,'vec_variance.nii.gz'));\ndisp(['dtiFiberUI threshold: ' num2str(fThresh/fMax)]);\n\n% Test for VALUE differences\n[T, DISTR, df] = dtiLogTensorTest('val', logTensor.mean, logTensor.stdev, logTensor.n, ssDt_ind);\n\nTimg = dtiIndToImg(T, mask);\nfThresh = finv(1-10^-4, df(1), df(2));\nfMax = finv(1-10^-12, df(1), df(2));\nTimg(Timg>fMax) = fMax;\nfMax = max(Timg(:));\nSimg = dtiIndToImg(logTensor.stdev,mask);\n\n% figure; imagesc(makeMontage(Timg,showSlices)); axis image; colormap hot; colorbar; \n% set(gcf,'Name','Values test'); title(sprintf('fthresh (p<10^-^4) = %0.1f',fThresh));\n%\n% figure; imagesc(makeMontage(Simg,showSlices)); axis image; colormap hot; colorbar; \n% set(gcf,'Name','Values test variance'); \n\n%\ndtiWriteNiftiWrapper(Timg, xformDtToAcpc, fullfile(subDir,['val_' DISTR '-test_' num2str(df(1)) ',' num2str(df(2)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(Simg, xformDtToAcpc, fullfile(subDir,'val_variance.nii.gz'));\ndisp(['dtiFiberUI threshold: ' num2str(fThresh/fMax)]);\n\n% figure; imagesc(makeMontage(sqrt(Timg),[20:55])); axis image; colormap hot; colorbar; \n% set(gcf,'Name','Vec Standardized Distance');\n\n% Possible to test for 'full' also.  Need more comments in dtiLogTensorTest\n\n% FDR analysis for eigenvector differences\n%\n% Sqrt(F) is the standardized distance between the groups.  Ask about this.\n%\nfdrVal = 0.05; fdrType = 'general';\nT(isnan(T)) = 0;\npvals = 1-fcdf(T, df(1), df(2));\n[n_signif,index_signif] = fdr(pvals,fdrVal,fdrType,'mean');\ndisp(n_signif);max(pvals(index_signif))\n\n% Convert back to an fThreshold\npThreshFDR = max(pvals(index_signif));\nfThreshFDR = finv(1-pThreshFDR, df(1), df(2));\ndisp(sprintf('f-threshold for FDR (%s method) of %0.3f: %0.2f (%0.3f).\\n',...\n    fdrType,fdrVal,fThreshFDR,fThreshFDR/fMax));\n\n\n%---- Make locally viewable versions of the images ----\n%\nlogPimg = dtiIndToImg(-log10(pvals), mask);\ncmap = autumn(256); maxLogP = 10; minLogP = -log10(pThreshFDR);\n\nanatRgb = repmat(mrAnatHistogramClip(double(ssDt_sn.anat.img),0.4,0.98),[1,1,1,3]);\ntmp = mrAnatResliceSpm(logPimg, inv(ssDt_sn.xformToAcPc), [], ssDt_sn.anat.mmPerVox, [1 1 1 0 0 0]);\ntmp(tmp>maxLogP) = maxLogP;\ntmp = (tmp-minLogP)./(maxLogP-minLogP);\noverlayMask = (tmp>=0);\ntmp(~overlayMask) = 0;\noverlayMask = repmat(overlayMask,[1 1 1 3]);\noverlayRgb = reshape(cmap(round(tmp*255+1),:),[size(tmp) 3]);\nanatRgb(overlayMask) = overlayRgb(overlayMask);\n\n% reorient so that the eyes point up\nanatRgb = flipdim(permute(anatRgb,[2 1 3 4]),1);\n%sl = [2:2:40];\nsl = [-36:2:60];\nfor(ii=1:length(sl)) slLabel{ii} = sprintf('Z = %d',sl(ii)); end\nslImg = inv(ssDt_sn.anat.xformToAcPc)*[zeros(length(sl),2) sl' ones(length(sl),1)]';\nslImg = round(slImg(3,:));\nanatOverlay = makeMontage3(anatRgb, slImg, ssDt_sn.anat.mmPerVox(1), 0, slLabel);\nmrUtilPrintFigure(fullfile(subDir,'ss_t1_vecSPM'));\nlegendLabels = explode(',',sprintf('%0.1f,',[minLogP:1:maxLogP]));\nlegendLabels{end} = ['>=' num2str(maxLogP)];\nmrUtilMakeColorbar(cmap, legendLabels, '-log10(p)', fullfile(subDir,'vecSPM_legend'));\n\ntemplateBrain = template.anat.img;\ntemplateBrain(template.anat.brainMask<0.25) = 0;\ntemplateBrain(template.anat.brainMask<0.5) = templateBrain(template.anat.brainMask<0.5)*.5;\navgRgb = repmat(templateBrain,[1,1,1,3]);\navgRgb(overlayMask) = overlayRgb(overlayMask);\n\n% reorient so that the eyes point up\navgRgb = flipdim(permute(avgRgb,[2 1 3 4]),1);\navgOverlay = makeMontage3(avgRgb, slImg, ssDt_sn.anat.mmPerVox(1), 0, slLabel);\n\n\nslImg = inv(ssDt_sn.xformToAcPc)*[zeros(length(sl),2) sl' ones(length(sl),1)]';\nslImg = round(slImg(3,:));\noverlayRgb = flipdim(permute(overlayRgb,[2 1 3 4]),1);\noverlay = makeMontage3(overlayRgb, slImg, [], 2);\n\n% figure; imagesc(makeMontage(logPimg,showSlices)); axis image; colormap hot; colorbar;\nthreshMask = zeros(size(pvals));\nthreshMask(index_signif) = 1;\nthreshMask = dtiIndToImg(threshMask, mask);\nimg = logPimg; img(threshMask<1) = 0;\n%  figure; imagesc(makeMontage(img,showSlices)); axis image; colormap hot; colorbar;\n\n\n%%%END HERE%%%\n\n\n%--------------------------------------------------------------------\n% FDR Analysis\n\n% Quantile transformation\nTchisq = chi2inv(cdf(DISTR, T, df(1), df(2)), df(1));\nDISTR = 'chi2';\n% Histograms\nH = fdrHist(Tchisq,0.2,1);\n\n% Empirical null\nTmax = prctile(Tchisq,90);\nw = (H.x < Tmax);\n[params, paramsCov, H0hat] = fdrEmpNull(H, w, DISTR, {}, df);\n[p0, s0, df0] = deal(params(1), params(2), params(3));\nparamsConf = [[log(p0), s0, df0] + 1.95*sqrt(diag(paramsCov))';\n    [log(p0), s0, df0] - 1.95*sqrt(diag(paramsCov))'];\n\n% p0 adjustment for theoretical null\n[params, paramsCov, H0] = fdrEmpNull(H, w, DISTR, {'df','s'}, df);\np0H0 = params(1);\n\n% FDR curves\n[fdrH0, t] = fdrCurveHist('FDR', H0, 1);\n[fdrH0hat, t] = fdrCurveHist('FDR', H0hat, 1);\n\n% Threshold\nthr = fdrThresh(1, fdrH0(:,1), t, level);\nthr = fdrThresh(1, fdrH0hat(:,1), t, level);\n\n\n%-----------------------------------------------------------------------\n% FDR Plots\n\n% Histogram of test stats\nfigure, set(gcf, 'name', 'Histograms'), hold on\nh = bar(H.x, H.hist, 1, 'w');\nh0 = plot(H0.x, H0.yhat, 'b');\nh1 = plot(H0hat.x, H0hat.yhat, 'r');\nhold off, legend([h0 h1], 'theo null','emp null',1)\nxlabel('T'); ylabel('voxel count');\na=axis; axis([0 prctile(T,99) a(3:4)]);\n\n% FDR curves\nfigure,\tset(gcf, 'name', 'FDR'), hold on\nplot(t, fdrH0(:,1), 'b')\nplot(t, fdrH0hat(:,1), 'r')\nlegend('theo null','emp null')\nplot(t, fdrH0(:,2), 'b:', t, fdrH0(:,3), 'b:')\nplot(t, fdrH0hat(:,2), 'r:', t, fdrH0hat(:,3), 'r:')\nhold off, axis([0 prctile(Tchisq,99.99) 0 1]);\nxlabel('threshold'); ylabel('FDR');\n\npthresh = 1-chi2cdf(t,df(1));\nfigure;plot(log10(pthresh), fdrH0(:,1), 'b')\nxlabel('log10(p-value)'); ylabel('FDR');\n\n\n% Test for eigenvalue differences\n[T, M, S, DISTR, df] = dtiLogTensorTest(1, [2:size(allDt6_ind,3)], allDt6_ind, 'val');\nTimg = dtiIndToImg(T, mask);\nfThresh = finv(1-10^-4, df(1), df(2));\nfMax = finv(1-10^-12, df(1), df(2));\nTimg(Timg>fMax) = fMax;\nfMax = max(Timg(:));\nfigure; imagesc(makeMontage(Timg,[20:55])); axis image; colormap hot; colorbar;\nset(gcf,'Name','Val test'); title(sprintf('fthresh (p<10^-^4) = %0.1f',fThresh));\ndtiWriteNiftiWrapper(Timg, xformDtToAcpc, fullfile(subDir,['val_' DISTR '-test_' num2str(df(1)) ',' num2str(df(2)) 'df.nii.gz']));\ndtiWriteNiftiWrapper(dtiIndToImg(S,mask), xformDtToAcpc, fullfile(subDir,'val_variance.nii.gz'));\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrScripts/diffusion/dtiEpilepsy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22738085596977434}}
{"text": "function [params] = sv_calcMcNodes(params,nNodeStart, nNodeEnd)\n% function [params] = sv_calcMcNodes(params,nNodeStart, nNodeEnd);\n% ----------------------------------------------------------------\n% Calculation of magnitude of completeness specifying the nodes to be calculated for distributing on different CPUs\n%\n% Input parameters:\n%   params.mCatalog           Earthquake catalog\n%   params.mPolygon           Polygon (defined by ex_selectgrid)\n%   params.vX                 X-vector (defined by ex_selectgrid)\n%   params.vY                 Y-vector (defined by ex_selectgrid)\n%   params.vUsedNodes         Used nodes vX * vY defining the mPolygon (defined by ex_selectgrid)\n%   params.bRandom            Perform random simulation (=1) or real calculation (=0)\n%   params.nCalculation       Number of random simulations\n%   params.bMap               Calculate a map (=1) or a cross-section (=0)\n%   params.bNumber            Use constant number (=1) or constant radius (=0)\n%   params.nNumberEvents      Number of earthquakes if bNumber == 1\n%   params.fMaxRadius         Maximum Radius using a constant number of events; works only with bNumber == 1\n%   params.fRadius            Radius of gridnode if bNumber == 0\n%   params.nMinimumNumber     Minimum number of earthquakes per node for determining a b-value\n%   params.fMinMag            Lower limit of magnitude range for testing\n%   params.fMaxMag            Upper limit of magnitude range for testing\n%   params.bTimePeriod        Calculate seismicity difference for 2 periods (0) until start and end of catalog or\n%                             a specific time period before and after fSplitTime (1)\n%   params.fTimePeriod        Length of time periods\n%   params.bTstart            Check for starting time of temporal mapping\n%   params.fTstart            Starting time for temporal mapping\n%   params.bBstnum            Check for boostrap sampling\n%   params.fBstnum            Number of bootstrap samples\n%   params.fBinning           Bin size for magnitude binning\n%   params.sComment           Comment on calculation\n\n% Output parameters:\n%   Same as input parameters including\n%   params.mValueGrid         Matrix of calculated values\n%   params.vcsGridNames       Names of parameters calculated\n%   Check sv_NodeCalcMc.m for a list of variables!!\n%\n% J. Woessner; woessner@seismo.ifg.ethz.ch\n% last update: 27.03.03\n\nglobal bDebug;\nif bDebug\n    report_this_filefun(mfilename('fullpath'));\nend\n\n% Initialize\nvResults = [];\nparams.sComment = [];\nif isempty(params.fBinning)\n    params.fBinning = 0.1;\nend\n\n% Determine time period of catalog\nparams.fTminCat = min(params.mCatalog(:,3));\nparams.fTmaxCat = max(params.mCatalog(:,3));\n% Adjust to decimal years\nfTimePeriod =params.fTimePeriod/365;\n\n% Init result matrix\nmValueGrid_ = [];\n\n% Temporary saving the original catalog\nmCatalog = params.mCatalog;\n\n% Check for bootstrapping or not\n% ------------------------------\n% Case of calculations with bootstrapping\nif (params.bBstnum == 1)\n    % Loop over time\n    fTstart = params.fTstart;\n    while fTstart < params.fTmaxCat\n        mValueGrid_ = [];\n        params.mCatalog = mCatalog;\n        % Create Indices to catalog and select quakes in time period\n        vSel = (fTstart <= params.mCatalog(:,3) & params.mCatalog(:,3) < fTstart+fTimePeriod);\n        params.mCatalog = params.mCatalog(vSel,:);\n        [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n         params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n        % Loop over all grid nodes\n        hWaitbar1 = waitbar(0,'Calculating nodes...');\n        set(hWaitbar1,'Numbertitle','off','Name','Node percentage');\n        for nNode_ = nNodeStart:nNodeEnd\n            % Create node catalog\n            mNodeCatalog_ = params.mCatalog(params.caNodeIndices{nNode_}, :);\n            % Check for constant number of events calculations\n            if (params.nGriddingMode == 0)\n                [mNodeCatalog_] = ex_CheckMaxRadius(mNodeCatalog_, params.mPolygon, nNode_, params.caNodeIndices, params.fMaxRadius, params.nNumberEvents, params.bMap);\n            end\n            [nX,nY] = size(mNodeCatalog_);\n            if (nX < params.nMinimumNumber)\n                mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN nX NaN NaN NaN NaN];\n            else\n                [rCalcNodeResult_] = sv_NodeCalcMc(params,mNodeCatalog_);\n                % Store the results\n                mValueGrid_= [mValueGrid_; rCalcNodeResult_.fMc_max rCalcNodeResult_.fMc_90 rCalcNodeResult_.fMc_95 rCalcNodeResult_.fMc_com...\n                        rCalcNodeResult_.fMc_EMR rCalcNodeResult_.fMc_shi rCalcNodeResult_.fMc_Bst...\n                        rCalcNodeResult_.fStd_Mc rCalcNodeResult_.fBvalue_Bst rCalcNodeResult_.fStd_B...\n                        rCalcNodeResult_.fAvalue_Bst rCalcNodeResult_.fStd_A nX...\n                        rCalcNodeResult_.bH rCalcNodeResult_.fPval rCalcNodeResult_.bH_Bst rCalcNodeResult_.fPval_Bst];\n            end; % End of if on nNode_\n            if rem(nNode_,floor(length(params.mPolygon(:,1))/10)) == 0\n                waitbar(nNode_/length(params.mPolygon(:,1)))\n                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n                % Temporary saving\n                params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n                    'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)', 'Mc(Bst-mean)', 'Mc(Bst-2nd-moment)',...\n                    'Mc(Bst-b)', 'Mc(b_2nd-moment)','Mc(Bst-a)', 'Mc(a_2nd-moment)','Number of events',...\n                    'H(KST)','P(KST)','H(KST_Bst)','P(KST_Bst)'));\n                params.mValueGrid = mValueGrid_;\n                % Add parameter to params.sComment\n                if  params.nGriddingMode == 0;   % Constant number\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                            num2str(params.fMaxRadius) ' km'];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                            '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n                elseif params.nGriddingMode == 1;   % Constant radius\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                else  % Rectangle mode\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                            ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                            '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                end; % END of params.nGriddingmode\n                vResults =[];\n            end; % End updating waitbar\n        end; % for nNode\n        close(hWaitbar1);\n        % Parameter description\n        params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n            'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)', 'Mc(Bst-mean)', 'Mc(Bst-2nd-moment)',...\n            'Mc(Bst-b)', 'Mc(b_2nd-moment)','Mc(Bst-a)', 'Mc(a_2nd-moment)','Number of events',...\n                    'H(KST)','P(KST)','H(KST_Bst)','P(KST_Bst)'));\n        params.mValueGrid = mValueGrid_;\n        % Add parameter to params.sComment\n        if  params.nGriddingMode == 0;   % Constant number\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                    num2str(params.fMaxRadius) ' km'];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        elseif params.nGriddingMode == 1;   % Constant radius\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        else  % Rectangle mode\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                    ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        end\n        vResults =[];\n        fTstart = fTstart+fTimePeriod;\n    end; % End of while fTstart\n\n    % Case of no bootstrapping\nelse\n    % Loop over time\n    fTstart = params.fTstart;\n    while fTstart < params.fTmaxCat\n        mValueGrid_ = [];\n        params.mCatalog = mCatalog;\n        % Create Indices to catalog and select quakes in time period\n        vSel = (fTstart <= params.mCatalog(:,3) & params.mCatalog(:,3) < fTstart+fTimePeriod);\n        params.mCatalog = params.mCatalog(vSel,:);\n        [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n         params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n        % Loop over all grid nodes\n        hWaitbar1 = waitbar(0,'Calculating nodes...');\n        set(hWaitbar1,'Numbertitle','off','Name','Node percentage');\n        for nNode_ = nNodeStart:nNodeEnd\n            % Create node catalog\n            mNodeCatalog_ = params.mCatalog(params.caNodeIndices{nNode_}, :);\n            % Check for constant number of events calculations\n            if (params.nGriddingMode == 0)\n                [mNodeCatalog_] = ex_CheckMaxRadius(mNodeCatalog_, params.mPolygon, nNode_, params.caNodeIndices, params.fMaxRadius, params.nNumberEvents, params.bMap);\n            end\n            [nX,nY] = size(mNodeCatalog_);\n            if (nX < params.nMinimumNumber)\n                mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN nX];\n            else\n                [rCalcNodeResult_] = sv_NodeCalcMc(params,mNodeCatalog_);\n                mValueGrid_= [mValueGrid_; rCalcNodeResult_.fMc_max rCalcNodeResult_.fMc_90 rCalcNodeResult_.fMc_95 rCalcNodeResult_.fMc_com...\n                        rCalcNodeResult_.fMc_EMR rCalcNodeResult_.fMc_shi nX];\n            end; % End of if on nX\n            if rem(nNode_,500) == 0\n                waitbar(nNode_/length(params.mPolygon(:,1)))\n                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n                % Temporary saving\n                params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n                    'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)','Number of events'));\n                params.mValueGrid = mValueGrid_;\n                % Add parameter to params.sComment\n                if  params.nGriddingMode == 0;   % Constant number\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                            num2str(params.fMaxRadius) ' km'];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                            '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n                elseif params.nGriddingMode == 1;   % Constant radius\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                else  % Rectangle mode\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                            ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                            '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                end; % END of params.nGriddingmode\n                vResults =[];\n            end; % End updating waitbar\n        end; % for nNode\n        close(hWaitbar1);\n        % Parameter description\n        params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n            'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)'));\n        params.mValueGrid = mValueGrid_;\n        % Add parameter to params.sComment\n        if  params.nGriddingMode == 0;   % Constant number\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                    num2str(params.fMaxRadius) ' km'];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        elseif params.nGriddingMode == 1;   % Constant radius\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        else  % Rectangle mode\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                    ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n        end\n        vResults =[];\n        fTstart = fTstart+fTimePeriod;\n    end; % End of while fTstart\nend; % END of if params.bBst\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/sv_calcMcNodes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.22737198240312495}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  qdd = call_direct_dynamics_fast(input)\n%  Auxiliar function for the simulink model SIMULATE_ROBOT_AND_CONTROLLER.\n%  Rearranges the inputs coming from the simulink model and calls the\n%  function accel.\n%  As a result the instantaneous acceleration at each joint is returned.\n%\n%  See also ACCEL.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.\nfunction qdd = call_direct_dynamics_2dofplanar(input)\n\nglobal robot\n\ntorque = input(1:2);   % Input torque at each joint\nq   = input(3:4);\t   % Joint positions\nqd  = input(5:6);\t   % Joint speeds\nfe=[0 0 0 0 0 0]'; %external forces applied\ntorque\n\n% Compute acceleration\nqdd = forwarddynamics_2dofplanar(robot, q, qd, torque, 9.81, fe)", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/simulink/simulate_2DOFplanar_arm/call_direct_dynamics_2dofplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.38121955922604406, "lm_q1q2_score": 0.22737198112680315}}
{"text": "function [diff_dose] = dicomrt_dosediff(doseone,dosetwo,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)\n% dicomrt_dosediff(doseone,dosetwo,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)\n%\n% Calculate dose difference between two 3D matrices\n% \n% doseone and dosetwo can be rtplan and/or monte carlo 3D dose distributions.\n% method is an OPTIONAL rameter which specify the way doses are normalised\n%\n% 1. method=a          matrices are normalised to the value a expressed in Gy\n% 2. method=[x, y, z]  matrices are independently normalised to the dose value at point (x,y,z) (in cm)\n% 3. method=dmean      matrices are independently normalised to the mean dose value in VOI voi2use (key insensitive)\n% 4. method=0          matrices are not normalised (default)   \n%\n% dose_xmesh,dose_ymesh,dose_zmesh are OPTIONAL x-y-z coordinates of the center of the matrix voxels\n% VOI is a cell array which contain the patients VOIs (OPTIONAL to use with option 3)\n% voi2use is a vector pointing to the number of VOI (OPTIONAL to use with option 3)\n%\n% Examples:\n%\n% C=dicomrt_dosediff(A,B,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,0)\n% Store in C the dose difference between B and A. C=(B-A). \n%\n% C=dicomrt_dosediff(A,B,60,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)\n% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where\n% Bnorm and Anorm are normalised to 60Gy (100%).\n%\n% C=dicomrt_dosediff(A,B,[10.5 -18 7],method,dose_xmesh,dose_ymesh,dose_zmesh)\n% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where\n% Bnorm and Anorm are normalised to the respective dose values at dnorm=(10.5 -18 7).\n%\n% C=dicomrt_dosediff(A,B,'Dmean',method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,3)\n% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where\n% Bnorm and Anorm are normalised to the respective mean dose values in VOI number 3\n%\n% See also: dicomrt_doseratio, dicomrt_loadmcdose\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument and set-up some parameters and variables\nerror(nargchk(2,8,nargin))\n\n% Define parameter\nvoilookup=1;\nfilter=0;\ndosenorm=0;\n\n% Check case and set-up some parameters and variables\n[doseone_dose_temp,type_doseone_dose,labeld1]=dicomrt_checkinput(doseone,1);\n[dosetwo_dose_temp,type_dosetwo_dose,labeld1]=dicomrt_checkinput(dosetwo,1);\ndoseone_dose=dicomrt_varfilter(doseone_dose_temp);\ndosetwo_dose=dicomrt_varfilter(dosetwo_dose_temp);\n\nif exist('VOI')==1 & exist('voi2use')==1\n    if strcmpi(type_doseone_dose,'mc')==1\n        doseone_dose_temp=dicomrt_mask(VOI,doseone_dose_temp,dose_xmesh,dose_ymesh,dose_zmesh,voilookup,filter,'y');\n    end\n    if strcmpi(type_dosetwo_dose,'mc')==1\n        dosetwo_dose_temp=dicomrt_mask(VOI,dosetwo_dose_temp,dose_xmesh,dose_ymesh,dose_zmesh,voilookup,filter,'y');\n    end\nend\n\n% Create label for dose diff\n%if type_doseone_dose=='mc' & type_dosetwo_dose=='rtplan'\n%    dose_diff_label='rtplan -mc'\n%elseif type_doseone_dose=='mc' & type_dosetwo_dose=='mc'\n%    dose_diff_label='mc2 - mc1'\n%elseif type_doseone_dose=='rtplan' & type_dosetwo_dose=='mc'\n%    dose_diff_label='mc - rtplan'\n%else\n%    dose_diff_label='rtplan2 - rtplan1'\n%end\n\nif exist('method')==1\n    if isnumeric(method)==1 & length(method)==1 & method~=0\n        % normalize to a specific dose level passed through \"method\"\n        doseone_dose=doseone_dose./method.*100;\n        dosetwo_dose=dosetwo_dose./method.*100;\n        diff_dose=dosetwo_dose-doseone_dose;\n    elseif isnumeric(method)==1 & length(method)==1 & method==0\n        % no normalisation is carried out\n        diff_dose=dosetwo_dose-doseone_dose;\n    elseif isnumeric(method)==1 & length(method)==3 & ...\n            (exist('dose_xmesh')~=1 | exist('dose_ymesh')~=1 | exist('dose_zmesh')~=1)\n        error('dicomrt_dosediff: This normalisation method requires mesh to be provided. Exit now!');\n    elseif isnumeric(method)==1 & length(method)==3 & ...\n            (exist('dose_xmesh')==1 | exist('dose_ymesh')==1 | exist('dose_zmesh')==1)\n        % normalize to a specific point in 3D passed through \"method\"\n        locx=dicomrt_findpointVECT(dose_xmesh,method(1));\n        locy=dicomrt_findpointVECT(dose_ymesh,method(2));\n        locz=dicomrt_findpointVECT(dose_zmesh,method(3));\n        doseone_dose=doseone_dose./doseone_dose(locy,locx,locz).*100;\n        dosetwo_dose=dosetwo_dose./dosetwo_dose(locy,locx,locz).*100;\n        diff_dose=dosetwo_dose-doseone_dose;\n    elseif ischar(method)==1 & strcmpi(method,'dmean')==1 & ...\n            (exist('VOI')~=1 | exist('voi2use')~=1)\n        error('dicomrt_dosediff: This normalisation method requires VOI and voi2use to be provided. Exit now!');\n    elseif ischar(method)==1 & strcmpi(method,'dmean')==1 & ...\n            (exist('VOI')==1 | exist('voi2use')==1)\n        % normalize to dmean\n        dmean_one=dicomrt_MDcal(doseone,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use);\n        dmean_two=dicomrt_MDcal(dosetwo,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use);\n        doseone_dose=doseone_dose./dmean_one.*100;\n        dosetwo_dose=dosetwo_dose./dmean_two.*100;\n        diff_dose=dosetwo_dose-doseone_dose;\n    end\nelse\n    % no normalisation is carried out\n    diff_dose=dosetwo_dose-doseone_dose;\nend\n\n% Restore original variable format\n[diff_dose]=dicomrt_restorevarformat(dosetwo_dose_temp,diff_dose);\n\n% Label Plan and update time of creation\nif iscell(diff_dose)==1\n    diff_dose{1,1}{1}.RTPlanLabel=[diff_dose{1,1}{1}.RTPlanLabel,'-DDIFF'];\n    diff_dose{1,1}{1}.RTPlanDate=date;\n    time=fix(clock);\n    creationtime=[num2str(time(4)),':',num2str(time(5))];\n    diff_dose{1,1}{1}.RTPlanTime=creationtime;\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/analysis/dicomrt_dosediff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.22729997186194545}}
{"text": "tdir = '/biac2/wandell2/data/templates/';\n\n% load the zeroth-iteration template (built from a simple average\n% of all the ac-pc aligned brains\n%im = loadAnalyze(fullfile(tdir,'SIRL55-0.img'));\n\nbaseDir = '/biac2/wandell2/data/reading_longitude/dti/*0*';\n[files,subCodes] = findSubjects(baseDir, '_dt6', {'es041113','tk040817'});\nN = length(files);\n\n% Load all the talscales\nfor(ii=[1:N])\n  fprintf('Loading scale factors from %s (%d of %d)...\\n',subCodes{ii}, ii, N);\n  d = load(files{ii},'anat');\n  sf(ii) = d.anat.talScale;\nend\n% To get the mean extent, we average the Talairach scale factors\n% and then divide Talairach's actual dimensions (in mm) by these\n% scales.\ntal = mrAnatGetTalairachDists;\nmeanExtent.sac = abs(tal.sac)/mean([sf(:).sac]);\nmeanExtent.iac = abs(tal.iac)/mean([sf(:).iac]);\nmeanExtent.lac = abs(tal.lac)/mean([sf(:).lac]);\nmeanExtent.rac = abs(tal.rac)/mean([sf(:).rac]);\nmeanExtent.aac = abs(tal.aac)/mean([sf(:).aac]);\nmeanExtent.acpc = abs(tal.acpc)/mean([sf(:).acpc]);\nmeanExtent.ppc = abs(tal.ppc)/mean([sf(:).ppc]);\nfor(ii=[1:N])\n  extent(ii).sac = abs(tal.sac)/sf(ii).sac;\n  extent(ii).iac = abs(tal.iac)/sf(ii).iac;\n  extent(ii).lac = abs(tal.lac)/sf(ii).lac;\n  extent(ii).rac = abs(tal.rac)/sf(ii).rac;\n  extent(ii).aac = abs(tal.aac)/sf(ii).aac;\n  extent(ii).acpc = abs(tal.acpc)/sf(ii).acpc;\n  extent(ii).ppc = abs(tal.ppc)/sf(ii).ppc;\n  newScale(ii).sac = meanExtent.sac/extent(ii).sac;\n  newScale(ii).iac = meanExtent.iac/extent(ii).iac;\n  newScale(ii).lac = meanExtent.lac/extent(ii).lac;\n  newScale(ii).rac = meanExtent.rac/extent(ii).rac;\n  newScale(ii).aac = meanExtent.aac/extent(ii).aac;\n  newScale(ii).acpc = meanExtent.acpc/extent(ii).acpc;\n  newScale(ii).ppc = meanExtent.ppc/extent(ii).ppc;\n  newScale(ii).pcReference = -meanExtent.acpc;\nend\n\n% Reslice using the talscale measurements.\nd = load(files{1},'anat');\nac = round(mrAnatXformCoords(inv(d.anat.xformToAcPc),[0 0 0]));\nimSkull = d.anat.img; \nim = imSkull; im(~d.anat.brainMask) = 0;\nsz = size(im);\n%imSkull = mrAnatHistogramClip(double(imSkull), 0.5, 0.99);\nproportionNonBrain = sum(~d.anat.brainMask(:))./prod(size(d.anat.brainMask));\nim = mrAnatHistogramClip(double(im), proportionNonBrain, 0.99);\nbb = [-d.anat.mmPerVox.*(ac-1); d.anat.mmPerVox.*(sz-ac)];\nts = newScale(1); ts.talScaleDir = 'tal2acpc';\n% warp T1 to tal space\nts.outMat = inv(d.anat.xformToAcPc);\n[im,newXform] = mrAnatResliceSpm(im,ts,bb,[1 1 1],[7 7 7 0 0 0],0);\nim(isnan(im)) = 0;\nim(im<0) = 0; im(im>1) = 1;\nax = zeros(sz(2), sz(1), N+1);\ncr = zeros(sz(3), sz(1), N+1);\nsg = zeros(sz(3), sz(2), N+1);\nmeanIm = im;\nax(:,:,1) = flipud(permute(squeeze(im(:,:,ac(3))),[2,1]));\ncr(:,:,1) = flipud(permute(squeeze(im(:,ac(2),:)),[2,1]));\nsg(:,:,1) = flipud(permute(squeeze(im(ac(1),:,:)),[2,1]));\nfor(ii=[2:N])\n  fprintf('Processing %s (%d of %d)...\\n',subCodes{ii}, ii, N);\n  d = load(files{ii},'anat');\n  % All coords should be the same.\n  ac = round(mrAnatXformCoords(inv(d.anat.xformToAcPc),[0 0 0]));\n  im = d.anat.img; im(~d.anat.brainMask) = 0;\n  im = mrAnatHistogramClip(double(im), 0.4, 0.99);\n  ts = newScale(ii); ts.talScaleDir = 'tal2acpc';\n  ts.outMat = inv(d.anat.xformToAcPc);\n  [im,newXform] = mrAnatResliceSpm(im,ts,bb,[1 1 1],[7 7 7 0 0 0],0);\n  im(isnan(im)) = 0;\n  im(im<0) = 0; im(im>1) = 1;\n  meanIm = meanIm + im;\n  ax(:,:,ii) = flipud(permute(squeeze(im(:,:,ac(3))),[2,1]));\n  cr(:,:,ii) = flipud(permute(squeeze(im(:,ac(2),:)),[2,1]));\n  sg(:,:,ii) = flipud(permute(squeeze(im(ac(1),:,:)),[2,1]));\nend\nmeanIm = meanIm./N;\nfigure; image(makeMontage(uint8(meanIm*255))); \ncolormap(gray(256)); axis equal tight off;\nax(:,:,N+1) = mean(ax(:,:,[1:N]), 3);\ncr(:,:,N+1) = mean(cr(:,:,[1:N]), 3);\nsg(:,:,N+1) = mean(sg(:,:,[1:N]), 3);\nax = uint8(ax.*255+0.5);\ncr = uint8(cr.*255+0.5);\nsg = uint8(sg.*255+0.5);\nfigure;image(makeMontage(ax));colormap(gray(256));axis equal tight off;\nfigure;image(makeMontage(cr));colormap(gray(256));axis equal tight off;\nfigure;image(makeMontage(sg));colormap(gray(256));axis equal tight off;\n\ntdir = '/snarp/u1/data/templates/';\nimwrite(makeMontage(ax), gray(256), fullfile(tdir, 'SIRL55scaledToMean_ax.png'));\nimwrite(makeMontage(cr), gray(256), fullfile(tdir, 'SIRL55scaledToMean_cr.png'));\nimwrite(makeMontage(sg), gray(256), fullfile(tdir, 'SIRL55scaledToMean_sg.png'));\n\n% Now build an atlas from the mean image\nV.dat = int16(meanIm.*(2^15-1)+0.5);\nnotes = ['SIRL55ms: average of 55 mean-Tal-scaled brains. Created at ' datestr(now,31)];\nmmPerVox = d.anat.mmPerVox;\norigin = ac;\nhdr = saveAnalyze(V.dat, fullfile(tdir,'SIRL55ms'), mmPerVox, notes, origin);\nsave(fullfile(tdir,'SIRL55ms_details.mat'), 'meanIm','notes','extent','meanExtent','origin','mmPerVox');\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrScripts/diffusion/dtiBuildTemplate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22729517886700887}}
{"text": "function [coord_norm] = warp_fsaverage_sym(cfg, elec)\n\n% WARP_FSAVERAGE_SYM maps left or right hemisphere electrodes onto \n% FreeSurfer's fsaverage_sym's left hemisphere. To perform this mapping, \n% you first need to have processed the subject's MRI with FreeSurfer's \n% recon-all functionality and additionaly have registered the subject's resulting \n% surfaces to freesurfer fsaverage_sym template using surfreg as described \n% in section 1.2 of https://surfer.nmr.mgh.harvard.edu/fswiki/Xhemi\n%\n% The configuration must contain the following options\n%   cfg.headshape      = string, filename containing subject headshape\n%                      (e.g. <path to freesurfer/surf/lh.pial>)\n%   cfg.fshome         = string, path to freesurfer\n%\n% See also FT_ELECTRODEREALIGN, WARP_FSAVERAGE\n\n% Copyright (C) 2019, Arjen Stolk\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nsubj_pial = ft_read_headshape(cfg.headshape);\n[PATHSTR, NAME] = fileparts(cfg.headshape); % lh or rh\nif strcmp(NAME, 'lh')\n  subj_reg = ft_read_headshape([PATHSTR filesep 'lh.fsaverage_sym.sphere.reg']);\nelseif strcmp(NAME, 'rh')\n  subj_reg = ft_read_headshape([PATHSTR(1:strfind(PATHSTR, [filesep 'surf'])-1) filesep 'xhemi' filesep 'surf' filesep 'lh.fsaverage_sym.sphere.reg']);\nend\nif ~isfolder([cfg.fshome filesep 'subjects' filesep 'fsaverage_sym']) || ~isfolder([PATHSTR(1:strfind(PATHSTR, [filesep 'surf'])-1) filesep 'xhemi'])\n  ft_error(['fsaverage_sym and/or xhemi folders cannot be found'])\nend\nfsavg_pial = ft_read_headshape([cfg.fshome filesep 'subjects' filesep 'fsaverage_sym' filesep 'surf' filesep 'lh.pial']);\nfsavg_reg = ft_read_headshape([cfg.fshome filesep 'subjects' filesep 'fsaverage_sym' filesep 'surf' filesep 'lh.sphere.reg']); % always map onto the left hemi\n\nfor e = 1:numel(elec.label)\n  % subject space (3D surface): electrode pos -> vertex index\n  dist = sqrt(sum(((subj_pial.pos - repmat(elec.elecpos(e,:), size(subj_pial.pos,1), 1)).^2),2));\n  [dum, minidx] = min(dist);\n  \n  % intersubject space (3D sphere): vertex index -> vertex pos -> template vertex index\n  dist2 = sqrt(sum(((fsavg_reg.pos - repmat(subj_reg.pos(minidx,:), size(fsavg_reg.pos,1), 1)).^2),2));\n  [dum, minidx2] = min(dist2);\n  clear minidx\n  \n  % template space (3D surface): template vertex index -> template electrode pos\n  coord_norm(e,:) = fsavg_pial.pos(minidx2,:);\n  clear minidx2\nend\nclear subj_pial subj_reg fsavg_pial fsavg_reg\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/warp_fsaverage_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.227223340873694}}
{"text": "function [DCM,BMR,BMA] = spm_dcm_bmr_all(DCM,field,OPT)\n% Bayesian model reduction of all permutations of model parameters\n% FORMAT [RCM,BMR,BMA] = spm_dcm_bmr_all(DCM,field,OPT)\n%\n% DCM      - A single estimated DCM (or PEB) structure:\n%\n%  DCM.M.pE  - prior expectation\n%  DCM.M.pC  - prior covariance\n%  DCM.Ep    - posterior expectation\n%  DCM.Cp    - posterior covariances\n%  DCM.beta  - prior expectation of reduced parameters (default: 0)\n%  DCM.gamma - prior variance    of reduced parameters (default: 0)\n%              NB: beta = 'pE' uses full priors\n%\n% field      - parameter fields in DCM{i}.Ep to optimise [default: {'A','B'}]\n%             'All' will invoke all fields (i.e. random effects)\n%             If Ep is not a structure, all parameters will be considered\n%\n% OPT        - Bayesian model selection or averaging: 'BMS' or 'BMA'\n%              [default: 'BMA']\n%\n% Returns:\n%\n% DCM - Bayesian Model Average (BMA) over models in the final iteration of \n%       the search:\n%\n%       DCM.Ep    - (BMA) posterior expectation\n%       DCM.Cp    - (BMA) posterior covariance\n%       DCM.Pp    - Model posterior over parameters (with and without)\n%\n% BMR -  (Nsub) summary structure reporting the model space from the last\n%        iteration of the search:\n%\n%        BMR.name - character/cell array of parameter names\n%        BMR.F    - free energies (relative to full model)\n%        BMR.P    - and posterior (model) probabilities\n%        BMR.K    - [models x parameters] model space (1 = off, 0 = on)\n%\n% BMA - Baysian model average (over reduced models; see spm_dcm_bma)\n%\n%--------------------------------------------------------------------------\n% This routine searches over reduced (nested) models of a full model (DCM) \n% using Bayesian model reduction and performs Bayesian Model Averaging.\n% 'Reduced' means some free parameters (parameters with a non-\n% zero prior covariance) are switched off by fixing their prior variance \n% to zero. \n%\n% If there are fewer than nmax = 8 free parameters, all permutations of \n% switching off parameters will be tested. Otherwise, this routine \n% implements the following greedy search procedure. The nmax parameters \n% are identified which, when switched off individually, produce the least \n% reduction (greatest increase) in model evidence. All permutations of \n% switching off these parameters are then evaluated and the best \n% permutation is retained. This procedure is repeated until all nmax\n% parameters are retained or there are no more parameters to consider. \n% Finally, BMA is performed on the models from the last iteration.\n% \n% NB: The full model should be estimated prior to running this function. \n%\n% See also: spm_dcm_post_hoc - this routine is essentially a simplified\n% version of spm_dcm_post_hoc\n%__________________________________________________________________________\n% Copyright (C) 2010-2014 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston, Peter Zeidman\n% $Id: spm_dcm_bmr_all.m 7717 2019-11-27 11:10:36Z peter $\n\n\n%-specification of null prior covariance\n%--------------------------------------------------------------------------\nif isfield(DCM,'beta'),  beta  = DCM.beta;  else, beta  = 0; end\nif isfield(DCM,'gamma'), gamma = DCM.gamma; else, gamma = 0; end\n\n%-Check fields of parameter stucture (and options)\n%--------------------------------------------------------------------------\nif nargin < 3\n    OPT   = 'BMA';\nend\nif nargin < 2 || isempty(field)\n    field = {'A','B'};\nend\nif ischar(field)\n    field = {field};\nend\n\n%-deal with filenames structure\n%--------------------------------------------------------------------------\nif ischar(DCM)\n    DCM = load(DCM,'DCM');\n    DCM = DCM.DCM;\nend\n\n% Get prior covariances\n%--------------------------------------------------------------------------\nif isstruct(DCM.M.pC), DCM.M.pC = diag(spm_vec(DCM.M.pC)); end\nif spm_length(DCM.M.pE) ~= size(DCM.M.pC,1)\n    DCM.M.pC = diag(spm_vec(DCM.M.pC));\nend\n\n% Get priors and posteriors\n%--------------------------------------------------------------------------\nqE  = DCM.Ep;\nqC  = DCM.Cp;\npE  = DCM.M.pE;\npC  = DCM.M.pC;\n\n% Remove (a priori) null space\n%--------------------------------------------------------------------------\nU   = spm_svd(pC);\nqE  = U'*spm_vec(qE);\npE  = U'*spm_vec(pE);\nqC  = U'*qC*U;\npC  = U'*pC*U;\n\n\n%-Greedy search (GS) - eliminating parameters in a top down fashion\n%==========================================================================\n\n% Accumulated reduction vector (C)\n%--------------------------------------------------------------------------\nq   = diag(DCM.M.pC);\nif sum(q < 1024)\n    C   = double(q > mean(q(q < 1024))/1024);\nelse\n    C   = double(q > 0);\nend\nGS  = 1;\nwhile GS\n    \n    %-Find free coupling parameters\n    %----------------------------------------------------------------------\n    if isstruct(DCM.Ep)\n        k = spm_fieldindices(DCM.Ep,field{:});\n    else\n        k = 1:spm_length(DCM.Ep);\n    end\n    k = k(find(C(k))); %#ok<FNDSB>\n    \n    % If there are too many parameters find those with the least evidence\n    %----------------------------------------------------------------------\n    nparam = length(k);\n    nmax   = fix(max(nparam/4,8));\n    if nparam > nmax\n        \n        % Model search over new prior without the i-th parameter\n        %------------------------------------------------------------------\n        Z     = zeros(1,nparam);\n        for i = 1:nparam\n            \n            % Identify parameters to retain r and to remove s\n            %--------------------------------------------------------------\n            r   = C; r(k(i)) = 0; s = 1 - r;\n\n            % Create reduced prior covariance matrix\n            %--------------------------------------------------------------\n            R   = U'*diag(r + s*gamma)*U;\n            rC  = R*pC*R;\n            \n            % Create reduced prior means\n            %--------------------------------------------------------------\n            if isnumeric(beta)\n                S  = U'*diag(r)*U;\n                rE = S*pE + U'*s*beta;\n            else\n                rE = pE;\n            end\n            \n            Z(i) = spm_log_evidence(qE,qC,pE,pC,rE,rC);\n        end\n        \n        % Find parameters with the least evidence\n        %------------------------------------------------------------------\n        [z,i] = sort(-Z);\n        k     = k(i(1:nmax));\n        \n        % Flag a greedy search\n        %------------------------------------------------------------------\n        GS = 1;\n        \n    elseif isempty(k)\n        fprintf('\\nThere are no free parameters in this model.\\n')\n        return\n    else\n        GS = 0;\n    end\n    \n    \n    % compare models\n    %======================================================================\n    for j = 1:2\n        \n        if j == 1\n            % compare models with and without nmax parameters first\n            %--------------------------------------------------------------\n            K = repmat(logical([1;0]),1,numel(k));\n        else\n            % compare all combinations\n            %--------------------------------------------------------------\n            k = k(1:min(8,end));\n            K = spm_perm_mtx(numel(k));\n        end\n        \n        % Model search over new prior (covariance)\n        %------------------------------------------------------------------\n        nK    = size(K,1);\n        G     = zeros(1,nK);\n        for i = 1:nK\n            \n            % Identify parameters to retain (r) and to remove (s)\n            %--------------------------------------------------------------\n            r    = C; r(k(K(i,:))) = 0; s = 1 - r;\n            \n            % Create reduced prior covariance matrix\n            %--------------------------------------------------------------\n            R    = U'*diag(r + s*gamma)*U;\n            rC   = R*pC*R;\n            \n            % Create reduced prior means\n            %--------------------------------------------------------------\n            if isnumeric(beta)\n                S  = U'*diag(r)*U;\n                rE = S*pE + U'*s*beta;\n            else\n                rE = pE;\n            end\n            \n            G(i) = spm_log_evidence(qE,qC,pE,pC,rE,rC);\n        end\n        \n        % if sufficient complexity reduction then omit combinations\n        %------------------------------------------------------------------\n        if G(1) - G(end) > nmax && nparam > nmax\n            break;\n        else\n            nmax = 8;\n        end\n    end\n    \n    % posterior probability\n    %----------------------------------------------------------------------\n    p            = spm_softmax(G(:));\n    \n    %-Get selected model and prune redundant parameters\n    %======================================================================\n    [z,i]        = max(p);\n    C(k(K(i,:))) = 0;\n    \n    % Continue greedy search if any parameters have been eliminated\n    %----------------------------------------------------------------------\n    nelim  = full(sum(K(i,:)));\n    GS     = GS & nelim;\n    \n    % Show results\n    % --------------------------------------------------------------------- \n    fprintf('%i out of %i free parameters removed \\n',nelim,nparam)\n    \n    if nmax <= 8\n        spm_figure('Getwin','BMR - all'); clf\n        subplot(3,2,1)\n        if numel(G) > 32, plot(G,'k'), else, bar(G,'c'), end\n        title('log-posterior','FontSize',16)\n        xlabel('model','FontSize',12)\n        ylabel('log-probability','FontSize',12)\n        axis square\n        \n        subplot(3,2,2)\n        if numel(G) > 32, plot(p,'k'), else, bar(p,'r'), end\n        title('model posterior','FontSize',16)\n        xlabel('model','FontSize',12)\n        ylabel('probability','FontSize',12)\n        axis square\n        drawnow\n    end\n    \nend\n\n\n%-Inference over families (one family per coupling parameter)\n%==========================================================================\nfor i = 1:length(k)\n    Pk(1,i) = mean(p(~K(:,i)));\n    Pk(2,i) = mean(p( K(:,i)));\nend\nPk    = Pk(1,:)./sum(Pk);\nPp    = C;\nPp(k) = Pk;\n\n\n%-Bayesian model selection or average\n%==========================================================================\nqE    = DCM.Ep;\nqC    = DCM.Cp;\npE    = DCM.M.pE;\npC    = DCM.M.pC;\npE    = spm_vec(pE);\n\nswitch OPT\n    \n    case('BMA')\n        % Bayesian model averaging\n        %------------------------------------------------------------------\n        Gmax     = max(G);\n        \n    case('BMS')\n        % Bayesian model selection (place winning G outside Occam's window\n        %------------------------------------------------------------------\n        [Gmax,i] = max(G);\n        G(i)     = G(i) + 16;\n        Gmax     = Gmax + 16;\n        \n    otherwise\nend\n\nBMA   = {};\nfor i = 1:length(K)\n    \n    % if this mdel is in Occam's window, inlcude in BMA\n    %----------------------------------------------------------------------\n    if G(i) > (Gmax - 8)\n        \n        % reduced model\n        %------------------------------------------------------------------\n        r            = C;\n        r(k(K(i,:))) = 0;\n        s            = 1 - r;\n        R            = diag(r + s*gamma);\n        rC           = R*pC*R;\n        S            = diag(r);\n        if isnumeric(beta)\n            rE       = S*spm_vec(pE) + s*beta;\n        else\n            rE       = pE;\n        end\n        \n        % BMR\n        %------------------------------------------------------------------\n        [F,Ep,Cp]    = spm_log_evidence_reduce(qE,qC,pE,pC,rE,rC);\n        BMA{end + 1} = struct('Ep',Ep,'Cp',Cp,'F',F);\n    end\nend\n\nswitch OPT\n    case('BMA')\n        \n        % Bayesian model averaging\n        %------------------------------------------------------------------\n        BMA   = spm_dcm_bma(BMA);\n        Ep    = BMA.Ep;\n        Cp    = BMA.Cp;\n        \n    case('BMS')\n        \n        % Bayesian model selection\n        %------------------------------------------------------------------\n        BMA   = BMA{1};\n        Ep    = BMA.Ep;\n        Cp    = BMA.Cp;\n        \n    otherwise\nend\n\nif isstruct(Cp) || (spm_length(Cp) == spm_length(Ep))\n    Cp = diag(spm_vec(Cp));\nend\n\n% Show full and reduced conditional estimates (for Bayesian average)\n%--------------------------------------------------------------------------\nspm_figure('Getwin','BMR - all');\n\nif isstruct(DCM.Ep)\n    i  = spm_find_pC(pC,DCM.Ep,field);\nelse\n    i  = 1:spm_length(DCM.Ep);\nend\nqE     = spm_vec(qE);\nEp     = spm_vec(Ep);\n\nj = i(ismember(i,1:length(spm_vec(Ep))));\n\n% BMR summary and plotting\n%--------------------------------------------------------------------------\ntry\n    Pnames     = spm_fieldindices(DCM.Ep,k);\ncatch\n    try\n        Np     = numel(DCM.Pnames);\n        Pnames = DCM.Pnames(rem(k - 1,Np) + 1);\n    catch\n        Pnames = 'all parameters';\n    end\nend\nBMR.name = Pnames;\nBMR.F    = G;\nBMR.P    = p;\nBMR.K    = K;\nBMR.k    = k;\n\nsubplot(3,2,3), spm_plot_ci(qE(i),qC(i,i))\ntitle('MAP (full)','FontSize',16)\naxis square, a = axis;\n\nsubplot(3,2,4), spm_plot_ci(Ep(j),abs(Cp(j,j)))\ntitle('MAP (reduced)','FontSize',16), axis square, axis(a)\n\nsubplot(3,2,5), imagesc(1 - K')\nxlabel('model'), ylabel('parameter'), title('model space','FontSize',16)\nset(gca,'YTickLabel',BMR.name);\naxis tight, axis square\n\nsubplot(3,2,6)\nNp = length(i);\nbar(1:Np,diag(Pp(i)))\nxlabel('parameter'), title(' posterior','FontSize',16)\naxis square, drawnow, axis([0 (Np + 1) 0 1])\n\n\n%-Save Bayesian parameter average (Ep,Cp) and family-wise inference (Pp)\n%==========================================================================\nif isstruct(DCM.Ep)\n    if Np < 32\n        legend(spm_fieldindices(DCM.Ep,i))\n    end\n    Pp    = spm_unvec(Pp,DCM.Ep);\n    Ep    = spm_unvec(Ep,DCM.Ep);\nend\n\nDCM.Pp    = Pp;        % Model posterior over parameters (with and without)\nDCM.Ep    = Ep;        % Bayesian model averages\nDCM.Cp    = Cp;        % Bayesian model variance\n\n% Clear free energy if supplied (which is no longer meaningful)\nif isfield(DCM,'F')\n    DCM = rmfield(DCM,'F');\nend\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dcm_bmr_all.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22719058138093468}}
{"text": "function [adfreq, n, ts, fn, d] = nex_cont(filename, varname)\n% nex_cont(filename, varname): Read continuous variable from a .nex file\n%\n% [adfreq, n, ts, fn, d] = nex_cont(filename, varname)\n%\n% INPUT:\n%   filename - if empty string, will use File Open dialog\n%   varname - variable name\n%\n%           continuous (a/d) data come in fragments. Each fragment has a timestamp\n%           and a number of a/d data points. The timestamp corresponds to\n%           the time of recording of the first a/d value in this fragment.\n%           All the data values stored in the vector d. \n% OUTPUT:\n%   n - total number of data points \n%   ts - array of fragment timestamps (one timestamp for fragment, in seconds)\n%   fn - number of data points in each fragment\n%   d - array of a/d values (in millivolts)\n\n% original from Plexon, download from http://www.plexoninc.com (8/4/02)\n% modifications by Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nn = 0;\nadfreq = 0;\nts = 0;\nfn = 0;\nd = 0;\n\nif(nargin ~= 2)\n   disp('2 input arguments are required')\n   return\nend\n\nif(ischar(filename) == 0)\n   disp('input arguments should be character arrays')\n   return\nend\n\nif(ischar(varname) == 0)\n   disp('input arguments should be character arrays')\n   return\nend\n\nif(length(filename) == 0)\n   [fname, pathname] = uigetfile('*.nex', 'Select a Nex file');\n    filename = strcat(pathname, fname);\nend\n\nfid = fopen(filename, 'r', 'ieee-le');\nif(fid == 0)\n   return\nend\n\ndisp(strcat('file = ', filename));\nmagic = fread(fid, 1, 'int32');\nversion = fread(fid, 1, 'int32');\ncomment = fread(fid, 256, 'char');\nfreq = fread(fid, 1, 'double');\ntbeg = fread(fid, 1, 'int32');\ntend = fread(fid, 1, 'int32');\nnvar = fread(fid, 1, 'int32');\nfseek(fid, 260, 'cof');\nname = zeros(1, 64);\nfound = 0;\nfor i=1:nvar\n    type = fread(fid, 1, 'int32');\n    var_version = fread(fid, 1, 'int32');\n    name = fread(fid, [1 64], 'char');\n    offset = fread(fid, 1, 'int32');\n    nf = fread(fid, 1, 'int32');\n    dummy = fread(fid, 32, 'char');\n    adfreq = fread(fid, 1, 'double');\n    adtomv = fread(fid, 1, 'double');\n    n = fread(fid, 1, 'int32');\n    name = char(name);\n    name = deblank(name);\n    k = strcmp(name, deblank(varname));\n    if(k == 1)\n        if type ~= 5\n            disp(sprintf('%s is not a continuous variable', deblank(varname)));\n            return;\n        end\n        found = 1;\n        fseek(fid, offset, 'bof');\n        ts = fread(fid, [1 nf], 'int32');\n        fn = fread(fid, [1 nf], 'int32');\n        d = fread(fid, [1 n], 'int16');\n        break\n    end\n    dummy = fread(fid, 76, 'char');\nend\n\nfclose(fid);\n\nif found == 0\n    disp('did not find variable in the file');\nelse\n    ts = ts/freq;\n    d = d*adtomv;\n    fn(nf+1) = n;\n    fn = diff(fn);\n    disp(strcat('number of data points = ', num2str(n)));\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/nex_cont.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.22719056866283735}}
{"text": "function  [ output_image, meta ]= read_gff( filename, varargin )\n%READ_GFF Sandia GSAT Image File Format\n%   complexdata = read_gff( filename, rowrange, colrange, subsample, decimationfun )\n%\n%   INPUTS:\n%      FILENAME:      Input file to read.\n%      ROWRANGE:      1x2 array [first row, last row], row #1 is top.\n%         Default is entire image range.  Can also use an empty array ([])\n%         to specify entire row range.\n%      COLRANGE:      1x2 array [first column, last column], column #1 is\n%         left side.   Default is entire image range.  Can also use an\n%         empty array ([]) to specify entire column range.\n%      SUBSAMPLE:     1x2 array [subsample rate in first dimension,\n%         subsample ratein second dimension].  Default is [1 1] (no\n%         subsampling).\n%      DECIMATIONFUN: Decimation function, used if SUBSAMPLE is defined to\n%         be greater than 1.  Options include 'none' (default)', 'max',\n%         'mean', or any other function defined in Matlab.\n%\n%   OUTPUTS:\n%      COMPLEXDATA:   Array of complex data values of data type single\n%         complex.\n%      META:          Structure containing metadata\n%\n%   Author: Wade Schwartzkopf (NGA/IDT)\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n% Read metadata\nnative_meta = read_gff_meta(filename);\nmeta=meta2sicd_gff(native_meta);\nmeta.native.gff=native_meta;\nif native_meta.RowMajor\n   datasize = [native_meta.RgCnt native_meta.AzCnt];\nelse\n   datasize = [native_meta.AzCnt native_meta.RgCnt];\nend\nswitch native_meta.ImageType\n    case 0\n        datatype='uchar';\n    case 1\n        if native_meta.BytesPerPixel == 4 % 2 bytes phase, 2 bytes magnitude\n            datatype='uint16';\n        else % 8 bytes total, 4 bytes phase, 2 bytes magnitude\n            datatype='uint32';\n        end\n    case 2\n        datatype='float32';\nend\nif native_meta.Endian\n    endian='b';\nelse\n    endian='l';\nend\n\n% Parse input parameters; reverse indices since image 180 degrees rotated\n% from shadows down orientations\nnewvarargin=varargin;\nif nargin>1\n    rowrange=datasize(1)-varargin{1}(end:-1:1)+1;\n    if native_meta.RowMajor\n        newvarargin{2}=rowrange;\n        newvarargin{1}=[];\n    else\n        newvarargin{1}=rowrange;\n    end\nend\nif nargin>2\n    colrange=datasize(2)-varargin{2}(end:-1:1)+1;\n    if native_meta.RowMajor\n        newvarargin{1}=colrange;\n    else\n        newvarargin{2}=colrange;\n    end\nend\nif nargin>3\n    if native_meta.RowMajor\n        newvarargin{3}=varargin{3}(end:-1:1);\n    end\nend\n\n% Read complex data\nfid = fopen(filename,'r',endian);\noutput_image = read_complex(fid,datasize,native_meta.Length,...\n    datatype,logical(native_meta.ImageType),newvarargin{:});\nfclose(fid);\n\nif native_meta.ImageType==1 % Int types are phase-magnitude, rather than real-imag, which read_complex expects\n    output_image=double(imag(output_image)).*exp(1i * double(real(output_image)) * 2*pi/(2^16));\nend\nif native_meta.RowMajor\n    output_image=output_image.';\nend\noutput_image=rot90(output_image,2); % GFF stored shadows up; switch to shadows down\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/IO/complex/gff/read_gff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547361921928}}
{"text": "function diffS = comparePyradWithIBSI1OrigImgWithInterp\n% Compare pyradiomics features against IBSI benchmark for config C. \n%--------------------------------------------------------------------------\n% AI 7/1/2020\n\n%% Calc. features for configuration 'C' using Pyradiomics\nfpath = fullfile(fileparts(fileparts(getCERRPath)),...\n    'Unit_Testing/data_for_cerr_tests/IBSI1_CT_phantom/IBSILungCancerCTImage.mat.bz2');\nplanC = loadPlanC(fpath,tempdir);\nplanC = updatePlanFields(planC);\nplanC = quality_assure_planC(fpath,planC);\nstrName='GTV-1';\n\nconfigPath_avg = fullfile(fileparts(fileparts(getCERRPath)),...\n    'Unit_Testing/settings_for_comparisons/pyRadConfigC_avg.yaml');\npyFeat1S = calcRadiomicsFeatUsingPyradiomics(planC,strName,configPath_avg);\nconfigPath_merge = fullfile(fileparts(fileparts(getCERRPath)),...\n    'Unit_Testing/settings_for_comparisons/pyRadConfigC_merge.yaml');\npyFeat2S = calcRadiomicsFeatUsingPyradiomics(planC,strName,configPath_merge);\n\n%% Compare with IBSI\n\n% Get IBSI bechmark\nibsiConfigCResult = fullfile(fileparts(fileparts(getCERRPath)),...\n    'Unit_Testing/data_for_cerr_tests/IBSI1_CT_phantom/IBSI_results_configC.mat');\ntemp = load(ibsiConfigCResult);\nIBSIfeatS = temp.IBSIfeatS;\n\n% Shape features\npyShapeS = getPyradFeatDict(pyFeat1S,{'original_shape'});\npyShapeS = mapPyradFieldnames(pyShapeS,'original','shape');\nshapeFeatC = fieldnames(IBSIfeatS.shapeS);\nfor n = 1:length(shapeFeatC)\n    ibsiVal = IBSIfeatS.shapeS.(shapeFeatC{n});\n    if isfield(pyShapeS,shapeFeatC{n})\n        pyRadVal = pyShapeS.(shapeFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.Shape.(shapeFeatC{n}) = pctDiff;\n    end\nend\n\n% First order features\npyFirstOrdS = getPyradFeatDict(pyFeat1S,{'original_firstorder'});\npyFirstOrdS = mapPyradFieldnames(pyFirstOrdS,'original','firstorder');\n%Convert kurtosis to excess kurtosis\npyFirstOrdS.kurtosis = pyFirstOrdS.kurtosis -3;\nfirstOrdFeatC = fieldnames(IBSIfeatS.Original.firstOrderS);\nfor n = 1:length(firstOrdFeatC)\n    ibsiVal = IBSIfeatS.Original.firstOrderS.(firstOrdFeatC{n});\n    if isfield(pyFirstOrdS,firstOrdFeatC{n})\n        pyRadVal = pyFirstOrdS.(firstOrdFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.FirstOrder.(firstOrdFeatC{n}) = pctDiff;\n    end\nend\n\n\n% GLCM\n%Avg\npyGlcmS = getPyradFeatDict(pyFeat1S,{'original_glcm'});\npyGlcmS = mapPyradFieldnames(pyGlcmS,'original','glcm');\nglcmFeatC = fieldnames(IBSIfeatS.Original.glcmFeatS.AvgS);\nfor n = 1:length(glcmFeatC)\n    ibsiVal = IBSIfeatS.Original.glcmFeatS.AvgS.(glcmFeatC{n});\n    if isfield(pyGlcmS,glcmFeatC{n})\n        pyRadVal = pyGlcmS.(glcmFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.GLCM.Avg.(glcmFeatC{n}) = pctDiff;\n    end\nend\n%Merge\npyGlcm2S = getPyradFeatDict(pyFeat2S,{'original_glcm'});\npyGlcm2S = mapPyradFieldnames(pyGlcm2S,'original','glcm');\nglcmFeat2C = fieldnames(IBSIfeatS.Original.glcmFeatS.CombS);\nfor n = 1:length(glcmFeat2C)\n    ibsiVal = IBSIfeatS.Original.glcmFeatS.CombS.(glcmFeat2C{n});\n    if isfield(pyGlcm2S,glcmFeat2C{n})\n        pyRadVal = pyGlcm2S.(glcmFeat2C{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.GLCM.Merge.(glcmFeat2C{n}) = pctDiff;\n    end\nend\n\n% GLRLM\n%Avg\npyGlrlmS = getPyradFeatDict(pyFeat1S,{'original_glrlm'});\npyGlrlmS = mapPyradFieldnames(pyGlrlmS,'original','glrlm');\nglrlmFeatC = fieldnames(IBSIfeatS.Original.rlmFeatS.AvgS);\nfor n = 1:length(glrlmFeatC)\n    ibsiVal = IBSIfeatS.Original.rlmFeatS.AvgS.(glrlmFeatC{n});\n    if isfield(pyGlrlmS,glrlmFeatC{n})\n        pyRadVal = pyGlrlmS.(glrlmFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.GLRLM.Avg.(glrlmFeatC{n}) = pctDiff;\n    end\nend\n%Merge\npyGlrlm2S = getPyradFeatDict(pyFeat2S,{'original_glrlm'});\npyGlrlm2S = mapPyradFieldnames(pyGlrlm2S,'original','glrlm');\nglrlm2FeatC = fieldnames(IBSIfeatS.Original.rlmFeatS.CombS);\nfor n = 1:length(glrlm2FeatC)\n    ibsiVal = IBSIfeatS.Original.rlmFeatS.CombS.(glrlm2FeatC{n});\n    if isfield(pyGlrlm2S,glrlm2FeatC{n})\n        pyRadVal = pyGlrlm2S.(glrlm2FeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.GLRLM.Merge.(glrlm2FeatC{n}) = pctDiff;\n    end\nend\n\n% NGTDM\npyNgtdmS = getPyradFeatDict(pyFeat1S,{'original_ngtdm'});\npyNgtdmS = mapPyradFieldnames(pyNgtdmS,'original','ngtdm');\nngtdmFeatC = fieldnames(IBSIfeatS.Original.ngtdmFeatS);\nfor n = 1:length(ngtdmFeatC)\n    ibsiVal = IBSIfeatS.Original.ngtdmFeatS.(ngtdmFeatC{n});\n    if isfield(pyNgtdmS,ngtdmFeatC{n})\n        pyRadVal = pyNgtdmS.(ngtdmFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.NGTDM.(ngtdmFeatC{n}) = pctDiff;\n    end\nend\n\n% SZM features\npyGlszmS = getPyradFeatDict(pyFeat1S,{'original_glszm'});\npyGlszmS = mapPyradFieldnames(pyGlszmS,'original','glszm');\nglszmFeatC = fieldnames(IBSIfeatS.Original.szmFeatS);\nfor n = 1:length(glszmFeatC)\n    ibsiVal = IBSIfeatS.Original.szmFeatS.(glszmFeatC{n});\n    if isfield(pyGlszmS,glszmFeatC{n})\n        pyRadVal = pyGlszmS.(glszmFeatC{n});\n        pctDiff = (pyRadVal-ibsiVal)*100/ibsiVal;\n        diffS.GLSZM.(glszmFeatC{n}) = pctDiff;\n    end\nend\n\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/Unit_Testing/tests_for_cerr/comparePyradWithIBSI1OrigImgWithInterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547361921928}}
{"text": "%     NeuroSLAM System Copyright (C) 2018-2019 \n%     NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n%     Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n%     The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n%     The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n%     Reference:\n%     Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n%     \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n% Feb 6, 2019\ngroundTruthFile = 'C:\\NeuroSLAM_Datasets\\02_NeuroSLAM_Groudtruth\\01_SynPerData_GT.txt';\nexpMapFile = 'C:\\NeuroSLAM_Datasets\\03_NeuroSLAM_Experiments_Results\\SynPerData\\01_exp_map_ml.txt';\n% plot_3d_multilayer_experience_map(groundTruthFile, expMapFile, xExpMapScaling, yExpMapScaling, zExpMapScaling, xExpMapTrans, yExpMapTrans, zExpMapTrans, xGtScaling, yGtScaling, zGtScaling)\nplot_3d_multilayer_experience_map(groundTruthFile, expMapFile, 0.1, 0.1, 0.1, 1.2, 1.3, 0, 21.5,23, 23);", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/08_draw_fig_for_paper/01_EM_OM/SynPerData/draw_3d_ml_em_synperdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547361921928}}
{"text": "function data=createdatamatpt(data,E,win)\n% Helper function to create an event triggered matrix from a single\n% channel of spike times. \n% Usage:  data=createdatamatpt(data,E,win)\n% Inputs:\n% data   (input spike times as a structural array or as a column vector) - required\n% E      (events to use as triggers) - required \n% win    (window around triggers to use data matrix -[winl winr]) - required \n%          e.g [1 1] uses a window starting 1 sec before E and\n%              ending 1 sec after E if E and data are in secs.\n% Note that E, win and data must have consistent units\n% Outputs:\n% data      (event triggered data as a structural array - times are stored\n% relative to the E-winl\n%\nif nargin < 3; error('Need all input arguments'); end;\nif isstruct(data);\n   fnames=fieldnames(data);\n   eval(['dtmp=data.' fnames{1} ';'])\nelse\n   dtmp=data(:);\nend;\nNE=length(E);\nwinl=win(1);\nwinr=win(2);\ndata2(1:NE)=struct('times',[]);\nfor n=1:NE,\n    indx=find(dtmp > E(n)-winl & dtmp<= E(n)+winr);\n    if ~isempty(indx)\n       data2(n).times=dtmp(indx)-E(n)+winl;\n    else\n       data2(n).times=[];\n    end\nend\ndata=data2;", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/pointtimes/createdatamatpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547297395536}}
{"text": "%% --------------------------\n% MemNet_M6R6 for image denoising (gaussian noise)\n% edit by yingtai 12/08/2017\n% -------------------------------\nfunction test_MemNet_M6R6_GD()\nsetenv('LC_ALL','C')\naddpath /data2/taiying/MSU_Code/119-caffe-matlab/matlab; % change to your caffe path\nsetenv('GLOG_minloglevel','2')\naddpath('../');\naddpath('../evaluation_func/');\naddpath('../evaluation_func/matlabPyrTools-master/');\n\n%% parameters\ngpu_id = 5;\nNoise_level = 30;\ndata_set_id = 1;\nthresh_hei = 120; % threshold patch size for inference, since too big image may cost too much memory\nthresh_wid = 120;\nrf = 16;\n\npathfolder = ['../../data/GaussianDenoising/'];\nif data_set_id == 1\n    % S14\n    setTestCur = 'S14';\n    path = [pathfolder setTestCur '/'];\n    d = dir([path '*.bmp']);\n    filenum = 14;\nend\nif data_set_id == 2\n    % BSD200\n    setTestCur = 'BSD200';\n    path = [pathfolder setTestCur '/'];\n    d = dir([path '*.jpg']);\n    filenum = 200;\nend\n\nsavepath = ['./results/'];\nfolderResultCur = fullfile(savepath, [setTestCur,'_Noise',num2str(Noise_level)]);\n%%% folder to store results\nif ~exist(folderResultCur,'file')\n    mkdir(folderResultCur);\nend\n\nmean_noised = [];\nmean_memnet = [];\n% caffe.set_mode_cpu(); % for CPU\ncaffe.set_mode_gpu(); % for GPU\ncaffe.set_device(gpu_id);\n\n\nweights = ['../../model/MemNet_M6R6_80C64_GD.caffemodel'];\nmodel_path = './MemNet_M6R6_80C64_deploy';\n\nnoise_set =[];\nmemnet_set = [];\nim_b_set = cell(filenum,1);\nim_h_set = cell(filenum,1);\nim_gnd_set = cell(filenum,1);\n\nfor iii = 1:1:length(d)\n    disp(['id: ' num2str(iii)]);\n    imageName = d(iii).name;\n    imageName = imageName(1:end-4);\n    im  = imread([path d(iii).name]);\n    randn('seed',54);\n    \n    %% test: resize\n    if data_set_id == 3\n        im = imresize(im,1/2);\n    end\n    \n    %% rgb -> gray\n    im_gray = im;\n    if size(im,3)>1\n        im_gray = rgb2gray(im);\n    end\n    im_gnd = im2double(im_gray);\n    \n    [hei,wid,channels] = size(im_gnd);\n    % add noise\n    im_b = single(im_gnd + Noise_level/255*randn(size(im_gray)));\n    \n    %% adaptively spilt\n    % decide patch numbers\n    hei_patch = ceil(hei/(thresh_hei+rf));\n    wid_patch = ceil(wid/(thresh_wid+rf));\n    hei_stride = ceil(hei/hei_patch);\n    wid_stride = ceil(wid/wid_patch);\n    use_start_x = 0;\n    use_start_y = 0;\n    use_end_x = 0;\n    use_end_y = 0;\n    \n    ext_start_x = 0;\n    ext_end_x = 0;\n    ext_start_y = 0;\n    ext_end_y = 0;\n    \n    posext_start_x = 0;\n    posext_start_y = 0;\n    posext_end_x = 0;\n    posext_end_y = 0;\n    \n    % extract each patch for inference\n    im_h = [];\n    for x = 1 : hei_stride : hei\n        for y = 1 : wid_stride : wid\n            % decide the length of hei and wid for each patch\n            use_start_x = x;\n            use_start_y = y;\n            if x - rf > 1 % add border\n                ext_start_x = x-rf;\n                posext_start_x = rf+1;\n            else\n                ext_start_x = x;\n                posext_start_x = 1;\n            end\n            if y-rf > 1\n                ext_start_y = y-rf;\n                posext_start_y = rf+1;\n            else\n                ext_start_y = y;\n                posext_start_y = 1;\n            end\n            \n            use_end_x = use_start_x+hei_stride-1;\n            use_end_y = use_start_y+wid_stride-1;\n            \n            \n            if use_start_x+hei_stride+rf-1 <= hei\n                hei_length = hei_stride+rf;\n                ext_end_x = use_start_x+hei_length-1;\n                posext_end_x = hei_length-rf+posext_start_x-1;\n                \n            else\n                hei_length = hei-ext_start_x+1;\n                ext_end_x = ext_start_x+hei_length-1;\n                posext_end_x = hei_length;\n                use_end_x = ext_start_x+hei_length-1;\n            end\n            if use_start_y+wid_stride+rf-1 <= wid\n                wid_length = wid_stride+rf;\n                ext_end_y = use_start_y+wid_length-1;\n                posext_end_y = wid_length-rf+posext_start_y-1;\n                \n            else\n                wid_length = wid-ext_start_y+1;\n                ext_end_y = ext_start_y+wid_length-1;\n                posext_end_y = wid_length;\n                use_end_y = ext_start_y+wid_length-1;\n            end\n            \n            subim_input = im_b(ext_start_x : ext_end_x, ext_start_y : ext_end_y);  % input\n            data = permute(subim_input,[2, 1, 3]);\n            model = [model_path '.prototxt'];\n            subim_output = do_cnn(model,weights,data);\n            subim_output = subim_output';\n            subim_output = subim_output(posext_start_x:posext_end_x,posext_start_y:posext_end_y);\n            % fill im_h with sub_output\n            im_h(use_start_x:use_end_x,use_start_y:use_end_y) = subim_output;\n        end\n    end\n    \n    im_h1 = single(im_h) * 255;\n    im_gnd1 = single(im_gnd) * 255;\n    im_b1 = single(im_b) * 255;\n    \n    im_b_set{iii} = im_b1;\n    im_h_set{iii} = im_h1;\n    im_gnd_set{iii} = im_gnd1;\n  \n    %% compute PSNR and SSIM and IFC\n    noised(1) = compute_psnr(im_gnd1,im_b1);\n    memnet(1) = compute_psnr(im_gnd1,im_h1);\n    noised(2) = ssim_index(im_gnd1,im_b1);\n    memnet(2) = ssim_index(im_gnd1,im_h1);\n    \n    noise_set = [noise_set; noised];\n    memnet_set = [memnet_set; memnet];\n    %% save images\n    imwrite(uint8(im_h1),fullfile(folderResultCur,[imageName,'_Noise',num2str(Noise_level),'.png']));\nend\nmean_noised = [mean_noised; [mean(noise_set(:,1)) mean(noise_set(:,2))]];\nmean_memnet = [mean_memnet; [mean(memnet_set(:,1)) mean(memnet_set(:,2))]];\n\n%%% save PSNR and SSIM metrics\nPSNR_set = memnet_set(:,1);\nSSIM_set = memnet_set(:,2);\nsave(fullfile(folderResultCur,['PSNR_',setTestCur,'_Noise',num2str(Noise_level),'.mat']),['PSNR_set'])\nsave(fullfile(folderResultCur,['SSIM_',setTestCur,'_Noise',num2str(Noise_level),'.mat']),['SSIM_set'])\n\ndisp(['noise = ' num2str(mean_noised(1,:)) '---- MemNet = ' num2str(mean_memnet(1,:))]);\n\nend\n \n\n\n", "meta": {"author": "tyshiwo", "repo": "MemNet", "sha": "d37a6abd4467e6af2dea84bf9a64429a40c87f28", "save_path": "github-repos/MATLAB/tyshiwo-MemNet", "path": "github-repos/MATLAB/tyshiwo-MemNet/MemNet-d37a6abd4467e6af2dea84bf9a64429a40c87f28/test/MemNet_M6R6_80C64/test_MemNet_M6R6_GD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.22709170494192044}}
{"text": "warning('off','all');\n\ntic;\nimage = double(imread('forest.jpg'))/255;\n\nimage = imresize(image, 0.1);\n\nresult = dehaze(image, 0.95, 15);\ntoc;\n\nfigure, imshow(image)\nfigure, imshow(result)\n\nwarning('on','all');", "meta": {"author": "sjtrny", "repo": "Dark-Channel-Haze-Removal", "sha": "65d8f60b5bddef1665aa8ee88fdba73a4f61a664", "save_path": "github-repos/MATLAB/sjtrny-Dark-Channel-Haze-Removal", "path": "github-repos/MATLAB/sjtrny-Dark-Channel-Haze-Removal/Dark-Channel-Haze-Removal-65d8f60b5bddef1665aa8ee88fdba73a4f61a664/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.22689722178358437}}
{"text": "% Wrapper for vl_nntranslate2D block\n% inputs{1} :   X     : 1 x 2 x n x b\n% inputs{2} :   T     : 1 x 2 x 1 x b\n% outputs{1}:   y     : 1 x 2 x n x b\n\nclassdef translate2D < dagnn.Layer\n    methods\n        function outputs = forward(~, inputs, ~)\n            \n            useGPU = isa(inputs{1}, 'gpuArray');\n            if useGPU\n                outputs{1} = gpuArray ( vl_nntranslate2D(gather(inputs{1}), gather(inputs{2})) );\n            else\n                outputs{1} = vl_nntranslate2D(inputs{1}, inputs{2});\n            end\n                        \n        end\n        \n        function [derInputs, derParams] = backward(~, inputs, ~, derOutputs)\n            \n            useGPU = isa(inputs{1}, 'gpuArray');\n            if useGPU\n                [y,dsdy] = vl_nntranslate2D(gather(inputs{1}),gather(inputs{2}), gather(derOutputs{1}));\n                derInputs = {gpuArray(y),gpuArray(dsdy)};\n            else\n                [y,dsdy] = vl_nntranslate2D(inputs{1},inputs{2}, derOutputs{1});\n                derInputs = {y,dsdy};\n            end\n            \n            derParams = {};\n        end\n        \n        function outputSizes = getOutputSizes(~, inputSizes)\n            outputSizes = inputSizes{1};\n        end\n        \n        function obj = translate2D(varargin)\n            obj.load(varargin);\n        end\n    end\nend\n", "meta": {"author": "anilbas", "repo": "3DMMasSTN", "sha": "c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837", "save_path": "github-repos/MATLAB/anilbas-3DMMasSTN", "path": "github-repos/MATLAB/anilbas-3DMMasSTN/3DMMasSTN-c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837/dagnn/translate2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22687580170644353}}
{"text": "function [rec,prec,ap] = wsddnVOCevaldet(VOCopts,cls,res,draw)\n\n% load test set\ntic;\nVOCopts.annocachepath=[VOCopts.localdir '%s_anno_cache.mat'];\ncp=sprintf(VOCopts.annocachepath,VOCopts.testset);\nif exist(cp,'file')\n  fprintf('%s: pr: loading ground truth\\n',cls);\n  load(cp,'gtids','recs');\nelse\n  [gtids,t]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');\n  for i=1:length(gtids)\n    % display progress\n    if toc>1\n      fprintf('%s: pr: load: %d/%d\\n',cls,i,length(gtids));\n      drawnow;\n      tic;\n    end\n    \n    % read annotation\n    recs(i)=PASreadrecord(sprintf(VOCopts.annopath,gtids{i}));\n  end\n  save(cp,'gtids','recs');\nend\n\nfprintf('%s: pr: evaluating detections\\n',cls);\n\n% hash image ids\nhash=wsddnVOChash_init(gtids);\n\n% extract ground truth objects\n\nnpos=0;\ngt(length(gtids))=struct('BB',[],'diff',[],'det',[]);\nfor i=1:length(gtids)\n  % extract objects of class\n  clsinds=strmatch(cls,{recs(i).objects(:).class},'exact');\n  gt(i).BB=cat(1,recs(i).objects(clsinds).bbox)';\n  gt(i).diff=[recs(i).objects(clsinds).difficult];\n  gt(i).det=false(length(clsinds),1);\n  npos=npos+sum(~gt(i).diff);\nend\n\n% load results\nids        = res.ids;\nconfidence = res.confidence;\nBB         = res.bbox';\n\n% sort detections by decreasing confidence\n[sc,si]=sort(-confidence);\nids=ids(si);\nBB=BB(:,si);\n\n% assign detections to ground truth objects\nnd=length(confidence);\ntp=zeros(nd,1);\nfp=zeros(nd,1);\ntic;\nfor d=1:nd\n  % display progress\n  if toc>1\n    fprintf('%s: pr: compute: %d/%d\\n',cls,d,nd);\n    drawnow;\n    tic;\n  end\n  \n  % find ground truth image\n  i=wsddnVOChash_lookup(hash,ids{d});\n  if isempty(i)\n    error('unrecognized image \"%s\"',ids{d});\n  elseif length(i)>1\n    error('multiple image \"%s\"',ids{d});\n  end\n  \n  % assign detection to ground truth object if any\n  bb=BB(:,d);\n  ovmax=-inf;\n  for j=1:size(gt(i).BB,2)\n    bbgt=gt(i).BB(:,j);\n    bi=[max(bb(1),bbgt(1)) ; max(bb(2),bbgt(2)) ; min(bb(3),bbgt(3)) ; min(bb(4),bbgt(4))];\n    iw=bi(3)-bi(1)+1;\n    ih=bi(4)-bi(2)+1;\n    if iw>0 & ih>0\n      % compute overlap as area of intersection / area of union\n      ua=(bb(3)-bb(1)+1)*(bb(4)-bb(2)+1)+...\n        (bbgt(3)-bbgt(1)+1)*(bbgt(4)-bbgt(2)+1)-...\n        iw*ih;\n      ov=iw*ih/ua;\n      if ov>ovmax\n        ovmax=ov;\n        jmax=j;\n      end\n    end\n  end\n  % assign detection as true positive/don't care/false positive\n  if ovmax>=VOCopts.minoverlap\n    if ~gt(i).diff(jmax)\n      if ~gt(i).det(jmax)\n        tp(d)=1;            % true positive\n        gt(i).det(jmax)=true;\n      else\n        fp(d)=1;            % false positive (multiple detection)\n      end\n    end\n  else\n    fp(d)=1;                    % false positive\n  end\nend\n\n% compute precision/recall\nfp=cumsum(fp);\ntp=cumsum(tp);\nrec=tp/npos;\nprec=tp./(fp+tp);\n\nap=wsddnVOCap(rec,prec);\n\nif draw\n  % plot precision/recall\n  plot(rec,prec,'-');\n  grid;\n  xlabel 'recall'\n  ylabel 'precision'\n  title(sprintf('class: %s, subset: %s, AP = %.3f',cls,VOCopts.testset,ap));\nend\n", "meta": {"author": "hbilen", "repo": "WSDDN", "sha": "bfdaa3f9ffed45e52a11a1342fd7476e08dfac39", "save_path": "github-repos/MATLAB/hbilen-WSDDN", "path": "github-repos/MATLAB/hbilen-WSDDN/WSDDN-bfdaa3f9ffed45e52a11a1342fd7476e08dfac39/pascal/wsddnVOCevaldet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.2268385646115766}}
{"text": "function [Ep,Cp] = spm_dcm_sparse(DCM,field)\n% Bayesian model reduction of all permutations of model parameters\n% FORMAT [RCM,BMR] = spm_dcm_sparse(DCM,field\n%\n% DCM      - A single estimated DCM (or PEB) structure:\n%\n%  DCM.M.pE  - prior expectation\n%  DCM.M.pC  - prior covariance\n%  DCM.Ep    - posterior expectation\n%  DCM.Cp    - posterior covariances\n%  DCM.gamma - prior variance    of reduced parameters (default: 0)\n%\n% field      - parameter fields in DCM{i}.Ep to optimise [default: {'A','B'}]\n%             'All' will invoke all fields (i.e. random effects)\n%             If Ep is not a structure, all parameters will be considered\n%\n% Returns:\n%  Ep    - (BMA) posterior expectation\n%  Cp    - (BMA) posterior covariance\n%\n%--------------------------------------------------------------------------\n% This routine searches over reduced (nested) models of a full model (DCM)\n% using Bayesian model reduction and performs Bayesian Model Averaging.\n% 'Reduced' means some free parameters (parameters with a non-\n% zero prior covariance) are switched off by fixing their prior variance\n% to zero.This version incorporates a sparsity  prior over models (with a\n% Gaussian hyperprior). In other words, the free energy is taken to be the\n% likelihood of some data under a given model. The prior on that model\n% corresponds to a softmax function of the prior entropy. Finally, the\n% softmax (Gibbs) parameter is equipped with a Gaussian prior. Using\n% Bayesian model reduction, this routine evaluates the joint probability\n% over model and softmax sparsity parameter. The marginals over model space\n% are then used to form Bayesian model averaging.\n%\n% The greedy search in this version simply evaluates the log evidence of\n% models with and without each parameter and then successively removes the\n% parameters with the least evidence.\n%\n% See also: spm_dcm_bmr and spm_dcm_bmr_all\n%__________________________________________________________________________\n% Copyright (C) 2010-2014 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston, Peter Zeidman\n% $Id: spm_dcm_sparse.m 7082 2017-05-27 19:36:36Z karl $\n\n\n%-Number of parameters to consider before invoking greedy search\n%--------------------------------------------------------------------------\nnmax  = 8;\n\n%-specification of null prior covariance\n%--------------------------------------------------------------------------\nif isfield(DCM,'beta'),  beta  = DCM.beta;  else, beta  = 0; end\nif isfield(DCM,'gamma'), gamma = DCM.gamma; else, gamma = 0; end\n\n%-Check fields of parameter stucture\n%--------------------------------------------------------------------------\nif nargin < 2 || isempty(field)\n    field = {'A','B'};\nend\nif ischar(field)\n    field = {field};\nend\n\n%-dela with filenames stucture\n%--------------------------------------------------------------------------\nif ischar(DCM)\n    DCM = load(DCM,'DCM');\n    DCM = DCM.DCM;\nend\n\n% Get prior covariances\n%--------------------------------------------------------------------------\nif isstruct(DCM.M.pC), DCM.M.pC = diag(spm_vec(DCM.M.pC)); end\nif spm_length(DCM.M.pE) ~= size(DCM.M.pC,1)\n    DCM.M.pC = diag(spm_vec(DCM.M.pC));\nend\n\n% Get priors and posteriors\n%--------------------------------------------------------------------------\nqE  = DCM.Ep;\nqC  = DCM.Cp;\npE  = DCM.M.pE;\npC  = DCM.M.pC;\n\n% Remove (a priori) null space\n%--------------------------------------------------------------------------\nU   = spm_svd(pC);\nqE  = U'*spm_vec(qE);\npE  = U'*spm_vec(pE);\nqC  = U'*qC*U;\npC  = U'*pC*U;\n\n\n%-Greedy search (GS) - eliminating parameters in a top down fashion\n%==========================================================================\n\n% Accumulated reduction vector (C)\n%--------------------------------------------------------------------------\nq   = diag(DCM.M.pC);\nif sum(q < 1024)\n    C   = double(q > mean(q(q < 1024))/1024);\nelse\n    C   = double(q > 0);\nend\n\n%-Find free coupling parameters\n%----------------------------------------------------------------------\nif isstruct(DCM.Ep)\n    k = spm_fieldindices(DCM.Ep,field{:});\nelse\n    k = 1:spm_length(DCM.Ep);\nend\nk     = k(find(C(k))); %#ok<FNDSB>\n\n% Model search over new prior without the i-th parameter\n%------------------------------------------------------------------\nnparam = length(k);\nfor i  = 1:nparam\n    \n    % Identify parameters to retain r and to remove s\n    %--------------------------------------------------------------\n    r    = C; r(k(i)) = 0; s = 1 - r;\n    \n    % Create reduced priors\n    %--------------------------------------------------------------\n    R    = U'*diag(r + s*gamma)*U;\n    rC   = R*pC*R;\n    F(i) = spm_log_evidence(qE,qC,pE,pC,pE,rC);\n        \nend\n\n% Find parameters with the least evidence\n%--------------------------------------------------------------------------\n[F,i] = sort(-F);\nk     = k(i);\nM     = cell(0);\nfor i = 1:nparam\n    \n\n    % parameters to retain (r) and to remove (s)\n    %----------------------------------------------------------------------\n    r    = C; r(k(1:i)) = 0; s = 1 - r;\n    \n    % Create reduced prior covariance matrix\n    %----------------------------------------------------------------------\n    R    = U'*diag(r + s*gamma)*U;\n    rC   = R*pC*R;\n    \n    % record\n    %----------------------------------------------------------------------\n    M(i).F  = spm_log_evidence(qE,qC,pE,pC,pE,rC)\n    M(i).H  = spm_logdet(rC);\n    M(i).rC = rC;\n    \nend\n\n% Sparsity hyperpriors\n%--------------------------------------------------------------------------\ns     = (1:64)/64;\nPs    = exp(-((1:64) - 32).^2/(2*16));\nPs    = Ps/sum(Ps);\n\n%  model likelihood, model prior and  sparsity hyperprior\n%--------------------------------------------------------------------------\nLm    = spm_softmax(spm_vec(M.F));\nfor i = 1:numel(s)\n    Pm      = spm_softmax(-s(i)*spm_vec(M.H));\n    Qm(:,i) = Lm.*Pm*Ps(i);\nend\n\n% evidence and log evidence\n%--------------------------------------------------------------------------\nQm    = Qm/sum(sum(Qm));\nG     = log(sum(Qm,2));\n\n%-Bayesian model average\n%==========================================================================\nqE    = DCM.Ep;\nqC    = DCM.Cp;\npE    = DCM.M.pE;\npC    = DCM.M.pC;\npE    = spm_vec(pE);\nGmax  = max(G);\nBMA   = {};\nfor i = 1:length(G)\n    if G(i) > (Gmax - 4)    \n        [F,Ep,Cp]    = spm_log_evidence_reduce(qE,qC,pE,pC,pE,M(i).rC);\n        BMA{end + 1} = struct('Ep',Ep,'Cp',Cp,'F',F);\n    end\nend\n\nBMA   = spm_dcm_bma(BMA);\nEp    = BMA.Ep;\nCp    = BMA.Cp;\nif isstruct(Cp) || (spm_length(Cp) == spm_length(Ep))\n    Cp = diag(spm_vec(Cp));\nend\n\n% Show results\n% -------------------------------------------------------------------------\nGRAPHICS = 1;\n\nif ~GRAPHICS, return, end\n\nspm_figure('Getwin','BMR - all'); clf\nsubplot(3,2,1)\nimagesc(log(Qm)')\ntitle('Joint density','FontSize',16)\nxlabel('model','FontSize',12)\nylabel('sparsity','FontSize',12)\naxis square\n\nsubplot(3,2,2)\nplot(DCM.Ep,Ep,'.',DCM.Ep,DCM.Ep,':')\ntitle('Full and reduced expectations','FontSize',16)\nxlabel('Full expectations','FontSize',12)\nylabel('Reduced expectations','FontSize',12)\naxis square\n\nsubplot(3,2,3)\nplot(s,sum(Qm,1))\ntitle('Marginal over sparsity','FontSize',16)\nxlabel('sparsity parameter','FontSize',12)\nylabel('probability','FontSize',12)\naxis square\n\nsubplot(3,2,4)\nplot(sum(Qm,2))\ntitle('Marginal over  model','FontSize',16)\nxlabel(' model','FontSize',12)\nylabel('probability','FontSize',12)\naxis square\ndrawnow\n\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dcm_sparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.22672304076723712}}
{"text": "function [pesq_mos]= pesq(ref_wav, deg_wav)\n\n% ----------------------------------------------------------------------\n%            PESQ objective speech quality measure\n%\n%   This function implements the PESQ measure based on the ITU standard\n%   P.862 [1].\n%\n%\n%   Usage:  pval=pesq(cleanFile.wav, enhancedFile.wav)\n%           \n%         cleanFile.wav - clean input file in .wav format\n%         enhancedFile  - enhanced output file in .wav format\n%         pval          - PESQ value\n%\n%    Note that the PESQ routine only supports sampling rates of 8 kHz and\n%    16 kHz [1]\n%\n%  Example call:  pval = pesq ('sp04.wav','enhanced.wav')\n%\n%  \n%  References:\n%   [1] ITU (2000). Perceptual evaluation of speech quality (PESQ), and \n%       objective method for end-to-end speech quality assessment of \n%       narrowband telephone networks and speech codecs. ITU-T\n%       Recommendation P. 862   \n%\n%   Authors: Yi Hu and Philipos C. Loizou \n%\n%\n% Copyright (c) 2006 by Philipos C. Loizou\n% $Revision: 0.0 $  $Date: 10/09/2006 $\n% ----------------------------------------------------------------------\n\nif nargin<2\n    fprintf('Usage: [pesq_mos]=pesq(cleanfile.wav,enhanced.wav) \\n');\n    return;\nend;\n\nglobal Downsample DATAPADDING_MSECS SEARCHBUFFER Fs WHOLE_SIGNAL\nglobal Align_Nfft Window \n\n[ref_data,sampling_rate]= audioread( ref_wav);\n% if sampling_rate~=8000 & sampling_rate~=16000\n%     error('Sampling frequency needs to be either 8000 or 16000 Hz');\n% end\n\nsetup_global( sampling_rate);\n\n% Window= hann( Align_Nfft, 'periodic'); %Hanning window\n% Window= Window'; \nTWOPI= 6.28318530717959;\n%for count = 0: Align_Nfft- 1\n%    Window(1+ count) = 0.5 * (1.0 - cos((TWOPI * count) / Align_Nfft));\n%end\n\ncount=0:Align_Nfft- 1;\nWindow= 0.5 * (1.0 - cos((TWOPI * count) / Align_Nfft));\n  \n\n\nref_data= ref_data';\nref_data= ref_data* 32768;\nref_Nsamples= length( ref_data)+ 2* SEARCHBUFFER* Downsample;\nref_data= [zeros( 1, SEARCHBUFFER* Downsample), ref_data, ...\n    zeros( 1, DATAPADDING_MSECS* (Fs/ 1000)+ SEARCHBUFFER* Downsample)];\n\ndeg_data= audioread( deg_wav);\ndeg_data= deg_data';\ndeg_data= deg_data* 32768;\ndeg_Nsamples= length( deg_data)+ 2* SEARCHBUFFER* Downsample;\ndeg_data= [zeros( 1, SEARCHBUFFER* Downsample), deg_data, ...\n    zeros( 1, DATAPADDING_MSECS* (Fs/ 1000)+ SEARCHBUFFER* Downsample)];\n\nmaxNsamples= max( ref_Nsamples, deg_Nsamples);\n\nref_data= fix_power_level( ref_data, ref_Nsamples, maxNsamples);\ndeg_data= fix_power_level( deg_data, deg_Nsamples, maxNsamples);\n\nstandard_IRS_filter_dB= [0, -200; 50, -40; 100, -20; 125, -12; 160, -6; 200, 0;...    \n    250, 4; 300, 6; 350, 8; 400, 10; 500, 11; 600, 12; 700, 12; 800, 12;...\n    1000, 12; 1300, 12; 1600, 12; 2000, 12; 2500, 12; 3000, 12; 3250, 12;...\n    3500, 4; 4000, -200; 5000, -200; 6300, -200; 8000, -200]; \n\nref_data= apply_filter( ref_data, ref_Nsamples, standard_IRS_filter_dB);\ndeg_data= apply_filter( deg_data, deg_Nsamples, standard_IRS_filter_dB);\n% \n\n\n\n% for later use in psychoacoustical model\nmodel_ref= ref_data;\nmodel_deg= deg_data;\n\n[ref_data, deg_data]= input_filter( ref_data, ref_Nsamples, deg_data, ...\n    deg_Nsamples);\n\n\n[ref_VAD, ref_logVAD]= apply_VAD( ref_data, ref_Nsamples);\n[deg_VAD, deg_logVAD]= apply_VAD( deg_data, deg_Nsamples);\n\n\ncrude_align (ref_logVAD, ref_Nsamples, deg_logVAD, deg_Nsamples,...\n    WHOLE_SIGNAL);\n\nutterance_locate (ref_data, ref_Nsamples, ref_VAD, ref_logVAD,...\n    deg_data, deg_Nsamples, deg_VAD, deg_logVAD);\n\nref_data= model_ref;\ndeg_data= model_deg;\n\n% make ref_data and deg_data equal length\nif (ref_Nsamples< deg_Nsamples)\n    newlen= deg_Nsamples+ DATAPADDING_MSECS* (Fs/ 1000);\n    ref_data( newlen)= 0;\nelseif (ref_Nsamples> deg_Nsamples)\n    newlen= ref_Nsamples+ DATAPADDING_MSECS* (Fs/ 1000);\n    deg_data( newlen)= 0;\nend\n\n\npesq_mos= pesq_psychoacoustic_model (ref_data, ref_Nsamples, deg_data, ...\n    deg_Nsamples );\n\n\n\n\n", "meta": {"author": "vipchengrui", "repo": "traditional-speech-enhancement", "sha": "79cefa66c7a69587f1864a7334cc9da7e31e883d", "save_path": "github-repos/MATLAB/vipchengrui-traditional-speech-enhancement", "path": "github-repos/MATLAB/vipchengrui-traditional-speech-enhancement/traditional-speech-enhancement-79cefa66c7a69587f1864a7334cc9da7e31e883d/speech_quality_objective_evaluation/bin/obj_evaluation/pesq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.22672302706907035}}
{"text": "function [data, wAxis, dAxis, xAxis, yAxis, misc] = lscload(filename)\n% Reads in IR image data from PerkinElmer block structured files.\n% This version is compatible with '1994' standard LSC files.\n%\n% [data, wAxis, dAxis, xAxis, yAxis, misc] = lscload(filename):\n%   data:  2D array, [W, D]     wavelength x distance\n%   wAxis: vector of e.g. wavenumbers\n%   dAxis: vector of distance along line\n%   xAxis: vector for stage x positions (e.g. micrometers)\n%   yAxis: vector for stage y positions (e.g. micrometers)\n%   misc: miscellanous information in name,value pairs\n\n% Copyright (C)2007 PerkinElmer Life and Analytical Sciences\n% Stephen Westlake, Seer Green\n%\n% History\n% 2007-05-01 SW     Initial version\n\n% Block IDs\nDS4C3IData            = 5100;   % 4D DS: header info\nDS4C3IPts             = 5101;   % 4D DS: point coordinates (CvCoOrdArray)\nDS4C3IPtsCont         = 5102;   % 4D DS: point coordinates (continuator for large CvCoOrdArray)\nDS4C3ITemp2DData      = 5103;   % 4D DS: temp block for storing part of component 2d dataset\nDS4C3I2DData          = 5104;   % 4D DS: release sw block for storing ALL of component 2d data\nDS4C3IFloatPts        = 5105;   % 4D DS: point coordinates (FloatArray)\nDS4C3IFloatPtsCont    = 5106;   % 4D DS: point coordinates (continuator for large FloatArray)\nDS4C3IHistory         = 5107;   % 4D DS: history record\n\nfid = fopen(filename,'r');\nif fid == -1\n    error('Cannot open the file.');\n    return\nend\n\n% Fixed file header of signature and description\nsignature = setstr(fread(fid, 4, 'uchar')');\nif ~strcmp(signature, 'PEPE')\n    error('This is not a PerkinElmer block structured file.');\n    return\nend\ndescription = setstr(fread(fid, 40, 'uchar')');\n\n% Initialize a variable so we can tell if we have read it.\ndLen = int32(0);\nqLen = int32(0);\n\n% The rest of the file is a list of blocks\nwhile ~feof(fid)\n    blockID = fread(fid,1,'int16');\n    blockSize = fread(fid,1,'int32');\n    \n    % feof does not go true until after the read has failed.\n    if feof(fid)\n        break\n    end\n    \n    switch blockID\n        case DS4C3IData\n            len = fread(fid,1,'int16');\n            alias = setstr(fread(fid, len, 'uchar')');\n        \n            dDelta = fread(fid, 1, 'double');       % distance delta\n            angle = fread(fid, 1, 'double');        % angle (radians)\n            wDelta = fread(fid, 1, 'double');       % wavenumber delta\n            fread(fid, 1, 'double');      % zstart\n            fread(fid, 1, 'double');      % zend    \n            fread(fid, 1, 'double');      % min data value\n            fread(fid, 1, 'double');      % max data value\n            x0 = fread(fid, 1, 'double');           % stage x0\n            y0 = fread(fid, 1, 'double');           % stage y0\n            w0 = fread(fid, 1, 'double');           % wavenumber start\n            dLen = fread(fid, 1, 'int32');          % distance points\n            qLen = fread(fid, 1, 'int32');          % should be 1\n            wLen = fread(fid, 1, 'int32');          % wavelength points            \n            \n            len = fread(fid, 1, 'int16');\n            dLabel = setstr(fread(fid, len, 'uchar')');\n            len = fread(fid, 1, 'int16');\n            setstr(fread(fid, len, 'uchar')');\n            len = fread(fid, 1, 'int16');\n            wLabel = setstr(fread(fid, len, 'uchar')');\n            len = fread(fid, 1, 'int16');\n            zLabel = setstr(fread(fid, len, 'uchar')');\n\n            % imshow row 1 is the top, i.e. fsm row N.\n            d = dLen;\n            \n        case DS4C3IFloatPts         % the next spectrum\n            data(d, :) = fread(fid, wLen, 'float');\n            if d == 0\n                error('There are too many data points.');\n                return\n            end\n            % set up the index for the next point\n            d = d - 1;\n     \n        otherwise               % unknown block, just seek past it\n            fseek(fid, blockSize, 'cof');\n    end\nend\nfclose(fid);\n\nif dLen == 0\n    error('The file does not contain spectral image data.');\n    return\nend\nif qLen ~= 1\n    error('The file does not contain line scan data.');\n    return\nend\n\n% d0 is implicitly 0\ndEnd = (dLen - 1) * dDelta;\nwEnd = w0 + (wLen - 1) * wDelta;\n\n% Calculate end stage positions from angle and hypoteneuse\nxEnd = x0 + dEnd * cos(angle);\nyEnd = y0 + dEnd * sin(angle);\nxDelta = dDelta * cos(angle);\nyDelta = dDelta * sin(angle);\n\n% Expand the axes specifications into vectors\n% D axis is reversed to match the image data\nxAxis = x0 : xDelta : xEnd;\nyAxis = y0 : yDelta : yEnd;\ndAxis = dEnd : -dDelta : 0;\nwAxis = w0 : wDelta : wEnd;\n\n% Return the other details as name,value pairs\nmisc(1,:) = {'dLabel', dLabel};\nmisc(2,:) = {'wLabel', wLabel};\nmisc(3,:) = {'zLabel', zLabel};\nmisc(4,:) = {'alias', alias};\nmisc(5,:) = {'angle', angle};\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22736-perkinelmer-ir-data-file-import-tools/lscload.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.2266395581678939}}
{"text": "function [data_train, labels_train, data_devel, labels_devel, raw_devel, PC, means_norm, stds_norm, devel_ids, devel_success] = ...\n    Prepare_HOG_AU_data(train_users, devel_users, au_train, rest_aus, Bosphorus_dir, params_data_dir)\n\n%%\naddpath(genpath('../data extraction/'));\n\n% First extracting the labels\n[ labels_train, valid_ids_train, filenames ] = extract_Bosphorus_labels(Bosphorus_dir, train_users, au_train);\n\n[ labels_other, ~, ~ ] = extract_Bosphorus_labels(Bosphorus_dir, train_users, rest_aus);\n\n% Reading in the HOG data (of only relevant frames)\n[train_appearance_data, valid_ids_train_hog, vid_ids_train_string] = Read_HOG_files(filenames, params_data_dir);\n\n[train_geom_data] = Read_geom_files(filenames,  params_data_dir);\n\n% Subsample the data to rebalance it\nif(numel(train_users) > 0)\n    reduced_inds = false(size(labels_train,1),1);\n    reduced_inds(labels_train > 0) = true;\n\n    % make sure the same number of positive and negative samples is taken\n    pos_count = sum(labels_train > 0);\n    neg_count = sum(labels_train == 0);\n\n    num_other = floor( pos_count / (size(labels_other, 2)));\n\n    inds_all = 1:size(labels_train,1);\n\n    for i=1:size(labels_other, 2)+1\n   \n        if(i > size(labels_other, 2))\n            % fill the rest with a proportion of neutral\n            inds_other = inds_all(sum(labels_other,2)==0 & ~labels_train );   \n                num_other_i = min(numel(inds_other), pos_count - sum(labels_train(reduced_inds,:)==0));     \n        else\n                % take a proportion of each other AU\n            inds_other = inds_all(labels_other(:, i) & ~labels_train );      \n            num_other_i = min(numel(inds_other), num_other);        \n        end\n        inds_other_to_keep = inds_other(round(linspace(1, numel(inds_other), num_other_i)));\n        reduced_inds(inds_other_to_keep) = true;\n\n    end\n\n    % Remove invalid ids based on CLM failing or AU not being labelled\n    reduced_inds(~valid_ids_train) = false;\n    reduced_inds(~valid_ids_train_hog) = false;\n\n    labels_other = labels_other(reduced_inds, :);\n    labels_train = labels_train(reduced_inds,:);\n    train_appearance_data = train_appearance_data(reduced_inds,:);\n    train_geom_data = train_geom_data(reduced_inds,:);\n    vid_ids_train_string = vid_ids_train_string(reduced_inds,:);\nend\n%% Extract devel data\n\n% First extracting the labels\n[ labels_devel, valid_ids_devel, filenames_devel ] = extract_Bosphorus_labels(Bosphorus_dir, devel_users, au_train);\n\n% Reading in the HOG data (of only relevant frames)\n[devel_appearance_data, valid_ids_devel_hog, vid_ids_devel_string] = Read_HOG_files(filenames_devel, params_data_dir);\ndevel_success = valid_ids_devel_hog;\ndevel_ids = vid_ids_devel_string;\n\n[devel_geom_data] = Read_geom_files(filenames_devel, params_data_dir);\n\n% Peforming zone specific masking\nif(au_train < 8 || au_train == 43 || au_train == 45) % upper face AUs ignore bottom face\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_upper.mat';\n    load(pca_file);\nelseif(au_train > 9) % lower face AUs ignore upper face and the sides\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_lower.mat';\n    load(pca_file);\nelseif(au_train == 9) % Central face model\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_rigid.mat';\n    load(pca_file);\nend\n     \n% Grab all data for validation as want good params for all the data\nraw_devel = cat(2, devel_appearance_data, devel_geom_data);\n\ndevel_appearance_data = bsxfun(@times, bsxfun(@plus, devel_appearance_data, -means_norm), 1./stds_norm);\n\ndata_devel = devel_appearance_data * PC;\n\ndata_devel = cat(2, data_devel, devel_geom_data);\n\nvalid_ids_devel = valid_ids_devel & devel_success;\ndata_devel = data_devel(valid_ids_devel,:);\nlabels_devel = labels_devel(valid_ids_devel,:);\nraw_devel = raw_devel(valid_ids_devel,:);\ndevel_success = devel_success(valid_ids_devel,:);\ndevel_ids = devel_ids(valid_ids_devel);\n\nif(numel(train_users) > 0)\n    train_appearance_data = bsxfun(@times, bsxfun(@plus, train_appearance_data, -means_norm), 1./stds_norm);\n\n    data_train = train_appearance_data * PC;\n    data_train = cat(2, data_train, train_geom_data);\nelse\n    data_train = [];\nend\n\ngeom_size = max(size(train_geom_data, 2), size(devel_geom_data, 2));\n\nPC_n = zeros(size(PC)+geom_size);\nPC_n(1:size(PC,1), 1:size(PC,2)) = PC;\nPC_n(size(PC,1)+1:end, size(PC,2)+1:end) = eye(geom_size);\nPC = PC_n;\n\nmeans_norm = cat(2, means_norm, zeros(1, geom_size));\nstds_norm = cat(2, stds_norm, ones(1, geom_size));\n\nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/AU_training/experiments/Bosphorus/Prepare_HOG_AU_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.22659551455995938}}
{"text": "function [sumD] = mesh_fit_elec_optim(SUMD,scalp,elec)\n\n% mesh_fit_elec_optim - optimise the fitting of electrodes to scalp vertices\n%\n% This function is in development.  It needs rotations and \n% translations of elec vertices to fit those of the scalp \n% vertices and a minimisation function for the difference \n% between the vertex locations of the nearest scalp vertices \n% and those of the electrodes.\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  09/2002, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfprintf('Still in development\\n'); return\n\n\n% Rotations/translations/scaling here???\n\n[k,d] = dsearchn(scalp,elec);\n\nsumD = sum(d) - SUMD;\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_fit_elec_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.22659550916004534}}
{"text": "function [gb_thin_CSG, gb_thin_CS, gb_fat_CS, texton] = simpleGPb(I)\n\n% place the current directory on the top of paths (so rgb2lab in this\n% directory will get called when needed)\ncurr_dir = fileparts(which(mfilename));\nrmpath(curr_dir);\naddpath(curr_dir);\n\n[gb_thin_CSG, gb_thin_CS, gb_fat_CS] = Gb_CSG(I);\ntexton = genTexton(I);\ngb_thin_CSG = uint8(round(255*gb_thin_CSG));\ngb_thin_CS = uint8(round(255*gb_thin_CS));\ngb_fat_CS = 255*gb_fat_CS;\ntexton = uint8(texton);\n\nend", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rigor/rigor_src/extern_src/extra_gb_code/simpleGPb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.22646602603285415}}
{"text": "clear\n\nExtract_table_results_49\n%% \nscrsz = get(0,'ScreenSize');\nfigure1 = figure('Position',[20 50 3*scrsz(3)/4 0.9*scrsz(4)]);\n\nset(figure1,'Units','Inches');\npos = get(figure1,'Position');\nset(figure1,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])\n\n% Create axes\naxes1 = axes('Parent',figure1,'FontSize',40,'FontName','Helvetica');\n\nline_width = 6;\nhold on;\n\n[error_x, error_y] = cummErrorCurve(ceclm_error);\nplot(error_x, error_y, 'r','DisplayName', 'OpenFace 2.0', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(clnf_error);\nplot(error_x, error_y, 'DisplayName', 'OpenFace', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(cfss_error);\nplot(error_x, error_y, 'DisplayName', 'CFSS', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(sdm_error);\nplot(error_x, error_y, 'DisplayName', 'SDM', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(pocr_error);\nplot(error_x, error_y,'DisplayName', 'PO-CR', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(cfan_error);\nplot(error_x, error_y,'DisplayName', 'CFAN', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(tcdcn_error);\nplot(error_x, error_y,'DisplayName', 'TCDCN', 'LineWidth',line_width);\n\n[error_x, error_y] = cummErrorCurve(error_3ddfa);\nplot(error_x, error_y,'DisplayName', '3DDFA', 'LineWidth',line_width);\n\nset(gca,'xtick',[0:0.02:0.10])\nxlim([0.02,0.10]);\nxlabel('Size normalised MSE','FontName','Helvetica');\nylabel('Proportion of images','FontName','Helvetica');\ngrid on\n% title('Fitting in the wild without outline','FontSize',60,'FontName','Helvetica');\n\nleg = legend('show', 'Location', 'SouthEast');\nset(leg,'FontSize',40)\n\nprint -dpdf results/Janus-no-outline.pdf\nprint -dpng results/Janus-no-outline.png", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/experiments_JANUS/Display_ceclm_results_49.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22646601970491806}}
{"text": "% example8_10.m\nnet1=competlayer(40);\nload simpleclass_dataset\nnet2=newsom(simpleclassInputs,[5 8]);\nview(net1)\nview(net2)\n\nweb -broswer http://www.ilovematlab.cn/forum-222-1.html", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u795e\u7ecf\u7f51\u7edc\u539f\u7406\u4e0e\u5b9e\u4f8b\u7cbe\u89e3\u300b\u968f\u4e66\u9644\u5e26\u6e90\u7a0b\u5e8f/\u7b2c8\u7ae0 \u81ea\u7ec4\u7ec7\u7ade\u4e89\u795e\u7ecf\u7f51\u7edc/example8_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.22631842207536568}}
{"text": "function [Oq,Oqval,DEOPA,goodperiods] = OP(simppeak,SIG,dSIG,valid,doublepeaks,COEF,resampC,Ts,method)\n% OP: Opening Peaks detection.\n% Input files:\n% - <simppeak>: contains a list of closing-peak times in ms, and amplitudes\n% (<simppeak> is a 2-column matrix)\n% - <dSIG>: Derivative of EGG signal\n% - <valid> : vector containing information on peaks that have several summits\n% - <doublepeaks>: vector containing information on peaks that cluster together\n% - <COEF>: contains, among other coefficients, the smoothing step chosen by the\n% user. It is not used in analyzing the positive part of the signal, only in the\n% negative part, for the calculation of Oq.\n% - <resampC>: coefficient for reinterpolation\n% - <Ts>: the inverse of the sampling rate\n% - <method>: indication on the method which is to be used in the handling of \n% double / multiple peaks: selecting either the first or the highest. \n% (The fact that there is not one single peak will also be passed on\n% to the following functions, so this choice is not of much consequence.)\n%\n% Output files: \n% <Oq>: vector containing open quotient values detected using the maxima\n% <Oqval>: open quotient values computed by peak detection (single peaks only)\n% <DEOPA>: vector containing DEOPA values\n% <SM>, for Success of Method: variable indicating the number of Oq values that\n% could be calculated using peak detection.\n% <goodperiods>: beginning and end of cycles for which closing peaks are unique.\n% <validGOI>: ratio of highest to second highest peak.\n%\n% No use of autocorrelation or comparison across cycles, otherwise the method \n% would not give results up to the end of voicing: border phenomena.\n% Passages where voice quality changes quickly are not found only at the offset\n% of voicing: they can be word-internal, as in the case of consonantal glottal\n% stops, ejectives, implosives, or glottalized tones, e.g. in Vietnamese tone\n% C2, which has medial glottal constriction.\n%\n% Method: detecting maxima; checking the plausibility of results; if results are\n% implausible, detecting maxima anew with increased smoothing step\n\n% Setting the output vector Oqval at []; otherwise, in case no single period has \n% single closing and opening peaks, this output argument is not assigned during\n% call to OP.\nOqval = [];\n\n% creating a matrix containing the beginning and end of periods for which Oq\n% will be calculated. Values are converted to indices.\ngoodperiods = [];\n\nif ~isempty(simppeak)\n    if length(simppeak(:,1)) > 1\n        for i = 1: length(simppeak(:,1)) - 1\n            goodperiods(i,1) = round(simppeak(i,1) * (1 / Ts));\n            goodperiods(i,2) = round(simppeak(i + 1,1) * (1 / Ts));\n        end\n\n        % Previous calculation method: eliminating periods for which closing peaks are\n        % not unique:\n        % %%%%%%%%%%%%%%%%%%%%%% Determining periods for which closings are unique\n        % % Open quotient measurements are attempted only when closings are unique. For\n        % % each glottal cycle, there are two condition: \n        % % 1) that the values associated to the peak in <valid> be\n        % % above 0.6, i.e. within the peak there is no other summit that is higher than\n        % % 60% of the highest summit\n        % % 2) that none of the neighbouring peaks be higher than 60% of the candidate peak.\n        % \n        % goodperiods = []; \n        % for i = 1:length(valid) - 1\n        %     if (doublepeaks(i) == 0) & (valid(i) < 0.6) & (doublepeaks(i + 1) == 0) & (valid(i) < 0.6)\n        %         goodperiodsnb = goodperiodsnb + 1;\n        %         goodperiods(goodperiodsnb,1) = Tgci(i,1);\n        %         goodperiods(goodperiodsnb,2) = Tgci(i + 1,1);\n        %     end\n        % end\n\n\n        %%%%%%%%%%%%%%%%%%%%%% First measurement of openings: done by detecting\n        %%%%%%%%%%%%%%%%%%%%%% local minima, without any condition on the values obtained.\n        texis = exist('goodperiods');\n        if texis == 1\n            if length(goodperiods(:,1)) > 0\n                for i = 1:length(goodperiods(:,1))\n                    % A rounding of the indices is necessary: as there has been\n                    % reinterpolation, the values are not integers.\n                    [DEOPA(i),GOI(i)] = min(    dSIG( round(goodperiods(i,1)):round(goodperiods(i,2) ))   );\n                    % correction: adding the index corresponding to the first point of the\n                    % excerpt\n                    GOI(i) = GOI(i) + goodperiods(i,1);\n                    %% Calculation of Oq, in %\n                    Oq(i) = 100 * ((  goodperiods(i,2) - GOI(i)  ) / (  goodperiods(i,2) - goodperiods(i,1)  ));\n                end\n        %     else\n        %         DEOPA = 0;\n        %         GOI = 0;\n        %         Oq = 0;\n            end\n        end\n\n        %%%%%%%%%%%%%%%%%%%%%%%% Measurement by peak detection and barycentre calculation\n        texis = exist('goodperiods');\n        if texis == 1\n            if length(goodperiods(:,1)) > 0\n                for i = 1:length(goodperiods(:,1))\n                    % if you want to see information displayed as analysis is being\n                    % conducted, uncomment the two lines below:\n                    %% disp(['Treating period number ',num2str(i)])\n                    %% disp(goodperiods(i,:))\n                    % placing the indices of beginning and end of the relevant portion of\n                    % the signal in variables\n                    % A rounding of the indices is necessary: as there has been\n                    % reinterpolation, the values are not integers. In the present state of\n                    % the programme, this rounding is performed earlier, when the\n                    % <goodperiods> matrix is built up.\n                    BE = goodperiods(i,1);           % BEginning of period\n                    EN = goodperiods(i,2);           % ENd of period\n                    % placing the extract in a vector, inverting it because CRO operates on\n                    % a positive signal. An extra precaution must be taken: excluding the\n                    % first and last eight points of the signal (by setting them at zero):\n                    % it is physically impossible that a clear opening will take place \n                    % at these points, so close to the closing; technically, a small part of\n                    % the signal immediately before the closing peak that marks the\n                    % beginning of the period (res. after the closing peak that marks its\n                    % end) may be included and result in program crash.\n                    dSIGextr = - dSIG(BE:EN);\n                    L = length(dSIGextr);\n                    if L > 16\n                        dSIGextr(1:8) = 0;\n                        dSIGextr(L-7:L) = 0;\n                    end\n                    % Also creating an extract for the EGG signal, which is used later on,\n                    % by AMPOS\n                    SIGextr = - SIG(BE:EN);\n\n                    %%%%%%%%%%%%%%%%%% Calling the function CRO to detect crossings. \n                    % The <method> toggle (3rd value in <COEF>) must be set at 0, and the\n                    % amplitude threshold (4th value in <COEF>) passed on to the function.\n                    COEFOPEN = COEF;\n                    COEFOPEN(3) = 0;\n\n                    % setting the threshold for peak detection (empirically). Choice in\n                    % Henrich 2001:123 : setting it at 70% of the highest point.\n                    COEFOPEN(4) = 0.70 * max(dSIGextr);\n\n                    % finding out the crossings with the DEGG signal. In the best cases, it is\n                    % expected that there will be only two crossings, one up and one down.\n                    % But this is not frequent: the signal is often dented.\n                    [rimsOPEN] = CRO(dSIGextr,COEFOPEN);\n\n                    if isempty(rimsOPEN)\n                        % If there is no single detected threshold crossing: the user should\n                        % changed the maximum F0 value and ask for the results to be\n                        % calculated anew. The user is advised to do so inside the <rim>\n                        % function.\n                        Oqval(i) = 0;\n                        DEOPA(i) = 0;\n                    else\n                        % finding out the amplitude and position of the peaks. No\n                        % reinterpolation of the signal is useful, as the signal-to-noise ratio in\n                        % the negative part of the DEGG signal is poor. Quite the opposite: the\n                        % signal is smoothed (over 3 samples, i.e. 0.07 ms).\n\n                        % The threshold for exclusion of small peaks is set at 0.7 in the case of \n                        % opening peaks, following Henrich 2001:123. This has in fact already\n                        % been applied before, in detection of peak rims by RIM; but the\n                        % function PEAKSHAPE called by AMPOS needs this input.\n                        propthresh = 0.7;\n                       % figure(1)\n                       % clf\n                       % plot(SIGextr)\n                        [TGOI,TGOIFo,validGOI,validtimeGOI] = AMPOS(SIGextr,rimsOPEN,1,Ts,method,propthresh);\n\n                        % detection of double / multiple closing peaks (\"peak clusters\"). The\n                        % threshold passed to this function is: (the inverse of) one-fifth of\n                        % the period, under the assumption that peaks separated by more than\n                        % one-fifth of the period should not be considered as a bundle. In these\n                        % cases, no Oq is calculated.\n                        maxF = 1 / ( (goodperiods(i,2) - goodperiods(i,1)) / 5);\n                        doublepeaks = detectmult(TGOI,maxF);\n\n                        % choice of opening peak, leaving only one, following the method\n                        % specified by the user. If there are 2 peaks that are too far apart for\n                        % averaging to make sense, there will be 2 lines in simppeak: two \"real\n                        % peaks\" according to the criteria used in the SIMP function.\n                        [simppeak,BUND] = simp(TGOI,doublepeaks,method);\n\n                        % calculating the open quotient when possible. The condition is: if\n                        % there is one single value in <simppeak>, the matrix where detected\n                        % peaks are stored. If there are two (or more) values, this indicates\n                        % that there were two (or more) peaks that were too far apart for\n                        % averaging to make sense, and it seems best not to give an Fo value;\n                        % the Oq value is then set at zero. This is also what happens if it \n                        % remains unaffected: it comes out as a zero inside the vector; but if\n                        % the last values are zero, then the length of the vector is less than\n                        % the size of the Fo vector, resulting in assignment problems. So the\n                        % value is set at zero in this programme.\n                        % inside the vector).\n                        if length(simppeak(:,1)) == 1\n                            % transforming the time of peak to an index\n                            indexsimppeak = simppeak(1,1) * (1 / Ts);\n                            Oqval(i) = 100 * (       ((goodperiods(i,2) - goodperiods(i,1)) - indexsimppeak ) / ...\n                                  (goodperiods(i,2) - goodperiods(i,1))       );\n                        else\n                              Oqval(i) = 0;\n                        end\n                    % end of \"if\" loop: condition on existence of rimsOPEN values.    \n                    end\n                end\n            end\n        end\n    else\n        goodperiods = []; Oq = []; Oqval = []; DEOPA = [];\n    end\nelse\n    goodperiods = []; Oq = []; Oqval = []; DEOPA = [];\nend\n        %%%%%%%%%%% The method for detecting opening peaks is fairly similar to\n        %%%%%%%%%%% that for detecting closing peaks. Concerning the detection\n        %%%%%%%%%%% of multiple peaks, however, in the case of closing peaks\n        %%%%%%%%%%% the threshold for detection was set rather low, and the\n        %%%%%%%%%%% peaks were later sorted according to size and closeness to\n        %%%%%%%%%%% one another. In the case of opening peaks, the period is\n        %%%%%%%%%%% known already, so the threshold is fixed straight away,\n        %%%%%%%%%%% on the basis of the highest point in this part of the\n        %%%%%%%%%%% signal: if the second highest peak is 70% as high as the\n        %%%%%%%%%%% highest peak, it is decided that the peak is not unique\n        %%%%%%%%%%% (following Henrich 2001:123).\n\n        %%%%%%%%%%% It is an issue whether this threshold must apply\n        %%%%%%%%%%% within the peak region as well as in the comparison of\n        %%%%%%%%%%% neighbouring peaks. The fine detail of the peak is often\n        %%%%%%%%%%% slightly dented (see figures); this will result in\n        %%%%%%%%%%% \"secondary peaks\" being detected very close to the maximum\n        %%%%%%%%%%% (about 0.1 ms to its left and right). A time condition could\n        %%%%%%%%%%% be added: if the secondary peak is very close\n        %%%%%%%%%%% (threshold empirically set at a time value, e.g. 0.5 ms, or\n        %%%%%%%%%%% as a proportion of the period), it would not count as\n        %%%%%%%%%%% a doubled peak. In the present programme, the solution\n        %%%%%%%%%%% chosen instead is to use smoothing of the signal.\n        \n%         % In an earlier version, the algorithm was: \n%         % 1) retrieve highest peak in TGOI; 2) check that it is unique\n%         % internally; 3) check that the neighbouring peaks are less than 70% of its\n%         % height. GOIC stands for Glottis-Opening-Instant Candidate.\n%         % First step:\n%         [GOICvalue,GOICindex] = max (TGOI(:,2));\n%         % Second step: finding out whether the peak is unique internally. For\n%         % this: look up the corresponding slot in vector <validtimeGOI>.\n%         if validtimeGOI(GOICindex) < threshtime\n%             % retrieving the index of maximum value in TGOI relative to the \n%             % beginning of the <dSIGextr> extract: it is the value\n%             % in the first column of <TGOI> at the line indicated in\n%             % <GOICindex>\n%             GOICindex = TGOI(GOICindex,1);\n%             % changing the relative index <GOICindex> into an index relative \n%             % to the <SIG> signal as a\n%             % whole, for computation of the open quotient\n%             GOICindex = GOICindex + goodperiods(i,1);\n%             % calculation of open quotient\n%             Oqval(i) = 100 * (       (goodperiods(i,2) - GOICindex ) / ...\n%                 (goodperiods(i,2) - goodperiods(i,1))       );\n%         end\n            \n            %%%%%%%%%%% Note:             \n            %% In the first version of the programme, the threshold for detection \n            %% of peak regions was first set at 40% of the signal, and the\n            %% condition on peak amplitude was added later, by recovering the \n            % second highest peak in TGOI and\n            % comparing its amplitude to that of the highest peak. \n            %% In the present version of the function, only the peaks above 70% of the maximum\n            %% within the dSIG extract <dSIGextr> are detected, so that\n            %% this part of the function is not necessary anymore.\n            %% The calculations were as follows:\n            \n%             COEFOPEN(4) = 0.7 * max(dSIGextr);\n%             % Setting value for TGOI(GOICindex,2) at zero and re-calculating the\n%             % maximum: \n%             TGOI(GOICindex,2) = 0;\n%             [GOICvalue2,GOICindex2] = max (TGOI(:,2));\n%             % condition on whether the proportion of the two peaks is below\n%             % threshold\n%             if GOICvalue2 / GOICvalue < threshGOI\n%                 % retrieving the index of maximum value in TGOI: it is the value\n%                 % in the first column of <TGOI> at the line indicated in\n%                 % <GOICindex>\n%                 GOICindex = TGOI(GOICindex,1);\n%                 % changing the relative index <GOICindex> into an index relative \n%                 % to the <SIG> signal as a\n%                 % whole, for computation of the open quotient\n%                 GOICindex = GOICindex + goodperiods(i,1);\n%                 % calculation of open quotient\n%                 Oqval(i) = 100 * (       (goodperiods(i,2) - GOICindex ) / ...\n%                     (goodperiods(i,2) - goodperiods(i,1))       );\n%             end", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/glottalsource/egg/peakdet/private/OP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.2263184134334258}}
{"text": "function evalPCK_multi(expidxs,bUseHeadSize,bHeadSizeFromRect,bTrain)\n\nfprintf('evalPCK()\\n');\n\nif (nargin < 2)\n    bUseHeadSize = true;\nend\n\nif (nargin < 3)\n    bHeadSizeFromRect = false;\nend\n\nif (nargin < 4)\n    bTrain = false;\nend\n\nif (bUseHeadSize)\n    prefix = 'pck-head-';\n    range = 0:0.01:0.5;\nelse\n    prefix = 'pck-torso-';\n    range = 0:0.01:0.2;\nend\n\nif (bTrain)\n    prefix = [prefix 'train-'];\nend\n\nif bTrain\n    image_set = 'train';\nelse\n    image_set = 'test';\nend\n\nlegendName = cell(0);\n\n[~,parts] = util_get_parts24();\njidxsUpperBody = 7:12;\nnJoints = 14;\n% nJoints = length(p.cidxs);\nfor expidx = expidxs\n    fprintf('**********************************************************************************\\n');\n    % load experiment parameters\n    p = exp_params(expidx);\n    \n    % load ground truth\n    if (~bTrain)\n        load(p.testGT);\n    else\n        load(p.trainGT);\n        annolist = annolist(1:17000);\n    end\n    \n    if (~exist('annolist','var'))\n        annolist = single_person_annolist;\n    end\n    annolist_gt = annolist;%(1:100)\n    \n    if (~exist(p.outputDir,'dir')), mkdir(p.outputDir); end\n    fnameEvalRes = [fileparts(p.outputDir) '/evalAll'];\n    \n    clear boxes boxes_nonms image_ids keypointsAll;\n    \n    if (~exist(p.latexDir,'dir')), mkdir(p.latexDir); end\n    if (~exist(p.plotsDir,'dir')), mkdir(p.plotsDir); end\n    \n%     assert(length(p.pidxs) == nJoints);\n%     assert(length(p.cidxs) == nJoints);\n    \n    if (~isfield(p,'bidxs'))\n        bidxs = 1:length(p.pidxs)+1;\n    else\n        bidxs = p.bidxs;\n    end\n\n    % Load keypoints\n    fn = fullfile(p.exp_dir, image_set, 'keypointsAll.mat');\n    if exist(fn, 'file') ~= 2\n        scoremaps2keypoints(expidx, image_set);\n    end\n    fprintf('loading %s\\n', fn);\n    load(fn, 'keypointsAll');\n    \n%     visBoxes(annolist_gt,keypointsAll,p.pidxs,parts);\n    nrects = 0;\n    for imgidx = 1:length(annolist_gt)\n        nrects = nrects + length(annolist_gt(imgidx).annorect);\n    end\n    \n    distAll = nan(nrects,nJoints);\n    accAll = zeros(length(range),nJoints+2);\n        \n    for i = 1:length(p.pidxs)\n      pidx = p.pidxs(i);\n      % part is a joint\n      assert(parts(pidx+1).pos(1) == parts(pidx+1).pos(2));\n      jidx = parts(pidx+1).pos(1);\n            \n      % compute distance to the ground truth jidx\n      distAll(:,i) = getNormGTJointDistMulti(keypointsAll,annolist_gt,jidx,bUseHeadSize,bHeadSizeFromRect,jidx,nrects);\n    end\n    matchPCK = double(distAll <= range(end));\n        \n    totalPCK = zeros(size(matchPCK,1),1);\n    nCorrect = zeros(size(matchPCK,1),1);\n    for imgidx = 1:length(totalPCK)\n      idxs = ~isnan(distAll(imgidx,:));\n%       idxs = ~isnan(matchPCK(imgidx,:));\n      totalPCK(imgidx) = sum(matchPCK(imgidx,idxs))/sum(idxs);\n%       totalPCK(imgidx) = sum(matchPCK(imgidx,idxs))/length(idxs);\n      nCorrect(imgidx) = sum(matchPCK(imgidx,idxs));\n    end\n        \n    for i = 1:length(p.pidxs)\n      dist = distAll(:,i);\n      % remove the cases without the ground truth\n      dist(isnan(dist)) = [];\n      % compute accuracy for each threshold\n      for k = 1:numel(range)\n        accAll(k,i) = 100*mean(dist<=range(k));\n      end\n    end\n                \n    % compute avg PCKh upper body\n    dist = reshape(distAll(:,jidxsUpperBody),size(distAll,1)*length(jidxsUpperBody),1);\n    dist(isnan(dist)) = [];\n    for k = 1:numel(range)\n      accAll(k,end-1) = 100*mean(dist<=range(k));\n    end\n    \n    % compute avg PCKh full body\n    dist = reshape(distAll,size(distAll,1)*size(distAll,2),1);\n    dist(isnan(dist)) = [];\n    for k = 1:numel(range)\n      accAll(k,end) = 100*mean(dist<=range(k));\n    end\n    \n    pidxs = p.pidxs;\n%     save(fnameEvalRes,'distAll','accAll','pidxs','keypointsAll','matchPCK');\n    \n    auc = area_under_curve(scale01(range),accAll(:,end));\n    legendName{end+1} = sprintf('%s, AUC: %1.1f%%', p.name, auc);\n    \n    tableFilename = [p.latexDir '/' prefix 'expidx' num2str(expidx) '.tex'];\n    [row, header] = genTableNew(accAll(end,:),auc,p.name);\n    row = strrep(row,'NaN','-');\n    fid = fopen(tableFilename,'wt');assert(fid ~= -1);\n    fprintf(fid,'%s\\n',row{1});fclose(fid);\n    fid = fopen([p.latexDir '/' prefix 'header.tex'],'wt');assert(fid ~= -1);\n    fprintf(fid,'%s\\n',header);fclose(fid);\n    \n%     fprintf('%s\\n',legendName{end});\nend\n\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/eval/evalPCK_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630080509968187}}
{"text": "% STD_DIPPLOT - Commandline function to plot cluster component dipoles. Dipoles for each\n%                 named cluster is displayed in a separate figure. To view all the clustered \n%                 components in the STUDY on the same figure (in a separate subplot), all \n%                 STUDY clusters must be requested.\n%                 To visualize dipoles, they first must be stored in the EEG dataset structures\n%                 using DIPFIT. Only components that have dipole locations will be displayed,\n%                 along with the cluster mean dipole (in red). \n% Usage:    \n%                 >> [STUDY] = std_dipplot(STUDY, ALLEEG, clusters);  \n% Inputs:\n%   STUDY      - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.\n%   ALLEEG     - global EEGLAB vector of EEG structures for the dataset(s) included in \n%                the STUDY. ALLEEG for a STUDY set is typically created using LOAD_ALLEEG.  \n%\n% Optional inputs:\n%   'clusters' - [numeric vector | 'all']  -> specific cluster numbers to plot.\n%                'all'  -> plot all clusters in STUDY.\n%                {default: 'all'}.\n%   'comps'    - [numeric vector]  -> indices of the cluster components to plot.\n%                'all'  -> plot all the components in the cluster \n%                {default: 'all'}.\n%   'mode'     - ['together'|'apart'|'multicolor'] Display all requested cluster on one \n%                figure ('together') or separate figures ('apart'). \n%                'together'-> plot all 'clusters' individually in one multi-pane figure (without the gui).\n%                'apart'   -> plot each cluster in a separate figure. \n%                'multicolor' -> plot all clusters in one figure, \n%                Note that this parameter has no effect if the 'comps' option (above) is used.\n%                {default: 'together'}\n%   'figure'   - ['on'|'off'] plots on a new figure ('on')  or plots on current\n%                figure ('off'). If 'figure','off' does not display gui controls,\n%                Useful for incomporating a cluster dipplot into a complex figure. \n%                {default: 'on'}. \n%   'groups'   - ['on'|'off'] use different colors for different groups.\n%                {default: 'off'}.\n%   'dipcolor' - [cell vector] color for dipoles in each cluster. (multicolor mode)\n%   'dipsize'  - [numeric vector] size for each cluster. (multicolor mode)\n%                {default if unspecified: will automatically color/size each\n%                cluster}\n% Outputs:\n%   STUDY      - the input STUDY set structure modified with plotted cluster \n%                mean dipole, to allow quick replotting (unless cluster means \n%                already exists in the STUDY).  \n%   Example:\n%   >> [STUDY] = std_dipplot(STUDY,ALLEEG, 'clusters', 5, 'mode', 'apart', 'figure', 'off');\n%                % Plot cluster-5 component dipoles (in blue), plus their mean dipole (in red), \n%                % on an existing (gui-less) figure. \n%\n%  See also  POP_CLUSTEDIT, DIPPLOT        \n%\n% Authors:  Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005\n%          'groups' added by Makoto Miyakoshi on June 2012.\n%          'multicolor' mode added by John Iversen to draw all clusters on\n%           a single panel, with each cluster indicated by different color/size dipoles.\n\n% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, hilit@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction STUDY = std_dipplot(STUDY, ALLEEG, varargin)\n\n% Set default values\ncls = []; % plot all clusters in STUDY\nfigureon = 1; % plot on a new figure\nmode = 'apart';\n\nSTUDY = pop_dipparams(STUDY, 'default');\n\nopt_dipplot = {'projlines',STUDY.etc.dipparams.projlines, 'axistight', STUDY.etc.dipparams.axistight, 'projimg', STUDY.etc.dipparams.projimg, 'dipolelength', 0, 'density', STUDY.etc.dipparams.density};\n\ndipcolor = [];\ndipsize = [];\n%, 'spheres', 'on'\ngroupval = 'off';\nnosphere = true;\nfor k = 3:2:nargin\n    switch varargin{k-2}\n        case 'clusters'\n            if isnumeric(varargin{k-1})\n                cls = varargin{k-1};\n                if isempty(cls)\n                    cls = 2:length(STUDY.cluster);\n                end\n            else\n                if ischar(varargin{k-1}) && strcmpi(varargin{k-1}, 'all')\n                    cls = 2:length(STUDY.cluster);\n                else\n                    error('std_dipplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.');\n                end\n            end\n            if length(cls) == 1, mode = 'apart'; else mode = 'together'; end\n        case 'comps'\n            if strcmpi(STUDY.etc.dipparams.density, 'on')\n                disp('Single dipole should not be plotted using dipole density, reverting to dipole plotting');\n                opt_dipplot{end} = 'off';\n            end\n            STUDY = std_plotcompdip(STUDY, ALLEEG,  cls, varargin{k-1}, opt_dipplot{:});\n            return;\n        case 'plotsubjects', % do nothing\n        case 'mode', mode = varargin{k-1};\n        case 'groups', groupval = varargin{k-1};\n        case 'figure'\n            if strcmpi(varargin{k-1},'off') \n                if strcmpi(STUDY.etc.dipparams.density, 'on')\n                    disp('Cannot plot dipole density within figure, reverting to dipole plotting');\n                    opt_dipplot{end} = 'off';\n                end\n                opt_dipplot{end + 1} = 'gui';\n                opt_dipplot{end + 1} = 'off';\n                figureon = 0;\n            end\n      case 'dipcolor'\n        dipcolor = varargin{k-1};\n      case 'dipsize'\n        dipsize = varargin{k-1};\n      case 'spheres'\n        opt_dipplot = { opt_dipplot{:}, 'spheres',  varargin{k-1} };  \n        nosphere = false;\n    end\nend\nif nosphere\n    opt_dipplot = { opt_dipplot{:}, 'spheres', 'on' };\nend\n\nif strcmpi(mode, 'together')\n    if strcmpi(STUDY.etc.dipparams.density, 'on')\n        disp('Cannot plot dipole density within figure, reverting to dipole plotting');\n        opt_dipplot{end} = 'off';\n    end\nend\n\n% select clusters to plot\n% -----------------------\nif isempty(cls)\n    tmp =[];\n    cls = 2:length(STUDY.cluster); % plot all clusters in STUDY\n    for k = 1: length(cls)\n        % don't include 'Notclust' clusters\n        if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) && ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)\n            tmp = [tmp cls(k)];\n        end\n    end\n    cls = tmp;\nend\n\nif strcmpi(mode, 'apart')  % case each cluster on a separate figure\n    for clus = 1: length(cls) % For each cluster requested\n        if length(STUDY.cluster(cls(clus)).comps) > 0  % check there are comps in cluster\n            max_r = 0;\n            clear cluster_dip_models;\n            len = length(STUDY.cluster(cls(clus)).comps);\n            ndip = 0;\n            dip_ind = [];\n            if ~isfield(STUDY.cluster(cls(clus)),'dipole')\n                STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');\n            elseif isempty(STUDY.cluster(cls(clus)).dipole)\n                STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');\n            end\n            for k = 1:len\n                abset   = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).index;\n                subject = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).subject;\n               if ~isfield(ALLEEG(abset), 'dipfit')\n                   warndlg2(['No dipole information available in dataset ' ALLEEG(abset).filename ' , abort plotting'], 'Aborting plot dipoles');\n                   return;\n               end\n               comp = STUDY.cluster(cls(clus)).comps(k); \n               cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;\n               cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;\n               cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;\n               if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n                   if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n                       load('-mat', ALLEEG(abset).dipfit.hdmfile);\n                       max_r = max(max_r, max(vol.r));\n                   else % old version of dipfit\n                       max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));\n                   end\n               end\n               comp_to_disp{k} = [subject  ', ' 'IC' num2str(comp) ];\n               if ~isempty(cluster_dip_models(k).posxyz)\n                   ndip = ndip +1;\n                   dip_ind = [dip_ind k];\n               end\n            end % finished going over cluster comps\n            \n            STUDY.cluster(cls(clus)).dipole = computecentroid(cluster_dip_models);\n            cluster_dip_models(end + 1) = STUDY.cluster(cls(clus)).dipole;\n           \n           % additional options\n           % ------------------\n           dip_color = cell(1,ndip+1);\n           dip_color(1:ndip) = {'b'};\n           dip_color(end) = {'r'};\n           options = opt_dipplot;\n           options{end+1} =  'mri';\n           options{end+1} =  ALLEEG(abset).dipfit.mrifile;\n           options{end+1} =  'coordformat';\n           options{end+1} =  ALLEEG(abset).dipfit.coordformat;\n           options{end+1} =  'dipnames';\n           options{end+1} = {comp_to_disp{dip_ind } [STUDY.cluster(cls(clus)).name ' mean']};\n           options{end+1} = 'color';\n           options{end+1} = dip_color;\n           \n           % if 'groups'==1, overwrite cluster_dip_models, dip_color and dipnames in option -makoto\n           if strcmpi(groupval, 'on')\n               [cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options);\n               break\n           end\n  \n           if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n               options{end+1} = 'sphere';\n               options{end+1} = max_r;\n           else\n               options{end+1} = 'meshdata';\n               options{end+1} = ALLEEG(abset).dipfit.hdmfile;\n           end\n           %enable both lines and images to be projected; increase #dipole limits\n           if ndip < 20 && strcmpi(options{1}, 'projlines') && length(cls) == 1\n               options{2} = 'on';\n           end\n           if ndip < 20 && strcmpi(options{5}, 'projimg') && length(cls) == 1\n             options{6} = 'on';\n           end\n           \n           % Dealing with projection lines\n           if strcmpi(options{2},'on')\n               projlinesvect = ones(1,length(cluster_dip_models));\n           elseif strcmpi(options{2},'off') && strcmp(STUDY.etc.dipparams.centrline,'on')\n               projlinesvect = zeros(1,length(cluster_dip_models));\n               projlinesvect(end) = 1;\n           elseif strcmpi(options{2},'off')\n               projlinesvect = zeros(1,length(cluster_dip_models));\n           end\n           options{2} = projlinesvect;\n           \n           if figureon\n               dipplot(cluster_dip_models, options{:});\n               fig_h = gcf;\n               set(fig_h,'Name', [STUDY.cluster(cls(clus)).name ' - ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ...\n                       ' sets - ' num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ],'NumberTitle','off');\n           else\n               dipplot(cluster_dip_models, options{:},'view', [0.5 -0.5 0.5]);\n               for gind = 1:length(options) % remove the 'gui' 'off' option\n                   if ischar(options{gind}) \n                       if strfind(options{gind}, 'gui')\n                           break;\n                       end\n                   end\n               end\n               options(gind:gind+1) = [];\n               dipinfo.dipmod =  cluster_dip_models;\n               dipinfo.op = options;\n               diptitle = [STUDY.cluster(cls(clus)).name ', ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' sets -' ...\n                   num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ];\n               dipinfo.title = diptitle;\n               set(gcf, 'UserData', dipinfo);\n               set(gca,'UserData', dipinfo);\n               rotate3d off;\n               axcopy(gca, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off''''); ']);\n           end\n        end % finished the if condition that cluster isn't empty\n    end % finished going over requested clusters\nend \n\nif strcmpi(mode, 'together')  % case all clusters are plotted in the same figure (must be a new figure)\n    N = length(cls);\n    rowcols(2) = ceil(sqrt(N)); % Number of rows in the subplot figure.\n    rowcols(1) = ceil(N/rowcols(2));\n    fig_h = figure; \n    orient tall\n    set(fig_h,'Color', 'black');\n    set(fig_h,'Name', 'All clusters dipoles','NumberTitle','off');\n    set(fig_h, 'resize','off');\n    for l = 1:N\n        len = length(STUDY.cluster(cls(l)).comps);\n        max_r = 0;\n        clear cluster_dip_models;\n        if ~isfield(STUDY.cluster(cls(l)),'dipole')\n            STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');\n        elseif isempty(STUDY.cluster(cls(l)).dipole)\n            STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');\n        end\n        for k = 1: len\n            abset = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).index;\n           if ~isfield(ALLEEG(abset), 'dipfit')\n               warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');\n               return;\n           end\n           comp = STUDY.cluster(cls(l)).comps(k);\n           cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;\n           cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;\n           cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;\n           if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n                if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n                   load('-mat', ALLEEG(abset).dipfit.hdmfile);\n                   max_r = max(max_r, max(vol.r));\n               else % old version of dipfit\n                   max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));\n               end\n           end\n        end % finished going over cluster comps\n        STUDY.cluster(cls(l)).dipole = computecentroid(cluster_dip_models);\n        cluster_dip_models(end + 1) = STUDY.cluster(cls(l)).dipole;\n        dip_color = cell(1,length(cluster_dip_models));\n        dip_color(1:end-1) = {'b'};\n        dip_color(end) = {'r'};\n        options = opt_dipplot;\n        options{end + 1} =  'gui';\n        options{end + 1} =  'off';\n        options{end+1} =  'mri';\n        options{end+1} =  ALLEEG(abset).dipfit.mrifile;\n        options{end+1} =  'coordformat';\n        options{end+1} =  ALLEEG(abset).dipfit.coordformat;\n        options{end+1} = 'color';\n        options{end+1} = dip_color;\n        if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n            options{end+1} = 'sphere';\n            options{end+1} = max_r;\n        else\n            options{end+1} = 'meshdata';\n            options{end+1} = ALLEEG(abset).dipfit.hdmfile;\n        end\n        \n        % Dealing with projection lines\n        if strcmpi(options{2},'on')\n            projlinesvect = ones(1,length(cluster_dip_models));\n        elseif strcmpi(options{2},'off') && strcmp(STUDY.etc.dipparams.centrline,'on')\n            projlinesvect = zeros(1,length(cluster_dip_models));\n            projlinesvect(end) = 1;\n        elseif strcmpi(options{2},'off')\n            projlinesvect = zeros(1,length(cluster_dip_models));\n        end\n           options{2} = projlinesvect;\n        \n        hsbplot = subplot(rowcols(1),rowcols(2),l);\n        % Creating new axis for title only\n        set(hsbplot,'visible','off');\n        htitle = title([ STUDY.cluster(cls(l)).name ' (' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(l)).comps)),' ICs)'],'color','white','Visible', 'on');\n        if rowcols(1)> 1, set(htitle,'Position', get(htitle,'Position')+ [0 0.05 0].*get(htitle,'Position') ); end\n        axes('Position', get(hsbplot,'Position'),'Color', 'black');\n        dipplot(cluster_dip_models, options{:});\n\n        %diptitle = [STUDY.cluster(cls(l)).name ', ' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) 'Ss'];\n        %title(diptitle, 'Color', 'white');\n        % Complex axcopy\n        %if l == 1\n        %    for gind = 1:length(options) % remove the 'gui' 'off' option\n        %        if ischar(options{gind}) \n        %            if strfind(options{gind}, 'gui')\n        %                break;\n        %            end\n        %        end\n        %    end\n        %    options(gind:gind+1) = [];\n        %end\n        %dipinfo.dipmod =  cluster_dip_models;\n        %dipinfo.op = options;\n        %dipinfo.title = diptitle;\n        %set(gcf, 'UserData', dipinfo);\n        %set(gca,'UserData', dipinfo);\n        %axcopy(gcf, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off'''');']);\n   end %finished going over all clusters\n   set(fig_h, 'resize','on');\nend % finished case of 'all' clusters\n\n% ========================================================================================\n% multicolor mode\n%   all clusters are plotted in the same axis, with each cluster indicated by color/size\n%   also enable 'data cursor' so that in data tip mode, clicking on a dipole\n%    will display its name\nif strcmpi(mode, 'multicolor')\n  N = length(cls);\n  %%%%%%%%%%%%%%%%%%%%% color list %%%%%%%%%%%%%%%%%%%%%\n  % This color list was developed for std_envtopo\n  % modified from dipgroups below\n  colors{1}  = [1 1 1];            % White\n  colors{2}  = [1 1 0];            % Yellow\n  colors{3}  = [1 0 1];            % Fuchsia\n  colors{4}  = [1 0 0];            % Red\n  colors{5}  = [0.875 0.875 0.875]; % Silver\n  colors{6}  = [0.5 0.5 0.5];      % Gray\n  colors{7}  = [0.5 0.5 0];        % Olive\n  colors{8}  = [0.5 0 0.5];        % Purple\n  colors{9}  = [0.5 0 0];          % Maroon\n  colors{10} = [0 1 1];            % Aqua\n  colors{11} = [0 1 0];            % Lime\n  colors{12} = [0 0.5 0.5];        % Teal\n  colors{13} = [0 0.5 0];          % Green\n  colors{14} = [0 0 1];            % Blue\n  colors{15} = [0 0 0.5];          % Navy\n  colors{16} = [0 0 0];            % Black\n  % Choosing and sorting 13 colors for clusters: Red, Green, Blue,\n  % Fuchsia, Lime, Aqua, Maroon, Olive, Purple, Teal, Navy, Gray, and White\n  colors = colors([4 13 14 3 11 10 9 7 8 12 15 6 1 ]);\n  fig_h = figure;\n  orient tall\n  set(fig_h,'Color', 'black');\n  set(fig_h,'Name', 'All clusters dipoles','NumberTitle','off');\n  set(fig_h, 'resize','off');\n  \n  idx = 0; %cumulative dipole index\n  centroidIdx = [];\n  clear cluster_dip_models;\n  for l = 1:N %loop over clusters\n    len = length(STUDY.cluster(cls(l)).comps);\n    max_r = 0;\n    \n    %color, size for every cluster can be passed as arguments, or\n    %automatically iterate through a set of colors/sizes\n    if ~isempty(dipcolor)\n      clusterColors{l} = dipcolor{idx};\n    else\n      colorIndex = mod(l-1, length(colors))+1;\n      clusterColors{l} = colors{colorIndex};\n    end\n    \n    if ~isempty(dipsize)\n      clusterSizes(l) = dipsize(idx);\n    else\n      %after rotating through color list once, change size of dipole\n      if l <= length(colors)\n        clusterSizes(l) = 30;\n      elseif l <= 2*length(colors)\n        clusterSizes(l) = 20;\n      else\n        clusterSizes(l) = 15;\n      end\n    end\n    \n    if ~isfield(STUDY.cluster(cls(l)),'dipole')\n      STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');\n    elseif isempty(STUDY.cluster(cls(l)).dipole)\n      STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');\n    end\n    clustStartIdx = idx + 1;\n    \n    for k = 1:len %loop over components within a cluster\n      idx = idx + 1;\n      abset = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).index;\n      subjname = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).subject;\n      if ~isfield(ALLEEG(abset), 'dipfit')\n        warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');\n        return;\n      end\n      comp = STUDY.cluster(cls(l)).comps(k);\n      cluster_dip_models(idx).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;\n      cluster_dip_models(idx).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;\n      cluster_dip_models(idx).rv = ALLEEG(abset).dipfit.model(comp).rv;\n      if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n        if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n          load('-mat', ALLEEG(abset).dipfit.hdmfile);\n          max_r = max(max_r, max(vol.r));\n        else % old version of dipfit\n          max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));\n        end\n      end\n      \n      dip_color{idx} = clusterColors{l};\n      dip_size(idx) = clusterSizes(l);\n      dip_label{idx} = sprintf('Cls %d (%s IC%d)',cls(l), subjname, comp);\n    end % finished going over cluster comps\n    \n    %add the cluster centroid\n    clustEndIdx = idx;\n    STUDY.cluster(cls(l)).dipole = computecentroid(cluster_dip_models(clustStartIdx:clustEndIdx));\n    idx = idx + 1;\n    centroidIdx(end+1) = idx;\n    cluster_dip_models(idx) = STUDY.cluster(cls(l)).dipole;\n    dip_color(idx) = {'k'};\n    dip_size(idx) = 10;\n    dip_label{idx} = sprintf('Cls %d centroid',cls(l));\n    clusterLabels{l} = sprintf('Cls %d',cls(l));\n    \n  end %loop over clusters\n  \n  options = opt_dipplot;\n  options{end + 1} =  'gui';\n  options{end + 1} =  'off';\n  options{end+1} =  'mri';\n  options{end+1} =  ALLEEG(abset).dipfit.mrifile;\n  options{end+1} =  'coordformat';\n  options{end+1} =  ALLEEG(abset).dipfit.coordformat;\n  options{end+1} = 'color';\n  options{end+1} = dip_color;\n  options{end+1} = 'dipolesize';\n  options{end+1} = dip_size;\n  options{end+1} = 'dipnames';\n  options{end+1} = dip_label;\n  if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n    options{end+1} = 'sphere';\n    options{end+1} = max_r;\n  else\n    options{end+1} = 'meshdata';\n    options{end+1} = ALLEEG(abset).dipfit.hdmfile;\n  end\n  \n  % Dealing with projection lines\n  if strcmpi(options{2},'on')\n      projlinesvect = ones(1,length(cluster_dip_models));\n  elseif strcmpi(options{2},'off') && strcmp(STUDY.etc.dipparams.centrline,'on')\n      projlinesvect = zeros(1,length(cluster_dip_models));\n      projlinesvect(centroidIdx) = 1;\n  elseif strcmpi(options{2},'off')\n      projlinesvect = zeros(1,length(cluster_dip_models));\n  end\n  options{2} = projlinesvect;\n  \n  dipplot(cluster_dip_models, options{:});\n  set(fig_h, 'resize','on');\n  \n  %data cursor will show component label\n  datacursormode on\n  dcm = datacursormode(gcf);\n  set(dcm,'Enable','on', 'UpdateFcn', @componentText)\n  \nend % multicolor. Supporting functions at end of file\n\n% ========================================================================================\n\n% STD_PLOTCOMPDIP - Commandline function, to visualizing cluster components dipoles. \n%                   Displays the dipoles of specified cluster components with the cluster mean \n%                   dipole on separate figures. \n%                   To visualize dipoles they first must be stored in the EEG dataset structures\n%                   using DIPFIT. Only components that have a dipole locations will be displayed,\n%                   along with the cluster mean dipole in red. \n% Usage:    \n%                   >> [STUDY] = std_plotcompdip(STUDY, ALLEEG, cluster, comps);  \n% Inputs:\n%   STUDY      - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.\n%   ALLEEG     - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY. \n%                     ALLEEG for a STUDY set is typically created using LOAD_ALLEEG.  \n%   cluster     - single cluster number.  \n%\n% Optional inputs:\n%   comps      - [numeric vector]  -> indices of the cluster components to plot.\n%                       'all'                       -> plot all the components in the cluster {default: 'all'}. \n%\n% Outputs:\n%   STUDY    - the input STUDY set structure modified with plotted cluster\n%                     dipole mean, to allow quick replotting (unless cluster mean \n%                     already existed in the STUDY).  \n%\n%   Example:\n%                         >> cluster = 4; comps= 1;  \n%                         >> [STUDY] = std_plotcompdip(STUDY,ALLEEG, cluster, comps);\n%                    Plots component 1 dipole in blue with the cluster 4 mean dipole in red. \n%\n%  See also  pop_clustedit, dipfit, std_dipplot         \n%\n% Authors:  Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005\n\n% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, hilit@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction STUDY = std_plotcompdip(STUDY, ALLEEG, cls, comp_ind, varargin)\nif ~exist('cls')\n    error('std_plotcompdip: you must provide a cluster number as an input.');\nend\nif isempty(cls)\n   error('std_plotcompdip: you must provide a cluster number as an input.');\nend\nif nargin == 3 % no components indices were given\n    % Default plot all components of the cluster\n    [STUDY] = std_dipplot(STUDY, ALLEEG, 'clusters', cls);\n    return\nend\n\nfor ci = 1:length(comp_ind)\n    abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index;\n    comp = STUDY.cluster(cls).comps(comp_ind(ci));\n    subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject;\n    if ~isfield(ALLEEG(abset), 'dipfit')\n        warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');\n        return;\n    end\n    if length(comp_ind) == 1 && isempty(ALLEEG(abset).dipfit.model(comp).posxyz)\n        warndlg2(strvcat('There is no dipole information available in', ...\n                       [ 'dataset ' num2str(abset) ' for this component, abort plotting']), 'Aborting plot dipoles');\n        return;\n    end\n    if ~isfield(STUDY.cluster(cls),'dipole')\n        STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');\n    elseif isempty(STUDY.cluster(cls).dipole)\n        STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');\n    end\n    comp_to_disp = [subject  ' / ' 'IC' num2str(comp) ];\n    cluster_dip_models.posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;\n    cluster_dip_models.momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;\n    cluster_dip_models.rv = ALLEEG(abset).dipfit.model(comp).rv;\n    cluster_dip_models(2) = STUDY.cluster(cls).dipole;\n    if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n        if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n            load('-mat', ALLEEG(abset).dipfit.hdmfile);\n            max_r = max(vol.r);\n        else\n            max_r = max(ALLEEG(abset).dipfit.vol.r);\n        end\n        dipplot(cluster_dip_models, 'sphere', max_r, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...\n           'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [ STUDY.cluster(cls).name ' mean' ] },...\n            'spheres', 'on', 'verbose', 'off', varargin{:});\n    else\n       dipplot(cluster_dip_models, 'meshdata', ALLEEG(abset).dipfit.hdmfile, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...\n          'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [STUDY.cluster(cls).name ' mean']}, ...\n          'spheres', 'off', 'verbose', 'off', varargin{:});\n    end\n    fig_h = gcf;\n    set(fig_h,'Name', [subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name],'NumberTitle','off');\nend\n        \n% -----------------------\n% load all dipoles and\n% compute dipole centroid\n% DEVELOPMENT: this function\n% should be the only one to\n% access dipole information\n% -----------------------\nfunction STUDY = std_centroid(STUDY,ALLEEG, clsind, tmp);\n\n    for clust = 1:length(clsind)\n        max_r = 0;\n        len = length(STUDY.cluster(clsind(clust)).comps);\n        tmppos = [ 0 0 0 ];\n        tmpmom = [ 0 0 0 ];\n        tmprv = 0;\n        ndip = 0;\n        for k = 1:len \n            fprintf('.');\n            comp  = STUDY.cluster(clsind(clust)).comps(k);\n            abset = STUDY.cluster(clsind(clust)).sets(1,k);\n            if ~isfield(ALLEEG(abset), 'dipfit')\n               warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole');\n               return;\n            end\n            if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz)\n                ndip   = ndip +1;\n                posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;\n                momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;\n                if size(posxyz,1) == 2\n                    if all(posxyz(2,:) == [ 0 0 0 ])\n                        posxyz(2,:) = [];\n                        momxyz(2,:) = [];\n                    end\n                end\n                tmppos = tmppos + mean(posxyz,1);\n                tmpmom = tmpmom + mean(momxyz,1);\n                tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv;\n                if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')\n                   if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model\n                       load('-mat', ALLEEG(abset).dipfit.hdmfile);\n                       max_r = max(max_r, max(vol.r));\n                   else % old version of dipfit\n                       max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));\n                   end\n               end\n            end\n        end\n        centroid{clust}.dipole.posxyz =  tmppos/ndip;\n        centroid{clust}.dipole.momxyz =  tmpmom/ndip;\n        centroid{clust}.dipole.rv =  tmprv/ndip;\n        if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') && (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit\n            centroid{clust}.dipole.maxr = max_r;\n        end\n        STUDY.cluster(clsind(clust)).dipole = centroid{clust}.dipole;\n    end\n    fprintf('\\n');\n\n% --------------------------------\n% new function to compute centroid\n% was programmed to debug the function\n% above but is now used in the code\n% --------------------------------\nfunction dipole = computecentroid(alldipoles)\n\n        max_r = 0;\n        len = length(alldipoles);\n        dipole.posxyz = [ 0 0 0 ];\n        dipole.momxyz = [ 0 0 0 ];\n        dipole.rv = 0;\n        ndip = 0;\n        count = 0;\n        warningon = 1;\n        for k = 1:len \n            if size(alldipoles(k).posxyz,1) == 2\n                if all(alldipoles(k).posxyz(2,:) == [ 0 0 0 ])\n                    alldipoles(k).posxyz(2,:) = [];\n                    alldipoles(k).momxyz(2,:) = [];\n                end\n            end\n            if ~isempty(alldipoles(k).posxyz)\n                dipole.posxyz = dipole.posxyz + mean(alldipoles(k).posxyz,1);\n                dipole.momxyz = dipole.momxyz + mean(alldipoles(k).momxyz,1);\n                dipole.rv     = dipole.rv     + alldipoles(k).rv;\n                count = count+1;\n            elseif warningon\n                disp('Some components do not have dipole information');\n                warningon = 0;\n            end\n        end\n        dipole.posxyz = dipole.posxyz/count;\n        dipole.momxyz = dipole.momxyz/count;\n        dipole.rv     = dipole.rv/count;\n        if isfield(alldipoles, 'maxr')\n            dipole.maxr = alldipoles(1).max_r;\n        end\n        \nfunction [cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options);\n\n    % first, extract the subject number\n    for n = 1:length(comp_to_disp)\n        subjectnum(n,1) = str2num(comp_to_disp{n}(1:3));\n    end\n\n    % second, extract group info\n    for n = 1:length(subjectnum)\n        subj_group{n,1} = ALLEEG(1,subjectnum(n)).group;\n    end\n\n    % third, replace the group names with numbers\n    for n = 1:length(subj_group)\n        for m = 1:length(STUDY.group)\n            if strcmp(subj_group{n,1}, STUDY.group{1,m})\n                subj_groupnum(n,1) = m;\n                break\n            end\n        end\n    end\n\n    % fourth, compute centroid for each group\n    for n = 1:length(STUDY.group)\n        samegroupIC = find(subj_groupnum==n);\n        cluster_dip_models(1,length(subj_groupnum)+n) = computecentroid(cluster_dip_models(1, samegroupIC));\n    end\n\n    % fifth, use subj_groupnum as a type of dipole color\n\n        %%%%%%%%%%%%%%%%%%%%% color list %%%%%%%%%%%%%%%%%%%%%\n        % This color list was developed for std_envtopo\n        % 16 colors names officially supported by W3C specification for HTML\n        colors{1,1}  = [1 1 1];            % White\n        colors{2,1}  = [1 1 0];            % Yellow\n        colors{3,1}  = [1 0 1];            % Fuchsia\n        colors{4,1}  = [1 0 0];            % Red\n        colors{5,1}  = [0.75  0.75  0.75]; % Silver\n        colors{6,1}  = [0.5 0.5 0.5];      % Gray\n        colors{7,1}  = [0.5 0.5 0];        % Olive\n        colors{8,1}  = [0.5 0 0.5];        % Purple\n        colors{9,1}  = [0.5 0 0];          % Maroon\n        colors{10,1} = [0 1 1];            % Aqua\n        colors{11,1} = [0 1 0];            % Lime\n        colors{12,1} = [0 0.5 0.5];        % Teal\n        colors{13,1} = [0 0.5 0];          % Green\n        colors{14,1} = [0 0 1];            % Blue\n        colors{15,1} = [0 0 0.5];          % Navy\n        colors{16,1} = [0 0 0];            % Black\n        % Silver is twice brighter because silver is used for a background color\n        colors{5,1} = [0.875 0.875 0.875];\n        % Choosing and sorting 12 colors for line plot, namely Red, Blue, Green, Fuchsia, Lime, Aqua, Maroon, Olive, Purple, Teal, Navy, and Gray\n        selectedcolors = colors([4 13 14 3 11 10 9 7 8 12 15 6]);\n\n    % determine the new dip colors\n    for n = 1:length(subj_groupnum)\n        dip_color{1,n}=selectedcolors{subj_groupnum(n,1)+1};\n    end\n    for n = 1:length(STUDY.group)\n        dip_color{1,end+1}= selectedcolors{n+1};\n    end\n    \n    for n = 1:length(options)\n        if      strcmp(options{1,n}, 'color')\n            options{1,n+1} = dip_color;\n        elseif  strcmp(options{1,n}, 'dipnames')\n            dipnames = options{1,n+1};\n            for m = 1:length(STUDY.group)\n                dipnames{1,length(subj_groupnum)+m}= [STUDY.group{1,m} ' mean'];\n            end\n            options{1,n+1} = dipnames;\n        end\n    end\n    \n% ========================================================================================\n% multicolor mode support functions\nfunction str = componentText(~,obj)\n% look up component name--used in data cursor callback in 'multicolor' mode\ntry\n  str = obj.Target.UserData.name;\n  h=findall(gcf,'type','hggroup');\n  h(1).FontSize = 14;\ncatch\n  str = '';\nend\n\n\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_dipplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630079339209552}}
{"text": "function destination = BV_CombineWithMask(sourceFile, destinationFile, maskFile, outFile, normalizeImages)\n%\n%   destination = BV_CombineWithMask(sourceFile, destinationFile, maskFile, outFile)\n%\n% Combines Analyze images using a mask\n%\n% Like this:\n%    destination(mask) = source(mask);\n%\n% EXAMPLE: \n%       BV_CombineWithMask(homog_brain, orig, brain_mask);\n%\n% $Author: bob $\n% $Date: 2003/12/20 00:01:50 $\n\nif (~exist('normalizeImages','var'))\n    normalizeImages=0;\nend\nif ~exist('outFile','var')\n    outFile = [destinationFile,'_Combined']\nend\n    \n% Load in the images:\n[source,mmPerVox]      = loadAnalyze(sourceFile,'',1);\n[destination,mmPerVox] = loadAnalyze(destinationFile,'',1);\n\n% Assume that mask is 0s and 1s\nmask = loadAnalyze(maskFile,'',1);\nmask = mask~=0;\n\n% Do some normalization if required\nif (normalizeImages);\n    disp('Normalizing...');\n    source = double(source);\n    source = source-min(source(:));\n    source = source/max(source(:))*65000;\n    source = uint16(source);\n    destination = double(destination);\n    destination = destination-min(destination(:));\n    destination = destination/max(destination(:))*65000;\n    destination = uint16(destination);\nend\n\n% Take the locations in the Source that are in the mask positions\n% and copy them into the Destination file.\ndestination(mask) = source(mask);\n\nif nargout == 0\n    saveAnalyze(double(destination),outFile, mmPerVox);\n    fprintf('Saving combined file:  %s\\n',outFile);\nend\n\nreturn;\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/combineWithMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22624518377989256}}
{"text": "function RecreateTspFile(fbasename)\n\n\ntspdata=load([fbasename '.tsp']);\ntspdata = tspdata(:,1);\n\nif size(tspdata,2)>1\n  warning('tsp has data in it! Are You sure you want to continue?')\n%   keyboard\nend\n\nnFramesTsp = size(tspdata,1);\ntspnew = [tspdata -1*ones(size(tspdata,1),6)];\n\n%readerobj  = VideoReader([fbasename '.mpg']);\n\nif ~exist([fbasename '.ogg'],'file') && exist([fbasename '.mpg'],'file')\n    %eval(['!ffmpeg -i ' fbasename '.mpg -f ogg ' fbasename '.ogg'])\n    eval(['!avconv -i ' fbasename '.mpg -f ogg ' fbasename '.ogg'])\nelseif ~exist([fbasename '.ogg'],'file') && ~exist([fbasename '.mpg'],'file')\n    error('No video file!!')\nend\n    \nwhl = ApproxMedianFilter_RB_LED([fbasename '.ogg']);\nfigure(1),clf\nplot(whl(:,1),whl(:,2))\nhold on\nplot(whl(:,3),whl(:,4),'r')\n\nnDiff = nFramesTsp - size(whl,1);\nif nDiff ~=0 %in case of frame drop, interpolate the output\n\n    twhl = (1:size(whl,1));\n    ttsp = (1:size(tspdata,1));\n    whl(whl==-1) = NaN;\n    interpData = interp1(twhl,whl,ttsp);\n    interpData(isnan(interpData)) = -1;\n    tspnew(:,[2 3 6 7]) = interpData;\nelse\n    tspnew(:,[2 3 6 7]) = whl;\nend\n\nfid = fopen([fbasename '.tsp'],'w');\nfprintf(fid,'%i\\t %f\\t %f\\t %f\\t %f\\t %f\\t %f\\t \\n',tspnew');\nfclose(fid);\n%eval(['!rm ' fbasename '.ogg'])\n \n      \n\n\n  ", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/preprocessing/amplipexToolbox/RecreateTspFile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22608156617653247}}
{"text": "function [w, s, h] = gp_pak(gp, param)\n%GP_PAK  Combine GP parameters into one vector\n%\n%  Description\n%    W = GP_PAK(GP, PARAM) takes a Gaussian Process structure\n%    GP and string PARAM defining, which parameters are packed and\n%    combines the parameters into a single row vector W. If PARAM\n%    is not given the function packs all parameters.\n%\n%    Each of the following strings in PARAM defines one group of\n%    parameters to pack:\n%      covariance  - pack parameters of covariance function\n%      likelihood  - pack parameters of likelihood\n%      inducing    - pack inducing inputs (in sparse approximations): \n%                    W = gp.X_u(:)\n%\n%    By combining the strings one can pack more than one group of\n%    parameters. For example:\n%      covariance+inducing  - pack covariance function parameters\n%                             and inducing inputs\n%      covariance+likelih   - pack covariance function parameters\n%                             and likelihood parameters\n%\n%    Inside each group (such as covariance functions) the\n%    parameters to be packed is defined by the existence of a prior\n%    structure. For example, if GP has two covariance functions but\n%    only the first one has prior for its parameters then only the\n%    parameters of the first one are packed. Thus, also inducing\n%    inputs require prior if they are to be optimized.\n%\n%    GP_PAK and GP_UNPAK functions are used, e.g., when GP\n%    parameters are optimized with GP_OPTIM or sampled with GP_MC.\n%    See GP_SET and option 'infer_params'.\n%\n%    [W, WS] = GP_PAK(GP, PARAM) returns also cell array of string\n%    labels for the weight vector elements, which makes diagnostics\n%    easier.\n%\n%    [W, WS, H] = GP_PAK(GP, PARAM) returns also hierarchy level H of \n%    different parameters (0 for likelihood parameters and 1 for covariance\n%    function parameters)\n%\n%  See also\n%    GP_UNPAK, GP_SET\n%\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n  w = []; s = {}; h = [];\n\n  if isfield(gp,'etr') && length(gp.etr) > 1\n    if strcmp(gp.type, 'PIC_BLOCK') || strcmp(gp.type, 'PIC')\n      ind = gp.tr_index;           % block indeces for training points\n      gp = rmfield(gp,'tr_index');\n    end\n    ns = length(gp.etr);\n    for i1 = 1:ns\n      Gp = take_nth(gp,i1);\n      [w(i1,:), s, h] = gp_pak(Gp);\n    end\n  else\n    \n    if nargin < 2\n      param = gp.infer_params;\n    end\n    \n    % Pack SVI variational parameters \n    if isfield(gp, 'latent_method') && isequal(gp.latent_method,'SVI') ...\n        && isfield(gp, 't1')\n      w=[gp.t1; gp.t2(:)]';\n      if length(gp.t1)>1\n        s = [s; sprintf('E[u] x %d', gp.nind); ...\n          sprintf('Cov[u] x %d', gp.nind^2)];\n      else\n        s = [s; 'E[u]'; 'Cov[u]'];\n      end\n    end\n    \n    % Pack the parameters of covariance functions\n    if ~isempty(strfind(param, 'covariance'))\n      ncf = length(gp.cf);\n      \n      for i=1:ncf\n        gpcf = gp.cf{i};\n        [wi, si, hi] = gpcf.fh.pak(gpcf);\n        w = [w wi];\n        s = [s; si];\n        h = [h hi];\n      end\n    end\n    \n    % Pack the parameters of likelihood function\n    if ~isempty(strfind(param, 'likelihood'))\n      [wi, si, hi] = gp.lik.fh.pak(gp.lik);\n      if isfield(gp, 'latent_method') && isequal(gp.latent_method, 'SVI') ...\n          && ~isequal(gp.lik.type, 'Gaussian') && isfield(gp, 't1') ...\n          && ~isempty(gp.lik.p.sigma2)\n        wi=log(gp.lik.sigma2);\n        si='log(sigma2)';\n        hi=0;\n      end\n      w = [w wi];\n      s = [s; si];\n      h = [h hi];\n    end\n    \n    % Pack the parameters of the second likelihood function (monotonic)\n    if ~isempty(strfind(param, 'likelihood')) && isfield(gp, 'lik_mono')\n      [wi, si, hi] = gp.lik_mono.fh.pak(gp.lik_mono);\n      if isfield(gp, 'latent_method') && isequal(gp.latent_method, 'SVI') ...\n           && isfield(gp, 't1') && ~isempty(gp.lik_mono.p.sigma2)\n        wi=log(gp.lik_mono.sigma2);\n        si='log(sigma2_mono)';\n        hi=0;\n      end\n      w = [w wi];\n      s = [s; si];\n      h = [h hi];\n    end\n    \n    % Pack the inducing inputs\n    if ~isempty(strfind(param, 'inducing'))\n      if isfield(gp,'p') && isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)\n        if ~iscell(gp.p.X_u)\n          % One prior for all inducing inputs\n          w = [w reshape(gp.X_u', numel(gp.X_u),1)'];\n%           w = [w gp.X_u'];\n          s = [s; sprintf('inducing x %d',numel(gp.X_u))];\n          h = [h ones(1,numel(gp.X_u))];\n          [wi,si,hi]=gp.p.X_u.fh.pak(gp.p.X_u);\n          w = [w wi];\n          s = [s; si];\n          h = [h 1+hi];\n        else\n          % Own prior for each inducing input\n          for i=1:size(gp.X_u,1)\n            w = [w gp.X_u(i,:)];\n            s = [s; sprintf('inducing x %d',numel(gp.X_u(i,:)))];\n            h = [h ones(1,size(gp.X_u(i,:),2))];\n            [wi,si,hi]=gp.p.X_u{i}.fh.pak(gp.p.X_u{i});\n            si=strcat(repmat('prior-', size(si,1),1),si);\n            w = [w wi];\n            s = [s; si];\n            h = [h 1+hi];            \n          end\n        end\n      end\n    end\n    \n    % Pack the prior weights and variances of mean functions\n    if ~isempty(strfind(param, 'mean'))\n      mf = length(gp.meanf);\n      \n      for i=1:mf\n        gpmf = gp.meanf{i};\n        [wi, si, hi] = gpmf.fh.pak(gpmf);\n        w = [w wi];\n        s = [s; si];\n        h = [h, hi];\n      end\n    end\n    \n  end\n\nend", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gp_pak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22608156617653244}}
{"text": "%  This scriptfile ask for several input parameters that can be setup\n%  at the beginning of each session. The default values are the\n%  extrema in the catalog\n%\n%a = org;        % resets the main catalogue \"a\" to initial state\n\n% TODO remove this file, it has been replaced by catalog_overview.m\nreport_this_filefun(mfilename('fullpath'));\n\n%  default values\nt0b = min(ZG.primeCatalog.Date);\nteb = max(ZG.primeCatalog.Date);\ntdiff = (teb - t0b)*365;\n\nif ~exist('par1', 'var')\n    %  if tdiff>10                 %select bin length respective to time in catalog\n    %     par1 = ceil(tdiff/100);\n    %  elseif tdiff<=10 & tdiff>1\n    %     par1 = 0.1;\n    %  elseif tdiff<=1\n    %     par1 = 0.01;\n    %  end\n    par1 = 30;\nend\n\nZG.big_eq_minmag = max(ZG.primeCatalog.Magnitude) -0.2;\ndep1 = 0.3*max(ZG.primeCatalog.Depth);\ndep2 = 0.6*max(ZG.primeCatalog.Depth);\ndep3 = max(ZG.primeCatalog.Depth);\nminti = min(ZG.primeCatalog.Date);\nmaxti  = max(ZG.primeCatalog.Date);\nminma = min(ZG.primeCatalog.Magnitude);\nmaxma = max(ZG.primeCatalog.Magnitude);\nmindep = min(ZG.primeCatalog.Depth);\nmaxdep = max(ZG.primeCatalog.Depth);\n\n%\n% make the interface\n%\nfigure_w_normalized_uicontrolunits(...\n    'Units','pixel','pos',[300 100 300 400 ],...\n    'Name','General Parameters!',...\n    'visible','off',...\n    'NumberTitle','off',...\n    'MenuBar','none',...\n    'NextPlot','new');\naxis off\n\ninp1B=uicontrol('Style','edit','Position',[.70 .90 .22 .05],...\n    'Units','normalized','String',num2str(ZG.primeCatalog.Count),...\n    'Callback','nueq=str2double(inp1B.String); inp1B.String=num2str(ZG.primeCatalog.Count);');\n\ninp1=uicontrol('Style','edit','Position',[.70 .80 .22 .05],...\n    'Units','normalized','String',num2str(ZG.big_eq_minmag),...\n    'Callback','ZG.big_eq_minmag=str2double(inp1.String); inp1.String=num2str(ZG.big_eq_minmag))');\n\ninp2=uicontrol('Style','edit','Position',[.70 .70 .22 .05],...\n    'Units','normalized','String',num2str(par1),...\n    'Callback','par1=str2double(inp2.String); inp2.String=num2str(par1);');\n\ninp3=uicontrol('Style','edit','Position',[.70 .60 .22 .05],...\n    'Units','normalized','String',num2str(minti),...\n    'Callback','minti=str2double(inp3.String); inp3.String=num2str(minti);');\n\n\ninp4=uicontrol('Style','edit','Position',[.70 .50 .22 .05],...\n    'Units','normalized','String',num2str(maxti),...\n    'Callback','maxti=str2double(inp4.String); inp4.String=num2str(maxti);');\n\ninp5=uicontrol('Style','edit','Position',[.70 .40 .22 .05],...\n    'Units','normalized','String',num2str(minma),...\n    'Callback','minma=str2double(inp5.String); inp5.String=num2str(minma);');\n\ninp6=uicontrol('Style','edit','Position',[.70 .30 .22 .05],...\n    'Units','normalized','String',num2str(maxma),...\n    'Callback','maxma=str2double(inp6.String); inp6.String=num2str(maxma);');\n\ninp7=uicontrol('Style','edit','Position',[.30 .15 .15 .05],...\n    'Units','normalized','String',num2str(mindep),...\n    'Callback','mindep=str2double(inp7.String); inp7.String=num2str(mindep);');\n\ninp8=uicontrol('Style','edit','Position',[.50 .15 .15 .05],...\n    'Units','normalized','String',num2str(maxdep),...\n    'Callback','maxdep=str2double(inp8.String); inp8.String=num2str(maxdep);');\n\n\n\nclose_button=uicontrol('Style','Pushbutton',...\n    'Position',[.65 .02 .20 .10 ],...\n    'Units','normalized','Callback','close;zmap_message_center.set_info('' '','' '');done','String','cancel');\n\ngo_button=uicontrol('Style','Pushbutton',...\n    'Position',[.35 .02 .20 .10 ],...\n    'Units','normalized',...\n    'Callback','close,think, sele_sub',...\n    'String','Go');\n\ninfo_button=uicontrol('Style','Pushbutton',...\n    'Position',[.05 .02 .20 .10 ],...\n    'Units','normalized',...\n    'Callback','zmaphelp(titstr,hlpStr)',...\n    'String','Info');\ntitstr = 'General Parameters';\nhlpStr = ...\n    ['This window allows you to select earthquakes '\n    'from a catalog. You can select a subset in   '\n    'time, magnitude and depth.                   '\n    '                                             '\n    'The top frame displays the number of         '\n    'earthquakes in the catalog - no selection is '\n    'possible.                                    '\n    '                                             '\n    'Two more parameters can be adjusted: The Bin '\n    'length in days that is used to sample the    '\n    'seismicity and the minimum magnitude of      '\n    'quakes displayed with a larger symbol in the '\n    'map.                                         '];\n\n\n\n\ntxt3 = text(...\n    'Color',[1 0 0 ],...\n    'Position',[0.02 1.00 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String',' EQs in catalog: ');\n\n\ntxt1 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.75 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Bin Length in days :');\n\ntxt2 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.87 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Plot Big Events with M > ');\n\ntxt4 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.63 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Beginning year: ');\n\ntxt5 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.51 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Ending year: ');\n\ntxt6 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.38 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Minimum Magnitude: ');\n\ntxt6 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.25 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','Maximum Magnitude: ');\n\ntxt7 = text(...\n    'Color',[0 0 0 ],...\n    'Position',[0.02 0.15 0 ],...\n    'Rotation',0 ,...\n    'FontSize',ZmapGlobal.Data.fontsz.m ,...\n    'FontWeight','bold' ,...\n    'String','       Min Depth     Max Depth  ');\n\n\n%clear txt1 txt2 txt3 txt4 txt5 txt6 txt7 inp1 inp1B inp3 inp3 inp4 inp5 inp6 inp7\nset(gcf,'visible','on')\nwatchoff\nstr = [ 'Please Select a subset of earthquakes'\n    ' and press Go                        '];\nzmap_message_center.set_message('Message',str);\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/inpu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.22593356383038596}}
{"text": "% ------------------------------------------------------------------------ \n%  Copyright (C)\n%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n%  University of California Berkeley (UCB) - USA\n% \n%  Jordi Pont-Tuset <jordi.pont@upc.edu>\n%  Pablo Arbelaez <arbelaez@berkeley.edu>\n%  June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n%    \"Multiscale Combinatorial Grouping,\"\n%    Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------ \nfunction rank_training(params, cache_dir)\n\nn_hiers = length(params.hiers);\n\n%% Load Pareto parameters\nn_cands = loadvar(params.files.pareto_point,'n_cands');\n\n% Some checks\nassert(n_hiers==size(n_cands,2));\nassert(params.n_r_cand==size(n_cands,1));\n\n%% Gather all features and quality of the training set candidates\nif exist(params.files.features_file,'file')\n    load(params.files.features_file);\n    disp(['Loaded: ' params.files.features_file '.'])\nelse\n    disp(['RECOMPUTING: ' params.files.features_file '.'])\n\n    % features = [];\n    % jaccards = [];\n\n    % Load which images to consider from the params.database (train, val, etc.)\n    im_ids = database_ids(params.database,params.gt_set_ranking);\n\n    num_images = length(im_ids);\n    parfor im_id = 1:num_images\n        out = cache_mcg_features(params, [], im_ids{im_id}, cache_dir);\n        f_lp = out.f_lp; f_ms = full(out.f_ms); feats = out.feats;\n        bboxes = out.bboxes; red_cands = out.red_cands; \n        b_feats_intersections = full(out.b_feats_intersection); \n\n        if(params.depth_features)\n          tt = tic();\n          sp = f_lp;\n          sp2regC = cands2labels(red_cands, f_ms);\n          sp2reg = false(max(sp(:)), length(sp2regC));\n          for i = 1:length(sp2regC), sp2reg(sp2regC{i},i) = true; end\n          D = getImage(im_ids{im_id}, 'depth');\n          D = double(D)./1000;\n          C = params.camera_matrix;\n          missingMask = getImage(im_ids{im_id}, 'rawdepth') == 0;\n          fdepth = depthFeatures(sp, sp2reg, D, missingMask, C);\n          feats = cat(2, feats, fdepth');\n          fprintf('%s: Time for depth features: %0.3f\\n', im_ids{im_id}, toc(tt));\n        end\n\n        % Eval candidates\n        gt = get_ground_truth(params.database, im_ids{im_id});\n        hier = struct('leaves_part', f_lp, 'ms_struct', ms_matrix2struct(f_ms));\n        jacc = eval_cands(hier, red_cands, gt);\n        max_jacc = max(jacc,[],1)';\n        \n        % fprintf('.');\n        % Sample candidates\n        % Get the optimum candidates for each object\n        % to ensure they are on the training set\n        [~,ids] = max(jacc,[],2);\n        if (length(ids)>params.n_samples)  % More objects than samples asked\n            ids = ids(1:params.n_samples);\n        end\n        ids_rest = setdiff(1:size(jacc,2),ids);\n        if (size(jacc,2)-length(ids))>params.n_samples\n            ids_rest = ids_rest(randperm(length(ids_rest),params.n_samples-length(ids)));\n        end\n        if isrow(ids_rest)\n            ids_rest = ids_rest';\n        end\n        sel_ids = [ids; ids_rest];\n\n        % Store\n        % features = [features; feats(sel_ids,:)]; %#ok<AGROW>\n        % jaccards = [jaccards; max_jacc(sel_ids,:)]; %#ok<AGROW>\n        \n        features{im_id} = feats(sel_ids,:); \n        jaccards{im_id} = max_jacc(sel_ids,:);\n    end\n    features = cat(1, features{:});\n    jaccards = cat(1, jaccards{:});\n\n    save(params.files.features_file,'features','jaccards');\nend\n\n%% Train the random forest\nif exist(params.files.trained_classifier,'file')\n    disp(['Already trained: ' params.files.trained_classifier '.'])\nelse\n    disp(['TRAINING: ' params.files.trained_classifier '.'])\n\n    % Train and save the result\n    rf = regRF_train(features,jaccards,50); %#ok<NASGU>\n    disp('Training done')\n\n    % Save the result\n    save(params.files.trained_classifier,'rf');\nend\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/mcg/scripts_training/rank_training.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2259048600042043}}
{"text": "function Ml = hmxPlus(Ml,Mr)\n%+========================================================================+\n%|                                                                        |\n%|         OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA         |\n%|           openHmx is part of the GYPSILAB toolbox for Matlab           |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018.                             |\n%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |\n%| LICENCE   : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or    |\n%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT   : matthieu.aussal@polytechnique.edu                          |\n%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : hmxPlus.m                                     |\n%|    #    |   VERSION    : 0.40                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 14.03.2018                                    |\n%| ( === ) |   SYNOPSIS   : Sum of H-Matrix with the rule                 |\n%|  `---'  |                Full > H-Matrix > Compr                       |\n%+========================================================================+\n\n% Check dimensions\nif sum(size(Ml) ~= size(Mr))\n    error('hmxPlus.m : matrix dimensions must agree.')\nend\n\n%%% H-Matrix + H-Matrix -> H-Matrix\nif isa(Ml,'hmx') && isa(Mr,'hmx')\n    % H-Matrix + H-Matrix --> H-Matrix (recursion)\n    if (Ml.typ == 0) && (Mr.typ == 0)\n        % Construction\n        for i = 1:4\n            Ml.chd{i} = hmxPlus(Ml.chd{i},Mr.chd{i});\n        end\n\n        % Fusion\n        Ml = hmxFusion(Ml);\n    \n    % H-Matrix + Compr -> H-Matrix    \n    elseif (Ml.typ == 0) && (Mr.typ == 1)\n        Ml = hmxPlusAB(Ml,Mr.dat{1},Mr.dat{2});\n             \n    % H-Matrix + Full -> Unavailable\n    elseif (Ml.typ == 0) && (Mr.typ == 2)\n        error('hmxPlus : unvailable case')\n\n        \n    % Compr + --- -> ---\n    elseif (Ml.typ == 1)\n        Ml = hmxPlusAB(Mr,Ml.dat{1},Ml.dat{2});\n        \n        \n    % Full + H-Matrix -> Unavailable\n    elseif (Ml.typ == 2) && (Mr.typ == 0)\n        error('hmxPlus : unvailable case')\n        \n    % Full + Compr -> Full\n    elseif (Ml.typ == 2) && (Mr.typ == 1)\n        Ml = hmxPlusAB(Ml,Mr.dat{1},Mr.dat{2});\n\n    % Full + Full -> Full                              \n    elseif (Ml.typ == 2) && (Mr.typ == 2)\n        Ml.dat = Ml.dat + Mr.dat;\n        \n        \n    else\n        error('hmxPlus : unvailable case')\n    end\n\n    \n    \n%%% H-Matrix + Matrix -> H-Matrix\nelseif isa(Ml,'hmx') \n    Ml = Ml + hmx(Ml.pos{1},Ml.pos{2},Mr,Ml.tol);\n\n    \n%%% Matrix + H-Matrix -> Matrix\nelseif isa(Mr,'hmx')\n    Ml = hmx(Mr.pos{1},Mr.pos{2},Ml,Mr.tol) + Mr;\n\n    \n%%% Unavailable  \nelse\n    error('hmxPlus.m : unavailable case')\nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openHmx/hmxPlus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.2258517017512102}}
{"text": "function voi = bf_sources_voi(BF, S)\n% Generate a set of VOIs specified in MNI coordinates\n% Copyright (C) 2013 Wellcome Trust Centre for Neuroimaging\n\n% $Id: bf_sources_voi.m 7703 2019-11-22 12:06:29Z guillaume $\n\n%--------------------------------------------------------------------------\nif nargin == 0\n    label = cfg_entry;\n    label.tag = 'label';\n    label.name = 'Label';\n    label.strtype = 's';\n    label.help = {'Label for the VOI'};\n    \n    pos = cfg_entry;\n    pos.tag = 'pos';\n    pos.name = 'MNI coordinates';\n    pos.strtype = 'r';\n    pos.num = [1 3];\n    pos.help = {'Locations for the VOI in MNI coordinates'};\n    pos.val = {};\n    \n    ori = cfg_entry;\n    ori.tag = 'ori';\n    ori.name = 'Orientation';\n    ori.strtype = 'r';\n    ori.num = [1 3];\n    ori.help = {'Source orientatons (only for single points, leave zeros for unoriented)'};\n    ori.val = {[0 0 0]};\n    \n    voidef = cfg_branch;\n    voidef.tag = 'voidef';\n    voidef.name = 'VOI';\n    voidef.val = {label, pos, ori};\n    \n    mask = cfg_files;\n    mask.tag = 'mask';\n    mask.name = 'MNI mask';\n    mask.filter = 'image';\n    mask.ufilter = '.*';\n    mask.num     = [1 1];\n    mask.help = {'Select a mask image'};\n    \n    maskdef = cfg_branch;\n    maskdef.tag = 'maskdef';\n    maskdef.name = 'Mask VOI';\n    maskdef.val  = {label, mask};\n    \n    vois = cfg_repeat;\n    vois.tag = 'vois';\n    vois.name = 'VOIs';\n    vois.num  = [1 Inf];\n    vois.values = {voidef, maskdef};\n    vois.val = {voidef};\n    \n    radius = cfg_entry;\n    radius.tag = 'radius';\n    radius.name = 'Radius';\n    radius.strtype = 'r';\n    radius.num = [1 1];\n    radius.val = {0};\n    radius.help = {'Radius (in mm) for the VOIs (leave 0 for single point)'};\n    \n    resolution = cfg_entry;\n    resolution.tag = 'resolution';\n    resolution.name = 'Resolution';\n    resolution.strtype = 'r';\n    resolution.num = [1 1];\n    resolution.val = {5};\n    resolution.help = {'Resolution for placing grid points in each VOI (in mm)'};\n    \n    voi = cfg_branch;\n    voi.tag = 'voi';\n    voi.name = 'VOIs in MNI space';\n    voi.val = {vois, radius, resolution};\n    \n    return\nelseif nargin < 2\n    error('Two input arguments are required');\nend\n\n\niskull = export(gifti(BF.data.mesh.tess_iskull), 'ft');\n\nM1 = BF.data.transforms.toNative;\nM1 = BF.data.transforms.toMNI/M1;\n\niskull = ft_convert_units(ft_transform_geometry(M1, iskull));\n\n       \n% transform MNI coords in MNI space into space where we are doing the\n% beamforming\nM = inv(BF.data.transforms.toMNI);\n\nif S.radius > 0\n    vec = -S.radius:S.resolution:S.radius;\n    [X, Y, Z]  = ndgrid(vec, vec, vec);\n    sphere   = [X(:) Y(:) Z(:)];\n    sphere(sqrt(X(:).^2 + Y(:).^2 + Z(:).^2) > S.radius, :) = [];\n    npnt = size(sphere, 1);\nelse\n    sphere = 0;\n    npnt = 1;\nend\n\ngrid = bf_sources_grid(BF, struct('resolution', S.resolution, 'space', 'MNI template'));\nmnigrid = ft_transform_geometry(BF.data.transforms.toMNI, grid);\n\nnvoi = numel(S.vois);\nvoi = [];\nvoi.label = {};\nvoi.pos = [];\nori = [];\nvoi.pos2voi = [];\n\nfor i = 1:nvoi\n    switch char(fieldnames(S.vois{i}))\n        case 'voidef'\n            voi.label{i} = S.vois{i}.voidef.label;\n            voi.pos = [voi.pos; sphere+repmat(S.vois{i}.voidef.pos, npnt, 1)];\n            ori     = [ori; S.vois{i}.voidef.ori];\n            voi.pos2voi  = [voi.pos2voi i*ones(1, npnt)];\n        case 'maskdef'\n            voi.label{i} = S.vois{i}.maskdef.label;\n            V   = spm_vol(char(S.vois{i}.maskdef.mask));\n            \n            vox = spm_eeg_inv_transform_points(inv(V.mat), mnigrid.pos);\n            Y   = spm_sample_vol(V, vox(:, 1),  vox(:, 2), vox(:, 3), 0);\n            ind = find(~isnan(Y) & abs(Y)>0);\n            voi.pos = [voi.pos; mnigrid.pos(ind, :)];\n            ori = [ori;zeros(length(ind), 3)];\n            voi.pos2voi  = [voi.pos2voi i*ones(1, length(ind))];\n    end\nend\n\nvoi.label = voi.label(:);\n\n% Remove points outside the brain\ninside = ft_inside_headmodel(voi.pos, struct('bnd', iskull));\n\nvoi.pos(~inside, :)  = [];\nvoi.pos2voi(~inside) = [];\n\nif any(any(ori))\n    voi.ori = ori(inside, :);\nend\n\n\nvoi = ft_transform_geometry(M, voi);", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/bf_sources_voi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.22585169298279464}}
{"text": "function [Y, xY] = spm_summarise(V,xY,fhandle,keepNaNs)\n% Summarise data within a Region of Interest\n% FORMAT [Y, xY] = spm_summarise(V,xY,fhandle)\n% V       - [1 x n] vector of mapped image volumes to read (from spm_vol)\n%           Or a char array of filenames\n% xY      - VOI structure (from spm_ROI)\n%           Or a VOI_*.mat (from spm_regions) or a mask image filename\n%           Or the keyword 'all' to summarise all voxels in the images\n%           Or a [3 x m] matrix of voxel coordinates {mm}\n% fhandle - function handle to be applied on image data within VOI\n%           Must transform a [1 x m] array into a [1 x p] array\n%           Default is Identity (returns raw data, vectorised into rows).\n%           Can also use keyword 'litres' to compute the total volume,\n%           within the region of interest, for a tissue segment image.\n%\n% Y       - [n x p] data summary\n% xY      - (updated) VOI structure\n%__________________________________________________________________________\n%\n% Example:\n% spm_summarise('beta_0001.nii',...\n%               struct('def','sphere', 'spec',8, 'xyz',[10 20 30]'),...\n%               @mean)\n%__________________________________________________________________________\n% Copyright (C) 2010-2015 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin, Ged Ridgway\n% $Id: spm_summarise.m 7384 2018-07-31 13:36:15Z guillaume $\n\n%-Argument checks\n%--------------------------------------------------------------------------\nif nargin < 1 || isempty(V)\n    [V, sts] = spm_select([1 Inf], 'image', 'Specify Images');\n    if ~sts, error('Must select 1 or more images'), end\nend\nif iscellstr(V), V = char(V); end\nif ischar(V), V = spm_data_hdr_read(V); end\nspm_check_orientations(V);\n\nif nargin < 2 || isempty(xY), xY = struct; end\nif ischar(xY)\n    if strcmpi(xY, 'all')\n        xY = struct('def', 'all');\n    elseif any(regexpi(xY, '\\.mat$'))\n        try\n            load(xY,'xY'); % VOI_*.mat file. Warns if .mat has no xY ...\n            xY = rmfield(xY,'XYZmm'); % ...  error if .mat has no xY\n        catch\n            xY = struct; % GUI specification in spm_ROI \n        end\n    else % assume mask image filename\n        xY = struct('def','mask', 'spec',xY);\n    end\nelseif isnumeric(xY) && any(size(xY, 1) == [3 4])\n    xY = struct('XYZmm', xY(1:3, :));\nelseif isstruct(xY) && isfield(xY,'fname')\n    xY = struct('def','mask', 'spec',xY);\nelseif ~isstruct(xY)\n    error('Incorrect xY specified')\nend\nif ~isfield(xY,'XYZmm'), [xY, xY.XYZmm] = spm_ROI(xY,V(1)); end\n\nif nargin < 3 || isempty(fhandle), fhandle = @(x) x; end\nif ischar(fhandle) && strcmp(fhandle, 'litres')\n    vsz     = abs(det(V(1).mat));  % voxel size in mm^3\n    fhandle = @(x) sum(x) * vsz / 1e6;\nend\nif ischar(fhandle), fhandle = str2func(fhandle); end\n\n% Undocumented option in case anyone wants to keep (e.g. to check for) NaNs\nif nargin < 4, keepNaNs = false; end\nif keepNaNs\n    dropNaNs = @(x) x;\nelse\n    dropNaNs = @(x) x(~isnan(x));\nend\n\n%-Summarise data\n%--------------------------------------------------------------------------\nXYZ = round(V(1).mat \\ [xY.XYZmm; ones(1, size(xY.XYZmm, 2))]);\n\n% Run on first volume to determine p, and transpose if column vector\nY = fhandle(dropNaNs(spm_data_read(V(1), 'xyz', XYZ)));\nif ndims(Y) > 2\n    error('Function must return a [1 x p] array')\nelseif size(Y, 1) ~= 1\n    if size(Y, 2) == 1\n        Y = Y';\n    else\n        error('Function returned a [%d x %d] array instead of [1 x p]', ...\n            size(Y, 1), size(Y, 2))\n    end\nend\n\n% Preallocate space and then run on remaining volumes\nY(2:numel(V), :) = 0;\nfor i = 2:numel(V)\n    Y(i, :) = fhandle(dropNaNs(spm_data_read(V(i), 'xyz', XYZ)));\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_summarise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22579550590184405}}
{"text": "function mesh = prepare_mesh_headshape(cfg)\n\n% PREPARE_MESH_HEADSHAPE\n%\n% Configuration options:\n%   cfg.headshape   = a filename containing headshape, a Nx3 matrix with surface\n%                     points, or a structure with a single or multiple boundaries\n%   cfg.smooth      = a scalar indicating the number of non-shrinking\n%                     smoothing iterations (default = no smoothing)\n%\n% See also PREPARE_MESH_MANUAL, PREPARE_MESH_SEGMENTATION\n\n% Copyrights (C) 2009, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% get the specific options\ncfg.headshape    = ft_getopt(cfg, 'headshape');\ncfg.smooth       = ft_getopt(cfg, 'smooth');   % no default\n\nif isa(cfg, 'config')\n  % convert the config-object back into a normal structure\n  cfg = struct(cfg);\nend\n\nif isa(cfg.headshape, 'config')\n  % convert the nested config-object back into a normal structure\n  cfg.headshape = struct(cfg.headshape);\nend\n\n% get the surface describing the head shape\nif isstruct(cfg.headshape) && numel(cfg.headshape)>1\n  % this applies for multilayer BEM models and concentric sphere models\n  headshape = [];\n  for i=1:numel(cfg.headshape)\n    [headshape(i).pos, headshape(i).tri] = headsurface([], [], 'headshape', cfg.headshape(i));\n  end\nelse\n  [headshape.pos, headshape.tri] = headsurface([], [], 'headshape', cfg.headshape);\nend\n\nif numel(headshape)>1 && numel(cfg.numvertices)==1\n  % use the same number of vertices for each of the head shape surfaces\n  cfg.numvertices = repmat(cfg.numvertices, size(headshape));\nend\n\nif ~isempty(cfg.numvertices) && ~isequal(cfg.numvertices, arrayfun(@(x) size(x.pos, 1), headshape))\n  for i=1:numel(headshape)\n    tri1 = headshape(i).tri;\n    pos1 = headshape(i).pos;\n    % The number of vertices is multiplied by 3 in order to have more\n    % points on the original mesh than on the sphere mesh (see below).\n    % The rationale for this is that every projection point on the sphere\n    % has three corresponding points on the mesh\n    if (cfg.numvertices(i)>size(pos1,1))\n      [tri1, pos1] = refinepatch(headshape(i).tri, headshape(i).pos, 3*cfg.numvertices(i));\n    else\n      [tri1, pos1] = reducepatch(headshape(i).tri, headshape(i).pos, 3*cfg.numvertices(i));\n    end\n    \n    % remove double vertices\n    [pos1, tri1] = remove_double_vertices(pos1, tri1);\n    \n    % replace the probably unevenly distributed triangulation with a regular one\n    % and retriangulate it to the desired accuracy\n    [pos2, tri2] = mysphere(cfg.numvertices(i)); % this is a regular triangulation\n    [pos1, tri1] = retriangulate(pos1, tri1, pos2, tri2, 2);\n    [pos1, tri1] = fairsurface(pos1, tri1, 1); % this helps redistribute the superimposed points\n    \n    % remove double vertices\n    [headshape(i).pos, headshape(i).tri] = remove_double_vertices(pos1, tri1);\n    fprintf('returning %d vertices, %d triangles\\n', size(headshape(i).pos,1), size(headshape(i).tri,1));\n  end\nend\n\n% smooth the mesh\nif ~isempty(cfg.smooth)\n  for i=1:numel(headshape)\n    [headshape(i).pos,headshape(i).tri] = fairsurface(headshape(i).pos, headshape(i).tri, cfg.smooth);\n  end\nend\n\n% the output should only describe one or multiple boundaries and should not\n% include any other fields\nmesh = keepfields(headshape, {'pos', 'tri'});\n\nfunction [tri1, pos1] = refinepatch(tri, pos, numvertices)\nfprintf('the original mesh has %d vertices, the requested number of vertices is %d\\n',size(pos,1),numvertices/3);\nfprintf('trying to refine the mesh...\\n');\n[pos1, tri1] = refine(pos, tri, 'updown', numvertices);\n\nfunction [pos, tri] = mysphere(N)\n% This is a copy of MSPHERE without the confusing output message\n% Returns a triangulated sphere with approximately M vertices\n% that are nicely distributed over the sphere. The vertices are aligned\n% along equally spaced horizontal contours according to an algorithm of\n% Dave Russel.\n%\n% Use as\n%  [pos, tri] = msphere(M)\n%\n% See also SPHERE, NSPHERE, ICOSAHEDRON, REFINE\n% Copyright (C) 1994, Dave Rusin\n\nstoreM    = [];\nstorelen  = [];\nincreaseM = 0;\nwhile (1)\n  \n  % put a single vertex at the top\n  phi = [0];\n  th  = [0];\n  \n  M = round((pi/4)*sqrt(N)) + increaseM;\n  for k=1:M\n    newphi = (k/M)*pi;\n    Q = round(2*M*sin(newphi));\n    for j=1:Q\n      phi(end+1) = newphi;\n      th(end+1)  = (j/Q)*2*pi;\n      % in case of even number of contours\n      if mod(M,2) && k>(M/2)\n        th(end) = th(end) + pi/Q;\n      end\n    end\n  end\n  \n  % put a single vertex at the bottom\n  phi(end+1) = [pi];\n  th(end+1)  = [0];\n  \n  % store this vertex packing\n  storeM(end+1).th  = th;\n  storeM(end  ).phi = phi;\n  storelen(end+1) = length(phi);\n  if storelen(end)>N\n    break;\n  else\n    increaseM = increaseM+1;\n    % fprintf('increasing M by %d\\n', increaseM);\n  end\nend\n\n% take the vertex packing that most closely matches the requirement\n[m, i] = min(abs(storelen-N));\nth  = storeM(i).th;\nphi = storeM(i).phi;\n\n% convert from spherical to cartehsian coordinates\n[x, y, z] = sph2cart(th, pi/2-phi, 1);\npos = [x' y' z'];\ntri = convhulln(pos);\n\nfunction [pos1, tri1] = fairsurface(pos, tri, N)\n\n% FAIRSURFACE modify the mesh in order to reduce overlong edges, and\n% smooth out \"rough\" areas. This is a non-shrinking smoothing algorithm.\n% The procedure uses an elastic model : At each vertex, the neighbouring\n% triangles and vertices connected directly are used. Each edge is\n% considered elastic and can be lengthened or shortened, depending\n% on their length. Displacement are done in 3D, so that holes and\n% bumps are attenuated.\n%\n% Use as\n%   [pos, tri] = fairsurface(pos, tri, N);\n% where N is the number of smoothing iterations.\n%\n% This implements:\n%   G.Taubin, A signal processing approach to fair surface design, 1995\n\n% This function corresponds to spm_eeg_inv_ElastM\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n%                    Christophe Phillips & Jeremie Mattout\n% spm_eeg_inv_ElastM.m 1437 2008-04-17 10:34:39Z christophe\n%\n% $Id$\n\nts = [];\nts.XYZmm = pos';\nts.tri   = tri';\nts.nr(1) = size(pos,1);\nts.nr(2) = size(tri,1);\n\n% Connection vertex-to-vertex\n%--------------------------------------------------------------------------\nM_con = sparse([ts.tri(1,:)';ts.tri(1,:)';ts.tri(2,:)';ts.tri(3,:)';ts.tri(2,:)';ts.tri(3,:)'], ...\n  [ts.tri(2,:)';ts.tri(3,:)';ts.tri(1,:)';ts.tri(1,:)';ts.tri(3,:)';ts.tri(2,:)'], ...\n  ones(ts.nr(2)*6,1),ts.nr(1),ts.nr(1));\n\nkpb   = .1;                       % Cutt-off frequency (default: .1)\nlam   = .5; mu = lam/(lam*kpb-1); % Parameters for elasticity. (default: .5)\nXYZmm = ts.XYZmm;\n\n% smoothing iterations\n%--------------------------------------------------------------------------\nfor j=1:N\n  \n  XYZmm_o = zeros(3,ts.nr(1)) ;\n  XYZmm_o2 = zeros(3,ts.nr(1)) ;\n  \n  for i=1:ts.nr(1)\n    ln = find(M_con(:,i));\n    d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));\n    if sum(d_i)==0\n      w_i = zeros(size(d_i));\n    else\n      w_i = d_i/sum(d_i);\n    end\n    XYZmm_o(:,i) = XYZmm(:,i) + ...\n      lam * sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);\n  end\n  \n  for i=1:ts.nr(1)\n    ln = find(M_con(:,i));\n    d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));\n    if sum(d_i)==0\n      w_i = zeros(size(d_i));\n    else\n      w_i = d_i/sum(d_i);\n    end\n    XYZmm_o2(:,i) = XYZmm_o(:,i) + ...\n      mu * sum((XYZmm_o(:,ln)-XYZmm_o(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);\n  end\n  \n  XYZmm = XYZmm_o2;\n  \nend\n\n% collect output results\n%--------------------------------------------------------------------------\n\npos1 = XYZmm';\ntri1 = tri;\n\nif 0\n  % this is some test/demo code\n  mesh = [];\n  [mesh.pos, mesh.tri] = mesh_sphere(162);\n  \n  scale = 1+0.3*randn(size(pos,1),1);\n  mesh.pos = mesh.pos .* [scale scale scale];\n  \n  figure\n  ft_plot_mesh(mesh)\n  \n  [mesh.pos, mesh.tri] = fairsurface(mesh.pos, mesh.tri, 10);\n  \n  figure\n  ft_plot_mesh(mesh)\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/private/prepare_mesh_headshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.22579550590184402}}
{"text": "function cellInfo = Optical_Flow_Bus(varargin) \n% OPTICAL_FLOW_BUS returns a cell array containing bus object information \n% \n% Optional Input: 'false' will suppress a call to Simulink.Bus.cellToObject \n%                 when the MATLAB file is executed. \n% The order of bus element attributes is as follows:\n%   ElementName, Dimensions, DataType, SampleTime, Complexity, SamplingMode, DimensionsMode, Min, Max, DocUnits, Description \n\nsuppressObject = false; \nif nargin == 1 && islogical(varargin{1}) && varargin{1} == false \n    suppressObject = true; \nelseif nargin > 1 \n    error('Invalid input argument(s) encountered'); \nend \n\ncellInfo = { ... \n  { ... \n    'Optical_Flow_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'vx', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'vy', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'quality', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved1', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved2', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n}'; \n\nif ~suppressObject \n    % Create bus objects in the MATLAB base workspace \n    Simulink.Bus.cellToObject(cellInfo) \nend \n", "meta": {"author": "Firmament-Autopilot", "repo": "FMT-Model", "sha": "adb85b9379cb4268f60bd8414f35aacfbdf8dec1", "save_path": "github-repos/MATLAB/Firmament-Autopilot-FMT-Model", "path": "github-repos/MATLAB/Firmament-Autopilot-FMT-Model/FMT-Model-adb85b9379cb4268f60bd8414f35aacfbdf8dec1/bus/Optical_Flow_Bus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22575051571482058}}
{"text": "\n% [K, dK_logtheta, dK_x2] = gpcov(x1, x2, logtheta)\n%\nfunction [K, dK_logtheta, dK_x2] = gpcovDot(logtheta, x1, x2)\n\nwarning('Under development, not ready')\n\n% Covariance matrix\nK = x1' * x2;\n\n% Gradient for hyperparameters\nif nargout >= 2\n  dK_logtheta = nan;\nend\n\n% Gradients for inputs x2\nif nargout >= 3\n  if isempty(x2)\n    error('Can''t calculate gradient: x2 not given');\n  end\n  d = rows(x2); % dimensionality of inputs\n  m = cols(x1); % number of other inputs\n  n = cols(x2); % number of inputs\n  dK_x2 = zeros([d,m,n]);\n  for j=1:n\n    dK_x2(:,:,j) = x1;\n  end\nend\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/gpcovDot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.2257004946920059}}
{"text": "%% Swan - Wiki\n% The student's guide to clean code development\n% Task 7: UML of FEM code in Swan repository\n\n% Instructions: run the following code, selecting previously the 'Swan'\n% main folder as your current matlab path\n\nfile = 'test2d_triangle';\na.fileName = file;\ns = FemDataContainer(a);\nfem = FEM.create(s);\nfem.solve();", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Wiki/Task7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22567060869650732}}
{"text": "%% build_system\n% Build a system to solve by MaxwellFDFD.\n\n%%% Syntax\n%  [osc, grid3d, s_factor_cell, eps_cell, mu_cell, J_cell] = build_system(ge, OSC, DOM, OBJ, SRC, [progmark])\n%  [..., obj_array, src_array, mat_array] = build_system(ge, OSC, DOM, OBJ, SRC, [pragmark])\n%  [..., eps_node_array, mu_node_array] = build_system(ge, OSC, DOM, OBJ, SRC, [pragmark])\n\n\n%%% Description\n% |build_system(ge, OSC, DOM, OBJ, SRC, [progmark])| constructs a system from\n% given objects and sources.  The constructed system is typically used inside\n% <maxwell_run.html maxwell_run>.\n%\n% |ge| is an instance of |GT| and indicates the grid type of the _E_-field.\n% Each following argument, |OSC|, |DOM|, |OBJ|, and |SRC|, represents a\n% group of parameters. Each group supports several flexible expressions.\n% For more details, see the relevant sections about the input parameter\n% groups in <maxwell_run.html |maxwell_run|>.\n%\n% An additional input parameter |progmark| is an instance of <ProgMark.html\n% ProgMark>, which outputs the progress of the system build procedure as the\n% standard output.  If it is not given, then it is created internally.\n%\n% |[osc, grid3d, s_factor_cell, eps_cell, mu_cell, J_cell, M_cell] = build_system(...)|\n% returns\n%\n% * |osc|, an instance of <Oscillation.html Oscillation>\n% * |grid3d|, an instance of <Grid3d.html Grid3d>, \n% * |s_factor_cell|, a cell array of PML s-factors: |{sx_array, sy_array,\n% sz_array}|\n% * |eps_cell|, a cell array of electric permittivity evaluated at the E-field\n% positions: |{eps_xx_array, eps_yy_array, eps_zz_array}|\n% * |mu_cell|,  a cell array of magnetic permeability evaluated at the H-field\n% positions: |{mu_xx_array, mu_yy_array, mu_zz_array}|\n% * |J_cell|, a cell array of electric current sources: |{Jx_array, Jy_array,\n% Jz_array}|\n% * |M_cell|, a cell array of electric current sources: |{Mx_array, My_array,\n% Mz_array}|\n% \n% |[..., obj_array, src_array, mat_array] = build_system(...)| returns\n% additionally arrays of instances of <EMObject.html |EMObject|>, <Source.html\n% |Source|>, and <Material.html |Material|>.  The |EMObject| and |Source|\n% elements represent the objects and sources placed in the simulation\n% domain, so they can be used to visualize the simulation domain.\n%\n% |[..., eps_node_array, mu_node_array] = build_system(...)| returns\n% additionally arrays of electric permittivity and magnetic permeability\n% evaluated at the nodes of the finite-difference grid.\n\n\n%%% Example\n%   gray = [0.5 0.5 0.5];  % [r g b]\n%   [osc, grid3d, s_factor_cell, eps_cell, mu_cell, J_cell, M_cell,\t...\n%       obj_array, src_array, mat_array, eps_node_array, mu_node_array] = build_system(...\n%       'OSC', 1e-9, 1550, ...\n%       'DOM', {['Palik/SiO2'], 'none'}, [-700, 700; -600, 600; -200, 1700], 20, BC.p, 200, ...\n%       'OBJ', ...\n%           {['Palik/SiO2'], 'none'}, Box([-50, 50; -50, 50; -200, 1700], [2, 2, 20]), ...  % OBJ1\n%           {['CRC/Ag'], gray}, [Box([-700, -25; -25, 25; -200, 1700], 20), Box([25, 700; -25, 25; -200, 1700], 20)], ...  % OBJ2\n%       'SRC', PointSrc(Axis.x, [0, 0, 200]) ...\n%       );\n\nfunction [osc, grid3d, s_factor_cell, eps_cell, mu_cell, J_cell, M_cell, ...\n\tobj_array, src_array, mat_array, eps_node, mu_node, isiso] = build_system(varargin)\n\n\tiarg = nargin; arg = varargin{iarg};\n\tif istypesizeof(arg, 'ProgMark')\n\t\tpm = arg;\n\t\tnarglim = nargin - 1;\n\telse\n\t \tpm = ProgMark();\n\t\tvarargin = [varargin, {pm}];\n\t\tnarglim = nargin;\n\tend\n\t\n\tiarg = 1; arg = varargin{iarg};\n\tchkarg(istypesizeof(arg, 'GT'), 'argument #%d should be \"ge\" (GT).', iarg);\n\tge = arg;\n\n\tiarg = iarg + 1; arg = varargin{iarg};\n\tchkarg(istypesizeof(arg, 'PML'), 'argument #%d should be \"pml\" (PML).', iarg);\n\tpml = arg;\n\t\n\tfunction material = create_material(varargin)\n\t\tnarg = nargin;\n\t\tif istypesizeof(varargin{end}, 'logical')\n\t\t\tnarg = narg - 1;\n\t\tend\n\t\t\n\t\tchkarg(narg >= 2, '# of arguments should be at least 2.')\n\t\tmatname = varargin{1};\n\t\tif isempty(strfind(matname, '/'))  % data table is not specified\n\t\t\tmaterial = Material(varargin{:});\n\t\telse  % data table is specified\n\t\t\tmaterial = Material.fromtable(osc, varargin{:});\n\t\tend\n\tend\n\n\tosc = Oscillation.empty();\n\tobj_dom = EMObject.empty();\n\tshape_array = Shape.empty();\n\tsshape_array = Shape.empty();\n\tmat_array = Material.empty();\n\tobj_array = EMObject.empty();\n\tsobj_array = EMObject.empty();\n\tsrcj_array = [];\n\tsrcm_array = [];\n\tisepsgiven = false;\n\tisTFSF = false;\n\twhile iarg < narglim\n\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\n\t\tif ischar(arg) && strcmpi(arg,'OSC')\n\t\t\t% Set up OSC.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tchkarg((istypesizeof(arg, 'real') && arg > 0) || istypesizeof(arg, 'Oscillation'), ...\n\t\t\t\t'\"argument #%d should be either \"L0\" (positive) or \"osc\" (instance of Oscillation).', iarg);\n\t\t\tif istypesizeof(arg, 'real')\n\t\t\t\tL0 = arg;\n\t\t\t\tiarg = iarg + 1; wvlen = varargin{iarg};\n\t\t\t\tchkarg(istypesizeof(wvlen, 'complex'), 'argument #%d should be \"wvlen\" (complex).', iarg);\n\t\t\t\tunit = PhysUnit(L0);\n\t\t\t\tosc = Oscillation(wvlen, unit);\n\t\t\telse  % arg is instance of Oscillation\n\t\t\t\tosc = arg;\n\t\t\tend\n\t\telseif ischar(arg) && strcmpi(arg,'DOM')\n\t\t\t% Set up DOM.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tchkarg(iscell(arg) || istypesizeof(arg, 'Material') || istypesizeof(arg, 'EMObject'), ...\n\t\t\t\t'argument #%d should be cell, instance of Material, or instance of EMObject.', iarg);\n\t\t\tif istypesizeof(arg, 'EMObject')\n\t\t\t\tobj_dom = arg;\n\t\t\t\tdomain = obj_dom.shape;\n\t\t\t\tchkarg(istypesizeof(domain, 'Domain'), 'argument #%d should be instance of EMObject with Domain as its shape.', iarg);\n\t\t\telse\n\t\t\t\tif iscell(arg)\n\t\t\t\t\tmat_dom = create_material(arg{:});\n\t\t\t\telse\n\t\t\t\t\tassert(istypesizeof(arg, 'Material'));\n\t\t\t\t\tmat_dom = arg;\n\t\t\t\tend\n\t\t\n\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\t\tchkarg(istypesizeof(arg, 'real', [Axis.count, Sign.count]) || istypesizeof(arg, 'Domain'), ...\n\t\t\t\t\t'argument #%d should be either \"box_dom\" ([xmin xmax; ymin ymax; zmin zmax]) or \"domain\" (instance of Domain).', iarg);\n\t\t\t\tif istypesizeof(arg, 'real', [Axis.count, Sign.count])\n\t\t\t\t\tbox_domain = arg;\n\t\t\t\t\tiarg = iarg + 1; dl_domain = varargin{iarg};\n\t\t\t\t\tchkarg(istypeof(dl_domain, 'real') && isexpandable2row(dl_domain, Axis.count), ...\n\t\t\t\t\t\t'\"argument #%d should be dl_domain (positive number or length-%d row vector of positive numbers).', iarg, Axis.count);\n\t\t\t\t\tdomain = Domain(box_domain, expand2row(dl_domain, Axis.count));\n\t\t\t\telse  % arg is instance of Domain\n\t\t\t\t\tdomain = arg;\n\t\t\t\tend\n\t\t\t\tobj_dom = EMObject(domain, mat_dom);\n\t\t\tend\n\t\t\tmat_array = [mat_array(1:end), obj_dom.material];\n\t\n\t\t\t% Set up boundary conditions and PML thicknesses.\n\t\t\tiarg = iarg + 1; bc = varargin{iarg};\n\t\t\tchkarg(istypeof(bc, 'BC') && isexpandable2mat(bc, Axis.count, Sign.count), ...\n\t\t\t\t'argument #%d should be \"bc\" (scalar, length-%d row vector, or %d-by-%d matrix with BC as elements).', iarg, Axis.count, Axis.count, Sign.count);\n\t\t\tiarg = iarg + 1; Lpml = varargin{iarg};\n\t\t\tchkarg(istypeof(Lpml, 'real') && isexpandable2mat(Lpml, Axis.count, Sign.count) && all(all(Lpml>=0)), ...\n\t\t\t\t'argument #%d should be \"Lpml\" (scalar, length-%d row vector, or %d-by-%d matrix with nonnegative numbers as elements).', iarg, Axis.count, Axis.count, Sign.count);\n\n\t\t\t% Set up the degree of the polynomial grading of the PML scale\n\t\t\t% factors.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tdeg_pml = 4;  % polynomial degree\n\t\t\tif istypeof(arg, 'real')\n\t\t\t\tdeg_pml = arg;\n\t\t\telse\n\t\t\t\tiarg = iarg - 1; % because deg_pml is optional argument\n\t\t\tend\n\t\n\t\t\t% Set up the target reflection coefficient of the PML.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tR_pml = exp(-16);  % target reflection coefficient\n\t\t\tif istypeof(arg, 'real')\n\t\t\t\tR_pml = arg;\n\t\t\telse\n\t\t\t\tiarg = iarg - 1; % because R_pml is optional argument\n\t\t\tend\n\t\t\t\n\t\t\t% Set up a flag to generate a grid dynamically.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\twithuniformgrid = false;  % generate a grid dynamically by default.\n\t\t\tif istypesizeof(arg, 'logical')\n\t\t\t\twithuniformgrid = arg;\n\t\t\telse\n\t\t\t\tiarg = iarg - 1; % because withuniformgrid is optional argument\n\t\t\tend\n\t\telseif ischar(arg) && (strcmpi(arg,'OBJ') || strcmpi(arg,'SOBJ'))\n\t\t\t% Set up OBJ.\n\t\t\tis_scatterer = strcmpi(arg,'SOBJ');\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tif istypesizeof(arg, 'complex', [0 0 0])  % 3D complex array with arbitrary size\n\t\t\t\tisepsgiven = true;\n\t\t\t\teps_node_cell = {arg, arg, arg};\n\t\t\t\tmu_node_temp = ones(size(arg));\n\t\t\t\tmu_node_cell = {mu_node_temp, mu_node_temp, mu_node_temp};\n\t\t\telse\n\t\t\t\t% Set up objects.\n\t\t\t\tobj_array_temp = EMObject.empty();\n\t\t\t\tshape_array_temp = Shape.empty();\n\t\t\t\twhile iscell(arg) || istypesizeof(arg, 'Material') || istypesizeof(arg, 'EMObject', [1 0])\n\t\t\t\t\tif istypesizeof(arg, 'EMObject', [1 0])\n\t\t\t\t\t\tobjs = arg;\n\t\t\t\t\t\tobj_array_temp = [obj_array_temp(1:end), objs];\n\t\t\t\t\t\tfor obj = objs\n\t\t\t\t\t\t\tshape_array_temp = [shape_array_temp(1:end), obj.shape];\n\t\t\t\t\t\t\tmat_array = [mat_array(1:end), obj.material];\n\t\t\t\t\t\tend\n\t\t\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\t\t\telse\n\t\t\t\t\t\tif iscell(arg)\n\t\t\t\t\t\t\tmat = create_material(arg{:});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tassert(istypesizeof(arg, 'Material'));\n\t\t\t\t\t\t\tmat = arg;\n\t\t\t\t\t\tend\n\t\t\t\t\t\tmat_array = [mat_array(1:end), mat];\n\n\t\t\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\t\t\t\twhile istypesizeof(arg, 'Shape', [1 0])\n\t\t\t\t\t\t\tshapes = arg;\n\t\t\t\t\t\t\tshape_array_temp = [shape_array_temp(1:end), shapes];\n\t\t\t\t\t\t\tobjs = EMObject(shapes, mat);\n\t\t\t\t\t\t\tobj_array_temp = [obj_array_temp(1:end), objs];\n\t\t\t\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tiarg = iarg - 1;\n\t\t\t\t\n\t\t\t\tif is_scatterer\n\t\t\t\t\tsshape_array = [sshape_array(1:end), shape_array_temp];\n\t\t\t\t\tsobj_array = [sobj_array(1:end), obj_array_temp];\n\t\t\t\telse\n\t\t\t\t\tshape_array = [shape_array(1:end), shape_array_temp];\n\t\t\t\t\tobj_array = [obj_array(1:end), obj_array_temp];\n\t\t\t\tend\n\t\t\tend\n\t\telseif ischar(arg) && strcmpi(arg,'SRCJ')\n\t\t\t% Set up sources.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tif ~istypesizeof(arg, 'Source', [1 0])\n\t\t\t\twarning('Maxwell:buildSys', 'no source is given.');\n\t\t\tend\n\n\t\t\twhile istypesizeof(arg, 'Source', [1 0])\n\t\t\t\tif istypesizeof(arg, 'TFSFPlaneSrc')\n\t\t\t\t\tisTFSF = true;\n\t\t\t\tend\n\t\t\t\tsrcj_array_curr = arg;\n\t\t\t\tfor src = srcj_array_curr\n\t\t\t\t\tsrc.set_gridtype(ge);\n\t\t\t\tend\n\t\t\t\tsrcj_array = [srcj_array(1:end), srcj_array_curr];\n\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tend\n\t\t\tiarg = iarg - 1;\n\t\telseif ischar(arg) && strcmpi(arg,'SRCM')\n\t\t\t% Set up sources.\n\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tif ~istypesizeof(arg, 'Source', [1 0])\n\t\t\t\twarning('Maxwell:buildSys', 'no source is given.');\n\t\t\tend\n\n\t\t\twhile istypesizeof(arg, 'Source', [1 0])\n\t\t\t\tif istypesizeof(arg, 'TFSFPlaneSrc')\n\t\t\t\t\tisTFSF = true;\n\t\t\t\tend\n\t\t\t\tsrcm_array_curr = arg;\n\t\t\t\tfor src = srcm_array_curr\n\t\t\t\t\tsrc.set_gridtype(alter(ge));\n\t\t\t\tend\n\t\t\t\tsrcm_array = [srcm_array(1:end), srcm_array_curr];\n\t\t\t\tiarg = iarg + 1; arg = varargin{iarg};\n\t\t\tend\n\t\t\tiarg = iarg - 1;\n\t\telseif iarg == narglim\n\t\t\tchkarg(false, ['some arguments are not used.\\n', ...\n\t\t\t\t'Suggestion: check if each parameter group is specified with beginning specifier.']);\n\t\tend\n\tend\n\tchkarg(~isempty(osc), 'OSC parameter groups should be set.');\n\tchkarg(~isempty(obj_dom), 'DOM parameter groups should be set.');\n\tobj_array = [obj_dom, obj_array];\n\tsrc_array = [srcj_array, srcm_array];\n\tif isTFSF && isempty(sobj_array)\n\t\twarning('Maxwell:objAssign', 'TF/SF source is used, but scatteres are not defined in SOBJ group.');\n\tend\n\t\n\tchkarg(iarg <= narglim, 'more arguments than expected.');\t\n\tpm.mark('initial setup');\n\t\n\tfprintf('\\tLength Unit: %s m\\n', osc.unit.value(PhysQ.L));\n\tfprintf('\\twvlen = %s, freq = %s eV\\n', num2str(osc.in_L0()), num2str(osc.in_eV()));\n\t\n\tmat_array = unique(mat_array);\n\tisiso = true;\n\tfprintf('materials used:\\n');\n\tfor mat = mat_array\n\t\tepstext = mat.eps;\n\t\tif length(unique(epstext)) == 1\n\t\t\tepstext = epstext(Axis.x);\n\t\tend\n\t\t\n\t\tmutext = mat.mu;\n\t\tif length(unique(mutext)) == 1\n\t\t\tmutext = mutext(Axis.x);\n\t\tend\n\t\t\n\t\tfprintf('\\t%s: eps = %s, mu = %s\\n', mat.name, mat2str(epstext), mat2str(mutext));\n\t\t\n\t\tisiso = isiso && mat.isiso;\n\tend\n\n\t% Generate a grid.\n\t[lprim, Npml] = generate_lprim3d(domain, Lpml, [shape_array, sshape_array], src_array, withuniformgrid);\n\tgrid3d = Grid3d(osc.unit, lprim, Npml, bc);\n\tif withuniformgrid\n\t\tpm.mark('uniform grid generation');\n\telse\n\t\tpm.mark('nonuniform grid generation');\n\tend\n\tfprintf('\\t[Nx Ny Nz] = %s\\n', mat2str(grid3d.N));\n\t\n\t% Generate a warning when a seemingly 2D simulation is defined on a 3D grid.\n\t[like2d, normal_axis] = is2dlike(grid3d.N);\n\tif like2d && grid3d.N(normal_axis) >= 2  % possible user mistake\n\t\twarning(['If this a 2D structure, N%s should be 1; ', ...\n\t\t\t'check d%s''s of objects and locations of sources'], char(normal_axis), char(normal_axis));\n\tend\n\n\t% Construct material parameters.\n\tif ~isepsgiven\n\t\t[eps_node_cell, mu_node_cell] = assign_material_node(grid3d, obj_array);  % Nx x Ny x Nz\n\tend\n\teps_cell = mean_material_node(grid3d, ge, eps_node_cell);\n\tmu_cell = mean_material_node(grid3d, alter(ge), mu_node_cell);\n\n\t% Construct PML s-factors.\n\ts_factor_cell = generate_s_factor(osc.in_omega0(), grid3d, deg_pml, R_pml);\n\tpm.mark('eps and mu assignment');\n\n\tif ~isTFSF\n\t\t% Solve for modes.\n\t\tfor src = src_array\n\t\t\tif istypesizeof(src, 'ModalSrc')\n\t\t\t\tmodalsrc = src;\n\t\t\t\tif ~modalsrc.ispreped\n\t\t\t\t\tprep_modalsrc(ge, pml, osc, grid3d, eps_cell, mu_cell, s_factor_cell, modalsrc);\n\t\t\t\tend\n\n\t\t\t\tneff = modalsrc.neff;\n\t\t\t\tbeta = 2*pi*neff / osc.in_L0();\n\t\t\t\tpm.mark('mode calculation');\n\t\t\t\tfprintf('\\tbeta = %s, n_eff = %s\\n', num2str(beta), num2str(neff));\n\t\t\tend\n\t\tend\n\telse  % isTFSF == true\n\t\t% Set up J for TF/SF.\n\t\tfor src = src_array\n\t\t\tif istypesizeof(src, 'TFSFPlaneSrc')\n\t\t\t\ttfsfsrc = src;\n\t\t\t\tcb_center = num2cell(tfsfsrc.shape.cb_center);\n\t\t\t\tfor bgobj = fliplr(obj_array)\n\t\t\t\t\tif bgobj.shape.contains(cb_center{:})\n\t\t\t\t\t\tbreak;  % assume that last object containing TF box center fills TF box\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\ttfsfsrc.set_bg_material(bgobj.material);\n\t\t\t\tF0 = tfsfsrc.create_incidentF(osc, grid3d);\n\t\t\t\tJM = cell(1, Axis.count);\n\t\t\t\tfor w = Axis.elems\n\t\t\t\t\tJM{w} = zeros(grid3d.N);\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif tfsfsrc.gt == ge\n\t\t\t\t\teqtype_tfsf = EquationType(FT.e, ge);  % for SRCJ, create E-field eq\n\t\t\t\telse\n\t\t\t\t\teqtype_tfsf = EquationType(FT.h, ge);  % for SRCM, create H-field eq\n\t\t\t\tend\n% \t\t\t\tA = create_eq(eqtype_tfsf, pml, osc.in_omega0(), eps_cell, mu_cell, s_factor_cell, JM, JM, grid3d);\n\t\t\t\teq = MatrixEquation(eqtype_tfsf, pml, osc.in_omega0(), eps_cell, mu_cell, s_factor_cell, JM, JM, grid3d);\n\t\t\t\tOp = eq.matrixfree_op();\n\t\t\t\t\t\t\t\n\t\t\t\tx0 = [F0{Axis.x}(:); F0{Axis.y}(:); F0{Axis.z}(:)];\n\t\t\t\tr = reordering_indices(Axis.count, grid3d.N);\n\t\t\t\tx0 = x0(r);\n\t\t\t\t\t\t\t\n% \t\t\t\tJM = (A*x0) ./ (-1i*osc.in_omega0());\n\t\t\t\tJM = Op(x0, 'notransp') ./ (-1i*osc.in_omega0());\n\t\t\t\tJM = reshape(JM, [Axis.count grid3d.N]);\n\t\t\t\tJM = permute(JM, [Axis.elems+1, 1]);\n\t\t\t\tJM = {JM(:,:,:,Axis.x), JM(:,:,:,Axis.y), JM(:,:,:,Axis.z)};\n\t\t\t\t\n\t\t\t\ttfsfsrc.setJM(JM, grid3d);\n\t\t\tend\n\t\tend\n\t\t\n\t\t% Add sobj_array to the already-generated eps and mu.\n\t\t[eps_node_cell, mu_node_cell] = assign_material_node(grid3d, sobj_array, eps_node_cell, mu_node_cell);  % Nx x Ny x Nz\n\t\teps_cell = mean_material_node(grid3d, ge, eps_node_cell);  % Nx x Ny x Nz\n\t\tmu_cell = mean_material_node(grid3d, alter(ge), mu_node_cell);  % Nx x Ny x Nz\n\n\t\tpm.mark('TF/SF source assignment');\n\tend\n\tobj_array = [obj_array, sobj_array];\n\t\n\teps_node = cell(1, Axis.count);\n\tmu_node = cell(1, Axis.count);\n\tfor w = Axis.elems\n\t\teps_node_cell{w} = expand_node_array(grid3d, eps_node_cell{w});  % (Nx+2) x (Ny+2) x (Nz+2)\n\t\tmu_node_cell{w} = expand_node_array(grid3d, mu_node_cell{w});  % (Nx+2) x (Ny+2) x (Nz+2)\n\t\t\n\t\teps_node{w} = Scalar3d(eps_node_cell{w}, grid3d, [GT.dual GT.dual GT.dual], osc, PhysQ.eps, '\\epsilon');\n\t\tmu_node{w} = Scalar3d(mu_node_cell{w}, grid3d, [GT.dual GT.dual GT.dual], osc, PhysQ.mu, '\\mu');\n\tend\n\t\t\n\t% Construct sources.\n\tJ_cell = assign_source(grid3d, srcj_array);\n\tM_cell = assign_source(grid3d, srcm_array);\n\tpm.mark('J assignment');\nend\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/io/build_system.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22567060869650732}}
{"text": "function v3d_write_volume(I,fname,scales)\n% Function for writing V3D volume files version R6.1\n% \n% v3d_write_volume(volume, filename, voxelsize in mm)\n%\n% examples:\n% I=uint16(rand(64,64,64)*65536);\n%\n% 1: v3d_write_volume(I);\n% 2: v3d_write_volume(I,'random.v3d',[2 2 2];\n\n% Filename\n    if((exist('fname','var')==0)), \n        [filename, pathname] = uiputfile('*.v3d', 'Write v3d-file'); \n        fname = [pathname filename]; \n    end\n    \n% Sizes\n    sizes=size(I);\n% Scales\n    if(exist('scales','var')==0), scales=ones(1,3); end;\n% Offset\n    offset=204; % Header size R6.1\n% Filesize\n    fsize=numel(I)*2+offset;\n% Format\n    fform='3D-RA';\n% Version\n    vers='6.1';\n% Voxelbits\n    bits=16; \n% par1;\n    par1 = 1072693248; % The meaning of this number is unknown\n\ndisp(['filename : ' num2str(fname)]);   \ndisp(['format : ' fform]);\ndisp(['version : ' vers]);\ndisp(['filesize : ' num2str(fsize)]);\nfprintf('sizes : %i, %i, %i\\n',sizes);\nfprintf('scales : %2.6f, %2.6f, %2.6f\\n',scales);\ndisp(['voxelbits : ' num2str(bits)]);\ndisp(['offset : ' num2str(offset)]);\ndisp(['par1 : ' num2str(par1)]);\nfprintf('\\n');\n\nfout=fopen(fname,'wb');\nfwrite(fout,[fform ' R' vers],'char');\nfwrite(fout,zeros(1,30),'uint8'); %seek\nfwrite(fout,sizes,'int');\nfwrite(fout,scales,'double');\n\nfwrite(fout,zeros(1,28),'uint8'); %seek \nfwrite(fout,par1,'int');\nfwrite(fout,zeros(1,28),'uint8'); %seek\nfwrite(fout,par1,'int');\nfwrite(fout,zeros(1,28),'uint8'); %seek\nfwrite(fout,par1,'int');\n\nfwrite(fout,bits,'int'); % Seems the new (R6.1) number of bits position\n\n% Meaning of this part of the header is unknown\nfwrite(fout,140,'int');\nfwrite(fout,1,'int');\nfwrite(fout,1075789855,'int');\nfwrite(fout,1068449823,'int');\nfwrite(fout,0,'int');\nfwrite(fout,0,'uint8');\nfwrite(fout,64,'uint8');\nfwrite(fout,143,'uint8');\nfwrite(fout,192,'uint8');\nfwrite(fout,1,'int');\n\n% Write uint16 volume\nfwrite(fout,uint16(I),'uint16');\n\nfclose('all');\n\n\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/ReadData3D/v3d/v3d_write_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22567060249536303}}
{"text": "function [dat] = read_nex_data(filename, hdr, begsample, endsample, chanindx)\n\n% READ_NEX_DATA for Plexon *.nex file\n%\n% Use as\n%   [dat] = read_nex_data(filename, hdr, begsample, endsample, chanindx)\n%\n% See also READ_NEX_HEADER, READ_NEX_EVENT\n\n% Copyright (C) 2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\ntry,\n  % work with the original header, not the FieldTrip one\n  hdr = hdr.orig;\ncatch\n  % assume that we got the original header\nend\n\nnumsmp = cell2mat({hdr.varheader.numsmp});\nadindx = find(cell2mat({hdr.varheader.typ})==5);\nsmpfrq = hdr.varheader(adindx(1)).wfrequency;\nsgn    = chanindx;\nnsmp   = (endsample-begsample+1);\ndat    = zeros(length(sgn), nsmp);\n\nfid = fopen_or_error(filename, 'r', 'ieee-le');\nfor sgnlop=1:length(sgn)\n\n  if hdr.varheader(sgn(sgnlop)).typ == 0\n    % read a spike channel\n    status = fseek(fid,hdr.varheader(sgn(sgnlop)).offset,'bof');\n    \n    % read the sample indices at which spikes occurred\n    tim = fread(fid,hdr.varheader(sgn(sgnlop)).cnt,'int32');\n    % downsample from 40kHz to the A/D sampling frequency\n    tim = (tim ./ hdr.filheader.frequency) * smpfrq + 1;  % add one sample, since ts=0 corresponds to sample=1\n    tim = round(tim);   % needed because of the edges in histc\n    % select only samples between the desired begin and end\n    % tim = tim(find(tim>=begsample & tim<=endsample));\n    % convert sample indices into a continuous signal\n    if ~isempty(tim)\n      dum = histc(tim-begsample, 0:(nsmp-1), 1);\n      dat(sgnlop,:) = dum(:)';\n    end\n\n  elseif hdr.varheader(sgn(sgnlop)).typ == 5\n    % read an A/D channel\n    status = fseek(fid,hdr.varheader(sgn(sgnlop)).offset,'bof');\n    \n    % this just reads the times of LFP starts\n    tim = fread(fid,hdr.varheader(sgn(sgnlop)).cnt,'int32');\n    % this just reads the indices of LFP starts\n    ind = fread(fid,hdr.varheader(sgn(sgnlop)).cnt,'int32');\n    if length(ind)>1\n      ft_error('multiple A/D segments are not supported');\n    end\n\n    % convert from timestamps to samples, expressed in the sampling frequency of the AD channels\n    tim = (tim ./ hdr.filheader.frequency) * smpfrq;\n    tim = round(tim);\n    \n    ch_begsample = begsample - tim;\n    ch_endsample = endsample - tim;\n    \n    if (ch_begsample<1)\n      ft_error(sprintf('cannot read before the begin of the recorded data (channel %d)', sgn(sgnlop)));\n    elseif (ch_endsample>hdr.varheader(sgn(sgnlop)).numsmp)\n      ft_error(sprintf('cannot read beyond the end of the recorded data (channel %d)', sgn(sgnlop)));\n    end\n    \n    % seek to the beginning of the interesting data, correct for the A/D card initialisation delay\n    fseek(fid,(ch_begsample-1)*2, 'cof');\n    % read the actual data for the whole channel\n    dum = fread(fid,nsmp,'int16');\n    % convert to mV\n    dat(sgnlop,:) = dum(:)' * hdr.varheader(sgn(sgnlop)).adtomv;\n\n  else\n    % ft_warning('unsupported data format for channel %s', hdr.label{sgn(sgnlop)});\n  end\n\nend\nstatus = fclose(fid);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_nex_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.22548489142879583}}
{"text": "function features = LoadSpikeFeatures(filename,rate)\n\n%LoadSpikeFeatures - Load spike features from file.\n%\n%  USAGE\n%\n%    features = LoadSpikeFeatures(filename,rate)\n%\n%    filename            spike file name (either .clu, .res or .fet)\n%    rate                sampling rate\n%\n%  OUTPUT\n%\n%    The output is a list of (timestamp,group,cluster,features...) t-uples.\n%\n%  SEE\n%\n%    See also GetSpikeFeatures.\n\n% Copyright (C) 2004-2011 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n[path,basename,extension] = fileparts(filename);\nif isempty(path), path = '.'; end\n\nelectrodeGroup = str2num(extension(2:end));\n[unused,basename,unused] = fileparts(basename);\n\n% Load .clu file\nfilename = [path '/' basename '.clu.' int2str(electrodeGroup)];\nif ~exist(filename),\n\terror(['File ''' filename ''' not found.']);\nend\nclu = load(filename);\nclu = clu(2:end);\n\n% Load .fet file\nfilename = [path '/' basename '.fet.' int2str(electrodeGroup)];\nif ~exist(filename),\n\terror(['File ''' filename ''' not found.']);\nend\nfile = fopen(filename,'r');\nif file == -1,\n\terror(['Cannot open file ''' filename '''.']);\nend\nnFeatures = fscanf(file,'%d',1);\nfet = fscanf(file,'%f',[nFeatures,inf])';\nfclose(file);\n\nfeatures = [fet(:,end)/rate electrodeGroup*ones(size(clu)) clu fet(:,1:end-1)];\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/IO/LoadSpikeFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.22546262429762706}}
{"text": "function optsetup = spm_cfg_eeg_inv_optimize\n%function optsetup = spm_cfg_eeg_inv_optimize\n% configuration file to set up optimization routines for M/EEG source\n% inversion\n%_______________________________________________________________________\n% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging\n\n% Gareth Barnes\n% $Id: spm_cfg_eeg_inv_optimize.m 6499 2015-07-16 13:37:41Z gareth $\n\n\nD = cfg_files;\nD.tag = 'D';\nD.name = 'M/EEG datasets';\nD.filter = 'mat';\nD.num = [1 Inf];\nD.help = {'Select the M/EEG mat files.'};\n\nval = cfg_entry;\nval.tag = 'val';\nval.name = 'Inversion index';\nval.strtype = 'n';\nval.help = {'Index of the cell in D.inv where the forward model can be found and the results will be stored.'};\nval.val = {1};\n\n\npriorname = cfg_entry;\npriorname.tag = 'priorname';\npriorname.name = 'Prefix for priors';\npriorname.strtype = 's';\npriorname.num = [1 Inf];\npriorname.val = {'priorset1'};\npriorname.help = {'Prefix for prior directory'};\n\nREMLopt = cfg_entry;\nREMLopt.tag = 'REMLopt';\nREMLopt.name = 'REML parameters';\nREMLopt.strtype = 'r';\nREMLopt.num = [1 2];\nREMLopt.val = {[-4,16]};\nREMLopt.help = {'Select REML parameters'};\n\nARDopt = cfg_entry;\nARDopt.tag = 'ARDopt';\nARDopt.name = 'Threshold for ARD hyperparameter';\nARDopt.strtype = 'r';\nARDopt.num = [1 1];\nARDopt.val = {[128]};\nARDopt.help = {'ARD threshold for pruning hyperparameters (relative to max)'};\n\nGSopt = cfg_entry;\nGSopt.tag = 'GSopt';\nGSopt.name = 'Set number of greed search iterations';\nGSopt.strtype = 'i';\nGSopt.num = [1 1];\nGSopt.val = {[16]};\nGSopt.help = {'Number of greedy search iterations'};\n\n\nopttype = cfg_repeat;\nopttype.tag = 'opttype';\nopttype.name = 'Optimize';\nopttype.help = {'Specify the optimization scheme'};\nopttype.num  = [1 Inf];\nopttype.values  = {REMLopt,ARDopt,GSopt};\nopttype.val  = {REMLopt};\n\n\n\noptsetup = cfg_exbranch;\noptsetup.tag = 'optsetup';\noptsetup.name = 'Inversion optimization';\noptsetup.val = {D,val,priorname,opttype};\noptsetup.help = {'Set optimization scheme for source reconstruction'};\noptsetup.prog = @opt_priors;\noptsetup.vout = @vout_opt_priors;\n\nfunction  out = opt_priors(job)\n\n\n\nD = spm_eeg_load(job.D{1});\n\n%% get data specific terms sorted out\ninverse=D.inv{job.val}.inverse;\nAY=inverse.AY;\n\nmesh=D.inv{job.val}.mesh.tess_mni;\n\n\n[a1,b1,c1]=fileparts(D.fname);\npriordir=[D.path filesep job.priorname '_' b1];\n\n\n[priorfiles] = spm_select('FPListRec',priordir,'.*\\.mat$');\n%[postfiles] = spm_select('FPListRec',priordir,'^post.*\\.mat$');\n\n% USEPOST=1;\n% if ~isempty(postfiles) && USEPOST,\n%     fprintf('Using only posterior\\n');\n%     priorfiles=postfiles;\n% end;\nNfiles=size(priorfiles,1);\nfprintf('Found %d prior files\\n',Nfiles);\nif Nfiles==0,\n    error('No prior file found in directory: %s', priordir);\nend;\n\n%% add in functional (from other modalities or experiment) hypotheses\n\nQe0=0;%% bounding ratio of noise to signal power\ndisp('NB NO min sensor noise level');  %% NO MIN SENSOR NOISE LEV\n\nQp_best=[];\nQe_best=[];\nFmax=-Inf;\nF_aug=-Inf;\nmaxpriors=512;\n\nfor j=1:Nfiles, %% move through prior files\n    %%% LOAD IN PRIOR FILE\n    \n    load(deblank(priorfiles(j,:)),'Qp','Qe','UL','F');\n    fprintf('Optimizing priorfile %d of %d \\n',j,Nfiles);\n    %% ALSO CONSIDER AUGMENTED VERSION OF PRIORS IN FILE WITH BEST SO FAR\n    Qp_aug=Qp; %% running with augmented Qp\n    for k=1:length(Qp_best), %\n        Qp_aug{length(Qp)+k}=Qp_best{k}; % augment with posterior from best so far\n    end;\n    Qe_aug=Qe; %% NB NOT AUGMENTING YET\n    \n    \n    if length(Qp_aug)>maxpriors,\n        Qp_aug=Qp_aug{1:maxpriors};\n        warning('Limiting priors');\n    end;\n    %%%%%%%%%%%% NOW OPTIMIZE ORIGINAL AND AUGMENTED INDEPENDENTLY\n    \n    \n    for k=1:length(job.opttype), %% move through optimization schemes\n        %%% TERMS WHICH EVOLVE ARE Qe and Qp (M, Cq, Cp follow)\n        priorcount(k)=length(Qp);\n        \n        [F,M,Cq,Cp,Qe,Qp] = spm_eeg_invert_EBoptimise(AY,UL,job.opttype(k),Qp,Qe,Qe0);\n        \n        if j>1, %% nothing to augment on 1st iteration\n            \n            [F_aug,M,Cq,Cp,Qe_aug,Qp_aug] = spm_eeg_invert_EBoptimise(AY,UL,job.opttype(k),Qp_aug,Qe_aug,Qe0);\n        end;\n    end;\n    \n    \n    if F_aug>F,\n        fprintf('Taking augmented set forward\\n');\n        Qp=Qp_aug;\n        Qe=Qe_aug;\n        F=F_aug;\n    end;\n    \n    if F>Fmax, %% keep a record of these if they are best\n        Qp_best=Qp;\n        Qe_best=Qe;\n        Fmax=F;\n    end;\n    \n    Qp=Qp_best;\n    Qe=Qe_best;\n    save(deblank(priorfiles(j,:)),'Qp','Qe','UL','F');\n    allF(j)=F;\nend; % for j\n\n\n%% Now get M, Cp, Cq etc based on Qp and Qe\n\n[LCpL,Q,sumLCpL,QE,Cy,M,Cp,Cq,Lq]=spm_eeg_assemble_priors(UL,Qp,{Qe});\n\n\ninverse.F=Fmax;\ninverse.M=M;\ninverse.qC=Cq;\ninverse.Cp=Cp; %% posterior source level\ninverse.Qe=Qe; %% posterior sensor level\ninverse.Qp=Qp;\ninverse.Is=1:size(Cp,1); % %% temporary fix\n\n\n\n\n\n%----------------------------------------------------------------------\n% evaluate conditional expectation (of the sum over trials)\n%----------------------------------------------------------------------\nSSR   = 0;\nSST   = 0;\nJ     = {};\n\nUY=inverse.UY;\n\n\n\nsourcevar=zeros(1,size(inverse.M,1));\nfor j = 1:numel(UY),\n    \n    % trial-type specific source reconstruction\n    %------------------------------------------------------------------\n    J{j} = inverse.M*UY{j};\n    Jtime=J{j}*inverse.T'; %% J is Nvert* Nsamples\n    sourcevar=sourcevar+var(Jtime'); %% ./inverse.qC';\n    % sum of squares\n    %------------------------------------------------------------------\n    SSR  = SSR + sum(var((UY{j} - UL*J{j}))); %% changed variance calculation\n    SST  = SST + sum(var( UY{j}));\n    \nend\n\ninverse.J=J;\n\n\n% accuracy; signal to noise (over sources)\n%======================================================================\ninverse.R2   = 100*(SST - SSR)/SST;\nfprintf('Percent variance explained %.2f\\n',full(inverse.R2));\nD.inv{job.val}.inverse=inverse;\n\n\n\nspm_eeg_invert_display(D);\n\nrmind=find(allF<max(allF)-3);\nfprintf('Removing %d poorest prior files\\n',length(rmind));\nfor j=1:length(rmind),\n    fprintf('Deleting %s\\n',priorfiles(rmind(j),:));\n    delete(deblank(priorfiles(rmind(j),:)));\nend;\n\n\n\n\n\n\nidnum=round(spm_data_id(sourcevar)*1000); %% get unique id for file\npostfilename=[priordir filesep sprintf('post%d.mat',idnum)];\npostgiftiname=[priordir filesep sprintf('post%d.gii',idnum)];\nfprintf('Making posterior %s based on diagonal\\n',postfilename);\nQp=[];\nQp{1}=sparse(diag(sourcevar));\nMmni=[];\nMmni.faces=D.inv{job.val}.mesh.tess_mni.face;\nMmni.vertices=D.inv{job.val}.mesh.tess_mni.vert;\nMmni.cdata=sourcevar';\nMmni=gifti(Mmni);\n\n\nsave(deblank(postfilename),'Qp','Qe','UL','Fmax','postgiftiname','-v7.3');\nsave(Mmni,postgiftiname);\n\n\nfigure;\nspm_mip(sourcevar,mesh.vert',6);\ntitle('Posterior');\ncolorbar;\n\n\n\n\nD.save;\nout.postname=postfilename;\nout.postgiftiname=postgiftiname;\nout.D = job.D;\n\n\nfunction dep = vout_opt_priors(job)\n% Output is always in field \"D\", no matter how job is structured\ndep = cfg_dep;\ndep.sname = 'M/EEG dataset(s) after imaging source reconstruction';\n% reference field \"D\" from output\ndep.src_output = substruct('.','D');\n% this can be entered into any evaluated input\ndep.tgt_spec   = cfg_findspec({{'filter','mat'}});\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_eeg_inv_optimize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22546262429762703}}
{"text": "function out = spm_run_bms_map (job)\n% Run Bayesian Model Selection Maps\n% SPM job execution function\n% takes a harvested job data structure and calls SPM functions to perform\n% Bayesian Inference for Model Selection of Log. Evidence Maps  \n% Input:\n% job    - harvested job data structure (see matlabbatch help)\n% Output:\n% out    - computation results, usually a struct variable.\n%\n%\n% Bayesian Inference on Model Space:\n%\n% The Random-effects 'RFX' method is described in Stephan et al. [1] \n% 'Bayesian Model Selection for Group Studies'.\n% Output files (for each model): \n%       BMS.mat \n%       Exceedance Probability Maps (*epm.<ext>),\n%       Posterior Probability Maps (*ppm.<ext>),\n%       Dirichlet Paramters (alpha) Maps (*alpha.<ext>).\n%\n% The Fixed-effects 'FFX' method adds together the log-evidences over \n% subjects/sessions for each group, then compares the group log-ev's. \n% This is also known as the Group Bayes Factor (GBF) approach [2]. \n% Output files (for each model):\n%       BMS.mat \n%       Posterior Probability Maps (*ppm.<ext>).\n%\n% BMS contains:\n%     BMS.fname\n%     BMS.map.ffx(rfx).data\n%     BMS.map.ffx(rfx).ppm \n%     BMS.map.ffx(rfx).xppm     - only for RFX (this is the expected posterior\n%                                 probability map ie. posterior mean)\n%     BMS.map.ffx(rfx).epm      - only for RFX (optional) - this is the \n%                                 exceedance probability map \n%     BMS.map.ffx(rfx).alpha    - only for RFX\n%\n% [1] Rosa et al., 2009, Bayesian Model Selection Maps for Group Studies,\n% NeuroImage.\n% [2] Stephan et al., 2009, Bayesian Model Selection for Group Studies,\n% NeuroImage.\n% [3] Penny et al., 2004, Comparing Dynamic Causal Models, NeuroImage.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Maria Joao Rosa\n% $Id: spm_run_bms_map.m 5740 2013-11-13 12:00:04Z guillaume $\n\n% Input\n% -------------------------------------------------------------------------\ndirect  = job.dir{1};\nfname   = fullfile(direct,'BMS.mat'); % Output filename (with full path)\nmask    = length(job.mask{1});        % Mask image\nif mask\n   mask_image = spm_vol(job.mask);    % Mask image Vol\nend\nnsamps    = str2num(job.nsamp);       % Number of samples (nmodels > 3)\ndo_maps   = job.out_file;           \ndo_ecp    = do_maps > 0;              % Compute Exceedance Probability\ndo_alpha  = do_maps > 1;              % Compute Alpha Parameters\n\n% Nb. of subjects and models\n% -------------------------------------------------------------------------\nnsubjs    = size(job.sess_map,2);\nnmodels   = size(job.sess_map{1}(1).mod_map,1);\nnsess     = size(job.sess_map{1},2);\nnnames    = size(job.mod_name,2);\nnames     = job.mod_name;\n\n% method\n% -------------------------------------------------------------------------\nif strcmp(job.method_maps,'FFX');\n    method = 'FFX';\nelse\n    method = 'RFX';\nend\n\n% Name models\n% -------------------------------------------------------------------------\nif nnames < nmodels\n    for nn=1:nmodels-nnames\n        names = [names, sprintf('m%d',nn)];\n    end\nend\n\nif size(unique(names(1:nmodels)),2) < nmodels,\n    id = 'Indentical names for different models!';  % Same name!\n    error(id);\nend\n\nif nsubjs == 1\n   method = 'FFX';                              % If only 1 subject do FFX\nend\n\n% Sort out log-evidence images dimensions\n% -------------------------------------------------------------------------\nVol_models(1,1) = spm_vol(job.sess_map{1}(1).mod_map(1));\n\nfirst_vol       = Vol_models(1,1);\nM               = first_vol{1}.mat;\nDIM             = first_vol{1}.dim(1:3)'; \n\nxdim            = DIM(1); \nydim            = DIM(2); \nzdim            = DIM(3);\n[xords,yords]   = ndgrid(1:xdim,1:ydim);\nxords           = xords(:)';  \nyords           = yords(:)';\nI               = 1:xdim*ydim;\nzords_init      = ones(1,xdim*ydim);\n\n% Setup images\n% -------------------------------------------------------------------------\nswitch method\n\n    case 'FFX',   % Fixed Effects\n        \n        % Check if BMS.mat exists\n        if exist(fullfile(job.dir{1},'BMS.mat'),'file')\n           load(fname);\n           if  isfield(BMS,'map') && isfield(BMS.map,'ffx')\n               str = { 'Warning: existing BMS.mat file has been over-written!'};\n               msgbox(str)\n           end\n        end\n        \n        % Save BMS data\n        out.files{1} = fname;\n            \n        % Create PPM image files for each model\n        model_ppm(1:nmodels) = struct(...\n        'fname',    '',...\n        'dim',      DIM',...\n        'dt',       [spm_type('float32') spm_platform('bigend')],...\n        'mat',      M,...\n        'pinfo',    [1 0 0]',...\n        'n', [1 1], ...\n        'descrip',  '');\n\n        % Load Vols for all subjects/models \n        for i = 1:nmodels\n            model_ppm(i).fname   = fullfile(direct,[sprintf('%s_model_ppm',names{i}) spm_file_ext]);\n            model_ppm(i).descrip = sprintf('PPM: %s model',names{i});\n            BMS.map.ffx.ppm{i}   = model_ppm(i).fname;\n            \n            for s = 1:nsubjs,\n                for se = 1:nsess,\n                    nsessi      = size(job.sess_map{s},2);\n                    nmodelsi    = size(job.sess_map{s}(se).mod_map,1);\n                    if (nsess == nsessi && nmodels == nmodelsi)\n                        Vol_models(s,i,se) = spm_vol(job.sess_map{s}(se).mod_map(i));\n                        tmp = Vol_models(s,i,se);\n                    else\n                        msgbox('The number of sessions/models should be the same for all subjects!')\n                        return\n                    end\n                    % Stop if log-ev images have different dimensions\n                    if tmp{1}.dim(1)~=xdim || tmp{1}.dim(2)~=ydim || tmp{1}.dim(3)~=zdim\n                       error('Log-evidence images must have the same dimensions!')\n                    end\n                end\n            end      \n        end\n\n        % Create files\n        model_ppm = spm_create_vol(model_ppm);\n        BMS.fname = fname;\n        \n        % Save data and BMS\n        BMS.fname = fname;\n        BMS.map.ffx.data = job.sess_map;\n        save(out.files{1},'BMS', spm_get_defaults('mat.format'));\n\n    case 'RFX',  % Random Effects\n        \n        % Check if BMS.mat exists\n        if exist(fullfile(job.dir{1},'BMS.mat'),'file')\n           load(fname);\n           if  isfield(BMS,'map') && isfield(BMS.map,'rfx')\n               str = { 'Warning: existing BMS.mat file has been over-written!'};\n               msgbox(str)\n           end\n        end\n                \n        % BMS structure\n        out.files{1}   = fname; \n    \n        % Create PPM image files for each model\n        model_exp_r(1:nmodels) = struct(...\n        'fname',    '',...\n        'dim',      DIM',...\n        'dt',       [spm_type('float32') spm_platform('bigend')],...\n        'mat',      M,...\n        'pinfo',    [1 0 0]',...\n        'n', [1 1], ...\n        'descrip',  '');\n   \n        if do_ecp\n            % Create EPM image files for each model\n            model_xp(1:nmodels) = struct(...\n            'fname',    '',...\n            'dim',      DIM',...\n            'dt',       [spm_type('float32') spm_platform('bigend')],...\n            'mat',      M,...\n            'pinfo',    [1 0 0]',...\n            'n', [1 1], ...\n            'descrip',  '');   \n        end\n        \n        if do_alpha\n            % Create alpha image files for each model\n            model_alpha(1:nmodels) = struct(...\n            'fname',    '',...\n            'dim',      DIM',...\n            'dt',       [spm_type('float32') spm_platform('bigend')],...\n            'mat',      M,...\n            'pinfo',    [1 0 0]',...\n            'n', [1 1], ...\n            'descrip',  '');\n        end\n        \n        % Load Vols for all subjects/models\n        for i = 1:nmodels\n            model_exp_r(i).fname   = fullfile(direct,[sprintf('%s_model_xppm',names{i}) spm_file_ext]);\n            model_exp_r(i).descrip = sprintf('Exp_r: %s model',names{i});\n            BMS.map.rfx.ppm{i}     = model_exp_r(i).fname;\n            if do_ecp\n            model_xp(i).fname      = fullfile(direct,[sprintf('%s_model_epm',names{i}) spm_file_ext]);\n            model_xp(i).descrip    = sprintf('XP: %s model',names{i});\n            BMS.map.rfx.epm{i}     = model_xp(i).fname;\n            end\n            if do_alpha\n            model_alpha(i).fname   = fullfile(direct,[sprintf('%s_model_alpha',names{i}) spm_file_ext]);\n            model_alpha(i).descrip = sprintf('Alpha: %s model',names{i});\n            BMS.map.rfx.alpha{i}   = model_alpha(i).fname;\n            end\n            for s = 1:nsubjs,\n                for se = 1:nsess,\n                    nsessi      = size(job.sess_map{s},2);\n                    nmodelsi    = size(job.sess_map{s}(se).mod_map,1);\n                    if (nsess == nsessi && nmodels == nmodelsi)\n                        Vol_models(s,i,se) = spm_vol(job.sess_map{s}(se).mod_map(i));\n                        tmp = Vol_models(s,i,se);\n                    else\n                        msgbox('The number of sessions/models should be the same for all subjects!')\n                        return\n                    end\n                    % Stop if log-ev images have different dimensions\n                    if tmp{1}.dim(1)~=xdim || tmp{1}.dim(2)~=ydim || tmp{1}.dim(3)~=zdim\n                       error('Log-evidence images must have the same dimensions!')\n                    end\n                end\n            end \n        end\n        \n        % Create files     \n        model_exp_r              = spm_create_vol(model_exp_r);\n        if do_ecp, model_xp      = spm_create_vol(model_xp); end\n        if do_alpha, model_alpha = spm_create_vol(model_alpha); end\n        \n        % Save data and BMS\n        BMS.fname = fname;\n        BMS.map.rfx.data = job.sess_map;\n        save(out.files{1},'BMS', spm_get_defaults('mat.format')); \n    \nend\n\n\n% Progress bar\n% -------------------------------------------------------------------------\nspm_progress_bar('Init',zdim,'BMS Maps (Inference)','Slices complete');\n\n\n% Loop through image slices\n% -------------------------------------------------------------------------\nfor z = 1:zdim,\n    \n    spm_progress_bar('Set',z);                  % Update progress bar\n    j = repmat(NaN,xdim,ydim);                  % Init. image values\n    \n    fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'Computing maps...')\n    str   = sprintf('Slice %d out of %d',z,zdim); % Display slice nb.\n    fprintf('\\r%-40s: %30s',str,' ')\n \n    zords   = z*zords_init;                     % Slice z\n    xyz     = [xords(I); yords(I); zords(I)];   % Slice coordinates\n    nVox    = size(xyz,2);                      % Nb. of voxels per slice\n    \n    if mask\n        % Voxels inside mask\n        mask_xyz  = mask_image{1}.mat\\M*[xyz(:,1:nVox);ones(1,nVox)];\n        gamma     = spm_get_data(mask_image{1},mask_xyz);\n        b         = find(gamma>0.5);            % Voxels in the mask\n    else\n        b         = 1:nVox;                     % All voxels\n    end\n    \n    z_models        = NaN(nsubjs,nmodels,nVox);       % Data \n    z_models(1,1,:) = spm_get_data(first_vol{1},xyz); % Data: all subs/mods  \n    non_nan         = find(~isnan(z_models(1,1,:)));  % Voxels ~NaN\n\n\n    % Find voxels ~NaN and sum sessions\n    % ---------------------------------------------------------------------\n    for s = 1:nsubjs,\n        for k = 1:nmodels,\n                sum_tmp_data    = [];\n            for ns = 1:nsess,\n                tmp_data        = Vol_models(s,k,ns);\n                sum_tmp_data    = [sum_tmp_data; spm_get_data(tmp_data{1},xyz)];\n            end\n                z_models(s,k,:) = sum(sum_tmp_data,1);\n                non_nani        = find(~isnan(z_models(s,k,:)));\n                non_nan         = intersect(non_nan,non_nani);\n        end\n    end\n\n    % Voxels to be analysed\n    non_nan = intersect(non_nan,b);    \n    Nvoxels = length(non_nan);\n\n    % Method\n    % ---------------------------------------------------------------------\n    switch method\n            \n          % Fixed Effects\n          % ---------------------------------------------------------------\n          case 'FFX',            \n                \n            \n              \n              if Nvoxels > 0                % Slice with ~NaN voxels\n                  \n                zz     = sum(z_models,1);   % Sum all subjects/sessions\n                mz     = mean(zz,2);        % Get mean of all models\n                zzmean = zeros(1,nmodels,length(mz));\n                for jj = 1:nmodels\n                    zzmean(1,jj,:) = mz; \n                end\n                \n                if nmodels==1\n                    % Process log Bayes factor image\n                    zz  = exp(zz);              % Exponentiate log-bf values\n                    % Calculate posterior probabiliy\n                    pz  = zeros(1,1,length(zz));\n                    pz  = zz./(1+zz);\n                    j(non_nan)   = pz(1,1,non_nan);\n                    model_ppm(1) = spm_write_plane(model_ppm(k),j,z);\n                else\n                    zz  = zz-zzmean;            % Subtract mean\n                    zz  = exp(zz);              % Exponentiate log-ev values\n                    tzz = sum(zz,2);            % Sum exp(log-ev.)\n                    \n                    % Calculate posterior probabiliy\n                    pz  = zeros(1,nmodels,length(zz));\n                    for k = 1:nmodels,\n                        pz(1,k,:)    = zz(1,k,:)./tzz;\n                        j(non_nan)   = pz(1,k,non_nan);\n                        model_ppm(k) = spm_write_plane(model_ppm(k),j,z);\n                    end\n                end            \n                \n              else\n                % Nvoxels = 0\n                for k = 1:nmodels,\n                    % Write NaN for slice z\n                    model_ppm(k) = spm_write_plane(model_ppm(k),j,z);\n                end\n              end\n              \n          % Fixed Effects\n          % ---------------------------------------------------------------\n          case 'RFX',\n                \n                if Nvoxels > 0\n                    % Initialise results\n                    exp_r_total              = zeros(Nvoxels,nmodels);\n                    if do_ecp, xp_total      = zeros(Nvoxels,nmodels); end\n                    if do_alpha, alpha_total = zeros(Nvoxels,nmodels); end\n\n                    % Do BMS in all voxels of slice z\n                    for n = 1:Nvoxels,\n                        lme = z_models(:,:,non_nan(n));\n                        \n                        if nmodels==1\n                            % Provide evidence for dummy null model\n                            lme=0.5*[lme, -lme];\n                            [alpha,exp_r,xp] = spm_BMS(lme,nsamps,0,0,do_ecp);\n                            \n                            exp_r_total(n,:)              = exp_r(1);  % Cond. Expecta.\n                            if do_ecp, xp_total(n,:)      = xp(1); end % Exceeda. Prob.\n                            if do_alpha, alpha_total(n,:) = alpha(1); end % Dirichlet par.\n                        else\n                            \n                            % Group BMS\n                            [alpha,exp_r,xp] = spm_BMS(lme,nsamps,0,0,do_ecp);\n                            \n                            exp_r_total(n,:)              = exp_r;  % Cond. Expecta.\n                            if do_ecp, xp_total(n,:)      = xp; end % Exceeda. Prob.\n                            if do_alpha, alpha_total(n,:) = alpha; end % Dirichlet par.\n                        end\n                    end\n\n                    % Write images\n                    for i = 1:nmodels,\n                        j(non_nan)     = exp_r_total(:,i);\n                        model_exp_r(i) = spm_write_plane(model_exp_r(i),j,z);\n                        if do_ecp\n                        j(non_nan)     = xp_total(:,i);\n                        model_xp(i)    = spm_write_plane(model_xp(i),j,z);\n                        end\n                        if do_alpha\n                        j(non_nan)     = alpha_total(:,i);\n                        model_alpha(i) = spm_write_plane(model_alpha(i),j,z);\n                        end\n                    end\n                else\n                    % Write images when Nvoxels = 0\n                    for i = 1:nmodels,\n                        model_exp_r(i) = spm_write_plane(model_exp_r(i),j,z);\n                        if do_ecp, model_xp(i) = spm_write_plane(model_xp(i),j,z); end\n                        if do_alpha, model_alpha(i) = spm_write_plane(model_alpha(i),j,z); end\n                    end\n                end\n      \n    end\n\nend % Loop over slices\n\n% Clear progress bar\n% -------------------------------------------------------------------------\nspm_progress_bar('Clear');\ndisp('Done.');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_bms_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.22535146911042409}}
{"text": "function mv = mv_exportSelectivity(mv, saveFlag, threshold, conditions);\n%\n% mv = mv_exportSelectivity(mv, [saveFlag], [threshold], conditions);\n%\n% Export, from a MultiVoxel UI to a mrVista view,\n% a  parameter map of selectivity indices for each voxel,\n% this map is saved as Selectivity-ROI.mat\n% a corresponding colormap is save SelectivityCmap.mat \n% which can be loaded from the Color Map UI\n%\n% Category indepdendent selecitivities range from 0-1 \n% The color indicates both the selectivity and category preference\n% Thus, selectivity values are mapped to: category+selectivity\n% where category are integers ranging from 0:Ncats-1\n%\n%  A second map is saved as a corAnal\n%  note that this will overwrite the default corAnal performed on these data\n%  This map is used for thresholding the selectivity map\n%  co field contains voxel reliability (note that cothres has values of 0-1\n%  thus, all negative reliabilities are going to be thresholded by default)\n%  ph contains category independent selectivities\n%  The co and ph fields can used to threshold the selectivity maps\n% \n% When loading a saved selectivity map need to load 3 files:\n% File -> load Parmater Map-> Selectvity-ROIname\n% File-> load CorAnal\n% Color Map -> Parameter Map Mode -> Load colormap from file -> SelectivityCamp\n%\n% ras, 09/2005\n% kgs 10/2005\n\nif ieNotDefined('mv'), mv = get(gcf,'UserData'); end\nif ~exist('threshold','var')\n    threshold=0.1;\nend\n%%%%%check that a view exists\nmrGlobals;\nswitch mv.roi.viewType\n    case 'Inplane', view = getSelectedInplane;\n    case 'Volume', view = getSelectedVolume;\n    case 'Gray', view = getSelectedGray;\n    case 'Flat', view = getSelectedFlat;\nend\nif isempty(view), error('No mrVista view opened.'); return; end    \n\n% get relevant params about the view\nmapdims = viewGet(view,'dataSize');\nnScans = viewGet(view,'numScans');\nscan = mv.params.scans(1);\n    \n%%%%%get amplitudes for selected conditions\nwhichConds = find(tc_selectedConds(mv));\nwhichConds = whichConds(whichConds>1)-1; % remove null\nnConds = length(whichConds);\n\n%%%%%compute selectivity index\n[scaledSel sel]= mv_selectivity(mv, whichConds, threshold);\n\n% plug in the values to the map volume:\nmapvol = zeros(mapdims);\nind = roiIndices(view,mv.coords);\nmapvol(ind) = scaledSel;\n\n%%%%%get voxel reliabilities, map to co map\nif ~isfield(mv,'wta'), mv=mv_reliability(mv,'plotFlag',0); end\ncovol = zeros(mapdims);\ncovol(ind) = sel;\n% % hack: move to range 0:1 instead of -1:1 so cothres can apply to the\n% % whole range and not only positive numbers\n% covol = 0.5*ones(mapdims);\n% covol(ind) = mv.wta.voxR/2+covol(ind); \n\n%%%%%map the reliabilityinto the ph map\nphvol = zeros(mapdims);\n% phvol(ind) = mod(sel, 1);\nphvol(ind) = normalize(mv.wta.voxR, 0, 2*pi);\n\n\n%%%%%create a color map\nM = view.ui.mapMode;\ncolorsPerCond = floor(128/nConds);\nM.numColors = colorsPerCond*nConds;\ncolors=[];\nfor i=1:nConds\n    % make each condition have a gradient of colors up to\n    % the full color specified by the color order\n    col = mv.trials.condColors{whichConds(i)+1}; % full color\n    for j = 1:colorsPerCond\n        w = 0.3+ 0.5*(j-1)/colorsPerCond; % weight of color\n        colors(end+1,:)=(w*col+ ((colorsPerCond-j+1)/(colorsPerCond))*[.7 .7 .7]);     \n    end\nend\nM.cmap = [gray(M.numGrays); colors];\nmax(M.cmap)\nM.clipMode = [0.01 nConds+0.02]; % set to manual clip mode\n\n% save the color map\ncmapPath = fullfile(dataDir(view),'SelectivityCmap.mat');\ncmap = M.cmap(M.numGrays+1:end,:);\nsave(cmapPath,'cmap');\nfprintf('Saved color map in %s\\n',cmapPath);\n\n%%%%%set in view\nmap = cell(1,nScans); co = cell(1,nScans); ph = cell(1,nScans);\nmapName = sprintf('Selectivity_%s',mv.roi.name);\nmap{scan} = mapvol; co{scan} = covol; ph{scan} = phvol;\nview.map = map; view.mapName = mapName;\nview.co = co; view.ph = ph; view.amp=map;\nview.ui.mapMode = M;\ntry \n    view=setParameterMap(view,map,mapName);\nend\nif saveFlag==1,\n    saveParameterMap(view,[],1);\n    saveCorAnal(view,1)\nend\ntry\n    refreshScreen(view);\ncatch\n    return\nend\n\n% evaluate this in the workspace, so the view\n% itself is updated\nassignin('base','map',map);\nassignin('base','co',co);\nassignin('base','ph',ph);\nassignin('base','tmp',M);\n\nevalin('base',sprintf('%s=setParameterMap(%s,map,''%s'');',...\n    view.name,view.name,mapName));\nevalin('base',sprintf('%s=setDisplayMode(%s,''map'');',...\n    view.name,view.name));\nevalin('base',sprintf('%s.map = map;',view.name));\nevalin('base',sprintf('%s.ui.mapMode=tmp;',view.name));\nevalin('base',sprintf('%s.co=co;',view.name));\nevalin('base',sprintf('%s.ph=ph;',view.name));\nevalin('base',sprintf('%s=refreshScreen(%s);',view.name,view.name));\n\ndisp('Exported voxel selectivity to mrVista view.')\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/MultiVoxelUI/mv_exportSelectivity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22532226845945535}}
{"text": "function [newnode,newelem,newface]=meshrefine(node,elem,varargin)\n%\n% [newnode,newelem,newface]=meshrefine(node,elem,face,opt)\n%\n% refine a tetrahedral mesh by adding new nodes or constraints\n%\n% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)\n%\n% input parameters:\n%      node: existing tetrahedral mesh node list\n%      elem: existing tetrahedral element list\n%      face: (optional) existing tetrahedral mesh surface triangle list\n%      opt:  options for mesh refinement:\n%        if opt is a Nx3 array, opt is treated as a list of new nodes to\n%          be inserted into the mesh (must be located on the surface or inside)\n%        if opt is a struct, it can have the following fields:\n%          opt.newnode: same as setting opt to an Nx3 array\n%          opt.reratio: radius-edge ratio, by default, iso2mesh uses 1.414\n%          opt.maxvol: maximum element volume\n%\n% outputs:\n%      newnode: node coordinates of the tetrahedral mesh\n%      newelem: element list of the tetrahedral mesh\n%      newface: mesh surface element list of the tetrahedral mesh \n%             the last column denotes the boundary ID\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nexesuff=getexeext;\nexesuff=fallbackexeext(exesuff,'tetgen');\n\nnewpt=[];\nopt=struct;\nif(length(varargin)==1)\n\tface=[];\n\tif(isstruct(varargin{1}))\n\t\topt=varargin{1};\n    else\n\t\tnewpt=varargin{1};\n\tend\nelseif(length(varargin)>=2)\n    face=varargin{1};\n    if(isstruct(varargin{2}))\n        opt=varargin{2};\n    else\n        newpt=varargin{2};\n    end\nelse\n\terror('meshrefine requires at least 3 inputs');\nend\nif(isstruct(opt) && isfield(opt,'newnode'))\n    newpt=opt.newnode;\nend\n\n% call tetgen to create volumetric mesh\ndeletemeshfile(mwpath('pre_refine.*'));\ndeletemeshfile(mwpath('post_refine.*'));\n\nmoreopt='';\nsetquality=0;\nif(isstruct(opt) && isfield(opt,'reratio'))\n\tmoreopt=[moreopt sprintf(' -q %.10f ',opt.reratio)];\n\tsetquality=1;\nend\nif(isstruct(opt) && isfield(opt,'maxvol'))\n    moreopt=[moreopt sprintf(' -a %.10f ',opt.maxvol)];\nend\n\nif(~isempty(newpt))\n\tsavetetgennode(newpt,mwpath('pre_refine.1.a.node'));\n\tmoreopt=' -i ';\nend\nif(size(elem,2)==3 && setquality==0)\n    if(~isempty(newpt))\n        error('inserting new point can not be used for surfaces');\n    end\n    nedge=savegts(node, elem,mwpath('pre_refine.gts'));\n    exesuff=fallbackexeext(getexeext,'gtsrefine');\nelseif(size(elem,2)==3)\n    savesurfpoly(node,elem,[],[],[],[],mwpath('pre_refine.poly'));\nelse\n    savetetgennode(node, mwpath('pre_refine.1.node'));\n    savetetgenele (elem, mwpath('pre_refine.1.ele'));\nend\n\nfprintf(1,'refining the input mesh ...\\n');\n\nif(size(elem,2)==3 && setquality==0)\n    if(isstruct(opt) && isfield(opt,'scale'))\n        moreopt=sprintf('%s -n %d ',moreopt,round(nedge*opt.scale));\n    else\n        error('you must give opt.scale value for refining a surface');\n    end\nend\nif(isstruct(opt) && isfield(opt,'moreopt'))\n\tmoreopt=[moreopt opt.moreopt];\nend\n\nif(size(elem,2)==3 && setquality==0)\n    system([' \"' mcpath('gtsrefine') exesuff '\" ' moreopt ' < \"' ...\n          mwpath('pre_refine.gts') '\" > \"' mwpath('post_refine.gts') '\"']);\n    [newnode,newelem]=readgts(mwpath('post_refine.gts'));\n    newface=newelem;\nelseif(size(elem,2)==3)\n    system([' \"' mcpath('tetgen') exesuff '\" ' moreopt ' -p -A \"' mwpath('pre_refine.poly') '\"']);\n    [newnode,newelem,newface]=readtetgen(mwpath('pre_refine.1'));\nelse\n    system([' \"' mcpath('tetgen') exesuff '\" ' moreopt ' -r \"' mwpath('pre_refine.1') '\"']);\n    [newnode,newelem,newface]=readtetgen(mwpath('pre_refine.2'));\nend\n\n% read in the generated mesh\n\nfprintf(1,'mesh refinement is complete\\n');\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/iso2mesh/meshrefine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22523334961371688}}
{"text": "%Voice Based Biometric System\n%By Ambavi K. Patel.\n\n\nfunction ip2=preprocess(ip1,fs1,intval1)\n[rw,cm]=size(ip1);\nif rw==1\n    ip1=ip1';\nelse ip1=ip1;\nend;\nip1=ip1(:,1);                %to make one dimentional\nlen1=length(ip1);\ni = 1;\nwhile abs(ip1(i)) < 0.002 && i<48000% Silence detection\ni = i + 1;\nend\nip1(1:i) = [];\nip1=ip1-mean(ip1);\nip1=ip1*2;                 % amplification\nlen1=length(ip1);\ni=fs1*intval1;\nip2=zeros(i,1);        % to make uniform dimention size\nif len1<i\n    ip2(1:len1)=ip1(1:len1);\nelse \n    ip2(1:i)=ip1(1:i);\nend;\n    ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31328-voice-based-biometric-system/MFCC_MLPBPN/preprocess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.22521254000439042}}
{"text": "function pass = test_plotting( pref )\n% Check that the very basic plotting commands do not crash in diskfunv\n\nF = grad(diskfun(@(x,y) x.*cos(y)));\ntry\n    hold off\n    quiver(F),         j = ishold;\n    close all\n    if ( j == 0 )\n        pass(1) = 1;\n    else\n        pass(1) = 0;\n    end\ncatch\n    pass(1) = 0;\nend\n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/diskfunv/test_plotting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22514787529083652}}
{"text": "function []=panel6fdisp(N,n,T,Units,endo,Ymat,stringdates2,decimaldates2,Fstartlocation,Fendlocation,forecast_estimates,pref)\n\n\n\n\n\n\n% preliminary task: reshape Ymat\nYmat=reshape(Ymat,T,n,N);\n% preliminary task: gather in a cell the values to be plotted\n% initiate the cell\nplotdata={};\n% because forecasts have to be computed for each unit, loop over units\nfor ii=1:N\n% each cell entry is a matrix of actual and forecast values\n% this matrix comprises 4 rows: the first row is actual data, while the three other rows are the estimates (point estimates and confidence bands) for the forecasts\n% also, this matrix has a number of rows equal to the dimension of decimaldates2, which comprises the total period sample+forecasts\n   % loop over variables\n   for jj=1:n\n      plotdata{jj,1,ii}=nan(4,size(decimaldates2,1));\n      % record actual sample values\n      plotdata{jj,1,ii}(1,1:T)=Ymat(:,jj,ii)';\n      % copy the last point of the actual sample for the forecast part of the matrix (required to have a clean plot)\n      plotdata{jj,1,ii}(:,Fstartlocation-1)=repmat(Ymat(Fstartlocation-1,jj,ii),4,1);\n      % record forecast, lower bound\n      plotdata{jj,1,ii}(2,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(1,:);\n      % record forecast, point estimate\n      plotdata{jj,1,ii}(3,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(2,:);\n      % record forecast, upper bound\n      plotdata{jj,1,ii}(4,Fstartlocation:Fendlocation)=forecast_estimates{jj,1,ii}(3,:);\n   end\nend\n% then plot the figure\nif pref.plot\nforecast=figure('Tag','BEARresults');\nset(forecast,'Color',[0.9 0.9 0.9]);\nset(forecast,'name','unconditional forecasts');\n% initiate the count\ncount=0;\n% loop over units\nfor ii=1:N\n   % loop over endogenous variables\n   for jj=1:n\n   % increment count\n   count=count+1;\n   % then plot\n   subplot(N,n,count)\n   hold on\n   Xpatch=[decimaldates2(Fstartlocation-1:Fendlocation,1)' fliplr((decimaldates2(Fstartlocation-1:Fendlocation,1))')];\n   Ypatch=[plotdata{jj,1,ii}(2,Fstartlocation-1:Fendlocation) fliplr(plotdata{jj,1,ii}(4,Fstartlocation-1:Fendlocation))];\n   Fpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);\n   set(Fpatch,'facealpha',0.6);\n   set(Fpatch,'edgecolor','none');\n   plot(decimaldates2,plotdata{jj,1,ii}(3,:),'Color',[0.4 0.4 1],'LineWidth',2);\n   plot(decimaldates2,plotdata{jj,1,ii}(1,:),'Color',[0 0 0],'LineWidth',2);\n   hold off\n   set(gca,'XLim',[decimaldates2(1,1) decimaldates2(end,1)],'FontName','Times New Roman');\n   set(gca,'XGrid','on');\n   set(gca,'YGrid','on');\n      % top labels\n      if count<=n\n      title(endo{count,1},'FontWeight','normal');\n      end\n      % side labels\n      if jj==1\n      ylabel(Units{ii,1},'FontWeight','normal');\n      end\n   end\nend\nend\n\n\n\n% save on Excel\n% create the cell that will be saved on excel\nforecastcell={};\n% build preliminary elements: space between the tables\nvertspace=repmat({''},size(stringdates2,1)+3,1);\nhorzspace=repmat({''},3,6*n);\n% loop over units\nfor ii=1:N\n% initiate the cell of results\nunitcell={};\n   % loop over endogenous variables (horizontal dimension)\n   for jj=1:n\n   % create a header\n   header=[{[Units{ii,1} ': ' endo{jj,1}]} {''} {''} {''} {''};{''} {''} {''} {''} {''};{''} {'actual'} {'lower bound'} {'median'} {'upper bound'}];\n   % complete the cell\n   endocell=[[header;stringdates2 num2cell((plotdata{jj,1,ii})')] vertspace];\n   % concatenate to the previous parts of unitcell\n   unitcell=[unitcell endocell];\n   end\n% concatenate to the previous parts of afcell\nforecastcell=[forecastcell;horzspace;unitcell];\nend\n% trim\nforecastcell=forecastcell(4:end,1:end-1);\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),forecastcell,'forecasts','B2');\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/panel6fdisp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2251478752908365}}
{"text": "function plotIPDF(SO3F,r,varargin)\n% plot inverse pole figures\n%\n% Input\n%  odf - @SO3FunHarmonic\n%  r   - @vector3d specimen directions\n%\n% Options\n%  RESOLUTION - resolution of the plots\n%\n% Flags\n%  antipodal - include <VectorsAxes.html antipodal symmetry>\n%  complete  - plot entire (hemi)--sphere\n%\n% See also\n% S2Grid/plot savefigure Plotting Annotations_demo ColorCoding_demo PlotTypes_demo\n% SphericalProjection_demo\n\nif numel(SO3F)>1\n  warning(['You try to plot an multivariate function. Plot the desired components ' ...\n    'manually. In the following the first component is plotted.'])\nend\n\nplotIPDF@SO3Fun(SO3F.subSet(1),r,varargin{:});\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunHarmonic/plotIPDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22514787529083646}}
{"text": "classdef (Abstract) FilterX < BaseX % Extends trackingX.BaseX\n% FilterX Abstract class\n%\n% Summary of FilterX:\n% This is the base class for all TrackingX filters.\n% Any custom defined Filter should be derived from this FilterX base class.\n%\n% By default, FilterX objects are designed with the intention to be utilised \n% as (Markov-Chain) State Estimators that opererate on a given problem as \n% deterministic Finite State Machines (FSMs), with self-contained memory.\n% In other words, it is expected that for most problems, FilterX objects will \n% go through any heavy parameterisation once, after which they will be used\n% to recursively execute a Prediction-Update State Estimation loop. \n% FilterX objects aim to preserve all the inter-state information they require \n% such that they can execute the next FSM step, without being provided with\n% information they already know.    \n%\n%\n% FilterX Properties:\n%   + Model      - Object handle to StateSpaceModelX class, containing model\n%                  parameterisations. Normally set once during filter initialisation and\n%                  accessed later on.\n%   + Prior      - Structure containing prior information (e.g. pdf)\n%                  Normally set once during filter initialisation and\n%                  accessed later on.\n%   + Prediction - Structure containing prediction information (e.g. pdf)\n%                  Data is over-written on every prediction step and is \n%                  subsequently read by the update (and later) step(s)\n%   + Posterior  - Structure containing posterior information (e.g. pdf)\n%                  Data is over-written on every update step and is subsequently\n%                  utilised by \n%   + MeasurementList   - A (matrix of) column vector(s) representing the\n%                         measurement(s) to be used during the filter update step\n%\n%   (*) Signifies properties necessary to instantiate a class object\n%\n% FilterX Methods:\n%   + FilterX    - Constructor method\n%   + predict    - Performs filter prediction step\n%   + update     - Performs filter update/correction step\n%\n% (+) denotes puplic properties/methods\n% \n% See also TransitionModelX, MeasurementModelX and ControlModelX\n%\n% November 2018 Lyudmil Vladimirov, University of Liverpool.\n\n    properties\n        Model\n        MeasurementList\n    end\n    \n    properties (Access = protected)\n        \n    end\n    \n    methods (Abstract)\n        predict(this);\n        update(this);\n    end\n    \n    methods (Access = protected)\n        function initialise_(this, config)\n            if (isfield(config,'Model'))\n                this.Model = config.Model;\n            end\n        end\n    end\n          \n    methods\n        function this = FilterX(varargin)\n        % FilterX Constructor method\n        %   \n        % Parameters\n        % ----------\n        % Model: StateSpaceModelX\n        %  Object handle to a given state-space model\n        %\n        % Usage\n        % -----\n        % * FilterX(__, Name, Value) instantiates an object handle, configured \n        %   the parameters specified by one or more Name,Value pair arguments. \n        % * FilterX(config) instantiates an object handle configured with  \n        %   the parameters specified inside the 'config' structure, whose  \n        %   fieldnames correspond to the parameter names as given in the \n        %   Parameters section above.\n        %   \n        %  See also predict, update, iterate, smooth.\n            \n            if(nargin==0)\n                return;\n            end\n            \n            % First check to see if a structure was received\n            if(nargin==1)\n                if(isstruct(varargin{1}))\n                    this.initialise_(varargin{1});\n                    return;\n                end\n            end\n            \n            % Otherwise, fall back to input parser\n            parser = inputParser;\n            parser.KeepUnmatched = true;\n            parser.parse(varargin{:});\n            this.initialise_(parser.Unmatched); \n        end\n        \n        function initialise(this, varargin)\n        % initialise Initialisation method. Reset and re-configure the filter.\n        %   \n        % Parameters\n        % ----------\n        % Model: StateSpaceModelX\n        %  Object handle to a given state-space model.\n        %\n        % Usage\n        % -----\n        % * filter.initialise(__, Name, Value) instantiates an object handle,  \n        %   configured the parameters specified by one or more Name,Value\n        %   pair arguments. \n        % * filter.initialise(config) instantiates an object handle configured  \n        %   with the parameters specified inside the 'config' structure, whose  \n        %   fieldnames correspond to the parameter names as given in the \n        %   Parameters section above.\n        %   \n        %  See also predict, update, iterate, smooth.\n            \n            if(nargin==1)\n                return;\n            end\n            \n            % First check to see if a structure was received\n            if(nargin==2)\n                if(isstruct(varargin{1}))\n                    this.initialise_(varargin{1});\n                    return;\n                end\n            end\n            \n            % Otherwise, fall back to input parser\n            parser = inputParser;\n            parser.KeepUnmatched = true;\n            parser.parse(varargin{:});\n            this.initialise_(parser.Unmatched); \n        end\n        \n        % ===============================>\n        % ACCESS METHODS\n        % ===============================>       \n        function set.Model(this,newModel)\n            this.Model = setModel(this,newModel);\n        end\n        \n        function set.MeasurementList(this,newMeasurementList)\n            this.MeasurementList = setMeasurementList(this,newMeasurementList);\n        end\n    end\n\n    methods (Access = protected)\n        % ===============================>\n        % ACCESS METHOD HANDLES\n        % ===============================>\n        function Prior = setPrior(this,newPrior)\n            Prior = newPrior;\n        end\n        function Prediction = setPrediction(this,newPrediction)\n            Prediction = newPrediction;\n        end\n        function Posterior = setPosterior(this,newPosterior)\n            Posterior = newPosterior;\n        end\n        function Model = setModel(this,newModel)\n            Model = newModel;\n        end\n        function measurementList = setMeasurementList(this,newMeasurementList)\n            measurementList = newMeasurementList;\n        end\n    end\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Abstract Classes/FilterX/FilterX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2250751736345606}}
{"text": "function TestPhoneRecognizerLSTM_TIMIT()\n\nmodeldir = my_dir('nnet');\nmodelfiles = findFiles(['nnet/' modeldir{1}], 'mat');\nmodelfiles = sort_nnet_by_itr(modelfiles);      % get the last iteration model\n\ndnn = load(modelfiles{1});\npara = dnn.para;\npara.IO = RemoveIOStream(para.IO, 2);   % during evaluation, we don't have the label usually. So remove that stream from the configuration\nlayer = dnn.layer(1:end-2);     % we discard the last two layers that is not useful for ASR\n\nclean_cond = 1;\n[Data_cv, ~, para] = LoadData_TIMIT(para, 'test');\n\npara.out_layer_idx = length(layer) + [0];   % you can specify which layers' activation will be outputed\n\n\nfor i=1:length(Data_cv(1).data)\n    tmpData(1).data{1} = Data_cv(1).data{i};\n    output = FeatureTree2(tmpData, para, layer);\n    posterior = output{1}{1};\n    \n    subplot(2,1,1); imagesc(Data_cv(1).data{i});    title('Feature');\n    subplot(2,1,2); imagesc(posterior);       title('Posteriorgram and true label'); hold on\n    plot(Data_cv(2).data{i}, 'r'); hold off;\n    pause\nend\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/classification_framewise/TestPhoneRecognizerLSTM_TIMIT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22507516791523255}}
{"text": "function PlotImu6(aedat, numBins, startTime, endTime)\n\n%{\n%}\n\nif isfield(aedat.data, 'imu6')\n    data = aedat.data.imu6;\nelse\n    return\nend\n\nif ~exist('numBins', 'var') || (exist('numBins', 'var') && numBins == 0)\n\tnumBins = data.numEvents;\nend\n\nif exist('startTime', 'var') && startTime > 0 \n    startTime = startTime * 1e6;\nelse\n    startTime = aedat.info.firstTimeStamp;\nend\n\nif exist('endTime', 'var') && endTime > 0 \n    endTime = endTime * 1e6;\nelse\n    endTime = aedat.info.lastTimeStamp;\nend\n\ndurationUs = double(endTime - startTime);\ndurationOfBinUs = durationUs / numBins;\ndurationOfBinS = durationOfBinUs / 1000000;\n\ntimeBinBoundariesUs = double(startTime) : durationOfBinUs : double(endTime);\ntimeBinCentresS = (timeBinBoundariesUs(1 : end - 1) + durationOfBinUs / 2) / 1000000;\n\nif numBins == data.numEvents\n    accelX = data.accelX;\n    accelY = data.accelY;\n    accelZ = data.accelZ;\n    gyroX  = data.gyroX;\n    gyroY  = data.gyroY;\n    gyroZ  = data.gyroZ;\n    temperature   = data.temperature;\nelse\n    accelX = zeros(numBins, 1);\n    accelY = zeros(numBins, 1);\n    accelZ = zeros(numBins, 1);\n    gyroX  = zeros(numBins, 1);\n    gyroY  = zeros(numBins, 1);\n    gyroZ  = zeros(numBins, 1);\n    temperature = zeros(numBins, 1);\n    \n    for bin = 1 : numBins\n\t\tfirstTimeStampIndex = find(data.timeStamp >= timeBinBoundariesUs(bin), 1, 'first');\n\t\tlastTimeStampIndex = max(firstTimeStampIndex, find(data.timeStamp < timeBinBoundariesUs(bin + 1), 1, 'last'));\n\t\tif ~isempty(firstTimeStampIndex) && ~isempty(lastTimeStampIndex) \n\t\t\taccelX(bin) = mean(data.accelX(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\taccelY(bin) = mean(data.accelZ(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\taccelZ(bin) = mean(data.accelY(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\tgyroX(bin) = mean(data.gyroX(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\tgyroY(bin) = mean(data.gyroY(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\tgyroZ(bin) = mean(data.gyroZ(firstTimeStampIndex : lastTimeStampIndex));\n\t\t\ttemperature(bin) = mean(data.temperature(firstTimeStampIndex : lastTimeStampIndex));\n\t\tend\n    end\nend\n\nfigure\nlegendLocal = {};\nhold all\nplot(timeBinCentresS, accelX, '-')\nlegendLocal = [legendLocal 'accelX'];\nplot(timeBinCentresS, accelY, '-')\nlegendLocal = [legendLocal 'accelY'];\nplot(timeBinCentresS, accelZ, '-')\nlegendLocal = [legendLocal 'accelZ'];\nxlabel('Time (s)')\nylabel('Acceleration (g)')\nlegend(legendLocal)\n\nfigure\nlegendLocal = {};\nhold all\nplot(timeBinCentresS, gyroX)\nlegendLocal = [legendLocal 'gyroX'];\nplot(timeBinCentresS, gyroY)\nlegendLocal = [legendLocal 'gyroY'];\nplot(timeBinCentresS, gyroZ)\nlegendLocal = [legendLocal 'gyroZ'];\nxlabel('Time (s)')\nylabel('Angular velocity (deg/s)')\nlegend(legendLocal)\n\nfigure\nplot(timeBinCentresS, temperature)\nxlabel('Time (s)')\nylabel('temperature (C)')\n\n", "meta": {"author": "panpanfei", "repo": "Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "sha": "aabdd6ae323726132b0e0592ce151461e3ad7c5a", "save_path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera/Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera-aabdd6ae323726132b0e0592ce151461e3ad7c5a/event_cvpr_github/read_data/code/AedatTools-master/Matlab/PlotImu6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2250751679152325}}
{"text": " function y = mtimes(ob, x)\n%function y = mtimes(ob, x)\n%\ty = G * x\tor x = G' * y\n%\tCopyright 2002-2-20\tJeff Fessler\tThe University of Michigan\n\n%\n%\tscalar * G\n%\nif isa(ob, 'double') & length(x) == 1 & isa(x, 'Gtomo2_dsc')\n\ty = x;\n\ty.scale = ob;\n\treturn\nend\n\nif ob.apower ~= 1, error notdone, end\n\n\n%\n%\tpartial projection or backprojection (for ordered subsets)\n%\nif ob.is_subset\n\t%\n\t%\tGt(:,ii)' * x\t\tpartial forward projection\n\t%\n\tif ~ob.is_transpose\n\t\tif ob.is_masked\n\t\t\tx = embed(x, ob.mask);\n\t\tend\n\t\ty = wtfmex('dsc,proj', ob.arg', single(x), ob.mask, ...\n\t\t\tint32(ob.ia_start), int32(ob.ia_inc), ...\n\t\t\tint32(ob.nthread), ob.chat);\n\t\ty = y(:,(ob.ia_start+1):ob.ia_inc:ob.na);\n\n\n\t%\n\t%\tGt(:,ii) * y\t\tpartial back projection\n\t%\n\telse\n\t\ty = zeros(ob.nb,ob.na);\n\t\tia = (ob.ia_start+1):ob.ia_inc:ob.na;\n\t\ty(:,ia) = reshape(x, ob.nb, length(ia));\n\t\ty = wtfmex('dsc,back', ob.arg', single(y), ob.mask, ...\n\t\t\tint32(ob.ia_start), int32(ob.ia_inc), ...\n\t\t\tint32(ob.nthread), ob.chat);\n\t\tif ob.is_masked\n\t\t\ty = y(ob.mask);\n\t\tend\n\tend\n\n\n%\n%\tfull projection\n%\nelseif ~ob.is_transpose\n\tif ob.is_masked\n\t\tx = embed(x, ob.mask);\n\tend\n\ty = wtfmex('dsc,proj', ob.arg', single(x), ob.mask, ...\n\t\tint32(0), int32(1), int32(ob.nthread), ob.chat);\n\n\n%\n%\tfull back-projection\n%\nelse\n\ty = wtfmex('dsc,back', ob.arg', single(x), ob.mask, ...\n\t\tint32(0), int32(1), int32(ob.nthread), ob.chat);\n\tif ob.is_masked\n\t\ty = y(ob.mask);\n\tend\nend\n\ny = ob.scale * double(y(:));\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/arch/@Gtomo2_dsc/arch/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22507516791523247}}
{"text": "function [pos,picon,picoff,janelas,messages]=twave3D(w,timenew,i,freq,S,QRSoff,samp,rrmed,messages)\n%\n%[pos,picon,picoff,janelas]=twave3D(w,timenew,i,freq,S,QRSoff,samp,rrmed)\n%\n% multilead T wave delineation\n%\n%Input Parameters:\n%   w: matrix with WT scales 1 to 5\n%   timenew:  QRS times in inedexes refering the interval included in the current excerpt (borders excluded)\n%   i: beat number\n%   freq: sampling frequency (heasig.freq)\n%   S: lattest S wave position found in any lead\n%   QRSoff: lattest QRS end position found in any lead\n%   samp: samples included in the current excerpt (borders excluded)\n%   rrmed: Exponentially averaged RR\n%\n%Output Parameters:\n%   pos: fiducial marks structure (position)\n%   picon: position of the first relevant modulos maximum in the wavelet\n%   picoff: position of the last relevant modulos maximum in the wavelet\n%   janelas: T wave seach windows\n%\n% Rute Almeida\n% Last update: Rute Almeida  05AGO2011\n%\n% Designed for MATLAB Version R12; tested with MATLAB Version R13\n%\n\n%%%%%% Constants and Thresholds  !!!!!!!!!!!!!!!!!!!!!!!!!\nif ~isfield(messages.setup.wavedet,'umbraldetT')\n    messages.setup.wavedet.umbraldetT = 0.25;  % We use umbraldet*sqrt(mean(w(time(i):time(i+1),4).^2))\nend\nif ~isfield(messages.setup.wavedet,'umbralsig')\n    messages.setup.wavedet.umbralsig  =  1/8;\nend\nif ~isfield(messages.setup.wavedet,'Kton')\n    messages.setup.wavedet.Kton = 4;      % 2 4!\nend\nif ~isfield(messages.setup.wavedet,'inivent_tol')\n    messages.setup.wavedet.inivent_tol  =  0.1;\nend\nif ~isfield(messages.setup.wavedet,'inivent_tol_S')\n    messages.setup.wavedet.inivent_tol_S=0.05; % sec\nend\nif ~isfield(messages.setup.wavedet,'finvent_tol')\n    messages.setup.wavedet.finvent_tol=0.240;% sec\nend\nif ~isfield(messages.setup.wavedet,'finvent_max')\n    messages.setup.wavedet.finvent_max=0.6;% sec\nend\nif ~isfield(messages.setup.wavedet,'min_vent')\n    messages.setup.wavedet.min_vent=0.1;%sec\nend\nif ~isfield(messages.setup.wavedet,'Tmax_Tmin_time_min')\n    messages.setup.wavedet.Tmax_Tmin_time_min=0.15;%sec\nend\nif ~isfield(messages.setup.wavedet,'Tmax_Tmin_bifasic')\n    messages.setup.wavedet.Tmax_Tmin_bifasic=2.5;\nend\n\nKton=messages.setup.wavedet.Kton;\nKtoff=messages.setup.wavedet.Kton;\nmessages.warnings=[messages.warnings {'Recall that in twave3D ktoff=kton.'}];\numbraldetT = messages.setup.wavedet.umbraldetT;\numbralsig = messages.setup.wavedet.umbralsig;\ninivent_tol= messages.setup.wavedet.inivent_tol;\ninivent_tol_S=messages.setup.wavedet.inivent_tol_S;\nfinvent_tol=messages.setup.wavedet.finvent_tol;\nfinvent_max= messages.setup.wavedet.finvent_max;\nmin_vent=messages.setup.wavedet.min_vent;\nTmax_Tmin_time_min= messages.setup.wavedet.Tmax_Tmin_time_min;%sec\nTmax_Tmin_bifasic=messages.setup.wavedet.Tmax_Tmin_bifasic;% extra criteria\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\njanelas=[];%%31May05\n% Initialization of auxiliary variables\nT = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];\n% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];\n% maxp=[];\npicon_keep=[];%multileadchange\npicoff_keep=[];%multileadchange\nlead_keep=[];%multileadchange\n\ninivent = round(inivent_tol*freq);   % Begining of window\nif ~isempty(S),              % If there is an S wave\n    inivent = max(inivent, S-timenew(i)+round(inivent_tol_S*freq));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% changed 13/06/02 Rute\nif rrmed <= freq,\n    %if rrmed >= freq,\n    finvent = round(finvent_max*freq);     % End of window\nelse\n    finvent = round(rrmed*finvent_max);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  %% changed 13/06/02 Rute\n\n% using timenew from diffferent leads ty ca dist less tahn 0.24 sec!!!\nif i~=length(timenew),                 % For last beat in the segment\n    finvent = min(finvent,timenew(i+1)-timenew(i)-round(finvent_tol*freq));\nelse\n    finvent = min(finvent,timenew(i)-timenew(i-1)-round(finvent_tol*freq));\nend\n\n% We work at scale scale (in general).\nif isempty(QRSoff),   % Should never happen, but...\n    % begwin = inivent + timenew(i);\n    begwin = inivent;\nelse\n    %  begwin = max(inivent + timenew(i), QRSoff+1);\n    begwin = max(inivent , QRSoff+1-timenew(i));\nend\n%endwin = min(finvent + timenew(i),length(w)); %% Rute 20/05/02\nendwin = min(finvent ,length(w)); %% Rute 20/05/02\njanelas=[janelas; i begwin endwin];%31May05\nif ~isempty(begwin+1:endwin ) % 22.04.05\n    \n    % Positive maxima and negative minima in the window\n    maxpos = begwin + modmax(w(begwin+1:endwin ),2,0,+1);\n    minpos = begwin + modmax(w(begwin+1:endwin ),2,0,-1);\n    [maxim ind] = max(w(maxpos ));   % The biggest of the positive\n    maxpos = maxpos(ind);\n    [minim ind] = min(w(minpos ));   % The biggest of the negative\n    minpos = minpos(ind);\n    \n    if isempty(maxpos),               % If no local positive maximum\n        % The maximum will be the first\n        % or the last sample\n        if (w(begwin )>=w(endwin )) && w(begwin )>0,\n            maxpos = begwin; maxim = w(maxpos );\n        elseif (w(endwin )>=w(begwin )) && w(endwin )>0,\n            maxpos = endwin; maxim = w(maxpos );\n        end\n    end\n    if isempty(minpos),               % if no local negative minimum\n        % the minimum will be the first\n        % or the last sample\n        if (w(begwin )<=w(endwin )) && w(begwin )<0,\n            minpos = begwin; minim = w(minpos );\n        elseif (w(endwin )<=w(begwin )) && w(endwin )<0,\n            minpos = endwin; minim = w(minpos );\n        end\n    end\n    \n    absmax = abs(maxim);\n    absmin = abs(minim);\n    \n    if i<length(timenew),\n        veficaz = sqrt(mean(w .^2)); % all w 03.Dec.04 interval was restricted before\n    else                        % if last beat of the segment\n        veficaz = sqrt(nanmean(w.^2)); % all w 03.Dec.04 interval was restricted before\n    end\n    \n    hay_onda = ((absmax>umbraldetT*veficaz)|(absmin>umbraldetT*veficaz));\n    \n    % Rute 18/06/02\n    if endwin-begwin<(min_vent*freq) % se a janela tem amplitude menor do que min_vent seg enato nao existe onda T\n        hay_onda =0;\n    end\n    \n    % Is there a wave?\n    if hay_onda,\n        if absmax >= absmin,    % the greatest modulus maximum is the maximum\n            % Now we search the two minima nearest to maxpos, one before and one after\n            minapos = max(modmax(w(begwin+1:maxpos-1 ),2,0,-1));\n            minapos = begwin + minapos; % Position of the negative minimum before the maximum\n            if isempty(minapos) && (maxpos ~= begwin) && (w(begwin )<0),\n                minapos = begwin;% If no local minimum before the maximum, take the first sample\n            end\n            minppos = min(modmax(w(maxpos+1:endwin ),2,0,-1));\n            minppos = maxpos + minppos; % Position of the positive maximum after the minimum\n            if isempty(minppos) && (maxpos ~= endwin) && (w(endwin )<0),\n                minppos = endwin;        % If no local minimum after the maximum, take the last sample\n            end\n            \n            mina = abs(w(minapos ));     % Amplitude of minimum before maximum\n            minp = abs(w(minppos ));     % Amplitude of minimum after maximum\n            \n            if (mina < umbralsig*absmax), % If mina is not big enough\n                mina =[];                  % forget it\n            elseif (maxpos-minapos>Tmax_Tmin_time_min*freq), %or if ther are more than 150 ms to maxpos\n                mina = [];\n            end\n            if (minp < umbralsig*absmax), % If minp is not big enough\n                minp =[];                  % forget it\n            elseif (minppos-maxpos>Tmax_Tmin_time_min*freq), % and also if there are more than 150 ms to maxpos\n                minp =[];\n            end\n            \n            if ~isnan(mina)&~isnan(minp),      %#ok<AND2> %%% NUEVO JP\n                if (mina >= minp)&&(minp < umbralsig*absmax*Tmax_Tmin_bifasic),\n                    minp = [];\n                elseif (minp> mina)&&(mina < umbralsig*absmax*Tmax_Tmin_bifasic),\n                    mina = [];\n                end\n            end\n            \n            % Test which modulus maxima are significative and find zero crossings\n            if isempty(mina),\n                if isempty(minp),\n                    tipoT = 2;      % only upwards T wave\n                    if maxpos - minapos > 2,         % if not !!!!!!!!!!!\n                        ind = zerocros(flipud(w(minapos:maxpos )));   %Scale 3 !!! % also in scale 4!!!!!!! 03.Dec.04\n                        T = maxpos - ind +1;                           % Zero crossing = T wave position\n                        picoff = maxpos;                               %wavelet  peak to detect offset\n                    elseif isempty(minapos);  % If there were no minimum, there is no zero crossing\n                        T = picant (w(begwin:maxpos ),maxpos);       % Take the minimum at scale 4\n                        if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute\n                            picoff = maxpos;\n                        else\n                            picoff = []; % if did not exist a peak in scale 4 there is no T\n                        end %%%%%%%%%%%% 14/06/02 Rute\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                else      % minp exists (is significative) but mina not\n                    tipoT = 0;  \t\t%normal T wave\n                    if minppos -maxpos >2,       % if not!!!!!!???\n                        ind = zerocros(w(maxpos:minppos ));  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(w(maxpos:minppos));\n                        %                         end %%%%%%%%%%%%%%Rute 03/09/02\n                        T = maxpos + ind -1;\n                        picon = maxpos;\t\t% For determining onset and offset\n                        picoff = minppos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                end\n            else\n                if isempty(minp),   %  mina exists (is significative) but minp not\n                    tipoT = 1;  \t%inverted T wave\n                    if maxpos -minapos >2,  % if not !!!!!!!!!\n                        ind = zerocros(w(minapos:maxpos));  % wavelet zero crossing is T wave peak  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(w(minapos:maxpos ));  % wavelet zero crossing is T wave peak  %% 03/09/02 Rute\n                        %                         end %%%%%%%%%%%%%%Rute 03/09/02\n                        T = minapos + ind -1;\n                        picon = minapos;\n                        picoff = maxpos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                else    % both mina and minp are significative.  Biphasic wave.\n                    tipoT = 5;\t% biphasic neg-pos T wave\n                    if maxpos - minapos > 2,    %!!!!!!!!!!!!\n                        ind = zerocros(flipud(w(minapos:maxpos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(flipud(w(minapos:maxpos ))); %% 03/09/02 Rute\n                        %                         end%%%%%%%%%%%%%%Rute 03/09/02\n                        T = maxpos - ind +1;\n                        picon = minapos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                    if minppos - maxpos > 2,    %!!!!!!!!!!!!\n                        ind = zerocros(flipud(w(maxpos:minppos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(flipud(w(maxpos:minppos ))); %% 03/09/02 Rute\n                        %                         end %%%%%%%%%%%%%%Rute 03/09/02\n                        %Tprima = maxpos + ind -1; %18.11.05\n                        Tprima = minppos- ind +1;\n                        picoff = minppos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                end\n            end\n        else        % If the greatest modulus maximum is the minimum\n            % Search two maxima, one before and one after the minimum\n            maxapos = max(modmax(w(begwin+1:minpos-1 ),2,0,1));\n            maxapos = begwin + maxapos;\n            if isempty(maxapos) && (minpos ~= begwin) && (w(begwin )>0),\n                maxapos = begwin;\n            end\n            maxppos = min(modmax(w(minpos+1:endwin ),2,0,1));\n            maxppos = minpos + maxppos;\n            if isempty(maxppos) && (minpos ~= endwin) && (w(endwin )>0),\n                maxppos = endwin;\n            end\n            maxa = abs(w(maxapos ));\n            maxp = abs(w(maxppos )) ;                                   % See if they are significative\n            if (maxa < umbralsig*absmin)\n                maxa =[];\n            elseif (minpos-maxapos>Tmax_Tmin_time_min*freq),\n                maxa = [];\n            end\n            if (maxp < umbralsig*absmin),\n                maxp =[];\n            elseif (maxppos-minpos>Tmax_Tmin_time_min*freq),\n                maxp = [];\n            end\n            if ~isnan(maxa)&~isnan(maxp),      %#ok<AND2> %%% NUEVO JP\n                if (maxa >= maxp)&&(maxp < umbralsig*absmin*Tmax_Tmin_bifasic),\n                    maxp = [];\n                elseif (maxp> maxa)&&(maxa < umbralsig*absmin*Tmax_Tmin_bifasic),\n                    maxa = [];\n                end\n            end\n            % Test which modulus maxima are significative and find zero crossings\n            if isempty(maxa),\n                if isempty(maxp),\n                    tipoT = 3;      % only downwards T wave\n                    if minpos - maxapos > 2, %!!!!!!!!\n                        ind = zerocros(flipud(w(maxapos:minpos )));   %Scale 3 % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(flipud(w(maxapos:minpos )));\n                        %                         end %%%%%%%%%%%%%%Rute 03/09/02\n                        T = minpos - ind +1;\n                        picoff = minpos;\n                    elseif isempty(maxapos);  % If there were no maximum, there is no zero crossing.\n                        T = picant (w(begwin:minpos ),minpos);  % menimo en escala 4.\n                        if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute\n                            picoff = minpos;\n                        else\n                            picoff = []; % if did not exist a peak in scale 4 there is no T\n                        end %%%%%%%%%%%% 14/06/02 Rute\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                else      % maxp is signficative, but not maxa\n                    tipoT = 1;  %inverted T wave\n                    if maxppos -minpos >2,  % !!!!!!\n                        ind = zerocros(w(minpos:maxppos ));  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n                        %                             ind = zerocros(w(minpos:maxppos ));  %% 03/09/02 Rute\n                        %                         end %%%%%%%%%%%%%%Rute 03/09/02\n                        T = minpos + ind -1;\n                        picon = minpos;\t\t% For calculating onset and offset\n                        picoff = maxppos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                end\n            else\n                if isempty(maxp),   % maxa is significative, but not maxp\n                    tipoT = 0;       %normal T wave\n                    if minpos -maxapos >2,\n                        ind = zerocros(w(maxapos:minpos )); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        %                             ind = zerocros(w(maxapos:minpos )); %% 03/09/02 Rute\n                        %end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        T = maxapos + ind -1;\n                        picon = maxapos;\n                        picoff = minpos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                else    % both maxa and maxp are significative.  Biphasic wave.\n                    tipoT = 4;\t% biphasic pos-neg T wave\n                    if minpos - maxapos > 2,  %!!!!!!!!!!!\n                        ind = zerocros(flipud(w(maxapos:minpos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        %                             ind = zerocros(flipud(w(maxapos:minpos ))); %% 03/09/02 Rute\n                        %                         end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        T = minpos - ind +1;\n                        picon = maxapos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        %                         [i tipoT]\n                        disp('caso nao previsto; onda T nao marcada!')\n                    end\n                    if maxppos - minpos > 2,    %!!!!!!!!!!!!\n                        ind = zerocros(flipud(w(minpos:maxppos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04\n                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        %                             ind = zerocros(flipud(w(minapos:maxpos ))); %% 03/09/02 Rute\n                        %                         end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n                        %Tprima = minpos + ind -1; %18.11.05 DUVIDA\n                        Tprima = maxppos- ind +1;\n                        picoff = maxppos;\n                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute\n                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];\n                    end\n                end\n            end\n        end\n        \n        % T wave onset and offset detection\n        %if isempty(T), picon=[]; picoff=[]; end\n        \n        picon_keep=[picon_keep picon]; %multileadchange\n        picoff_keep=[picoff_keep picoff];%multileadchange\n        lead_keep=[lead_keep 4];%multileadchange\n        \n        if ~isempty(picon),\n            Ton = searchon (picon, w(max(begwin,picon-0.12*freq):picon ), Kton);\n        end\n        if ~isempty(picoff),\n            Toff=searchoff(picoff, w(picoff:min([size(w,1) picoff+0.12*freq ])  ) , Ktoff);\n            if (Toff > endwin),\n                Toff = endwin;\n            end\n        end\n    else\n        tipoT=9;\n        messages.warnings=[messages.warnings {'unknown case: unable to find T wave in multilead approach using scale 4.'}];\n    end       %% utilizar a escala 5 07/06/02 Rute %%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \nend\n% Filling the structure with positions\nif isempty(Ton), Ton = NaN; end;\nif isempty(Toff), Toff = NaN;  end;\nif isempty(T), T=NaN; end;\nif isnan(T),\n    picon_keep=[picon_keep NaN]; %multileadchange\n    picoff_keep=[picoff_keep NaN];%multileadchange\n    lead_keep=[lead_keep NaN];%#ok<NASGU> %multileadchange\nend\nif isempty(Tprima), Tprima=NaN; end;\nif isempty(tipoT), tipoT=NaN; end;\npos.Ton= Ton+samp(1)-1+timenew(i)-1;\npos.Toff= Toff+samp(1)-1+timenew(i)-1;\npos.T= T+samp(1)-1+timenew(i)-1;\npos.Tprima= Tprima+samp(1)-1+timenew(i)-1;\npos.Ttipo= tipoT;\n% T = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];\n% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];\n% maxp=[];\n%end\n% position.Ton(intervalo(1):intervalo(2)) = pos.Ton+samp(1)-1;\n% position.Toff(intervalo(1):intervalo(2))= pos.Toff+samp(1)-1;\n% position.T(intervalo(1):intervalo(2)) = pos.T+samp(1)-1;\n% position.Tprima(intervalo(1):intervalo(2)) = pos.Tprima+samp(1)-1;\n% position.Ttipo(intervalo(1):intervalo(2)) = pos.Ttipo;\n% pos.Ton\n% Ton = pos.Ton(i)\n% Toff= pos.Toff(i)\n% T= pos.T(i)\n% Tprima = pos.Tprima(i)\n% Ttipo= pos.Ttipo(i);\n%timenew(i)\n%picon_keep\npicoff=picoff_keep+timenew(i)-1;\npicon=picon_keep+timenew(i)-1;\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/wavedet/twave3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.22497233561726088}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MRiLab auto generated file: DO NOT EDIT!     %\n% Generated by MRiLab \"DoWriteXML2m\" Generator %\n% MRiLab Version 1.3                           %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [rfAmp,rfPhase,rfFreq,rfCoil,GzAmp,GyAmp,GxAmp,ADC,Ext,uts,ts,flags]=PSD_GRE3DSpiral\nglobal VCtl\nglobal VVar\nCV1=10e-3;\nCV10=0;\nCV11=0;\nCV12=0;\nCV13=0;\nCV14=0;\nCV2=20e-3;\nCV3=0;\nCV4=0;\nCV5=0;\nCV6=0;\nCV7=0;\nCV8=0;\nCV9=0;\nrfAmpAll=[];\nrfPhaseAll=[];\nrfFreqAll=[];\nrfCoilAll=[];\nGzAmpAll=[];\nGyAmpAll=[];\nGxAmpAll=[];\nADCAll=[];\nExtAll=[];\nrfTimeAll=[];\nGzTimeAll=[];\nGyTimeAll=[];\nGxTimeAll=[];\nADCTimeAll=[];\nExtTimeAll=[];\nSEtAll=[];\nuts=[];\nts=[];\nflags=[];\nif VCtl.PlotSeq == 1\nrfAmp=[];\nrfPhase=[];\nrfFreq=[];\nrfCoil=[];\nGzAmp=[];\nGyAmp=[];\nGxAmp=[];\nADC=[];\nExt=[];\nFreq=1;\nNotes='regular TR section';\nAttributeOpt={'on','off'};\nSwitch=AttributeOpt{1};\nTREnd=Inf;\nTRStart=1;\ntE=VCtl.TR;\ntS=0;\nif VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')\n% do nothing\nelse\nts = [ts tS tE];\nend\nts = [0 max(ts)-min(ts)];\nreturn;\nend\n%==============Pulses 1==============\nrfAmp=[];\nrfPhase=[];\nrfFreq=[];\nrfCoil=[];\nGzAmp=[];\nGyAmp=[];\nGxAmp=[];\nADC=[];\nExt=[];\nrfTime=[];\nGzTime=[];\nGyTime=[];\nGxTime=[];\nADCTime=[];\nExtTime=[];\nFreq=1;\nNotes='regular TR section';\nAttributeOpt={'on','off'};\nSwitch=AttributeOpt{1};\nTREnd=Inf;\nTRStart=1;\ntE=VCtl.TR;\ntS=0;\nif isempty(tS) | isempty(tE) | (tS>=tE)\nerror('SE setting is incorrect for Pulses 1!');\nend\nif VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')\n% do nothing\nelse\n%--------------------\nAttributeOpt={'on','off'};\np.AnchorTE=AttributeOpt{1};\nAttributeOpt={'Non','Hamming','Hanning'};\np.Apod=AttributeOpt{1};\np.CoilID=1;\np.DupSpacing=0;\np.Duplicates=1;\np.FA=VCtl.FlipAng;\np.Notes='excitation rf';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.TBP=4;\np.dt=20e-6;\np.rfFreq=0;\np.rfPhase=0;\np.tEnd=1e-3;\np.tStart=0;\nif strcmp(p.Switch,'on')\nif strcmp(p.AnchorTE,'on')\nswitch VCtl.TEAnchor\ncase 'Start'\nVCtl.TEAnchorTime=p.tStart; \ncase 'Middle'\nVCtl.TEAnchorTime=(p.tStart+p.tEnd)/2; \ncase 'End'\nVCtl.TEAnchorTime=p.tEnd;\nend\nend\n[rfAmp1,rfPhase1,rfFreq1,rfCoil1,rfTime1]=rfSinc(p);\nif strcmp(VCtl.MultiTransmit,'off')\nif VCtl.MasterTxCoil==rfCoil1(1)\nrfAmp=[rfAmp rfAmp1];\nrfPhase=[rfPhase rfPhase1];\nrfFreq=[rfFreq rfFreq1];\nrfCoil=[rfCoil rfCoil1];\nrfTime=[rfTime rfTime1];\nend\nelse\nrfAmp=[rfAmp rfAmp1];\nrfPhase=[rfPhase rfPhase1];\nrfFreq=[rfFreq rfFreq1];\nrfCoil=[rfCoil rfCoil1];\nrfTime=[rfTime rfTime1];\nend\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Gz1Sign=1;\np.Gz2Sign=0;\np.Notes='cartesian phase';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.t1End=CV2;\np.t1Start=CV1;\np.t2End=VCtl.TE+CV2;\np.t2Start=VCtl.TE+CV1;\np.tRamp=100e-6;\nif strcmp(p.Switch,'on')\n[GzAmp1,GzTime1]=GzCartesian(p);\nGzAmp=[GzAmp GzAmp1];\nGzTime=[GzTime GzTime1];\nend\np=[];\n%--------------------\np.Notes='spiral encoding';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.dt=0.004e-3;\np.tStart=VCtl.TE;\nif strcmp(p.Switch,'on')\n[GyAmp1,GyTime1]=GySpiral(p);\nGyAmp=[GyAmp GyAmp1];\nGyTime=[GyTime GyTime1];\nend\np=[];\n%--------------------\np.Notes='spiral encoding';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.dt=0.004e-3;\np.tStart=VCtl.TE;\nif strcmp(p.Switch,'on')\n[GxAmp1,GxTime1]=GxSpiral(p);\nGxAmp=[GxAmp GxAmp1];\nGxTime=[GxTime GxTime1];\nend\np=[];\n%--------------------\np.Notes='spiral readout';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=VCtl.TE;\nif strcmp(p.Switch,'on')\n[ADC1,ADCTime1]=ADCSpiral(p);\nADC=[ADC ADC1];\nADCTime=[ADCTime ADCTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=1;\np.Notes='reset K space location';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=1e-3;\nif strcmp(p.Switch,'on')\n[Ext1,ExtTime1]=ExtBit(p);\nExt=[Ext Ext1];\nExtTime=[ExtTime ExtTime1];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=5;\np.Notes='calculate remaining scan time';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=0;\nif strcmp(p.Switch,'on')\n[Ext2,ExtTime2]=ExtBit(p);\nExt=[Ext Ext2];\nExtTime=[ExtTime ExtTime2];\nend\np=[];\n%--------------------\np.DupSpacing=0;\np.Duplicates=1;\np.Ext=9;\np.Notes='real time recon';\nAttributeOpt={'on','off'};\np.Switch=AttributeOpt{1};\np.tStart=VCtl.TE+CV2;\nif strcmp(p.Switch,'on')\n[Ext3,ExtTime3]=ExtBit(p);\nExt=[Ext Ext3];\nExtTime=[ExtTime ExtTime3];\nend\np=[];\n%--------------------\nSEt=[tS tE];\nrfAmp(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfPhase(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfFreq(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nrfCoil(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nGzAmp(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];\nGyAmp(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];\nGxAmp(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];\nADC(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];\nExt(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];\nrfTime(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];\nGzTime(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];\nGyTime(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];\nGxTime(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];\nADCTime(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];\nExtTime(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];\nrfAmp(abs(rfAmp)<eps) = 0;\nrfTime = rfTime + SEt(1);\nGzTime = GzTime + SEt(1);\nGyTime = GyTime + SEt(1);\nGxTime = GxTime + SEt(1);\nADCTime = ADCTime + SEt(1);\nExtTime = ExtTime + SEt(1);\nrfAmpAll=[rfAmpAll rfAmp];\nrfPhaseAll=[rfPhaseAll rfPhase];\nrfFreqAll=[rfFreqAll rfFreq];\nrfCoilAll=[rfCoilAll rfCoil];\nGzAmpAll=[GzAmpAll GzAmp];\nGyAmpAll=[GyAmpAll GyAmp];\nGxAmpAll=[GxAmpAll GxAmp];\nADCAll=[ADCAll ADC];\nExtAll=[ExtAll Ext];\nrfTimeAll=[rfTimeAll rfTime];\nGzTimeAll=[GzTimeAll GzTime];\nGyTimeAll=[GyTimeAll GyTime];\nGxTimeAll=[GxTimeAll GxTime];\nADCTimeAll=[ADCTimeAll ADCTime];\nExtTimeAll=[ExtTimeAll ExtTime];\nSEtAll=[SEtAll SEt];\nend\n%====================================\nif isempty(rfTimeAll)\nerror('rf sequence line can not be empty! Master Tx coil element must be used.');\nend\nif isempty(GzTimeAll)\nerror('GzSS sequence line can not be empty!');\nend\nif isempty(GyTimeAll)\nerror('GyPE sequence line can not be empty!');\nend\nif isempty(GxTimeAll)\nerror('GxR sequence line can not be empty!');\nend\nif isempty(ADCTimeAll)\nerror('ADC sequence line can not be empty!');\nend\nif isempty(ExtTimeAll)\nerror('Ext sequence line can not be empty!');\nend\nSEflag=repmat([0 0 0 0 0 0]',[1 2]);\nrfflag=repmat([1 0 0 0 0 0]',[1 max(size(rfTimeAll))]);\nGzflag=repmat([0 1 0 0 0 0]',[1 max(size(GzTimeAll))]);\nGyflag=repmat([0 0 1 0 0 0]',[1 max(size(GyTimeAll))]);\nGxflag=repmat([0 0 0 1 0 0]',[1 max(size(GxTimeAll))]);\nADCflag=repmat([0 0 0 0 1 0]',[1 max(size(ADCTimeAll))]);\nExtflag=repmat([0 0 0 0 0 1]',[1 max(size(ExtTimeAll))]);\nts=[[min(SEtAll) max(SEtAll)] rfTimeAll GzTimeAll GyTimeAll GxTimeAll ADCTimeAll ExtTimeAll]-min(SEtAll);\nflags=[SEflag rfflag Gzflag Gyflag Gxflag ADCflag Extflag];\n[ts,ind]=sort(ts);\nuts=unique(ts);\nflags=flags(:,ind);\n[rfTime,ind]=sort(rfTimeAll-min(SEtAll));\nrfAmp=rfAmpAll(:,ind);\nrfPhase=rfPhaseAll(:,ind);\nrfFreq=rfFreqAll(:,ind);\nrfCoil=rfCoilAll(:,ind);\n[GzTime,ind]=sort(GzTimeAll-min(SEtAll));\nGzAmp=GzAmpAll(:,ind);\n[GyTime,ind]=sort(GyTimeAll-min(SEtAll));\nGyAmp=GyAmpAll(:,ind);\n[GxTime,ind]=sort(GxTimeAll-min(SEtAll));\nGxAmp=GxAmpAll(:,ind);\n[ADCTime,ind]=sort(ADCTimeAll-min(SEtAll));\nADC=ADCAll(:,ind);\n[ExtTime,ind]=sort(ExtTimeAll-min(SEtAll));\nExt=ExtAll(:,ind);\nrfAmp(1) = 0;\nrfPhase(1) = 0;\nrfFreq(1) = 0;\nGzAmp(1) = 0;\nGyAmp(1) = 0;\nGxAmp(1) = 0;\nADC(1) = 0;\nExt(1) = 0;\nrfAmp(end) = 0;\nrfPhase(end) = 0;\nrfFreq(end) = 0;\nGzAmp(end) = 0;\nGyAmp(end) = 0;\nGxAmp(end) = 0;\nADC(end) = 0;\nExt(end) = 0;\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/PSD/3D/GradientEcho/PSD_GRE3DSpiral/PSD_GRE3DSpiral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.37022538564692026, "lm_q1q2_score": 0.2249723313948123}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%\n% Compute features for a set of video files from datasets\n% \nclose all; \nclear;\nwarning('off','all');\naddpath(genpath('./lib/iqm/FRIQUEE_feat_sel_release'));\n\n%% \n% parameters\nalgo_name = 'FRIQUEE_feat_sel'; \ndata_name = 'KONVID_1K'; \n\n%% *You need to customize here*\nif strcmp(data_name, 'TEST_VIDEOS')\n    data_path = 'videos'; % dataset video path\nelseif strcmp(data_name, 'KONVID_1K')\n    data_path = '/media/ztu/Seagate-ztu-ugc/KONVID_1K/KoNViD_1k_videos';\nelseif strcmp(data_name, 'LIVE_VQC')\n    data_path = '/media/ztu/Seagate-ztu-ugc/LIVE_VQC/VideoDatabase';\nelseif strcmp(data_name, 'YOUTUBE_UGC')\n    data_path = '/media/ztu/Seagate-ztu-ugc/YT_UGC/original_videos';\nelseif strcmp(data_name, 'LIVE_VQA')\n    data_path = '/media/ztu/Seagate-ztu/LIVE_VQA/videos';\nend\n\nvideo_tmp = 'video_tmp';\nif ~exist(video_tmp, 'dir'), mkdir(video_tmp); end\nfeat_path = '../features';\nfilelist_csv = fullfile(feat_path, [data_name,'_metadata.csv']);\nfilelist = readtable(filelist_csv);\nnum_videos = size(filelist,1);\nout_path = './feat_sel_mats';\nif ~exist(out_path, 'dir'), mkdir(out_path); end\nout_feat_name = fullfile(out_path, [data_name,'_',algo_name,'_feats.mat']);\nout_feat_frames_name = fullfile(out_path, [data_name,'_',algo_name,'_frames_feats.mat']);\nfeats_mat = [];\nfeats_mat_frames = cell( num_videos, 1 );\n%===================================================\n\ntic\nfor i = 1:num_videos\n\n    % get video full path and decoded video name\n\tif strcmp(data_name, 'TEST_VIDEOS')\n\t    video_name = fullfile(data_path,  filelist.video_name{i});\n\t    yuv_name = fullfile(video_tmp, [filelist.video_name{i}, '.yuv']);\n\telseif strcmp(data_name, 'KONVID_1K')\n\t    video_name = fullfile(data_path,  [num2str(filelist.flickr_id(i)),'.mp4']);\n\t    yuv_name = fullfile(video_tmp, [num2str(filelist.flickr_id(i)), '.yuv']);\n\telseif strcmp(data_name, 'LIVE_VQC')\n\t    video_name = fullfile(data_path, filelist.File{i});\n\t    yuv_name = fullfile(video_tmp, [filelist.File{i}, '.yuv']);\n\telseif strcmp(data_name, 'YOUTUBE_UGC')\n\t    video_name = fullfile(data_path, filelist.category{i},...\n\t\t[num2str(filelist.resolution(i)),'P'],[filelist.vid{i},'.mkv']);\n\t    yuv_name = fullfile(video_tmp, [filelist.vid{i}, '.yuv']);\n\telseif strcmp(data_name, 'LIVE_VQA')\n\t    strs = strsplit(filelist.filename{i}, '_');\n\t    video_name = fullfile(data_path, [strs{1}(1:2), '_Folder'], filelist.filename{i});\n\t    yuv_name = video_name;\n\tend\n\tfprintf('\\n---\\nComputing features for %d-th sequence: %s\\n', i, video_name);\n    if ~strcmp(video_name, yuv_name) \n    cmd = ['ffmpeg -loglevel error -y -i ', video_name, ' -pix_fmt yuv420p -vsync 0 ', yuv_name];\n    system(cmd);  \n    end\n\n    % get video meta data\n    width = filelist.width(i);\n    height = filelist.height(i);\n    framerate = round(filelist.framerate(i));\n    nb_frames = filelist.nb_frames(i);\n    \n    % read YUV frame (credit: Dae Yeol Lee)  \n    fp_input = fopen(yuv_name, 'r');\n    uv_width = width/2; \n    uv_height = height/2;\n    feats_frames = [];\n    \n    tic\n    for fr = 1:2:nb_frames-5\n%         fr % frame No. printer\n        \n        try\n            %% Start a file pointer\n            fseek(fp_input,(fr-1)*1.5*width*height, 'bof'); % Frame read for 8 bit\n            %% Y component \n            %1) read y stream\n            y_stream = fread(fp_input, width * height, 'uchar'); % for 8 bit\n            % 2) reshape into a plane\n            y_plane= reshape(y_stream, width, height).';\n            %% U component \n            %1) read u stream\n            u_stream = fread(fp_input, uv_width * uv_height, 'uchar'); % for 8 bit\n            % 2) reshape into a plane\n            u_plane= reshape(u_stream, uv_width, uv_height).';\n            %% V component \n            %1) read v stream\n            v_stream = fread(fp_input, uv_width * uv_height, 'uchar'); % for 8 bit\n            % 2) reshape into a plane\n            v_plane= reshape(v_stream, uv_width, uv_height).';\n            % yuv2rgb\n            u_plane = imresize(u_plane, size(y_plane), 'bicubic');\n            v_plane = imresize(v_plane, size(y_plane), 'bicubic');\n            rgb_plane = ycbcr2rgb(uint8(cat(3, y_plane, u_plane, v_plane)));\n                \n            % extract features\n%             tic\n            feat_tmp = extractFRIQUEEFeatures(rgb_plane);\n%             toc\n            feats_frames(end+1,:) = feat_tmp.friqueeALL;\n            \n        catch\n            continue\n        end\n        \n    end\n    fclose(fp_input);\n    delete(yuv_name)\n    feats_mat_frames{i} = feats_frames;\n    \n        % compute brisque mean and consistency within each 1-sec chunk!!\n    cons_feats = [];\n    mean_feats = [];\n    n_temp_vecs = length(feats_frames(:,1));\n    half_blk_len = floor(framerate/2);\n    \n    fprintf('Pooling mean and consistency features\\n');\n    \n    for j = 1:half_blk_len:n_temp_vecs - half_blk_len\n        \n        j_start = j; \n        j_end = j + half_blk_len;\n        \n        % compute consistency features\n        cons_feats = [cons_feats; std(feats_frames(j_start:j_end, :))];\n        mean_feats = [mean_feats; mean(feats_frames(j_start:j_end, :))];\n    end\n    \n    feats = [mean(mean_feats) ...\n             mean(cons_feats) ];\n         \n    feats_mat(i,:) = feats;\n    toc\nend\ntoc\nsave(out_feat_name, 'feats_mat');\nsave(out_feat_frames_name, 'feats_mat_frames');\n", "meta": {"author": "vztu", "repo": "VIDEVAL", "sha": "8a86166bb9a9c8fc5e5eac5db7a77771cf576947", "save_path": "github-repos/MATLAB/vztu-VIDEVAL", "path": "github-repos/MATLAB/vztu-VIDEVAL/VIDEVAL-8a86166bb9a9c8fc5e5eac5db7a77771cf576947/features/initial_feature_set/compute_friquee_features_for_feature_fusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.22496008359377326}}
{"text": "classdef OrientationUpdater < handle\n    \n    properties (GetAccess = public, SetAccess = protected)\n        alpha\n    end\n    \n    properties (Access = protected)\n        eigenVectors\n        eigenValues\n        optimalIndexOrientation\n    end\n    \n    methods (Access = public, Static)\n        \n        function obj = create(cParams)\n           f = OrientationUpdaterFactory();\n           obj = f.create(cParams);\n        end\n        \n    end\n    \n    methods (Access = public)\n           \n        function compute(obj,cParams)\n            obj.eigenVectors = cParams.pD;\n            obj.eigenValues  = cParams.pS;\n            obj.computeOptimalIndexOrientation();\n            obj.computeOrientation();\n        end\n        \n    end\n        \n    methods (Access = private)\n        \n        function computeOrientation(obj)\n            pD  = obj.eigenVectors;\n            ind = obj.optimalIndexOrientation;\n            isFirstOptimal  = ind == 1;\n            isSecondOptimal = ind == 2;\n            dir(:,isFirstOptimal)  = squeeze(pD(:,1,isFirstOptimal));\n            dir(:,isSecondOptimal) = squeeze(pD(:,2,isSecondOptimal));\n            obj.alpha = dir;\n        end\n        \n    end\n    \n    methods (Access = protected, Abstract)\n        computeOptimalIndexOrientation(obj)\n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/MinimizingOrientation/OrientationUpdater/OrientationUpdater.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22480642002378298}}
{"text": "function [GAH] = dicomrt_gahcal(VOI,gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,gahselect,xgrid)\n% dicomrt_gahcal(VOI,gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,gahselect,xgrid)\n%\n% Calculate GAMMA-AREA-HISTOGRAMS for VOIs and cell_case_study.\n% This function calculate GAHs for all the available VOIs or for a selected number of them.\n%\n% gamma contains the 3D gamma map\n% gamma_xmesh,gamma_ymesh,gamma_zmesh are x-y-z coordinates of the center of the gamma-voxels \n% VOIs is a cell array and contains all the Volumes of Interest\n% gahselect is an OPTIONAL parameter which contains the number of the VOI to calculate GAHs for.\n% xgrid is an OPTIONAL parameter that sets the resolution for GAH calculation (default = 30)\n%\n% GAHs are stored in a cell array with the following structure:\n%\n%  -------------------------------\n%  | [GAH-name] | [3D gamma mask] |\n%  |            -------------------\n%  |            | [gah section 1] |\n%  |            | [gah section 2] |\n%  |            |     ...         |\n%  |            | [gah section m] |\n%  |            -------------------\n%  |            | [info area 1]   |\n%  |            | [info area 2]   |\n%  |            |     ...         |  \n%  |            | [info area m]   |\n%  |            -------------------\n%  |            | Pixel area      | \n%  --------------------------------\n%\n% [gamma data] is a 2 columns vector with following structure:\n%\n% -----------------\n% | gamma | count |\n% -----------------\n% |       |       |\n% |       |       |\n% |       |       |\n% |       |       |\n% -----------------\n%\n% [info area] is a 2 columns vector with following structure:\n%\n% ---------------------------------\n% | area sec | z location section |\n% ---------------------------------\n%\n% Example:\n%\n% gah=dicomrt_gahcal(VOI,gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,4) returns \n% the GAH for the VOI number 4 in VOI and the gamma distribution stored in the \n% 3D matrix 'gamma'.\n%\n% See also dicomrt_gvhcal, dicomrt_gvhplot\n%           \n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument and set-up some parameters and variables\nerror(nargchk(5,7,nargin))\n\n% Check input parameters and set default parameter\nlist_variables=who;\nmatch=0;\n\n% Check voi\n[VOI_temp]=dicomrt_checkinput(VOI);\nVOI=dicomrt_varfilter(VOI_temp);\n\nif nargin==5 & (exist('gahselect')==1 | exist('xgrid')==1)\n    error('dicomrt_gahcal: Not enough input paramenters. Exit now!');\nend\n\nif exist('gahselect')~=1\n    gahselect=[1:1:size(VOI,1)];\nend\n\n% Check consistency for z values\nif gamma_zmesh(1)~=VOI{gahselect,2}{1}(1,3)\n    error(['dicomrt_gahcal: GAMMA map was not calculated for the selected voi (',VOI{gahselect,1},'). Exit now!']);\nend\n\n% Define xgrid\nif exist('xgrid')~=1\n    xgrid=[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.2 1.4 1.6 1.8 2.0 ...\n            3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 Inf];\nend\n\n% Define cell array\nGAH=cell(1,2);\nGAH{1,1}=['GAH-',VOI{gahselect,1}];\n\n% Notes on pixel area calculation\n% Although slice thickness may vary the pixel area is supposed to be the\n% same through all the volume. \npixelarea=(abs(gamma_xmesh(2)-gamma_xmesh(1)).*(abs(gamma_ymesh(2)-gamma_ymesh(1))));\n\n% start calculating time\ndisp(['GAH calculation for VOI: ',VOI{gahselect,1}]);\n% Initialise parameters\ncount=0; % count dimensions of gamma_section\ncount_empty=0; % count number of times gamma_section is not defined\n% mask gamma matrix with current VOI\n[mask_VOI,volume_VOI,mask4VOI]=dicomrt_mask(VOI_temp,gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,gahselect,'nan','n');\n% slice by slice select contents of mask_VOI ~=nan and put it into a vector for GAH calculation\n\nfor kk=1:size(mask_VOI{2,1},3)\n    xgrid_temp=xgrid;\n    agrid=histc(reshape(mask_VOI{2,1}(:,:,kk),1,size(mask_VOI{2,1},1)*size(mask_VOI{2,1},2)),xgrid_temp);\n    % get back voxels with dose<min(xgrid) cause histc does not\n    % account for it\n    temp_min=find(mask_VOI{2,1}(:,:,kk)<xgrid_temp(1) & mask_VOI{2,1}(:,:,kk)>0);\n    if isempty(temp_min)~=1\n        agrid(1)=agrid(1)+length(temp_min);\n    end\n    % Inf value will won't be plotted in the x grid. Therefore we\n    % collect all the Inf values in the last slot of xgrid/vgrid\n    agrid(end-1)=agrid(end-1)+agrid(end);\n    agrid(end)=[];\n    xgrid_temp(end)=[];\n    temp2=cumsum(agrid);\n    agrid=agrid.*pixelarea;\n    info_area=[temp2(end)*pixelarea VOI{gahselect,2}{kk}(1,3)];\n    gahdata=[xgrid_temp' agrid'];\n    % store data in cell array\n    GAH{1,2}{2,1}{kk}=gahdata;\n    GAH{1,2}{3,1}{kk}=info_area;\n    % plot frequency GAH\n    if isempty(agrid)~=1\n        figure;\n        if isempty(inputname(2))==1\n            set(gcf,'Name',['dicomrt_gahcal: ','fGAH for ',inputname(1)]);\n        else\n            set(gcf,'Name',['dicomrt_gahcal: ','fGAH for ',inputname(2)]);\n        end\n        agrid(end-1)=agrid(end-1)+agrid(end);\n        agrid(end)=[];\n        xgrid_temp(end)=[];\n        bar(xgrid_temp,agrid);\n        title([VOI{gahselect,1},' section: ',num2str(kk)],'Fontsize', 18,'Interpreter','none');\n        xlabel('\\gamma','Fontsize', 14);\n        ylabel('Area [cm^2]','Fontsize', 14);\n    else\n        warning(['dicomrt_gahcal: GAH is null for VOI: ',GAH{k,1},' section: ',num2str(kk)]);\n        gahdata=[0,0];\n        GAH{1,2}{2,1}{kk}=gahdata;\n    end\n    % store other data in cell array\n    GAH{1,2}{1,1}=mask_VOI{2,1};\n    GAH{1,2}{4,1}=pixelarea;\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/analysis/dicomrt_gahcal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.22478601050602487}}
{"text": "function [gKern, gVarmeans, gVarcovars] = rbfard2VardistPsi0Gradient(rbfard2Kern, vardist, covGrad)\n\n% RBFARD2VARDISTPSI0GRADIENT Description\n  \n% VARGPLVM\ngKern = zeros(1,rbfard2Kern.nParams); \ngKern(1) = covGrad*vardist.numData;\n \ngVarmeans = zeros(1,prod(size(vardist.means))); \ngVarcovars = zeros(1,prod(size(vardist.means))); \n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/rbfard2VardistPsi0Gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.22476999690478375}}
{"text": "classdef PTKAirwayGrowing < PTKPlugin\n    % PTKAirwayGrowing. Plugin for generating an artificial airway tree\n    %\n    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using \n    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.\n    %     See PTKPlugin.m for more information on how to run plugins.\n    %\n    %     Plugins should not be run directly from your code.\n    %\n    %\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n    %     Author: Tom Doel, 2012.  www.tomdoel.com\n    %     Distributed under the GNU GPL v3 licence. Please see website for details.\n    %\n    \n    properties\n        ButtonText = 'Volume filling<br> airways'\n        ToolTip = 'Grow the airways into the lobes'\n        Category = 'Airways'\n\n        AllowResultsToBeCached = true\n        AlwaysRunPlugin = false\n        PluginType = 'ReplaceOverlay'\n        HidePluginInDisplay = false\n        FlattenPreviewImage = true\n        PTKVersion = '1'\n        ButtonWidth = 6\n        ButtonHeight = 2\n        GeneratePreview = false\n        Visibility = 'Developer'\n    end\n    \n    methods (Static)\n        function results = RunPlugin(dataset, reporting)\n\n            left_and_right_lungs = dataset.GetResult('PTKLeftAndRightLungs');\n            lobes = dataset.GetResult('PTKLobes');\n                        \n            airways_by_lobe = dataset.GetResult('PTKReallocateAirwaysLabelledByLobe');\n            \n\n            upper_right_start_segment = airways_by_lobe.StartBranches.RightUpper;\n            middle_right_start_segment = airways_by_lobe.StartBranches.RightMid;\n            lower_right_start_segment = airways_by_lobe.StartBranches.RightLower;\n            upper_left_start_segment = airways_by_lobe.StartBranches.LeftUpper;\n            lower_left_start_segment = airways_by_lobe.StartBranches.LeftLower;\n            \n            right_lung = left_and_right_lungs.Copy;\n            right_lung.ChangeRawImage(left_and_right_lungs.RawImage == 1);\n\n            left_lung = left_and_right_lungs.Copy;\n            left_lung.ChangeRawImage(left_and_right_lungs.RawImage == 2);\n            \n            template = left_and_right_lungs.BlankCopy;\n            approx_number_points = 31000;\n            airway_generator = PTKAirwayGenerator(left_and_right_lungs, airways_by_lobe.StartBranches.Trachea, approx_number_points, reporting);\n            \n            \n            reporting.ShowProgress('RIGHT - upper');\n            reporting.UpdateProgressStage(0, 5);\n            lobes_fill = lobes.Copy;\n            lobes_fill.ChangeRawImage(lobes.RawImage == PTKColormapLabels.RightUpperLobe);\n            lobes_fill.CropToFit;\n            lobes_fill.AddBorder(2);\n            airway_generator.GrowTree(lobes_fill, upper_right_start_segment, reporting)\n            \n            reporting.ShowProgress('RIGHT - middle');\n            reporting.UpdateProgressStage(1, 5);\n            lobes_fill = lobes.Copy;\n            lobes_fill.ChangeRawImage(lobes.RawImage == PTKColormapLabels.RightMiddleLobe);\n            lobes_fill.CropToFit;\n            lobes_fill.AddBorder(2);\n            airway_generator.GrowTree(lobes_fill, middle_right_start_segment, reporting)\n            \n            reporting.ShowProgress('RIGHT - lower');\n            reporting.UpdateProgressStage(2, 5);\n            lobes_fill = lobes.Copy;\n            lobes_fill.ChangeRawImage(lobes.RawImage == PTKColormapLabels.RightLowerLobe);\n            lobes_fill.CropToFit;\n            lobes_fill.AddBorder(2);\n            airway_generator.GrowTree(lobes_fill, lower_right_start_segment, reporting)\n                                    \n            reporting.ShowProgress('LEFT - upper');\n            reporting.UpdateProgressStage(3, 5);\n            lobes_fill = lobes.Copy;\n            lobes_fill.ChangeRawImage(lobes.RawImage == PTKColormapLabels.LeftUpperLobe);\n            lobes_fill.CropToFit;\n            lobes_fill.AddBorder(2);\n            airway_generator.GrowTree(lobes_fill, upper_left_start_segment, reporting)\n            \n            reporting.ShowProgress('LEFT - lower');\n            reporting.UpdateProgressStage(4, 5);\n            lobes_fill = lobes.Copy;\n            lobes_fill.ChangeRawImage(lobes.RawImage == PTKColormapLabels.LeftLowerLobe);\n            lobes_fill.CropToFit;\n            lobes_fill.AddBorder(2);\n            airway_generator.GrowTree(lobes_fill, lower_left_start_segment, reporting)\n            \n            % Compute radius values based on Strahler orders\n            airway_generator.AirwayTree.ComputeStrahlerOrders;\n            \n%             airway_generator.AirwayTree.GenerateBranchParameters;\n            \n            % Add values of tissue density\n            density = dataset.GetResult('PTKDensityAverage');\n            airway_generator.AirwayTree.AddDensityValues(density.DensityAverage);            \n\n            results = [];\n            results.Airways = airway_generator.AirwayTree;\n            \n            count_terminal_points = results.Airways.CountTerminalBranches;\n            disp(['Number of terminal points: ' int2str(count_terminal_points)]);\n            \n            count_branches = results.Airways.CountBranches;\n            disp(['Number of branches: ' int2str(count_branches)]);\n\n            results.InitialImage = airway_generator.InitialApexImage;\n            if isempty(results.InitialImage)\n                results.InitialImage = zeros(template.ImageSize, 'uint8');\n            end\n\n        end\n        \n        function results = GenerateImageFromResults(airway_results, image_templates, reporting)\n            template_image = image_templates.GetTemplateImage(PTKContext.LungROI);\n\n            % Visualising the entire airway tree is Matlab is slow if the number\n            % of branches is greater than a few thousand\n            % PTKVisualiseAirwayGrowingTree(airway_results.Airways, reporting);\n\n            results = template_image;\n            results.ChangeRawImage(zeros(results.ImageSize, 'uint8'));\n            results = PTKDrawAirwayGrowingBranchesAsSegmentation(airway_results.Airways, template_image, reporting);\n        end\n        \n        \n    end\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Plugins/Airways/PTKAirwayGrowing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22476999083228258}}
{"text": "function computeAllModelChoice_STS(pathWORK,fSetNameType,outcome,freedomMat,maxOrder,nBoot)\n% -------------------------------------------------------------------------\n% function computeAllModelChoice_STS(pathWORK,fSetNameType,outcome,freedomMat,maxOrder,nBoot)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes feature set selection for a given feature set type \n% and for all experiments with different degrees of freedom. See ref. [1] \n% for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% - pathWORK: Full path to the STS WORKSPACE directory.\n% - fSetNameType: String specifying the name of the type of feature set \n%                 (e.g., 'PET', 'SEPARATE', 'FUSED', etc.)\n% - outcome: Column vector of size [nInst X 1] specifying the outcome status \n%            (1 or 0) for all instances.\n% - freedomMat:  Matrix of row vectors of 1's and 0's to specify the degree \n%                of freedom on texture extraction parameters for all \n%                experiments. For example, for an ith experiment where \n%                extraction parameters 1, 2 and 4 in paramAll are allowed \n%                to vary, use freedomMat(i,:) = [1,1,0,1].\n% - maxOrder: Integer specifying the maximal model order to construct.\n% - nBoot: Number of bootstrap samples to use.\n% -------------------------------------------------------------------------\n% OUTPUTS: Mutivariable models are saved in a folder named 'MODELS' in the \n%          STS WORKSPACE.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: May 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ncd([pathWORK,'/FSET']), pathFSET = pwd;\ncd([pathWORK,'/MODELS']), pathModels = pwd;\n\nnParamType = size(freedomMat,2);\nnFreedom = size(freedomMat,1);\ntStart = tic;\nfor i = 1:nFreedom\n    cd(pathFSET)\n    nameOpen=['FSET_',fSetNameType,'_'];\n    for j = 1:nParamType\n        nameOpen = [nameOpen,num2str(freedomMat(i,j))];\n    end\n    fSet = load(nameOpen); fSet = struct2cell(fSet); fSet = fSet{1};\n    fprintf(['SELECTING FEATURES (MODEL ORDERS OF 1 to % u) FOR ',nameOpen,' ... '],maxOrder)\n    tic\n    [models] = featureSelection_STS(fSet.Data,outcome,maxOrder,nBoot,fSet.Info,'IABR');\n    toc\n    cd(pathModels)\n    save(['MODELS',nameOpen(5:end)],'models')\nend\ntime = toc(tStart);\nfprintf('TOTAL TIME: %.2f seconds\\n',time)\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/STS_study/Functions/computeAllModelChoice_STS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22476471507003823}}
{"text": "classdef PTKWavefront < handle\n    % PTKWavefront. A data structure representing a segmented airway tree \n    %\n    %     PTKWavefront is used as part of the airway region growing process in \n    %     PTKAirwayRegionGrowingWithExplosionControl.\n    % \n    %     A root PTKTreeSegment is returned by \n    %     PTKAirwayRegionGrowingWithExplosionControl. From this you\n    %     can extract and analyse the resulting airway tree.\n    %\n    %     PTKTreeSegment is used in the construction and storage of\n    %     the airway trees. A PTKTreeSegment stores an individual\n    %     segment of the centreline tree, with references to the parent and child\n    %     PTKTreeSegments, so that it is possible to reconstruct the entire\n    %     tree from a single segment.\n    %\n    %     The way the airway voxels are stored in each segment is as follows:\n    %         The wavefront only exists during the region growing. It is a thick\n    %         layer of voxels which exists at the end of each segment\n    %         which is currently growing. If the wavefront forms more than one\n    %         connected component, the segment is ended and new child segments\n    %         formed from the wavefront components. When new voxels are added to\n    %         the front of the wavefront, old voxels from the back of the\n    %         wavefront are pushed out into the Pending voxels of the segment.\n    %         Pending voxels are 'accepted' or 'rejected' according to whether\n    %         the heuristics have determined an explosion has occurred.\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n    %     Author: Tom Doel, 2012.  www.tomdoel.com\n    %     Distributed under the GNU GPL v3 licence. Please see website for details.\n    %       \n        \n    properties (SetAccess = private)\n        CurrentBranch = []\n    end\n        \n    properties (Access = private)\n    \n        % The wavefront is a thick layer of voxels which is used to detect \n        % and process bifurcations in the airway tree before these voxels are\n        % added to the segement's list of pending indices\n        WavefrontVoxelIndices\n\n        % Additional voxels that were not originally part of the segment but \n        % were added later after a morphological closing operation\n        ClosedPoints\n\n        NumberOfVoxelsSkipped = 0\n                \n        WavefrontSize\n        PermittedVoxelSkips = 0\n        \n        MinimumDistanceBeforeBifurcatingMm\n        MinimumChildDistanceBeforeBifurcatingMm = 5\n        \n        FirstSegmentWavefrontSizeMm = 10\n        ChildWavefrontSizeMm = 5\n        VoxelSizeMm\n        MinCoords\n        MaxCoords\n        \n        % Generations greater than this are automatically terminated\n        MaximumNumberOfGenerations\n\n        MinimumNumberOfPointsThresholdMm3 = 6\n\n        ExplosionMultiplier = 7\n        \n    end\n    \n    methods\n        function obj = PTKWavefront(segment_parent, min_distance_before_bifurcating_mm, voxel_size_mm, maximum_generations, explosion_multiplier)\n            if nargin > 0\n                obj.WavefrontVoxelIndices = int32([]);\n\n                obj.MinimumDistanceBeforeBifurcatingMm = min_distance_before_bifurcating_mm;\n                max_voxel_size_mm = max(voxel_size_mm);\n                obj.VoxelSizeMm = voxel_size_mm;\n                obj.MaximumNumberOfGenerations = maximum_generations;\n                obj.ExplosionMultiplier = explosion_multiplier;\n                \n                voxel_volume = voxel_size_mm(1)*voxel_size_mm(2)*voxel_size_mm(3);\n                min_number_of_points_threshold = max(3, round(obj.MinimumNumberOfPointsThresholdMm3/voxel_volume));\n\n                if ~isempty(segment_parent)\n                    obj.WavefrontSize = ceil(obj.ChildWavefrontSizeMm/max_voxel_size_mm);\n                    obj.CurrentBranch = PTKTreeSegment(segment_parent, min_number_of_points_threshold, explosion_multiplier);\n                else\n                    obj.WavefrontSize = ceil(obj.FirstSegmentWavefrontSizeMm/max_voxel_size_mm);\n                    obj.CurrentBranch = PTKTreeSegment([], min_number_of_points_threshold, explosion_multiplier);\n                end\n            end\n        end\n\n        % Returns the very front layer of voxels at the wavefront\n        function frontmost_points = GetFrontmostWavefrontVoxels(obj)\n            frontmost_points = obj.WavefrontVoxelIndices{end}; \n        end\n        \n        % Returns the wavefront for this segment, which includes voxels that may\n        % be separated into child segments\n        function wavefront_voxels = GetWavefrontVoxels(obj)\n            wavefront_voxels = obj.ConcatenateVoxels(obj.WavefrontVoxelIndices);\n        end\n\n        % Add new voxels to this segment, and returns a list of all segments\n        % that require further processing (including this one, and any child\n        % segments which have been created as a result of bifurcations)\n        function segments_to_do = AddNewVoxelsAndGetNewSegments(obj, indices_of_new_points, image_size, reporting)\n            \n            % Check that indices are unique\n            if (numel(indices_of_new_points) ~= numel(unique(indices_of_new_points)))\n                reporting.Error('PTKWavefront:Duplicates', 'Algorithm error - some points have been duplicated');\n            end\n            \n            if any(ismember(indices_of_new_points, obj.CurrentBranch.GetAcceptedVoxels))\n                reporting.Error('PTKWavefront:Duplicates', 'Algorithm error - some points have been duplicated');\n            end\n                        \n            % First we move voxels at the rear of the wavefront into the\n            % PendingVoxels\n            if ~isempty(obj.WavefrontVoxelIndices)\n                while length(obj.WavefrontVoxelIndices) > obj.WavefrontSize\n                    obj.MoveVoxelsFromRearOfWavefrontToPendingVoxels;\n                end\n            end\n                        \n            % Next add the new points to the front of the wavefront\n            obj.WavefrontVoxelIndices{end + 1} = indices_of_new_points;\n\n            \n            % If an explosion has been detected then do not continue\n            if obj.CurrentBranch.MarkedExplosion\n                obj.MoveAllWavefrontVoxelsToPendingVoxels;\n%                 obj.DeleteSegmentIfNoAcceptedVoxels;\n                segments_to_do = PTKWavefront.empty; % This segment has been terminated\n                return\n            end\n            \n            obj.AdjustMaxAndMinForVoxels(indices_of_new_points, image_size);\n            \n            % Do not allow the segment to bifurcate until it is above a minimum\n            % length\n            if ~obj.MinimumLengthPassed\n                segments_to_do = obj; % This segment is to continue growing\n                return\n            end\n            \n            % Do not allow the segment to bifurcate until it is above a minimum size\n            if ~obj.WavefrontIsMinimumSize\n                segments_to_do = obj; % This segment is to continue growing\n                return\n            end\n            \n            % Determine whether to continue growing the current segment, or to\n            % split it into a new set of child segments\n            \n            % Find connected components from the wavefront (which is several voxels thick)\n            [offset, reduced_image, reduced_image_size] = MimImageCoordinateUtilities.GetMinimalImageForIndices(int32(obj.GetWavefrontVoxels)', image_size);\n            wavefront_connected_components = bwconncomp(reduced_image, 26);\n            number_of_components = wavefront_connected_components.NumObjects;\n            \n            % If there is only one component, it will be growing, so there is no\n            % need to do any further component analysis\n            if number_of_components == 1\n                segments_to_do = obj;\n                return;\n            end\n            \n            segments_to_do = PTKWavefront.empty;\n            growing_branches = [];\n            points_by_branches = [];\n            \n            % Iterate over the components and separate the wavefront voxels of\n            % the current segment into a new branch for each growing component\n            for component_number = 1 : wavefront_connected_components.NumObjects\n                \n                % Get voxel list, and adjust the indices to match those for the full image\n                indices_of_component_points = wavefront_connected_components.PixelIdxList{component_number};\n                indices_of_component_points = MimImageCoordinateUtilities.OffsetIndices(int32(indices_of_component_points), offset, reduced_image_size, image_size);\n                points_by_branches{component_number} = indices_of_component_points;\n                \n                still_growing = obj.IsThisComponentStillGrowing(indices_of_component_points);\n                if (still_growing)\n                    growing_branches(end + 1) = component_number;\n                end\n            end\n            \n            if length(growing_branches) < 1\n                reporting.Error('PTKWavefront:NoGrowingBranches', 'Algorithm error - no growing branches');\n            end\n            \n            if length(growing_branches) == 1\n                segments_to_do = obj;\n                return\n            end\n            \n            if length(growing_branches) > 1\n                \n                if ~isempty(obj.MaximumNumberOfGenerations)\n                    % If the maximum permitted number of generations is exceeded\n                    % then terminate this segment. This will discard any\n                    % remaining wavefront voxels and mark the segment as\n                    % incomplete (unless it is marked as exploded)\n                    if obj.CurrentBranch.GenerationNumber >= obj.MaximumNumberOfGenerations\n                        obj.CurrentBranch.EarlyTerminateBranch;\n                        return;\n                    end\n                end\n                \n                for index = 1 : length(growing_branches)\n                    segments_to_do(end + 1) = obj.SpawnChildFromWavefrontVoxels(points_by_branches{growing_branches(index)});\n                end\n                \n                % If the branch has divided, there may be some unaccepted points\n                % left over\n                obj.CompleteThisSegment;\n\n                if isempty(obj.CurrentBranch.GetAcceptedVoxels)\n                    reporting.ShowWarning('PTKWavefront:EmptyBranch', 'Algorithm error - no points in final branch');\n                end\n                \n            end\n\n        end\n        \n        \n        function CompleteThisSegment(obj)\n            obj.MoveAllWavefrontVoxelsToPendingVoxels;\n            obj.CurrentBranch.CompleteThisSegment\n        end\n    end\n        \n    methods (Access = private)\n        \n        function MoveAllWavefrontVoxelsToPendingVoxels(obj)\n            while ~isempty(obj.WavefrontVoxelIndices)                \n                obj.MoveVoxelsFromRearOfWavefrontToPendingVoxels;\n            end\n        end\n        \n        function MoveVoxelsFromRearOfWavefrontToPendingVoxels(obj)\n            % The wavefront may be empty after voxels have been divided\n            % amongst child branches\n            if ~isempty(obj.WavefrontVoxelIndices{1})\n                obj.CurrentBranch.AddPendingVoxels(obj.WavefrontVoxelIndices{1});\n            end\n            obj.WavefrontVoxelIndices(1) = [];\n        end\n\n        function AdjustMaxAndMinForVoxels(obj, voxel_indices, image_size)\n            [x, y, z] = ind2sub(image_size, voxel_indices);\n            mins = [min(x), min(y), min(z)];\n            maxs = [max(x), max(y), max(z)];\n            if isempty(obj.MinCoords)\n                obj.MinCoords = mins;\n                obj.MaxCoords = maxs;\n            else\n                obj.MinCoords = min(mins, obj.MinCoords);\n                obj.MaxCoords = max(maxs, obj.MaxCoords);\n            end\n        end\n\n        function is_minimum_size = WavefrontIsMinimumSize(obj)\n            is_minimum_size = (length(obj.WavefrontVoxelIndices) >= obj.WavefrontSize);\n        end\n        \n        function passed_minimum_lengths = MinimumLengthPassed(obj)\n            lengths = obj.MaxCoords - obj.MinCoords;\n            lengths = single(lengths).*obj.VoxelSizeMm;\n            max_length = max(lengths);\n            \n            passed_minimum_lengths = max_length >= obj.MinimumDistanceBeforeBifurcatingMm;\n        end\n\n        function new_segment = SpawnChildFromWavefrontVoxels(obj, voxel_indices)\n            wavefront_voxels = [];\n            for index = 1 : length(obj.WavefrontVoxelIndices)\n                wavefront_voxels{index} = intersect(int32(voxel_indices), obj.WavefrontVoxelIndices{index});\n                obj.WavefrontVoxelIndices{index} = setxor(wavefront_voxels{index}, obj.WavefrontVoxelIndices{index});\n            end\n            new_segment = PTKWavefront(obj.CurrentBranch, obj.MinimumChildDistanceBeforeBifurcatingMm, obj.VoxelSizeMm, obj.MaximumNumberOfGenerations, obj.ExplosionMultiplier);\n            new_segment.WavefrontVoxelIndices = wavefront_voxels;\n        end\n\n        function still_growing = IsThisComponentStillGrowing(obj, voxel_indices)\n            wavefront_voxels_end = intersect(int32(voxel_indices), obj.WavefrontVoxelIndices{end});\n            still_growing = ~isempty(wavefront_voxels_end);            \n        end\n        \n    end\n    \n    methods (Static, Access = private)\n        function concatenated_voxels = ConcatenateVoxels(voxels)\n            concatenated_voxels = [];\n            number_layers = length(voxels);\n            for index = 1 : number_layers\n                next_voxels = voxels{index};\n                if ~isempty(next_voxels)\n                    concatenated_voxels = cat(1, concatenated_voxels, next_voxels);\n                end\n            end\n        end\n    end\nend\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Airways/PTKWavefront.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.22476390108236005}}
{"text": "%RRT Class for rapidly-exploring random tree navigation\n%\n% A concrete subclass of the abstract Navigation class that implements the rapidly\n% exploring random tree (RRT) algorithm.  This is a kinodynamic planner\n% that takes into account the motion constraints of the vehicle.\n%\n% Methods::\n%  RRT          Constructor\n%  plan         Compute the tree\n%  query        Compute a path \n%  plot         Display the tree\n%  display      Display the parameters in human readable form\n%  char         Convert to string\n%\n% Properties (read only)::\n%  graph        A PGraph object describign the tree\n%\n% Example::\n%        goal = [0,0,0];\n%        start = [0,2,0];\n%        veh = Bicycle('steermax', 1.2);\n%        rrt = RRT(veh, 'goal', goal, 'range', 5);\n%        rrt.plan()             % create navigation tree\n%        rrt.query(start, goal)  % animate path from this start location\n%\n% References::\n% - Randomized kinodynamic planning,\n%   S. LaValle and J. Kuffner, \n%   International Journal of Robotics Research vol. 20, pp. 378-400, May 2001.\n% - Probabilistic roadmaps for path planning in high dimensional configuration spaces,\n%   L. Kavraki, P. Svestka, J. Latombe, and M. Overmars, \n%   IEEE Transactions on Robotics and Automation, vol. 12, pp. 566-580, Aug 1996.\n% - Robotics, Vision & Control, Section 5.2.5,\n%   P. Corke, Springer 2011.\n%\n% See also Navigation, PRM, DXform, Dstar, PGraph.\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n% Peter Corke 8/2009.\n\n%TODO\n%   more info to the display method\n%   distance metric choice or weightings\n%   pass time and model options to the simulation\n\nclassdef RRT < Navigation\n\n    properties\n        npoints         % number of points to find\n        graph           % graph Object representing random nodes\n\n        simtime         % path simulation time\n\n        xrange          % range of x coordinates\n        yrange          % range of y coordinates\n        \n        speed           % speed of vehicle\n        vehicle         % Vehicle class object describes kinematics\n        \n        revcost         % penalty for going backwards\n        \n        root            % coordinate of the root of the tree (3x1)\n    end\n\n    methods\n\n        function rrt = RRT(vehicle, varargin)\n        %RRT.RRT Create an RRT navigation object\n        %\n        % R = RRT.RRT(VEH, OPTIONS) is a rapidly exploring tree navigation\n        % object  for a vehicle kinematic model given by a Vehicle subclass object VEH.\n        %\n        % R = RRT.RRT(VEH, MAP, OPTIONS) as above but for a region with obstacles\n        % defined by the occupancy grid MAP.\n        %\n        % Options::\n        % 'npoints',N    Number of nodes in the tree (default 500)\n        % 'simtime',T    Interval over which to simulate kinematic model toward \n        %                random point (default 0.5s)\n        % 'goal',P       Goal position (1x2) or pose (1x3) in workspace\n        % 'speed',S      Speed of vehicle [m/s] (default 1)\n        % 'root',R       Configuration of tree root (3x1) (default [0,0,0])\n        % 'revcost',C    Cost penalty for going backwards (default 1)\n        % 'range',R      Specify rectangular bounds of robot's workspace:\n        %                - R scalar; X: -R to +R, Y: -R to +R\n        %                - R (1x2); X: -R(1) to +R(1), Y: -R(2) to +R(2)\n        %                - R (1x4); X: R(1) to R(2), Y: R(3) to R(4)\n        %\n        % Other options are provided by the Navigation superclass.\n        %\n        % Notes::\n        % - 'range' option is ignored if an occupacy grid is provided.\n        %\n        % Reference::\n        % - Robotics, Vision & Control\n        %   Peter Corke, Springer 2011.  p102.\n        %\n        % See also Vehicle, Bicycle, Unicycle.\n\n            % invoke the superclass constructor, it handles some options\n            rrt = rrt@Navigation(varargin{:});\n\n            rrt.vehicle = vehicle;\n\n            % handle the options not done by Navigation superclass\n            opt.npoints = 500;\n            opt.simtime = 0.5;\n            opt.speed = vehicle.speedmax;\n            opt.revcost = 1;\n            opt.root = [0 0 0];\n            \n            [rrt,args] = tb_optparse(opt, varargin, rrt);\n            \n            if isempty(rrt.occgrid)\n                opt = [];\n                opt.range = 5;\n                [opt,args] = tb_optparse(opt, args);\n                \n                % range can be specified as scalar, min/max, different min/max per\n                % direction\n                switch length(opt.range)\n                    case 1\n                        rrt.xrange = [-opt.range opt.range];\n                        rrt.yrange = [-opt.range opt.range];\n                    case 2\n                        rrt.xrange = [-opt.range(1) opt.range(1)];\n                        rrt.yrange = [-opt.range(2) opt.range(2)];\n                    case 4\n                        rrt.xrange = [opt.range(1) opt.range(2)];\n                        rrt.yrange = [opt.range(3) opt.range(4)];\n                    otherwise\n                        error('bad range specified');\n                end\n            else\n                rrt.xrange = [1 numcols(rrt.occgrid)];\n                rrt.yrange = [1 numrows(rrt.occgrid)];\n            end\n\n            rrt.graph = PGraph(3, 'distance', 'SE2', ...\n                'dweight', 2*pi/norm(sum([rrt.xrange; rrt.yrange])) );  % graph of points in SE(2)\n\n        end\n\n        function plan(rrt, varargin)\n        %RRT.plan Create a rapidly exploring tree\n        %\n        % R.plan(OPTIONS) creates the tree roadmap by driving the vehicle\n        % model toward random goal points.  The resulting graph is kept\n        % within the object.\n        %\n        % Options::\n        % 'goal',P        Goal pose (1x3)\n        % 'ntrials',N     Number of path trials (default 50)\n        % 'noprogress'    Don't show the progress bar\n        % 'samples'       Show progress in a plot of the workspace\n        %                 - '.' for each random point x_rand\n        %                 - 'o' for the nearest point which is added to the tree\n        %                 - red line for the best path\n        %\n        % Notes::\n        % - At each iteration we need to find a vehicle path/control that moves it\n        %   from a random point towards a point on the graph.  We sample ntrials of\n        %   random steer angles and velocities and choose the one that gets us\n        %   closest (computationally slow, since each path has to be integrated\n        %   over time).\n\n            opt.progress = true;\n            opt.samples = false;\n            opt.goal = [];\n            opt.ntrials = 50;\n            \n            opt = tb_optparse(opt, varargin);\n\n            if ~isempty(opt.goal)\n                rrt.goal = opt.goal;\n            end\n\n            % build a graph over the free space\n            rrt.message('create the graph');\n            rrt.graph.clear();\n\n            if rrt.verbose\n                clf\n                %idisp(1-rrt.occgrid, 'ynormal', 'nogui');\n                hold on\n            end\n\n            % check root node sanity\n            if isempty(rrt.root)\n                error('no root node specified');\n            end\n            if ~isvec(rrt.root, 3)\n                error('root must be 3-vector');\n            end\n            assert( ~rrt.isoccupied(rrt.root(1:2)), 'root node cell is occupied')\n\n            % add the goal point as the first node\n            vroot = rrt.graph.add_node(rrt.root);\n            data.vel = 0;\n            data.path = [];\n            rrt.graph.setvdata(vroot, data);\n\n            % graphics setup\n            if opt.progress\n                h = Navigation.progress_init('RRT planning...');\n            end\n            if opt.samples\n                clf\n                hold on\n                xlabel('x'); ylabel('y');\n            end\n\n            npoints = 0;\n            while npoints < rrt.npoints       % build the tree\n\n                % Step 3\n                % find random state x,y\n\n                % pick a point not in obstacle\n                while true\n                    xy = rrt.randxy();  % get random coordinate (x,y)\n                    \n                    if isempty(rrt.occgrid)\n                        break\n                    else\n                        % we have an occgrid\n                        xy = round( xy );  % round it to a grid cell coordinate\n                        \n                        % test if lies in the obstacle map\n                        try\n                            if ~rrt.isoccupied(xy)\n                                break;\n                            end\n                        catch\n                            % index error, point must be off the map\n                            continue;\n                        end\n                    end\n                end\n                theta = rrt.rand*2*pi;\n                xrand = [xy, theta]';\n                if opt.samples\n                    plot(xy(1), xy(2), '.')\n                end\n\n                % Step 4\n                % find the existing node closest in state space\n\n                vnear = rrt.graph.closest(xrand);   % nearest vertex\n                xnear = rrt.graph.coord(vnear);     % coord of nearest vertex\n%                 if rrt.graph.distance_metric(xnear, xrand) < 0.25\n%                     continue;\n%                 end\n\n                rrt.message('xrand (%g, %g) node %d', xy, vnear);\n\n                % Step 5\n                % figure how to drive the robot from xnear to xrand\n                                \n                best = rrt.bestpath(xnear, xrand, opt.ntrials);\n                \n                xnew = best.path(:,best.k);\n                if opt.samples\n                    plot(xnew(1), xnew(2), 'o');\n                    plot2(best.path', 'r');\n                    drawnow\n                end\n\n%                 % ensure that the path is collision free\n%                 if ~rrt.clearpath(y(:,1:2))\n%                     disp('path collision');\n%                     continue;\n%                 end\n\n                % Step 7,8\n                % add xnew to the graph, with an edge from xnear\n                vnew = rrt.graph.add_node(xnew);\n                \n\n                if rrt.graph.vdata(vnear).vel * best.vel < 0\n                    % we changed direction, penalise that\n                    cost = rrt.revcost;\n                else\n                    cost = 1;\n                end\n                rrt.graph.add_edge(vnear, vnew, cost);\n                \n                rrt.graph.setvdata(vnew, best);\n                \n                npoints = npoints + 1;\n                if opt.progress\n                    Navigation.progress(h, npoints / rrt.npoints);\n                end\n                \n            end\n\n            if opt.progress\n                Navigation.progress_delete(h)\n            end\n            rrt.message('graph create done');\n        end\n\n        function p_ = query(rrt, xstart, xgoal)\n        %RRT.query Find a path between two points\n        %\n        % X = R.path(START, GOAL) finds a path (Nx3) from pose START (1x3) \n        % to pose GOAL (1x3).  The pose is expressed as [X,Y,THETA]. \n        %\n        % R.path(START, GOAL) as above but plots the path in 3D, where the vertical\n        % axis is vehicle heading angle.  The nodes are shown as circles and the\n        % line segments are blue for forward motion and red for backward motion.\n        %\n        % Notes::\n        % - The path starts at the vertex closest to the START state, and ends\n        %   at the vertex closest to the GOAL state.  If the tree is sparse this\n        %   might be a poor approximation to the desired start and end.\n        %\n        % See also RRT.plot.\n\n            assert(rrt.graph.n > 0, 'RTB:RRT: there is no plan');\n            rrt.checkquery(xstart, xgoal);\n            \n            g = rrt.graph;\n            vstart = g.closest(xstart);\n            vgoal = g.closest(xgoal);\n\n            % find path through the graph using A* search\n            [path,cost] = g.Astar(vstart, vgoal);\n            \n            fprintf('A* path cost %g\\n', cost);\n          \n            % concatenate the vehicle motion segments\n            cpath = [];\n            for i = 1:length(path)\n                p = path(i);\n                data = g.vdata(p);\n                if ~isempty(data)\n                    if i >= length(path) || g.edgedir(p, path(i+1)) > 0\n                        cpath = [cpath data.path];\n                    else\n                        cpath = [cpath data.path(:,end:-1:1)];\n                    end\n                end\n            end\n\n            if nargout == 0\n                % plot the path\n                clf; hold on\n\n                plot2(g.coord(path)', 'o');     % plot the node coordinates\n                \n                for i = 1:length(path)\n                    p = path(i);\n                    b = g.vdata(p);            % get path data for segment\n                    \n                    % draw segment with direction dependent color\n                    if ~isempty(b)\n                        % if the vertex has a path leading to it\n                        \n                        if i >= length(path) || g.edgedir(p, path(i+1)) > 0\n                            % positive edge\n                            %  draw from prev vertex to end of path\n                            seg = [g.coord(path(i-1)) b.path]';\n                        else\n                            % negative edge\n                            %  draw reverse path to next next vertex\n                            seg = [  b.path(:,end:-1:1)  g.coord(path(i+1))]';\n                        end\n                        \n                        if b.vel > 0\n                            plot2(seg, 'b');\n                        else\n                            plot2(seg, 'r');\n                        end\n                    end\n                end\n\n                xlabel('x'); ylabel('y'); zlabel('\\theta');\n                grid\n            else\n                p_ = cpath';\n            end\n        end\n\n        function plot(rrt, varargin)\n        %RRT.plot Visualize navigation environment\n        %\n        % R.plot() displays the navigation tree in 3D, where the vertical axis is\n        % vehicle heading angle.  If an occupancy grid was provided this is also\n        % displayed.\n\n\n            % display the occgrid background\n            rrt.plot_bg(varargin{:});\n            \n            % display the graph\n            %rrt.graph.plot('noedges', 'NodeSize', 3, 'NodeFaceColor', 'm', 'NodeEdgeColor', 'm', 'edges');\n            \n            rrt.graph.plot('noedges', 'nocomponentcolor', 'NodeSize', 3, 'NodeFaceColor', 'b', 'NodeEdgeColor', 'b', 'edges');\nhold on\n            \n            % display the occgrid background\n            rrt.plot_fg(varargin{:});\n            axis([rrt.xrange rrt.yrange])\n            xlabel('x'); ylabel('y'); zlabel('\\theta');\n            grid on; hold off\n            view(0,90);\n            axis equal\n            rotate3d\n        end\n\n        % required by abstract superclass\n        function next(rrt)\n        end\n\n        function s = char(rrt)\n        %RRT.char  Convert to string\n        %\n        % R.char() is a string representing the state of the RRT\n        % object in human-readable form.\n        %\n        \n            % invoke the superclass char() method\n            s = char@Navigation(rrt);\n\n            % add RRT specific stuff information\n            s = char(s, sprintf('  region: X %f : %f; Y %f : %f', rrt.xrange, rrt.yrange));\n            s = char(s, sprintf('  sim time: %f', rrt.simtime));\n            s = char(s, sprintf('  speed: %f', rrt.speed));\n            s = char(s, sprintf(' Graph:'));\n            s = char(s, char(rrt.graph) );\n            if ~isempty(rrt.vehicle)\n                s = char(s, char(rrt.vehicle) );\n            end\n        end\n        \n\n    end % methods\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%    P R I V A T E    M E T H O D S\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    methods (Access='protected')\n\n        function best = bestpath(rrt, x0, xg, N)\n\n            % initial and final state as column vectors\n            x0 = x0(:); xg = xg(:);\n\n            best.d = Inf;\n            for i=1:N   % for multiple trials \n            \n                %choose random direction of motion and random steer angle\n                if rand > 0.5\n                    vel = rrt.speed;\n                else\n                    vel = -rrt.speed;\n                end\n                steer = (2*rrt.rand - 1) * rrt.vehicle.steermax;    % uniformly distributed\n                \n                % simulate motion of vehicle for this speed and steer angle which \n                % results in a path\n                x = rrt.vehicle.run2(rrt.simtime, x0, vel, steer)';\n                \n                %% find point on the path closest to xg\n                % distance of all path points from goal\n                d = colnorm( [bsxfun(@minus, x(1:2,:), xg(1:2)); angdiff(x(3,:), xg(3))] );\n                % the closest one\n                [dmin,k] = min(d);\n                \n                % is it the best so far?\n                if dmin < best.d\n                    % yes it is!  save it and the inputs that led to it\n                    best.d = dmin;\n                    best.path = x;\n                    best.steer = steer;\n                    best.vel = vel;\n                    best.k = k;\n                end\n            end \n        end \n\n        % generate a random coordinate within the working region\n        function xy = randxy(rrt)\n            xy = rrt.rand(1,2) .* [rrt.xrange(2)-rrt.xrange(1) rrt.yrange(2)-rrt.yrange(1)] + ...\n                [rrt.xrange(1) rrt.yrange(1)];\n        end\n\n        % test if a path is obstacle free\n        function c = clearpath(rrt, xy)\n            if isempty(rrt.occgrid)\n                c = true;\n                return;\n            end\n\n            xy = round(xy);\n            try\n                % test that all points along the path do not lie within an obstacle\n                for pp=xy'\n                    if rrt.isoccupied(pp) > 0\n                        c = false;\n                        return;\n                    end\n                end\n                c = true;\n            catch\n                % come here if we index out of bounds\n                c = false;\n                return;\n            end\n        end\n\n\n    end % private methods\nend % class\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/RRT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3629692193015556, "lm_q1q2_score": 0.22459825095508323}}
{"text": "laststream_range = 1+mod(laststream.smax:laststream.smax+size(laststream_chunk_clr,2)-1,laststream.buffer_len);\nlaststream.marker_pos(:,laststream_range) = 0;\nlaststream.buffer(:,laststream_range) = laststream_chunk_clr;\nlaststream.smax = laststream.smax + size(laststream_chunk_clr,2);", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/temp/update__laststream_chunk_clr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22450508185939286}}
{"text": "function res= experiment_run(exp,net)\n\nnet.cnn_id = exp.model;\nswitch net.cnn_mode\ncase 0 % matconvnet\n    exp.opts.normalize = get_cnn_normalize(net.normalization) ;\n    exp.opts.denormalize = get_cnn_denormalize(net.normalization) ;\ncase 1\n    switch exp.model\n    case {'alex','nin','gnet'} % alexnet, nin, inception\n        d = load('data/ilsvrc_2012_mean.mat');\n        mm = d.image_mean;\n    case 'vgg16' % vgg\n        mm = repmat(reshape([103.939, 116.779, 123.68],[1,1,3]),[256 256]);\n    case 'alexWeb'\n        mm = repmat(reshape([0.8309, 0.8310, 0.8328],[1,1,3]),[256 256]);\n    end \n    net.normalization=struct('imageSize',[net.im_sz net.im_sz 3],'averageImage',mm);\n    exp.opts.normalize = @(x) U_prepare_image(x, mm,exp.model,-2);\n    exp.opts.denormalize = @(x) U_prepare_image(x, mm,exp.model,-1);\nend\n\nnet.task = exp.opts.task;\nswitch exp.opts.task\ncase {1,2}\n    % 1: neuron inversion\n    % 2: neuron inpainting\n    res = invert_nn_dw(net, exp.opts.mask, exp.opts) ;\ncase 0\n    % feature inversion\n    % same as deep-goggle\n    if ischar(exp.opts.feats)\n        im = single(imread(exp.opts.feats));\n        if size(im,3) == 1, im = cat(3,im,im,im) ; end\n        exp.opts.feats = compute_features(net, exp.opts.normalize(im),0);\n        %keyboard\n    end\n    % gradient-descent\n    net.feats = exp.opts.feats;\n    res = invert_nn_dw(net, exp.opts.feats, exp.opts) ;\nend\n\n\nend\nfunction args = expandOpts(opts)\n% -------------------------------------------------------------------------\nargs = horzcat(fieldnames(opts), struct2cell(opts))' ;\nend\n\n\n", "meta": {"author": "donglaiw", "repo": "mNeuron", "sha": "fa8053693a4a0ef3193483c405248db5eedbb665", "save_path": "github-repos/MATLAB/donglaiw-mNeuron", "path": "github-repos/MATLAB/donglaiw-mNeuron/mNeuron-fa8053693a4a0ef3193483c405248db5eedbb665/deep-goggle2/experiment_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22450508185939286}}
{"text": "%% =======================================================================\n%  Start Here Script\n%  =======================================================================\n%  \n%  This script guides the user through examples of both simulations and\n%  Wi-Fi control models for the Parrot ARDrone.\n%  Authors:\n%       David Escobar Sanabria -> descobar@aem.umn.edu\n%       Pieter J. Mosterman -> pieter.mosterman@mathworks.com\n%  =======================================================================\n\n%%\n%  Cleaning workspace\nbdclose all;\nclear all;\nbdclose all;\nclc\n\n%%\ndisp('This script guides the user through examples of both simulations and');\ndisp('Wi-Fi control Simulink models for the Parrot ARDrone ');\ndisp(' '); \n\ndisp('Swlect one of the following options:'); \ndisp('    (1) Simulation'); \ndisp('    (2) Wi-Fi control. The computer shoud be connected to the drone'); \n\noption = input('');\n\n\n%%\nswitch option\n    case 1\n        \n        disp('Swlect one of the following options for simulation:'); \n        disp('    (1) Baseline simulation: The ARDrone block with inputs and scopes to visualize outputs'); \n        disp('    (2) Hover: Vehicle is held at constant position'); \n        disp('    (3) Waypoint tracking: Vehicle tracks a list of waypoints'); \n        option2 = input(' ');\n        \n        switch option2\n            case 1\n                cd simulation; \n                setupBaseModel; \n            case 2\n                cd simulation; \n                setupHoverSim; \n            case 3\n                cd simulation; \n                setupWPTrackingSim;\n            otherwise\n                disp('An incorrect option was selected')\n                \n        end\n        \n        \n    case 2\n        disp('Swlect one of the following options for Wi-Fi control:'); \n        disp('    (1) Hover: Vehicle is held at constant position'); \n        disp('    (2) Waypoint tracking: Vehicle tracks a list of waypoints'); \n        option2 = input(' ');\n        \n        switch option2\n            case 1\n                cd wifiControl; \n                setupHover; \n                % Building model using RTWT. Install rtwt if not installed \n                % using 'rtwintgt -setup'\n                rtwbuild('ARDroneHover');\n            case 2\n                cd wifiControl; \n                setupWPTracking;  \n                % Building model using RTWT. Install rtwt if not installed \n                % using 'rtwintgt -setup'\n                rtwbuild('ARDroneWPTracking');\n            otherwise\n                disp('An incorrect option was selected')\n        end\n        \n    otherwise\n       disp('An incorrect option was selected')\n\nend\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43719-ar-drone-simulink-development-kit-v1/ARDroneSimulinkDevKit_V1/start_here.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22443842230715266}}
{"text": "function info = cnn_imagenet_evaluate(varargin)\n% CNN_IMAGENET_EVALUATE   Evauate MatConvNet models on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n  '..', '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data', 'ILSVRC2012') ;\nopts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;\nopts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.networkType = [] ;\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 128 ;\nopts.train.numEpochs = 1 ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.expDir = opts.expDir ;\n\nopts = vl_argparse(opts, varargin) ;\ndisplay(opts);\n\n% -------------------------------------------------------------------------\n%                                                   Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n  imdb = load(opts.imdbPath) ;\nelse\n  imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n  mkdir(opts.expDir) ;\n  save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n%                                                    Network initialization\n% -------------------------------------------------------------------------\n\nnet = load(opts.modelPath) ;\nif isfield(net, 'net') ;\n  net = net.net ;\nend\n% Cannot use isa('dagnn.DagNN') because it is not an object yet\nisDag = isfield(net, 'params') ;\n\nif isDag\n  opts.networkType = 'dagnn' ;\n  net = dagnn.DagNN.loadobj(net) ;\n  trainfn = @cnn_train_dag ;\n\n  % Drop existing loss layers\n  drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;\n  for n = {net.layers(drop).name}\n    net.removeLayer(n) ;\n  end\n\n  % Extract raw predictions from softmax\n  sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;\n  predVar = 'prediction' ;\n  for n = {net.layers(sftmx).name}\n    % check if output\n    l = net.getLayerIndex(n) ;\n    v = net.getVarIndex(net.layers(l).outputs{1}) ;\n    if net.vars(v).fanout == 0\n      % remove this layer and update prediction variable\n      predVar = net.layers(l).inputs{1} ;\n      net.removeLayer(n) ;\n    end\n  end\n\n  % Add custom objective and loss layers on top of raw predictions\n  net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...\n               {predVar,'label'}, 'objective') ;\n  net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...\n               {predVar,'label'}, 'top1err') ;\n  net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...\n                                     'opts', {'topK',5}), ...\n               {predVar,'label'}, 'top5err') ;\n\n  % Make sure that the input is called 'input'\n  v = net.getVarIndex('data') ;\n  if ~isnan(v)\n    net.renameVar('data', 'input') ;\n  end\n\n  % Swtich to test mode\n  net.mode = 'test' ;\nelse\n  opts.networkType = 'simplenn' ;\n  net = vl_simplenn_tidy(net) ;\n  trainfn = @cnn_train ;\n  net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss\nend\n\n% Synchronize label indexes used in IMDB with the ones used in NET\nimdb = cnn_imagenet_sync_labels(imdb, net);\n\n% Run evaluation\n[net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...\n                      opts.train, ...\n                      'train', NaN, ...\n                      'val', find(imdb.images.set==2)) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchFn(opts, meta)\n% -------------------------------------------------------------------------\nuseGpu = numel(opts.train.gpus) > 0 ;\nbopts = meta.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\n\n% Most networks are trained by resizing images to 256 pixels and then\n% cropping a slightly smaller subarea. Reproduce this effect (center\n% crop) for a more accurate evaluation (it also avoids resizing the\n% images if these have been pre-processed to be of this size, which\n% accelerates everything).\n\nbopts.border = 256 - meta.normalization.imageSize ;\n\nswitch lower(opts.networkType)\n  case 'simplenn'\n    fn = @(x,y) getSimpleNNBatch(bopts,x,y) ;\n  case 'dagnn'\n    fn = @(x,y) getDagNNBatch(bopts,useGpu,x,y) ;\nend\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getSimpleNNBatch(opts, imdb, batch)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n                            'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction inputs = getDagNNBatch(opts, useGpu, imdb, batch)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n                            'prefetch', nargout == 0) ;\nif nargout > 0\n  if useGpu\n    im = gpuArray(im) ;\n  end\n  inputs = {'input', im, 'label', imdb.images.label(batch)} ;\nend\n", "meta": {"author": "jiangqy", "repo": "DCMH-CVPR2017", "sha": "67d0e84c0425fdac3fad30d67d5a2beb5e345cea", "save_path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017", "path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017/DCMH-CVPR2017-67d0e84c0425fdac3fad30d67d5a2beb5e345cea/DCMH_matlab/DCMH_matlab/matconvnet/examples/imagenet_read_code/cnn_imagenet_evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22442510359853268}}
{"text": "function subaperturedemo(varargin)\n%SUBAPERTUREDEMO Read image, generate, and view subaperture-processed image using MATLAB GUIs.\n%    subaperturedemo('PropertyName',PropertyValue,...)\n%\n% Calculates the subaperture-processed image of a complex image (selected\n% through a MATLAB dialog box) using the properties specified. The AOI over\n% which to compute the subaperture-processed image is selected through a MATLAB\n% GUI. This version of subaperture processing does NOT require that the complete\n% data fit into memory. It processes from any format handled by OPEN_READER and\n% outputs to files in SIO format.\n%\n%       Property name     Description\n%       frames            number of frames (default = 7)\n%       apfraction        fraction of aperture for each subaperture\n%                            (default = .25)\n%       method            'normal' (default), 'fullpixel', or 'minimal'\n%       platformdir       platform direction, 'right' (default) or 'left'\n%       dim               dimension over which to split subaperture\n%                            (default = 1)\n%       fill              fill factor\n%\n% Output frames are stored in one frame per file, where the first frame has\n% the filename OUTFILE, and each consecutive frame has the frame number\n% appended onto the filename.\n%\n% Written by: Wade Schwartzkopf, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\ndemo_core(@subaperturefile, varargin{:});\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Processing/subaperture/subaperturedemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22442510359853265}}
{"text": "classdef EventRate\n%EventRate Event Rate class constructor.\n% \n%    EventRate is a class that has been developed around plotting earthquake\n%    counts - i.e. the rate of events per unit time. It has evolved to compute\n%    other metrics such the hourly mean event rate, median event rate, mean \n%    magnitude and cumulative magnitude, which are important metrics for an AVO\n%    swarm tracking system.\n%\n%    EventRate can import information from:\n%    (1) a Catalog object. \n%    (2) a Datascope database written in the \"swarms1.0\" schema, defined at AVO. \n%        This is the format used by the swarm tracking system (Thompson &\n%        West, 2010).\n%\n%    ER = EventRate(Catalog_OBJECT, 'binsize', BINSIZE) creates an eventrate object\n%    from a Catalog object using non-overlapping bins of BINSIZE days. \n%\n%    ER = EventRate(Catalog_OBJECT, 'binsize', BINSIZE, 'stepsize', STEPSIZE) creates an eventrate object\n%    using overlapping bins. If omitted STEPSIZE==BINSIZE.\n%\n%%   EXAMPLES:\n%\n%       First create a catalog object from the demo database:\n%           dbpath = demodb('avo')\n%           catalogObject = readEvents('datascope', 'dbpath', dbpath, ...\n%                  'dbeval', ...\n%                  'deg2km(distance(lat, lon, 60.4853, -152.7431))<15.0' ...\n%                  );\n%\n%       (1) Create an eventrate object using a binsize of 1 day:\n%           erobj = catalogObject.eventrate('binsize', 1);\n%\n%       (2) Create an eventrate object using a binsize of 1 hour:\n%           erobj = catalogObject.eventrate('binsize', 1/24);\n%\n%       (3) Create an eventrate object using a binsize of 1 hour but a stepsize of 5 minutes:\n%           erobj = catalogObject.eventrate('binsize', 1/24, 'stepsize', 5/1440);\n%\n%%   PROPERTIES\n%\n%    For a list of all properties type properties(EventRate)\n%\n%    time                % (array) time of the center of each bin as a DATENUM\n%\n%    METRICS:\n%        counts \t\t     % (array) number of events in each bin\n%        mean_rate           % (array) number of events per hour in each bin\n%        median_rate\t     % (array) reciprocal of the median time interval between events. Represented as an hourly rate.\n%        cum_mag\t\t     % (array) total sum of energy in each bin, represented as a magnitude.\n%        mean_mag\t\t     % (array) mean magnitude of events in each bin \n%        median_mag          % (array) median magnitude of events in each bin\n%        min_mag             % (array) smallest magnitude in each bin\n%        max_mag             % (array) largest magnitude in each bin\n%\n%    SUMMARY DATA:\n%        numbins             % (scalar) number of bins used for grouping\n%                                events\n%        total_counts        % (scalar) sum of counts\n%        total_mag           % (scalar) total sum of energy of all catalogObjects, represented as a magnitude\n%\n%    METADATA:\n%        etype               % event type/classification. \n%        snum                % (scalar) start date/time in DATENUM format\n%        enum                % (scalar) end date/time in DATENUM format\n%        binsize             % (scalar) bin size in days\n%        stepsize            % (scalar) step size in days\n%        region              % (4-element vector) [minlon maxlon minlat maxlat]\n%        minmag              % (scalar) magnitudes smaller than this were eliminated\n%        dbroot              % path to the original data on disk\n%        archiveformat       % indicates if the source is a flat file, or\n%                              'daily' or 'monthly' volumes\n%        auth                % auth of the events\n%\n%%   METHODS\n%\n%    For a list of all methods type methods EventRate \n%\n%\n%%   See also Catalog, Catalog_lite\n%\n%% AUTHOR: Glenn Thompson\n\n% $Date: 2014-05-06 14:52:40 -0800 (Tue, 06 May 2014) $\n% $Revision: 404 $\n\n\n% I don't think these parts work anymore\n%       (4) Create a vector of eventrate objects subclassified using event types 'r', 'e', 'l', 'h', 't':\n%               erobj = eventrate(catalogObject, 1, 'etypes', 'relht');\n%           To plot counts on separate figures:\n%               erobj.plot()\n%           To plot counts and energy panels, each event type as a separate figure:\n%               erobj.plot('metric', {'counts';'energy'});\n%           To plot counts and energy panels on separate figures, each event type as panels:\n%               erobj.plot('metric', {'counts';'energy'}, 'plotmode', 'panels'); \n%           To plot counts and energy panels on separate figures, each event type stacked:\n%               erobj.plot('metric', {'counts';'energy'}, 'plotmode', 'stacked');\n%\n%       (5) A full example:\n%               catalogObject = catalog(fullfile(MVO_DATA, 'mbwh_catalog'), 'seisan', 'snum', datenum(1996,10,1), 'enum', datenum(2004,3,1), 'region', 'Montserrat')\n%               erobj = eventrate(catalogObject, 365/12, 'stepsize', 1, 'etypes', 'thlr');\n%               erobj.plot('metric', {'counts';'energy'}, 'plotmode', 'stacked');\n%\n\n%% PROPERTIES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    properties(GetAccess = 'public', SetAccess = 'public')\n        time = [];          % (array) in datenum format\n        counts = []; \t\t% (array) number of events in each bin\n\t\tmean_rate = [];      % (array) number of events per hour in each bin\n\t\tmedian_rate = [];\t% (array) reciprocal of the median time interval between events. Represented as an hourly rate.\n\t\tcum_mag = [];\t\t% (array) total sum of energy in each bin, represented as a magnitude.\n\t\tmean_mag = [];\t\t% (array)   \n        median_mag = [];     % (array)\n        energy = [];\n        total_counts = [];   % (scalar) sum of counts\n\t\ttotal_mag = [];      % (scalar) total sum of energy of all catalogObjects, represented as a magnitude\t\n        numbins = [];        % (scalar)\n        min_mag = [];\n        max_mag = [];\n        etype = '*';\n        snum = 0;\n        enum = now;\n        binsize = 1;\n        stepsize = 1;\n        misc_fields = {};\n        misc_values = {};\n    end\n    \n %% PUBLIC METHODS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   \n\tmethods\n        %% CONSTRUCTOR\n        function self = EventRate(time, counts, energy, median_energy, ...\n                smallest_energy, biggest_energy, median_time_interval, total_counts, ...\n                snum, enum, etypes, binsize, stepsize, numbins)\n            self.time = time;\n            self.counts = counts;          \n            self.median_rate = 1 ./ (median_time_interval * 24); \n            self.median_rate(counts<10) = 0;\n            self.median_rate = max([self.counts / (24 * binsize); self.median_rate]);      \n            self.median_mag = magnitude.eng2mag(median_energy);\n            self.energy = energy;\n            self.total_counts = total_counts;  \t\n            self.numbins = numbins;\n            self.min_mag = magnitude.eng2mag(smallest_energy);\n            self.max_mag = magnitude.eng2mag(biggest_energy);\n            self.etype = etypes;\n            self.snum = snum;\n            self.enum = enum;\n            self.binsize = binsize;\n            self.stepsize = stepsize;\n            if (enum-snum) < binsize\n                error('binsize cannot be bigger than data time range');\n            end\n        end\n        \n        %% ----------------------------------------------\n        %% GETTERS\n        function cum_mag = get.cum_mag(erobj)\n            cum_mag = magnitude.eng2mag(erobj.energy);\n        end\n        function mean_mag = get.mean_mag(erobj)\n            mean_mag = magnitude.eng2mag(erobj.energy./erobj.counts);\n        end\n        function mean_rate = get.mean_rate(erobj)\n            mean_rate = erobj.counts / (24 * erobj.binsize);\n        end\n        function total_mag = get.total_mag(erobj)\n            total_mag = magnitude.eng2mag(sum(erobj.energy));\n        end\n         \n    end % methods \n   \n    methods(Static)\n        cookbook()\n    end\n\nend\n\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@EventRate/EventRate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22439592501083908}}
{"text": "function x = project_sample(x, P)\n\nif ~isempty(P)\n    x = cellfun(@(x, P) permute(mtimesx(permute(x, [4 3 1 2]), P, 'speed'), [3 4 2 1]), x, P, 'uniformoutput', false);\nend", "meta": {"author": "he010103", "repo": "CFWCR", "sha": "c6a30234dd6448cef954b8b38f518fa8047c4850", "save_path": "github-repos/MATLAB/he010103-CFWCR", "path": "github-repos/MATLAB/he010103-CFWCR/CFWCR-c6a30234dd6448cef954b8b38f518fa8047c4850/implementation/dim_reduction/project_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.22439591360946462}}
{"text": "%% plane_intersect\n% Below is a demonstration of the features of the |plane_intersect| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |X=plane_intersect(V1,V2,V3,N1,N2,N3);|\n\n%% Description \n% UNDOCUMENTED \n%% Examples \n% \n%%\n% \n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>\n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_plane_intersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22428679240835314}}
{"text": "function [c, ceq] = ma_surfaceVelConstraint(stateLog, eventID, lbHorzVel, ubHorzVel, bodyIDApply, celBodyData, maData)\n%ma_semiMajorAxisConstraint Summary of this function goes here\n%   Detailed explanation goes here\n\n    normFact = 1;\n\n    if(ischar(eventID) && strcmpi(eventID,'final'))\n        eventNum = max(stateLog(:,13));\n    else\n        [~, eventNum] = getEventByID(eventID, maData.script);\n    end\n\n    eventLog = stateLog(stateLog(:,13)==eventNum,:);\n    finalEntry = eventLog(end,:);\n    \n    bodyID = finalEntry(8);\n\n    if(bodyID == bodyIDApply || bodyIDApply==-1)\n        horzVel = ma_GALongLatAltTasks(finalEntry, 'horzVel', celBodyData);\n\n        if(lbHorzVel == ubHorzVel)\n            c = [0 0];\n            ceq(1) = horzVel - ubHorzVel;\n        else\n            c(1) = lbHorzVel - horzVel;\n            c(2) = horzVel - ubHorzVel;\n            ceq = [0];\n        end\n        c = c/normFact;\n        ceq = ceq/normFact;\n    else\n        c = [0 0];\n        ceq = [0];\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/optimization/constraints/zArchive/ma_surfaceVelConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22428077029380183}}
{"text": "function varargout = sinh(varargin)\n%SINH   Hyperbolic sine of a DISKFUN.\n%\n% See also DISKFUN/SIN and DISKFUN/COSH.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = sinh@separableApprox(varargin{:});\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@diskfun/sinh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2242807702938018}}
{"text": "function computeAllFinalRF_HN(pathRF,nBoot,seed)\n\nstartpath = pwd;\n\ncd(pathRF), load('training')\nnameOutcomes = fieldnames(training.outcomes); nOutcomes = numel(nameOutcomes);\nfSetNames = fieldnames(training.textures.(nameOutcomes{1})); nFset = numel(fSetNames);\n\nfor o = 1:nOutcomes\n    if strcmp(nameOutcomes{o},'DeathSign')\n        outcome = training.outcomes.Death;\n    else\n        outcome = training.outcomes.(nameOutcomes{o});\n    end\n    for f = 1:nFset\n        text = training.textures.(nameOutcomes{o}).(fSetNames{f}); nText = size(text,2);\n        indClinic = training.clinical.bestAdd.(nameOutcomes{o}).(fSetNames{f});\n        cost = training.cost.(nameOutcomes{o}).(fSetNames{f});\n        tableTrain = [text,training.clinical.table(:,indClinic)];\n        cat = logical([zeros(1,nText),training.clinical.categories(indClinic)]);\n        rng(seed), [RF] = trainRF_table(tableTrain,outcome,cat,nBoot,cost);\n        RF = compact(RF); % Compact version\n        save(['RF_',[fSetNames{f},'clinic'],'_',nameOutcomes{o}],'RF')\n    end\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/computeAllFinalRF_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "\nfunction [Model cfg] = est_fitMVAR(varargin)\n%\n% Fit (adaptive) multivariate autoregressive model to EEG data. See [1] for\n% details on VAR model fitting and implementations.\n%\n%\n% Output:\n%\n%   Model structure with\n%       .Model          (numvars x coeffs) matrix of VAR coefficients\n%       .PE             (numvars x coeffs) prediction error (noise covariance) coefficients\n%       .algorithm      string denoting algorithm used for estimation\n%       .modelclass     string denoting model class (here, 'mvar')\n%\n% See Also: pop_est_fitMVAR(), pop_pre_prepData()\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual. Chapters 3,6.\n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift/\n%\n%\n% Author: Tim Mullen 2010, SCCN/INC, UCSD.\n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n% pre-cache some frequently used sub-arguments\npersistent subargs;\nif isempty(subargs)\n    subargs.algos = hlp_getMVARalgorithms('defaultNameOnly');\n    subargs.all_algos = hlp_getMVARalgorithms;\n    subargs.sift_domain = hlp_buildMVARHelpText;\nend\n\nverb = arg_extract(varargin,{'verb','VerbosityLevel'},[],2);\n\nhaveSigProc = hlp_isToolboxInstalled('Signal Processing Toolbox');\nif haveSigProc\n    taperFcns = {'rectwin','hamming','hann','bartlett','barthannwin',   ...\n                 'blackman','blackmanharris','bohmanwin','chebwin',     ...\n                 'flattopwin','gausswin','kaiser','nuttallwin',         ...\n                 'parzenwin','taylorwin','tukeywin','triang'};\nelse\n    taperFcns = {'rectwin'};   \nend\n\ng = arg_define([0 1],varargin, ...\n    arg_norep({'EEG','ALLEEG'},mandatory,[],'EEGLAB dataset'), ...\n    arg_subswitch({'algorithm','Algorithm'},subargs.algos,subargs.all_algos,{'Select a model fitting algorithm.',subargs.sift_domain},'cat','Modeling Parameters','suppress',{'ModelOrder','OrderSelector','InitialState'}), ...\n    arg({'morder','ModelOrder','modelOrder'},10,[1 Inf],'VAR model order.','cat','Modeling Parameters'), ...\n    arg_nogui({'winStartIdx','WindowStartIndices'},[],[],'Starting indices for windows. This is a vector of sample points (start of windows) at which to estimate windowed VAR model','cat','Modeling Parameters'), ...\n    arg({'winlen','WindowLength'},0.5,[eps Inf],'Sliding window length (sec)','cat','Modeling Parameters'), ...\n    arg({'winstep','WindowStepSize'},0.03,[eps Inf],'Window step size (sec)','cat','Modeling Parameters'), ...\n    arg({'taperfcn','TaperFunction'},'rectwin',taperFcns,{'Data tapering (windowing) function', ...\n                                                            sprintf(['\\n' ...\n                                                                     'Each data segment (e.g. all data in a sliding window) will be multipled by the data taper to smooth endpoints towards zero.', ...\n                                                                     '\\n' ...\n                                                                     'Available windows are:\\n' ...\n                                                                          'rectwin \\t - Rectangular window. This is equivalent to no taper.\\n', ...\n                                                                          'hamming \\t - Hamming window.\\n', ...\n                                                                          'hann \\t - Hann window.\\n', ...\n                                                                          'bartlett \\t - Bartlett window.\\n', ...\n                                                                          'barthannwin \\t - Modified Bartlett-Hanning window.\\n', ...\n                                                                          'blackman \\t - Blackman window.\\n', ...\n                                                                          'blackmanharris- Minimum 4-term Blackman-Harris window.\\n', ...\n                                                                          'bohmanwin \\t - Bohman window.\\n', ...\n                                                                          'chebwin \\t - Chebyshev window.\\n', ...\n                                                                          'flattopwin \\t - Flat Top window.\\n', ...\n                                                                          'gausswin \\t - Gaussian window.\\n', ...\n                                                                          'kaiser \\t - Kaiser window.\\n', ...\n                                                                          'nuttallwin \\t - Nuttall defined minimum 4-term Blackman-Harris window.\\n', ...\n                                                                          'parzenwin \\t - Parzen (de la Valle-Poussin) window.\\n', ...\n                                                                          'taylorwin \\t - Taylor window.\\n', ...\n                                                                          'tukeywin \\t - Tukey window.\\n', ...\n                                                                          'triang \\t - Triangular window.\\n' ...\n                                                                        ])},'cat','Modeling Parameters'), ...\n    arg({'epochTimeLims','EpochTimeLimits'},[],[],'Sub-epoch time limits (sec). This is relative to event time (e.g. [-1 2]). Default is the full epoch time range','cat','Modeling Parameters'), ...\n    arg({'prctWinToSample','WindowSamplePercent'},100,[1 100],'Percent of windows to sample','cat','Modeling Parameters'), ...\n    arg_subtoggle({'normalize','NormalizeData'},[],@pre_normData,'Z-normalize data within windows. Note this is not recommended for short windows','cat','Window Preprocessing'), ...\n    arg_subtoggle({'detrend','Detrend'},{}, ...\n    {arg({'method','DetrendingMethod'},'constant',{'linear','constant'},{'Detrend data within each window.', ...\n    sprintf(['\\n' ...\n    'Linear: removes the least-squares fit of a straight line.\\n' ...\n    'Constant: removes the mean from each trial (centering)' ...\n    ]) ...\n    } ...\n    )},'Detrend or center each time window','cat','Window Preprocessing'), ...\n    arg({'timer','Timer'},false,[],'Activate timer. Times are stored in EEG.CAT.Model.timeelapsed'), ...\n    arg({'setArgDirectMode','SetArgDirectMode'},true,[],'Set arg_direct mode to true. Can improve speed when number of windows is large. Disable if calling this function repeatedly in a tight loop.'), ...\n    arg({'verb','VerbosityLevel'},verb,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical') ...\n    );\n\n\n\n% commit EEG variable to workspace\n[data g] = hlp_splitstruct(g,{'EEG'});\narg_toworkspace(data);\nclear data;\n\n% do some error-checking\nif isempty(g.epochTimeLims)\n    g.epochTimeLims = [EEG.xmin EEG.xmax]; end\nif ~(all(g.epochTimeLims>=EEG.xmin) && all(g.epochTimeLims<=EEG.xmax))\n    error('Epoch time limits must be within the range [%0.3g %0.3g]',EEG.xmin,EEG.xmax); end\nif isempty(g.morder) || length(g.morder)>1\n    error('invalid entry for field ''morder.'' Make sure the model order is a single integer.'); end\n\nif nargout > 1, cfg = g; end\n\n%% do some adjustments to parameters\n\n% ensure we are using the right model order\ng.algorithm.morder = g.morder;\n\nif rem(g.winstep,1/EEG.srate)\n    if g.winstep<1/EEG.srate\n        g.winstep = 1/EEG.srate;\n    else\n        % adjust step size to nearest multiple of sampling interval\n        g.winstep = g.winstep-rem(g.winstep,1/EEG.srate);\n    end\n    \n    if g.verb,\n        fprintf('Adjusting window step size to nearest multiple of sampling interval\\n');\n        fprintf('\\tstep size is now %0.5g sec\\n',g.winstep);\n    end\nend\n\nif rem(g.winlen,1/EEG.srate)\n    if g.winlen<1/EEG.srate\n        g.winlen = 1/EEG.srate;\n    else\n        % adjust window length to nearest multiple of sampling interval\n        g.winlen = g.winlen-rem(g.winlen,1/EEG.srate);\n    end\n    \n    if g.verb,\n        fprintf('Adjusting window length to nearest multiple of sampling interval\\n');\n        fprintf('\\twindow length is now %0.5g sec\\n',g.winlen);\n    end\nend\nif g.winlen > EEG.xmax-EEG.xmin\n    g.winlen = EEG.xmax-EEG.xmin;\n    if g.verb,\n        fprintf('Window length exceeds epoch length. Adjusting window length to match epoch length\\n');\n        fprintf('\\twindow length is now %0.5g sec\\n',g.winlen);\n    end\nend\ntidx = getindex(EEG.CAT.times,g.epochTimeLims*1000);\nif ~all(isequal(EEG.CAT.times(tidx),g.epochTimeLims*1000))\n    \n    g.epochTimeLims = EEG.CAT.times(tidx)/1000;\n    \n    if g.verb\n        fprintf('Adjusting epoch time limits to match sampling interval\\n');\n        fprintf('\\tepoch limits are now [%0.5g, %0.5g] sec\\n',g.epochTimeLims(1),g.epochTimeLims(2));\n    end\nend\n\nwinLenPnts  = round(g.winlen*EEG.srate); % window size in points\nwinStepPnts = round(g.winstep*EEG.srate);\n\nif isempty(g.winStartIdx)\n    % starting point of each window (points)\n    g.winStartIdx  = tidx(1):winStepPnts:(tidx(2)-winLenPnts)+1;\n    %g.winStartIdx  =  round((double(g.epochTimeLims(1):g.winstep:g.epochTimeLims(2)-g.winlen)*EEG.srate)+1;\nend\n\nif g.prctWinToSample<100\n    % randomly select percentage of windows to work with\n    randwin = randperm(length(g.winStartIdx));\n    randwin = sort(randwin(1:ceil(length(g.winStartIdx)*g.prctWinToSample/100)));\n    g.winStartIdx = g.winStartIdx(randwin);\nend\n\nnumWins   = length(g.winStartIdx);\n\n% construct the data taper\ng.taper = window_func(g.taperfcn,winLenPnts).';\n\n\n%% Prepare data for model fitting\n\n% initialize results arrays\n[AR PE RC mu th lambdaOpt]  = deal(cell(1,numWins));\n\nif g.verb==2\n    waitbarTitle = sprintf('Fitting VAR[%d] model (%s)...', ...\n                        g.morder, ...\n                        num2str(g.algorithm.arg_selection));\n    \n    multiWaitbar(waitbarTitle,'Reset');\n    multiWaitbar(waitbarTitle, ...\n                 'Color', hlp_getNextUniqueColor, ...\n                 'CanCancel','on', ...\n                 'CancelFcn',@(a,b) disp('[Cancel requested. Please wait...]'));\nend\n\nif g.detrend.arg_selection\n    % detrend each window separately\n    if g.verb, fprintf('%s detrending each window...\\n',firstcaps(g.detrend.method)); end\n    for ch=1:EEG.CAT.nbchan\n        EEG.CAT.srcdata(ch,:,:) = locdetrend_siftmod(squeeze(EEG.CAT.srcdata(ch,:,:)), ...\n            EEG.srate,[g.winlen g.winstep],g.detrend.method);\n    end\n    if g.verb, fprintf('done.\\n'); end\nend\n\nif g.timer\n    timeElapsed = nan(1,numWins);\nelse\n    timeElapsed = [];\nend\n\n%% Main loop: fit MVAR models to each window\n\nalgFcnName = hlp_nanocache('algos',10,@hlp_getMVARalgorithms,'mfileNameOnly',g.algorithm.arg_selection);\n\nif g.setArgDirectMode && ~strcmp(algFcnName,'mvar_glADMM') % not necessary for glADMM\n    % set the arg_direct flag\n    % to improve speed\n   g = arg_setdirect(g,true);\nend\n\nfor t=1:numWins\n    \n    if g.timer, tic; end\n    \n    % get data for current window\n    data = EEG.CAT.srcdata(:,g.winStartIdx(t):g.winStartIdx(t)+winLenPnts-1,:);\n    if g.normalize.arg_selection\n        % normalize the data window\n        data = pre_normData('data',data,'method',g.normalize.method,'verb',0,'arg_direct',true);\n    end\n\n    % execute the model-fitting algorithm\n    switch nargout(algFcnName)\n        case 2\n            [AR{t} PE{t}] = feval(algFcnName, ...\n                'data',bsxfun(@times,g.taper,data), ...\n                g.algorithm,'arg_direct',true);\n        case 3\n            [AR{t} PE{t} argsout] = feval(algFcnName, ...\n                                   'data',bsxfun(@times,g.taper,data),...\n                                    g.algorithm,'arg_direct',true);\n            if isstruct(argsout)\n                % store contents of argsout fields in cell array at index t\n                % e.g. fieldname{t} = argsout.(fieldname)\n                fnames = fieldnames(argsout);\n                for k=1:length(fnames)\n                    eval([fnames{k} '{t}=argsout.(''' fnames{k} ''');']);\n                end\n            end\n        otherwise\n            error('SIFT:est_fitMVAR:badAlgArgs','%s must output either 2 or 3 arguments',algFcnName);\n    end\n        \n    if g.verb==2\n        drawnow;\n        % graphical waitbar\n        cancel = multiWaitbar(waitbarTitle,t/numWins);\n        if cancel\n            if strcmpi('yes',questdlg2( ...\n                            'Are you sure you want to cancel?', ...\n                            'Model Fitting','Yes','No','No'));\n                Model = [];\n                multiWaitbar(waitbarTitle,'Close');\n                return;\n            else\n                multiWaitbar(waitbarTitle,'ResetCancel',true);\n            end\n        end\n    end\n    \n    if g.timer, timeElapsed(t) = toc; end\nend\n\n%% Do some cleanup\nclear('-regexp','mvar_*')\nif g.verb==2\n    multiWaitbar(waitbarTitle,'Close'); \nend\n\n%% Construct Model object\nModel = hlp_sift_emptymodel;\n\nModel.AR = AR;\nModel.PE = PE;\nModel.RC = RC;\nModel.mu = mu;\nModel.th = th;\nModel.lambdaOpt = lambdaOpt;\nModel.winStartTimes = (g.winStartIdx-1)/EEG.srate;\nModel.morder        = g.morder;\nModel.winstep       = g.winstep;\nModel.winlen        = g.winlen;\nModel.algorithm     = g.algorithm.arg_selection;\nModel.modelclass    = 'mvar';\nModel.timeelapsed   = timeElapsed;\nModel.normalize     = g.normalize;\nModel.modelapproach = 'Segmentation VAR';\nModel.taperFcn      = g.taperfcn;\n\nswitch lower(g.algorithm.arg_selection)\n    case 'group lasso dal/scsa'\n        %     Model.ww = ww;\n        Model.lambda = g.algorithm.dal_args.lambda;\n    case 'group lasso (admm)'\n        Model.lambda = g.algorithm.admm_args.lambda;\n        Model.rho    = g.algorithm.admm_args.rho;\n        Model.alpha  = g.algorithm.admm_args.alpha;\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/est/est_fitMVAR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "\nfunction [dat_sf,W] = proc_multiBandSpatialFilter(dat,method)\n%PROC_MULTIBANDSPATIALFILTER - Apply spatial filtering method to multiple\n%frequency bands\n%\n%Synopsis:\n% [DAT_SF, W] = proc_multiBandSpatialFilter(DAT, METHOD);\n%\n%Arguments:\n% DAT    - data structure of epoched and pre-filtered data\n% METHOD - cell array containing in the first entry a function handle to\n%          the spatial filtering method and (optionally) in the following\n%          entries parameters for that function\n%\n%Returns:\n% DAT_SF - updated data structure, containing the spatially filtered data\n%          of all bands, appended as channels\n% W      - cell array with each entry containing the spatial filters (in\n%          the columns) of each band\n%\n%Description:\n% The input data structure is assumed to contain pre-filtered channels as\n% returned by the function proc_filterbank. proc_multiBandSpatialFilter can\n% be used either alone or as a processing step in the crossvalidation\n% function.\n%\n%See also: crossvalidation proc_filterbank proc_multiBandLinearDerivation\n\n% 10-2015: schultze-kraft@tu-berlin.de\n\nmisc_checkType(dat,'STRUCT(x clab y)');\nmisc_checkType(method,'CELL');\nprocFunc = method{1};\nmisc_checkType(procFunc,'!FUNC');\nif length(method)>1\n    procPar = method(2:end);\nelse\n    procPar = {};\nend\n\n% get number of frequency bands\nband_ix = zeros(1,length(dat.clab));\nflt_ix = cellfun(@(x) strfind(x,'flt'),dat.clab);\nfor ii = 1:length(dat.clab)\n    band_ix(ii) = str2double(dat.clab{ii}(flt_ix(ii)+3:end));\nend\nn_bands = max(band_ix);\n\n% band-wise apply spatial filtering method\nW = cell(1,n_bands);\ndat_sf = [];\nfor bi = 1:n_bands\n    dat2 = proc_selectChannels(dat,sprintf('*flt%d',bi));\n    [dat2,W{bi}] = procFunc(dat2,procPar{:});\n    dat_sf = proc_appendChannels(dat_sf,dat2);\nend\n\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_multiBandSpatialFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.224181923312239}}
{"text": "classdef SecondOrderGravOnlyPropagator < AbstractPropagator\n    %ForceModelPropagator Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        forceModels ForceModelsEnum = [ForceModelsEnum.Gravity]; \n    end\n    \n    properties(Constant)\n        propagatorEnum = PropagatorEnum.SecOrdGravOnly;\n    end\n    \n    methods\n        function obj = SecondOrderGravOnlyPropagator()\n\n        end\n        \n        function [t,y,te,ye,ie] = propagate(obj, integrator, tspan, eventInitStateLogEntry, ...\n                                            eventTermCondFuncHandle, termCondDir, maxT, checkForSoITrans, nonSeqTermConds, nonSeqTermCauses, minAltitude, celBodyData, ...\n                                            tStartPropTime, maxPropTime)\n                                       \n            if(not(isa(integrator, 'AbstractSecondOrderIntegrator')))\n                error('The selected integrator must be a second order integrator in order to use this propagator.');\n            end\n\n            plugins = eventInitStateLogEntry.lvdData.plugins;         \n            \n            %Create function handles\n            odefun = obj.getOdeFunctionHandle(eventInitStateLogEntry);\n            evtsFunc = obj.getOdeEventsFunctionHandle(eventInitStateLogEntry, eventTermCondFuncHandle, termCondDir, maxT, checkForSoITrans, nonSeqTermConds, nonSeqTermCauses, minAltitude, celBodyData);\n            odeOutputFun = obj.getOdeOutputFunctionHandle(tStartPropTime, maxPropTime, eventInitStateLogEntry, plugins);\n            \n            %Propagate!\n            [t0,y0,yp0] = eventInitStateLogEntry.getSecondOrderIntegratorStateRepresentation();\n\n            if(eventInitStateLogEntry.isHoldDownEnabled())\n                %Integrate in the body-fixed frame with zero rates\n                %For performance reasons\n                bodyInfo = eventInitStateLogEntry.centralBody;\n                [rVectECEF, vVectECEF] = getFixedFrameVectFromInertialVect(t0, y0(1:3)', bodyInfo, yp0(1:3)');\n                y0 = [rVectECEF', vVectECEF'];\n\n                [t,y,yp,te,ye,ype,ie] = integrator.integrate(odefun, tspan, y0, yp0, evtsFunc, odeOutputFun);\n\n                [rVectECI, vVectECI] = getInertialVectFromFixedFrameVect(t, y(:,1:3)', bodyInfo, yp(:,1:3)');\n                y = [rVectECI', vVectECI'];\n\n                if(~isempty(ye))\n                    [rVectECIe, vVectECIe] = getInertialVectFromFixedFrameVect(te, ye(:,1:3)', bodyInfo, ype(:,1:3)');\n                    ye = [rVectECIe', vVectECIe'];\n                end\n            else\n                [t, y, yp, te, ye, ype, ie] = integrator.integrate(odefun, tspan, y0, yp0, evtsFunc, odeOutputFun);\n            end   \n\n            y = horzcat(y,yp);\n            ye = horzcat(ye,ype);\n        end\n        \n        function odeFH = getOdeFunctionHandle(obj, eventInitStateLogEntry)\n            tankStates = eventInitStateLogEntry.getAllActiveTankStates();\n            dryMass = eventInitStateLogEntry.getTotalVehicleDryMass();\n            pwrStorageStates = eventInitStateLogEntry.getAllActivePwrStorageStates();\n            odeFH = @(t,y) SecondOrderGravOnlyPropagator.odefun(t,y, eventInitStateLogEntry, tankStates, dryMass, pwrStorageStates, obj.forceModels);\n        end\n        \n        function odeEventsFH = getOdeEventsFunctionHandle(~, eventInitStateLogEntry, eventTermCondFuncHandle, termCondDir, maxT, checkForSoITrans, nonSeqTermConds, nonSeqTermCauses, minAltitude, celBodyData)\n            odeEventsFH = @(t,y,yp) AbstractPropagator.odeEvents(t,vertcat(y,yp), eventInitStateLogEntry, eventTermCondFuncHandle, termCondDir, maxT, checkForSoITrans, nonSeqTermConds, nonSeqTermCauses, minAltitude, celBodyData);\n        end\n        \n        function odeOutputFH = getOdeOutputFunctionHandle(~, tStartPropTime, maxPropTime, eventInitStateLogEntry, plugins)           \n            odeOutputFH = @(t,y,yp,flag) SecondOrderGravOnlyPropagator.odeOutput(t,y,yp,flag, tStartPropTime, maxPropTime, eventInitStateLogEntry, plugins);\n        end\n        \n        function [value,isterminal,direction,causes] = callEventsFcn(obj, odeEventsFun, stateLogEntry)\n            [t,y,yp] = stateLogEntry.getSecondOrderIntegratorStateRepresentation();\n            [value,isterminal,direction,causes] = odeEventsFun(t,y,yp);\n        end\n        \n        function openOptionsDialog(obj)\n            fms = obj.forceModels;\n            \n            \n            fmArr = ForceModelsEnum.getEnumsOfDisablableForceModels();\n            fmArr = fmArr([fmArr.allowedForSecondOrder] == true);\n            \n            [~,initSelInds] = ismember(fms, fmArr);\n            initSelInds = initSelInds(initSelInds > 0);\n            \n            out = AppDesignerGUIOutput();\n            listdlgARH_App('ListString',{fmArr.name}, ...\n                            'SelectionMode', 'multiple', ...\n                            'ListSize', [300, 300], ...\n                            'Name', 'Select Force Models', ...\n                            'PromptString', {'Select the Force Models you wish to have enabled during this','event.  Gravity is always enabled.  Disabling Thrust during','periods of coasting may improve performance considerably.'}, ...\n                            'InitialValue', initSelInds, ...\n                            'out',out);\n            Selection = out.output{1};\n            ok = out.output{2};\n\n            if(ok == 1)\n                obj.forceModels = [ForceModelsEnum.getAllForceModelsThatCannotBeDisabled(), fmArr(Selection)'];\n            end\n        end\n        \n        function tf = canProduceThrust(obj)\n            tf = false;\n        end\n    end\n\n    methods(Static)\n        function [ut, rVect] = decomposeIntegratorTandY(t,y)\n            ut = t;\n            rVect = y(1:3);\n        end\n    end\n\n    methods(Static, Access=private)\n        %%%\n        %ODE Function\n        %%%\n        function d2ydt2 = odefun(t,y, eventInitStateLogEntry, tankStates, dryMass, powerStorageStates, fmEnums)\n            bodyInfo = eventInitStateLogEntry.centralBody;\n            if(isstruct(bodyInfo.celBodyData) || isempty(bodyInfo.celBodyData))\n                bodyInfo.celBodyData = eventInitStateLogEntry.celBodyData;\n            end\n\n            [ut, rVect] = SecondOrderGravOnlyPropagator.decomposeIntegratorTandY(t,y);\n            vVect = [0;0;0]; %placeholder - this ODE function can't be a function of velocity, only position\n            altitude = norm(rVect) - bodyInfo.radius;\n\n            holdDownEnabled = eventInitStateLogEntry.isHoldDownEnabled();\n            \n            d2ydt2 = zeros(length(y),1);\n            if(holdDownEnabled)\n                %launch clamp is enabled, only motion is circular motion\n                %(fixed to body)\n                %In this case, we are integrating in the body-fixed frame, \n                %so all rates are effectively zero        \n                d2ydt2(1:3) = [0;0;0]; \n            else\n                %launch clamp disabled, propagate like normal\n                if(altitude <= 0 && any(fmEnums == ForceModelsEnum.Normal))\n                    rswVVect = rotateVectorFromEciToRsw(vVect, rVect, vVect);\n                    rswVVect(1) = 0; %kill vertical velocity because we don't want to go throught the surface of the planet\n                    vVect = rotateVectorFromRsw2Eci(rswVVect, rVect, vVect);\n                end\n\n                thirdBodyGravity = eventInitStateLogEntry.thirdBodyGravity;\n\n                totalMass = eventInitStateLogEntry.getTotalVehicleMass(); %this isn't the total mass but because we can't \n\n                if(totalMass > 0)\n                    [forceSum] = TotalForceModel.getForce(fmEnums, ut, rVect, vVect, totalMass, bodyInfo, [], [], [], [], [], [], dryMass, [], thirdBodyGravity, [], []);\n                    accelVect = forceSum/totalMass; \n                else\n                    accelVect = zeros(3,1);\n                end\n\n                d2ydt2(1:3) = accelVect; \n            end\n        end\n        \n        %%%\n        %ODE Output\n        %%%\n        function status = odeOutput(t,y,yp,flag, intStartTime, maxIntegrationDuration, eventInitStateLogEntry, plugins)\n            y = vertcat(y,yp);\n            plugins.executePluginsAfterTimeStepOdeOutputFcn(t,y,flag, eventInitStateLogEntry);\n            \n            integrationDuration = toc(intStartTime);\n\n            status = 0;\n            if(integrationDuration > maxIntegrationDuration)\n                status = 1;\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Simulation/propagator/@SecondOrderGravOnlyPropagator/SecondOrderGravOnlyPropagator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.2241263521511697}}
{"text": "% REMOVE_KS2_DUPLICATE_SPIKES2 Double-counted spikes are hard to avoid with\n% Kilosort's template matching algorithm since the overall fit can be\n% improved by having multiple templates jointly account for a single variable waveform.\n% \n% This function takes the kilosort2 output rez and identifies pair of\n% spikes that are close together in time and space. The temporal threshold\n% is give by the parameter OVERLAP_S which is 0.5ms by default and\n% the spatial threshold (applied to the template primary sites) is given by\n% CHANNEL_SEPARATION_UM and is 100 by default.\n%\n% From these spike pairs, it identifies the pair with the larger template as\n% being the \"main\" or \"reference\" cluster and the duplicate spikes from the\n% other cluster are removed.\n%\n% All spike pairs are considered, not just those from CCG-contaminated\n% pairs, as in REMOVE_KS2_DUPLICATE_SPIKES2.\n%\n% Adrian Bondy, 2020\n%\n%=INPUT\n%\n%   rez structure\n%\n%=OPTIONAL INPUT, NAME-VALUE PAIRS\n%\n%   overlap_s\n%       the time interval, in second, within which a sequence of spikes are\n%       vetted for duplicates.\n%\n%   channel_separation_um\n%       When the primay channels of two spikes are within this distance, in\n%       microns, then the two spikes are vetted for duplicate.\n%\n%=EXAMPLE\n%\n%   >> rez = remove_ks2_duplicate_spikes(rez)\nfunction rez = remove_ks2_duplicate_spikes(rez, varargin)\n    input_parser = inputParser;\n    addParameter(input_parser, 'overlap_s', 5e-4, @(x) (isnumeric(x))) % the temporal window within which pairs of spikes will be considered duplicates (if they are also within the spatial window)\n    addParameter(input_parser, 'channel_separation_um', 100, @(x) (ischar(x))) % the spatial window within which pairs of spikes will be considered duplicates (if they are also within the temporal window)\n    parse(input_parser, varargin{:});\n    P = input_parser.Results;\n\n    spike_times = uint64(rez.st3(:,1));\n    spike_templates = uint32(rez.st3(:,2));\n\n    rez.U=gather(rez.U);\n    rez.W = gather(rez.W);\n    templates = zeros(rez.ops.Nchan, size(rez.W,1), size(rez.W,2), 'single');\n    for iNN = 1:size(templates,3)\n       templates(:,:,iNN) = squeeze(rez.U(:,iNN,:)) * squeeze(rez.W(:,iNN,:))';\n    end\n    templates = permute(templates, [3 2 1]); % now it's nTemplates x nSamples x nChannels\n    n_spikes=numel(spike_times);        \n    %% Make sure that the spike times are sorted\n    if ~issorted(spike_times)\n        [spike_times, spike_idx] = sort(spike_times);\n        spike_templates = spike_templates(spike_idx);\n    else\n        spike_idx=(1:n_spikes)';\n    end\n    %% deal with cluster 0\n    if any(spike_templates==0)\n        error('Currently this function can''t deal with existence of cluster 0. Should be OK since it ought to be run first in the post-processing.');\n    end\n    %% Determine the channel where each spike had that largest amplitude (i.e., the primary) and determine the template amplitude of each cluster\n    whiteningMatrix = rez.Wrot/rez.ops.scaleproc;\n    whiteningMatrixInv = whiteningMatrix^-1;\n\n    % here we compute the amplitude of every template...\n    % unwhiten all the templates\n    tempsUnW = zeros(size(templates));\n    for t = 1:size(templates,1)\n        tempsUnW(t,:,:) = squeeze(templates(t,:,:))*whiteningMatrixInv;\n    end\n\n    % The amplitude on each channel is the positive peak minus the negative\n    tempChanAmps = squeeze(max(tempsUnW,[],2))-squeeze(min(tempsUnW,[],2));\n\n    % The template amplitude is the amplitude of its largest channel\n    [tempAmpsUnscaled,template_primary] = max(tempChanAmps,[],2);\n    %without undoing the whitening\n    %template_amplitude = squeeze(max(templates, [], 2) - min(templates, [], 2));\n    %[~, template_primary] = max(template_amplitude, [], 2); \n\n    template_primary = cast(template_primary, class(spike_templates));\n    spike_primary = template_primary(spike_templates);\n\n    %% Number of samples in the overlap\n    n_samples_overlap = round(P.overlap_s * rez.ops.fs);\n    n_samples_overlap = cast(n_samples_overlap, class(spike_times));\n    %% Distance between each channel\n    chan_dist = ((rez.xcoords - rez.xcoords').^2 + (rez.ycoords - rez.ycoords').^2).^0.5;\n    n_spikes=numel(spike_times);\n    remove_idx = [];\n    reference_idx = [];\n    % check pairs of spikes in the time-ordered list for being close together in space and time. \n    % Check pairs that are separated by N other spikes,\n    % starting with N=0. Increasing N until there are no spikes within the temporal overlap window. \n    % This means only ever computing a vector operation (i.e. diff(spike_times))\n    % rather than a matrix one (i.e. spike_times - spike_times').\n    diff_order=0;\n    while 1==1\n        diff_order=diff_order+1;\n        fprintf('Now comparing spikes separated by %g other spikes.\\n',diff_order-1);\n        isis=spike_times(1+diff_order:end) - spike_times(1:end-diff_order);\n        simultaneous = isis<n_samples_overlap;\n        if any(isis<0)\n            error('ISIs less than zero? Something is wrong because spike times should be sorted.');\n        end\n        if ~any(simultaneous)\n            fprintf('No remaining simultaneous spikes.\\n');\n            break\n        end\n        nearby = chan_dist(sub2ind(size(chan_dist),spike_primary(1:end-diff_order),spike_primary(1+diff_order:end)))<P.channel_separation_um;\n        first_duplicate = find(simultaneous & nearby); % indexes the first (earliest in time) member of the pair\n        n_duplicates = length(first_duplicate);\n        if ~isempty(first_duplicate)\n            fprintf('On iteration %g, %g duplicate spike pairs were identified.\\n',diff_order,n_duplicates);\n            amps_to_compare=tempAmpsUnscaled(spike_templates([first_duplicate first_duplicate(:)+diff_order]));\n            if length(first_duplicate)==1\n                amps_to_compare = amps_to_compare(:)'; % special case requiring a dimension change\n            end\n            first_is_bigger =  diff(amps_to_compare,[],2)<=0;\n            remove_idx = [remove_idx ; spike_idx([first_duplicate(~first_is_bigger);(first_duplicate(first_is_bigger)+diff_order)])];\n            reference_idx = [reference_idx ; spike_idx([(first_duplicate(~first_is_bigger)+diff_order);first_duplicate(first_is_bigger)])];\n        end\n    end\n    [remove_idx,idx] = unique(remove_idx);\n    reference_idx = reference_idx(idx);    \n    logical_remove_idx = ismember((1:n_spikes)',remove_idx);\n    rez = remove_spikes(rez,logical_remove_idx,'duplicate','reference_time',spike_times(reference_idx),...\n        'reference_cluster',spike_templates(reference_idx));\nend", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/postProcess/remove_ks2_duplicate_spikes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2240579803390117}}
{"text": "%This is an example of using the matlab scripts for drawing MEMS fabrication process cross-section. Only support deposit, lithography, and etch(isotropic and anisotropic is not differentied here.). Materials can be used is Si, SiNi,SiO2, metal, PR(photoresistor).\n\n% basic syntax:\n% 1. deposit ('materialName', layerThickness), where materialName is one of Si, SiNi, SiO2, metal, PR. layerThickness is an integer, normally it is between 1 and 20.\n% 2. liga(mask), where mask is an series of char combined by ' ' and '-', this function lithography photoresistor, so it should used after an layer of PR is deposited.\n% 3. etch('materialName'): material which is appointed will be etched from top to bottom until meet an fully cover other material layer.\n% 4. removepr('PR'): remove all the photoresistor.\n% 5. drawlayers(); draw current result.\n% DATE: 30/8/2007\n% muwn.gu@gmail.com\n%========donot modify the head\nclear all;\nclear global;\nloadlayerprofile('MEMS');\nglobal layerMatrix;\nglobal Layerprofile;\nfigure(1);\n%===================\n\n%*******************replace below to your own process\nmask1 = ' --     ---     --      -  ';\t% metal 1\nmask2 = '    -----------            ';   % SiO2 beam\nmask3 = '  ---------------          ';\nmask4 = '                       --- ';  % SiO2\nmask5 = '                      ---  ';\t% metal 2\n\ndeposit ('Si', 10);\ndeposit('SiO2', 20);\ndeposit('SiNi', 5);\n\n% electrode\ndeposit('metal', 5); % metal 1 thick \ndeposit('PR', 10);\nliga(mask1);\netch ('metal');\nremovepr('PR');\ndrawlayers();\n\n% beams\ndeposit('SiO2', 5);\ndeposit('PR', 10);\nliga(mask2);\netch('SiO2');\nremovepr('PR');\ndrawlayers();\n\n\ndeposit('PoSi', 10);\ndeposit('PR', 10);\nliga(mask3);\netch('PoSi');\nremovepr('PR');\ndrawlayers();\netch('SiO2');\n\n% electrode\ndeposit('metal', 2); % metal 2 thin \ndeposit('PR', 10);\nliga(mask4);\netch ('metal');\nremovepr('PR');\ndrawlayers();\n%**********************************************\n\n%=================donot modify below===================\naxis ([15 80 0 Layerprofile.currentY])\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16167-draw-mems-process-steps/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22376590697551427}}
{"text": "function test_bug1508\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_freqanalysis\n\n% Stan reported a strange error caused by the following:\n% if the cfg.channel in a call to ft_freqanalysis contains channels that\n% are not in the data, the function crashes on the second trial\n\n%% Try to reproduce\ndata = [];\ndata.trial = {randn(3,100) randn(3,100)};\ndata.time  = {1:100 1:100};\ndata.label = {'chan1';'chan2';'chan3'};\n\ncfg = [];\ncfg.method  = 'mtmfft';\ncfg.channel = {'chan4'};\ncfg.output  = 'pow';\ncfg.taper   = 'hanning';\n\ntry\n  freq = ft_freqanalysis(cfg, data);\ncatch err\n  if strcmp(err.message,'no channels were selected')\n    % error is expected handling \n  else\n    error('test doesn''t result in expected error message')\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1508.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22375061921504102}}
{"text": "\nfunction DoTrajK(handles)\n\nglobal VObj;\nglobal VMag;\nglobal VCtl;\nglobal VSig;\nglobal VCoi;\n\n%preserve VObj VMag & VCoi\nVTmpObj=VObj;\nVTmpMag=VMag;\nVTmpCoi=VCoi;\n\nhandles.Simuh=guidata(handles.Simuh.SimuPanel_figure);\nDoDisableButton([],[],handles.Simuh);\n%% Do K-Space Traj\ntry\n    % Read tab parameters\n    fieldname=fieldnames(handles.Attrh2);\n    for i=1:length(fieldname)/2\n        try\n            eval(['TK.' fieldname{i*2} '=[' get(handles.Attrh2.(fieldname{i*2}),'String') '];']);\n        catch me\n            TAttr=get(handles.Attrh2.(fieldname{i*2}),'String');\n            eval(['TK.' fieldname{i*2} '=''' TAttr{get(handles.Attrh2.(fieldname{i*2}),'Value')}  ''';']);\n        end\n    end\n    \n    % Prescan config\n    DoPreScan(handles.Simuh);\n    \n    % Create SpinWatcher VOtk, VMtk & VCtk\n    VOtk=VObj;\n    VOtk.SpinNum=1;\n    VOtk.TypeNum=1;\n    VOtk.Rho=1;\n    VOtk.T1=1;\n    VOtk.T2=0.1;\n    VOtk.T2Star=0.01;\n    VOtk.XDim=1;\n    VOtk.YDim=1;\n    VOtk.ZDim=1;\n    VOtk.Mx= 0;\n    VOtk.My= 0;\n    VOtk.Mz= 1;\n\n    % Gradient Grid\n    VMtk=VMag;\n    VMtk.Gxgrid=0;\n    VMtk.Gygrid=0;\n    VMtk.Gzgrid=0;\n    VMtk.dB0=0;\n    VMtk.dWRnd=0;\n    VMtk.FRange=1;\n\n    % Coil\n    VCtk=VCoi;\n    VCtk.TxCoilmg=1;\n    VCtk.TxCoilpe=0;\n    VCtk.TxCoilNum=1;\n    VCtk.RxCoilx=1;\n    VCtk.RxCoily=0;\n    VCtk.RxCoilNum=1;\n    \n    %% Spin execution\n    VObj=VOtk;\n    VMag=VMtk;\n    VCoi=VCtk;\n    \n    % Generate Pulse line\n    DoPulseGen(handles);\n    \n    % Simulation Process\n    try\n        VCtl.CS=double(VObj.ChemShift*VCtl.B0);\n        VCtl.RunMode=int32(0); % Image scan\n        VCtl.MaxThreadNum=int32(handles.Simuh.CPUInfo.NumThreads);\n        DoDataTypeConv(handles.Simuh);\n        DoScanAtCPU; % global (VSeq,VObj,VCtl,VMag,VCoi,VVar,VSig) are needed\n    catch me\n        error_msg{1,1}='ERROR!!! Scan process aborted.';\n        error_msg{2,1}=me.message;\n        errordlg(error_msg);\n        %recover VObj\n        VObj=VTmpObj;\n        VMag=VTmpMag;\n        VCoi=VTmpCoi;\n        return;\n    end\ncatch me\n    error_msg{1,1}='ERROR!!! Spin execution process aborted.';\n    error_msg{2,1}=me.message;\n    errordlg(error_msg);\n    %recover VObj\n    VObj=VTmpObj;\n    VMag=VTmpMag;\n    VCoi=VTmpCoi;\n    return;\nend\n\nKx=VSig.Kx;\nKy=VSig.Ky;\nKz=VSig.Kz;\n\n%recover VObj\nVObj=VTmpObj;\nVMag=VTmpMag;\nVCoi=VTmpCoi;\n\npause(0.1);\n\nswitch TK.RenderMode\n    case 'VTK'\n        % VTK 3D rendering\n        switch TK.RenderPoint\n            case 'off'\n                DoKSpaceTrajVTK([Kx(:)';Ky(:)';Kz(:)'],ones(size(Kx(:)'))*1,0);\n            case 'on'\n                DoKSpaceTrajVTK([Kx(:)';Ky(:)';Kz(:)'],ones(size(Kx(:)'))*1,1);\n        end\n    case 'Matlab'\n        % Matlab 3D plot\n        figure('Color','k');\n        switch TK.RenderPoint\n            case 'off'\n                Ktraj=plot3(Kx(:),Ky(:),Kz(:),'w-');\n                grid on;\n            case 'on'\n                Ktraj=quiver3(Kx(:),Ky(:),Kz(:),[diff(Kx(:));0],[diff(Ky(:));0],[diff(Kz(:));0],'w-');\n                set(Ktraj,'AutoScale','off');\n        end\n        \n                set(gca,'Color','k','xcolor','c','ycolor','c','zcolor','c');\n        set(gca,'ydir','reverse');\n        xlabel('Kx','Color','w');\n        ylabel('Ky','Color','w');\n        zlabel('Kz','Color','w');\n        title('K-space Traj.','Color','w');\nend\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Src/Main/DoTrajK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22375061921504102}}
{"text": "function prfParams = hrfSet(prfParams,hrfParam,varargin)\n% hrfSave - save and update HRF parameters in pRF params structure\n%\n% prfParams = hrfSave(prfParams,hrfParam,valargin)\n%\n% 2009/03 SOD: wrote it.\n\nif ~exist('prfParams','var') || isempty(prfParams), error('Need prfParams'); end\nif ~exist('hrfParam','var') || isempty(hrfParam),   error('Need hrfParam');  end\n\nnScans = length(prfParams.stim);\n\n% loop over options\nswitch lower(hrfParam)\n    case {'hrftype'}\n        val = varargin2val(varargin{1},nScans);\n        for n = 1:nScans\n            switch lower(val{n})\n                case {'one gamma (boynton style)','o','one gamma' 'b' 'boynton'}\n                    prfParams.stim(n).hrfType = 'one gamma (Boynton style)';\n                case {'two gammas (spm style)' 't' 'two gammas' 'spm'}\n                    prfParams.stim(n).hrfType = 'two gammas (SPM style)';\n                case {'impulse' 'no hrf' 'none'}\n                    prfParams.stim(n).hrfType = 'impulse';\n            end\n        end\n        \n    case {'hrfparams' 'hrfparam'}\n        val = varargin2val(varargin{1},nScans);\n        for n = 1:nScans\n            switch prfParams.stim(n).hrfType\n                case {'one gamma (Boynton style)'}\n                    prfParams.stim(n).hrfParams{1} = val{n};\n                case {'two gammas (SPM style)'}\n                    prfParams.stim(n).hrfParams{2} = val{n};\n                \n%                 case {'impulse' 'no hrf' 'none'}\n%                     prfParams.stim(n).hrfParams{3} = val{n};\n                otherwise\n            end\n        end\n        \n    case {'hrf'}\n        hrfParams = hrfGet(prfParams,'hrfparams');\n        for n = 1:nScans\n            % compute hrf\n            [tmp tmphrf peak] = rfConvolveTC([1 zeros(1,prfParams.stim(n).nFrames-1)],...\n                prfParams.stim(n).framePeriod,...\n                prfParams.stim(n).hrfType,...\n                hrfParams{n});\n            \n            % we need to store the HRF for each scan because they might have\n            % different TRs. All other hrf parameters are independent of the TR.\n            prfParams.analysis.Hrf{n}    = tmphrf(:);\n            \n            % rfConvolveTC normalizes the hrf to the volume of the\n            % response. We save the peak amplitude so we can give the output\n            % in % BOLD relative to the maximum response as well.\n            prfParams.analysis.HrfMaxResponse = peak;\n        end;\n        \n    otherwise\n        fprintf(1,'[%s]:Unknown parameter (%s)',mfilename,hrfParam);\nend\n\nreturn\n\n\nfunction val=varargin2val(val,nScans)\nif ~iscell(val)\n    tmp = val;\n    val = cell(nScans,1);\n    for n = 1:nScans\n        val{n} = tmp;\n    end\nend\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/HRFestimation/hrfSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22375061921504102}}
{"text": "function Data = ParamStructData(S)\n\n%FUNCTION:\n%   This function takes a data struct, where every field contains a (N x M)\n%   matrix of numbers, and store the names of each field, the size of each\n%   field, and the total number of elements. This is then later used to\n%   pack everything into a struct.\n%\n%INPUTS:\n%   S = the data struct of interest. Each field must contain a matrix of\n%       numbers (no strings or other weird data types)\n%\n%OUTUTS:\n%   Data = struct with the added fields \n%       Data.Names = a (L x 1) cell array of field names\n%       Data.Size = a (L x 2) matrix of the size of these fields\n%       Data.Length = a scalar number of elements in S\n\n    Names = fieldnames(S);\n    Sizes = zeros(length(Names),2);\n    Idx = zeros(length(Names),2);\n    \n    for i=1:length(Names)\n       Sizes(i,:) = size(S.(Names{i})); \n    end\n    \n    %Figure out the start and end indicies of each field.\n    L = Sizes(:,1).*Sizes(:,2);\n    Idx(1,1) = 1;\n    for i=2:length(L)\n       Idx(i-1,2) = Idx(i-1,1)-1+L(i-1);\n       Idx(i,1) = Idx(i-1,2) + 1;\n    end\n    Idx(end,2) = sum(L);\n    \n    %Store the results:\n    Data.Names = Names;\n    Data.Sizes = Sizes;\n    Data.Idx = Idx;\n    \nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/DoublePendulum/ParamStructData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22362351616714526}}
{"text": "function writePOLY_pyramid(filename,V,E,F,H)\n  % WRITEPOLY_PYRAMID prints vertices, segments and facets to a .poly suitable\n  % for use with PYRAMID\n  %\n  % writePOLY_pyramid(filename,V,E,F,H)\n  %\n  % Inputs:\n  %   V  #V by dim=3 list of vertex positions\n  %   E  #E by 2+boundary_markers list of segment indices, indexing V, and\n  %     optional boundary markers\n  %   F  #F struct containing polygon information arrays\n  %     .facets  a #facets list of facets,  each facet is a polygon\n  %       **NOTE: facets index E *not* V, contrary to typical (V,F) meshes and\n  %       contrary to writePOLY_tetgen prototype\n  %     .boundary_markers a #facets list of boundary_markers\n  %     OR\n  %   F  #F by constant-degree+boundary_markers  list of facets\n  %\n  % Example:\n  %   % Mesh in (V,F)\n  %   % Gather all edges\n  %   E = [F(:,[2 3]);F(:,[3 1]);F(:,[1 2])];\n  %   [~,IE,IuE] = unique(sort(E,2),'rows');\n  %   % unique edges\n  %   uE = E(IE,:);\n  %   % reindex F into E\n  %   FinE = reshape(IuE,size(F));\n  %   Facets = [];\n  %   Facets.facets = mat2cell(FinE,ones(size(FinE,1),1),[3]);\n  %   Facets.boundary_marker = -ones(size(FinE,1),1);\n  %   writePOLY_pyramid(path,V,uE,Facets,[]);\n  %\n  % See also: cdt, tetgen, writePOLY_triangle, writePOLY_tetgen\n  %\n  %\n\n  % open file for writing\n  poly_file_handle = fopen(filename,'w');\n\n  dim = size(V,2);\n\n\n  if dim ~= 3\n    error('writePOLY_pyramid is for 3d meshes. Try writePOLY_triangle etc.');\n  end\n\n  % vertices section\n  fprintf(poly_file_handle,'# Part 1 - node list\\n');\n  format = '%d %.17g %.17g %.17g\\n';\n  fprintf(poly_file_handle,'%d %d 0 0\\n', size(V,1),size(V,2));\n  if ~isempty(V)\n    fprintf(poly_file_handle,format,[1:size(V,1);V']);\n  end\n\n  fprintf(poly_file_handle,'# Part 2 - segment list\\n');\n  fprintf(poly_file_handle,'%d %d\\n',size(E,1),size(E,2)-2);\n  format = ['%d %d %d' repmat(' %d',1,size(E,2)-2) '\\n'];\n  fprintf(poly_file_handle,format, [1:size(E,1);E']);\n\n  fprintf(poly_file_handle,'# Part 2 - facet list\\n');\n  % for now, always include boundary markers\n  % [num facets] [boundary markers]\n  assert(isempty(F) || isempty(F.facets) || iscell(F.facets));\n  if isempty(F)\n    fprintf(poly_file_handle,'0\\n');\n  else\n      fprintf(poly_file_handle,'%d %d\\n',numel(F.facets),~isempty(F.boundary_marker));\n      fs = cell2mat(cellfun(@size,F.facets,'UniformOutput',false));\n      % Try to print all at once if facets are all the same size\n      if ~isempty(fs) && all(fs(:,1) == 1) && all(fs(:,2) == fs(1,2))\n          % build format\n          fformat = [ ...\n              ... % index and size\n              '%d ' num2str(fs(1,2)) ...\n              ... % facet indices into segments\n              repmat(' %d',1,fs(1,2)) ...\n              ... % boundary markers\n              repmat(' %d',1,size(F.boundary_marker,2)) '\\n'];\n          % print all at once\n          fprintf(poly_file_handle,fformat, ...\n              [1:size(F.facets,1);[cell2mat(F.facets) F.boundary_marker]']);\n      else\n          % irregular face valences\n          for f=1:numel(F.facets)\n              % 1d list\n              assert(size(F.facets{f},1)==1 || size(F.facets{f},2) == 1);\n              fprintf('%d %d',f, numel(F.facets{f}));\n              % print indices\n              for p=1:numel(F.facets{f})\n                  fprintf(poly_file_handle,' %d',F.facets{f}(p));\n              end\n              fprintf(poly_file_handle,'\\n');\n          end\n      end\n  end\n\n  % [num holes]\n  fprintf(poly_file_handle,'# Part 3 - hole list\\n');\n  fprintf(poly_file_handle,'%d\\n',size(H,1));\n  if ~isempty(H)\n    assert(isempty(V) || size(H,2) == size(V,2));\n    fprintf(poly_file_handle,'%0.17g %0.17g %0.17g\\n',[1:size(H,1);H']);\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/writePOLY_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22362351616714524}}
{"text": "function [Data, para] = LoadWavMask_Simu_CHiME4(para, step, dataset)\nnCh = 6;\nwavlist_noisy = unique(my_cat('local/wavlist_tr05_simu'));\nwavlist_clean = findFiles(para.local.wavroot_clean, 'wav');\n\nfor i=1:length(wavlist_clean)   % build an index of clean files so we can find them quickly by utterance ID\n    [~,curr_uttID] = fileparts(wavlist_clean{i});\n    words = ExtractWordsFromString_v2(curr_uttID, '_');\n    clean_struct.(['U_' words{2}]) = wavlist_clean{i};\nend\n\nwavlist_noisy = wavlist_noisy(1:step:end);  % choose a portion of the data\nif strcmpi(dataset,'train')     % split to training and cross validation data\n    wavlist_noisy(50:50:end) = [];\nelse\n    wavlist_noisy = wavlist_noisy(50:50:end);\nend\n\n% Load data file list\nfor i=1:length(wavlist_noisy)\n    PrintProgress(i, length(wavlist_noisy), 500);\n    % provide the file name of the noisy speech,     \n    if para.topology.nChMask>1\n        ch_idx = randperm(nCh);\n        ch_idx(ch_idx==2) = [];     % we don't use channel 2\n        ch_idx = sort(ch_idx(1:para.topology.nChMask));\n        clear wav wavfile\n        for j=1:length(ch_idx)\n            wavfile{j} = [para.local.wavroot_noisy '/' wavlist_noisy{i} 'CH' num2str(ch_idx(j)) '.wav'];\n            if j==1 || ~para.local.useFileName\n                [wav(:,j),fs] = audioread(wavfile{j});\n            end\n        end\n        wav_noisy = wav(:,1);\n    else\n        wavfile{1} = [para.local.wavroot_noisy '/' wavlist_noisy{i}];\n        [wav, fs] = audioread(wavfile{1});\n        wav_noisy = wav;\n    end\n\n    [~,curr_uttID] = fileparts(wavlist_noisy{i});\n    words = ExtractWordsFromString_v2(curr_uttID, '_');\n    clean_uttID = words{2};\n    wavfile_clean = clean_struct.(['U_' clean_uttID]);\n    wav_clean = audioread(wavfile_clean);\n    \n    % Compute the mask based on local SNR estimate\n    \n    % The clean signal and noisy signal have different gains, so we need to\n    % first roughly normalize the absolute power of clean speech in wav_noisy and\n    % wav_clean\n    noise_power0 = mean(wav_noisy(1:fs*0.2).^2);\n    noisy_power0 = mean(wav_noisy.^2);\n    clean_power0 = noisy_power0 - noise_power0;\n    clean_power_true = mean(wav_clean.^2);\n    scale = sqrt(max(0,clean_power0) / clean_power_true);\n    scale = max(scale, 1);\n    wav_clean = wav_clean*scale;\n    \n    [~,spec_clean] = wav2abs(wav_clean,fs);\n    [~,spec_noisy] = wav2abs(wav_noisy,fs);\n    nFr = min(size(spec_clean,2), size(spec_noisy,2));\n    spec_clean = spec_clean(1:257,1:nFr);\n    spec_noisy = spec_noisy(1:257,1:nFr);\n    spec_noise = spec_noisy-spec_clean;\n    power_clean = abs(spec_clean).^2;\n    power_noisy = abs(spec_noisy).^2;\n    if 0\n        power_noise = power_noisy - power_clean;       % use the noisy-clean as noise estimate. This is not stable as sometimes the noisy and clean are not in the same scale\n    else\n        power_noise = repmat(mean(abs(spec_noisy(:,1:20)).^2,2), 1, nFr);   % use the first 20 frames as noise estimate\n    end\n    SNR = 10*log10(power_clean ./ power_noise);\n    mask{i} = logical(SNR>5);   % 0dB threshold gives us too many speech TF bins. So 5dB is used as threshold. The threshold may not be critical, as we are only using the mask to initialize the mask subnet. \n    if mod(i,100)==0\n        subplot(5,1,1:2); imagesc(log([abs(spec_clean).^2; abs(spec_noisy).^2; power_noise]));\n        subplot(5,1,3); imagesc(SNR);\n        subplot(5,1,4); imagesc(mask{i});\n        subplot(5,1,5); plot(wav_noisy); hold on; plot(wav_clean,'r'); hold off;\n        pause(.01);\n    end\n    \n    % make sure that the features generated from the wave have the same\n    % length as the mask\n    nSampleRequired = DecideWavLen4XFrames(nFr, para.topology.frame_len, para.topology.frame_shift);\n    if para.local.useFileName\n        for j=1:length(wavfile)\n            wavfile{j} = sprintf('%s 0 %2.3f', wavfile{j}, nSampleRequired/fs);\n        end\n        wavInt{i} = wavfile;\n    else\n        wavInt{i} = StoreWavInt16(wav(1:nSampleRequired,:))';      % note that the input waveform to the network should be a row vector\n    end\nend\n\nData(1).data = wavInt;\nData(2).data = mask;\npara.IO.context = [1 1];    % context size (for splicing) of data streams\npara.IO.sparse = [0 0];     % is the streams stored in sparse format?\npara.IO.DataSyncSet{1} = [];    % do we need to synchronize any two streams?\npara.IO.frame_rate = [16000 100];   % frame rate of the streams, i.e. how many frames per second. \npara.IO.isTensor = [1 1];   % whether we intend to use the input streams as tensor or just matrix. \n\nif para.local.useFileName\n    para.IO.inputFeature = [0 1];\n    para.IO.fileReader(1).name = 'wavfile';     % define the configurations used for reading the data from files\n    para.IO.fileReader(1).multiArrayFiles = 1;\n    para.IO.fileReader(1).array = 1;\n    para.IO.fileReader(1).fs = 16000;\n    para.IO.fileReader(1).precision = 'int16';  % store waveforms in int16 rather than floating points to save space. \n    para.IO.fileReader(2).name = '';\nelse\n    para.IO.inputFeature = [1 1];\nend\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/beamforming/mask_prediction/local/LoadWavMask_Simu_CHiME4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2235909002421654}}
{"text": "function imData=read_file_old(path_to_file,sframe,num2read)\n\n% Reads uncompressed multipage .tiff, .hdf5, or .avi files \n% Usage:  my_data=read_file('path_to_data_file, start frame, num to read);\n\n% INPUTS:\n% path_to_file:     location of file to be read\n% sframe:           first frame to read (optional, default: 1)\n% num2read:         number of frames to read (optional, default: read the whole file)\n\n% OUTPUT:\n% imData:           data in array format \n\n% Written by Eftychios A. Pnevmatikakis, Simons Foundation\n\nif nargin<2 || isempty(sframe); sframe = 1; end\n\n[~,~,ext] = fileparts(path_to_file);\n\nif strcmpi(ext,'.tiff') || strcmpi(ext,'.tif');\n    \n    %get image info\n    tiffInfo = imfinfo(path_to_file);\n    T = length(tiffInfo);\n    if nargin < 3 || isempty(num2read); num2read = T - sframe + 1; end\n    num2read = min(num2read,T - sframe + 1);\n    \n    Y1 = imread(path_to_file,'Index',sframe,'Info',tiffInfo);\n    imData = zeros([size(Y1),num2read],'like',Y1);\n    nd = ndims(Y1);\n    if nd == 2\n        imData(:,:,1) = Y1;   \n        for t = sframe+1:sframe+num2read-1\n            imData(:,:,t-sframe+1) = imread(path_to_file,'Index',t,'Info',tiffInfo);\n        end\n    elseif nd == 3\n        imData(:,:,:,1) = Y1;   \n        for t = sframe+1:sframe+num2read-1\n            imData(:,:,:,t-sframe+1) = imread(path_to_file,'Index',t,'Info',tiffInfo);\n        end        \n    end\n    \nelseif strcmpi(ext,'.hdf5') || strcmpi(ext,'.h5');\n    info = hdf5info(path_to_file);\n    dims = info.GroupHierarchy.Datasets.Dims;\n    name = info.GroupHierarchy.Datasets.Name;\n    if nargin < 3\n        num2read = dims(end)-sframe+1;\n    end\n    num2read = min(num2read,dims(end)-sframe+1);\n    imData = h5read(path_to_file,name,[ones(1,length(dims)-1),sframe],[dims(1:end-1),num2read]);\nelseif strcmpi(ext,'.avi')\n    v = VideoReader(path_to_file);\n    if nargin < 3\n        num2read = v.Duration*v.FrameRate-sframe+1;\n    end\n    Y1 = readFrame(v);\n    imData = zeros(v.Height,v.Width,num2read,'like',Y1);\n    i = 0;\n    while hasFrame(v)\n        video = readFrame(v);\n        i = i + 1;\n        if i >= sframe\n            imData(:,:,i-sframe+1) = video;\n        end\n        if i - sframe + 1 >= num2read\n            break;\n        end\n    end\nelse\n    error('Unknown file extension. Only .tiff, .avi and .hdf5 files are currently supported');\nend", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/read_file_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.22347071917150485}}
{"text": "function out = spm_run_fmri_data(job)\n% Set up the design matrix and run a design\n% SPM job execution function\n% takes a harvested job data structure and call SPM functions to perform\n% computations on the data.\n% Input:\n% job    - harvested job data structure (see matlabbatch help)\n% Output:\n% out    - computation results, usually a struct variable.\n%__________________________________________________________________________\n% Copyright (C) 2005-2019 Wellcome Trust Centre for Neuroimaging\n\n% $Id: spm_run_fmri_data.m 7739 2019-12-02 14:00:18Z guillaume $\n\n\noriginal_dir = pwd;\ncd(spm_file(job.spmmat{1},'fpath'));\n\nload(fullfile(pwd,'SPM.mat'));\n\n%-Image filenames\n%--------------------------------------------------------------------------\nSPM.xY.P = char(job.scans);\n\n%-Let SPM configure the design\n%--------------------------------------------------------------------------\nSPM = spm_fmri_spm_ui(SPM);\n\nif ~isempty(job.mask{1})\n    SPM.xM.VM         = spm_data_hdr_read(job.mask{:});\n    SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];\nend\n\n%-Save SPM.mat\n%--------------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration')                           %-#\nfmt = spm_get_defaults('mat.format');\ns = whos('SPM');\nif s.bytes > 2147483647, fmt = '-v7.3'; end\nsave('SPM.mat','SPM', fmt);\nfprintf('%30s\\n','...SPM.mat saved')                                    %-#\n\nout.spmmat{1} = fullfile(pwd, 'SPM.mat');\n\ncd(original_dir);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_fmri_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22322563167454432}}
{"text": "function ft_plot_montage(dat, varargin)\n\n% FT_PLOT_MONTAGE makes a montage of a 3-D array by selecting slices at regular distances\n% and combining them in one large 2-D image.  Note that the montage of MRI slices is not to\n% be confused with the EEG montage, which is a way of specifying the reference scheme\n% between electrodes.\n%\n% Use as\n%   ft_plot_montage(dat, ...)\n% where dat is a 3-D array.\n% \n% Additional options should be specified in key-value pairs and can be\n%   'transform'     = 4x4 homogeneous transformation matrix specifying the mapping from voxel space to the coordinate system in which the data are plotted.\n%   'location'      = 1x3 vector specifying a point on the plane which will be plotted, the coordinates are expressed in the coordinate system in which the data will be plotted. location defines the origin of the plane\n%   'orientation'   = 1x3 vector specifying the direction orthogonal through the plane which will be plotted (default = [0 0 1])\n%   'srange'        = \n%   'slicesize'     = \n%   'nslice'        = scalar, number of slices\n%   'maskstyle'     = string, 'opacity' or 'colormix', defines the rendering\n%   'background'    = needed when maskstyle is 'colormix', 3D-matrix with\n%                     the same size as the data matrix, serving as\n%                     grayscale image that provides the background\n% \n% See also FT_PLOT_ORTHO, FT_PLOT_SLICE, FT_SOURCEPLOT\n\n% undocumented, these are passed on to FT_PLOT_SLICE\n%   'intersectmesh'  = triangulated mesh through which the intersection of the plane will be plotted (e.g. cortical sheet)\n%   'intersectcolor' = color for the intersection\n\n% Copyrights (C) 2012, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\ntransform       = ft_getopt(varargin, 'transform', eye(4));\nloc             = ft_getopt(varargin, 'location');\nori             = ft_getopt(varargin, 'orientation');\nsrange          = ft_getopt(varargin, 'slicerange');\nslicesize       = ft_getopt(varargin, 'slicesize');\nnslice          = ft_getopt(varargin, 'nslice');\nbackgroundcolor = ft_getopt(varargin, 'backgroundcolor', [0 0 0]);\n\n% the intersectmesh and plotmarker options are passed on to FT_PLOT_SLICE\ndointersect = ~isempty(ft_getopt(varargin, 'intersectmesh'));\ndomarker    = ~isempty(ft_getopt(varargin, 'plotmarker'));\n\n% set the location if empty\nif isempty(loc) && (isempty(transform) || isequal(transform, eye(4)))\n  % go to the middle of the volume if the data seem to be in voxel coordinates\n  loc = size(dat)./2;\nelseif isempty(loc)\n  % otherwise take the origin of the coordinate system\n  loc = [0 0 0];\nend\n\n% check compatibility of inputs\nif size(loc, 1) == 1 && isempty(nslice)\n  nslice = 20;\nelseif size(loc, 1) == 1 && ~isempty(nslice)\n  % this is not a problem, slice spacing will be determined\nelseif size(loc, 1) > 1 && isempty(nslice)\n  % this is not a problem, number of slices is determined by loc\n  nslice = size(loc, 1);\nelseif size(loc, 1) > 1 && ~isempty(nslice)\n  if size(loc, 1) ~= nslice\n    ft_error('you should either specify a set of locations or a single location with a number of slices');\n  end\nend\n\n% set the orientation if empty\nif isempty(ori)\n  ori = [0 0 1];\nend\n\n% ensure the ori to have unit norm\nfor k = 1:size(ori,1)\n  ori(k,:) = ori(k,:)./norm(ori(k,:));\nend\n\n% determine the slice range\nif size(loc, 1) == 1 && nslice > 1\n  if isempty(srange) || (ischar(srange) && strcmp(srange, 'auto'))\n    srange = [-50 70];\n  else\n  end\n  loc = repmat(loc, [nslice 1]) + linspace(srange(1),srange(2),nslice)'*ori;\nend\n\n% ensure that the ori has the same size as the loc\nif size(ori,1)==1 && size(loc,1)>1\n  ori = repmat(ori, size(loc,1), 1);\nend\n\ndiv     = [ceil(sqrt(nslice)) ceil(sqrt(nslice))];\noptarg  = varargin;\ncorners = [inf -inf inf -inf inf -inf]; % get the corners for the axis specification\n\nfor k = 1:nslice\n  % define 'x' and 'y' axis in projection plane, the definition of x and y is more or less arbitrary\n  [x, y] = projplane(ori(k,:)); % z = ori\n  \n  % get the transformation matrix to project onto the xy-plane\n  T  = [x(:) y(:) ori(k,:)' loc(k,:)'; 0 0 0 1];\n  \n  optarg = ft_setopt(optarg, 'location',    loc(k,:));\n  optarg = ft_setopt(optarg, 'orientation', ori(k,:));\n  ix     = mod(k-1, div(1));\n  iy     = floor((k-1)/div(1));\n  h(k)   = ft_plot_slice(dat, optarg{:}); % FIXME is it safe to pass all optinoal inputs?\n  \n  xtmp = get(h(k), 'xdata');\n  ytmp = get(h(k), 'ydata');\n  ztmp = get(h(k), 'zdata');\n  siz  = size(xtmp);\n  if k==1 && isempty(slicesize)\n    slicesize = siz;\n  end\n  \n  % project the positions onto the xy-plane\n  pos = [xtmp(:) ytmp(:) ztmp(:)];\n  pos = ft_warp_apply(inv(T), pos);\n  \n  xtmp = reshape(pos(:,1), siz);\n  ytmp = reshape(pos(:,2), siz);\n  ztmp = reshape(pos(:,3), siz);\n  \n  % add some offset in the x and y directions to create the montage\n  offset(1) = iy*(slicesize(1)-1);\n  offset(2) = ix*(slicesize(2)-1); \n  \n  % update the specification of the corners of the montage plot\n  if ~isempty(xtmp)\n    c1 = offset(1) + min(xtmp(:));\n    c2 = offset(1) + max(xtmp(:));\n    c3 = offset(2) + min(ytmp(:));\n    c4 = offset(2) + max(ytmp(:));\n    c5 = min(ztmp(:));\n    c6 = max(ztmp(:));\n  end\n  corners = [min(corners(1),c1) max(corners(2),c2) min(corners(3),c3) max(corners(4),c4) min(corners(5),c5) max(corners(6),c6)];\n  \n  % update the positions\n  set(h(k), 'ydata', offset(1) + xtmp);\n  set(h(k), 'xdata', offset(2) + ytmp);\n  set(h(k), 'zdata',         0 * ztmp);\n  \n  if dointersect || domarker\n    if ~exist('pprevious', 'var'), pprevious = []; end\n    p = setdiff(findobj(gcf, 'type', 'patch'), pprevious);\n    for kk = 1:numel(p)\n      xtmp = get(p(kk), 'xdata');\n      ytmp = get(p(kk), 'ydata');\n      ztmp = get(p(kk), 'zdata');\n      siz2 = size(xtmp);\n      \n      pos = [xtmp(:) ytmp(:) ztmp(:)];\n      pos = ft_warp_apply(inv(T), pos);\n  \n      xtmp = reshape(pos(:,1), siz2);\n      ytmp = reshape(pos(:,2), siz2);\n      ztmp = reshape(pos(:,3), siz2);\n  \n      % update the positions\n      set(p(kk), 'ydata', offset(1) + xtmp);\n      set(p(kk), 'xdata', offset(2) + ytmp);\n      set(p(kk), 'zdata',         0.0001 * ztmp);\n    end\n    pprevious = [pprevious(:);p(:)];\n  end\n  % drawnow; %this statement slows down the process big time on some file\n  %systems. I don't know what's going on there, but the statement is not\n  %really necessary, so commented out.\nend\nset(gcf, 'color', backgroundcolor);\nset(gca, 'zlim', [0 1]);\n%axis equal;\naxis off;\nview([0 90]);\naxis(corners([3 4 1 2]));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [x, y] = projplane(z)\n[u, s, v] = svd([eye(3) z(:)]);\nx = u(:, 2)';\ny = u(:, 3)';\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/ft_plot_montage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22317699621927717}}
{"text": "function ans = calc_minDose(doseBinsMidPtsV, volsHistV, volumeType)\n% Calculates the minimum dose for a given DVH\n% The last argument 'volumeType' is ignored in this instance\n%\n%  MODIFICATION ALERT:  THIS FUNCTION IS UTILIZED BY THE DREXLER CODEBASE\n%\n%  Last modified: AJH 11/05\n% \n%  Usage:  calc_minDose(doseBinsV, volsHistV)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nind = find(volsHistV~=0,1,'first');\nans = doseBinsMidPtsV(ind);\n\nreturn;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/calc_minDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.22317699621927714}}
{"text": "function [H,Rest,activeUEs] = functionExampleSetup_Quadriga(L,Kdrop,B,noiseVariancedBm,Kmax,f,M,polarizations)\n%This function generates the channel realizations between UEs at random\n%locations and the BSs in the running example, defined in Section 4.1.3.\n%BSs with cylindrical arrays and channel are generated using QuaDRiGa from\n%the Fraunhofer Heinrich Hertz Institute. The Urban Microcell NLOS scenario\n%is used for channel modeling. QuaDRiGa needs to be installed separately\n%(http://www.quadriga-channel-model.de) and is delivered with a separate\n%license. This function has been tested using QuaDRiGa version 1.4.8-571.\n%\n%INPUT:\n%L                = Number of BSs and cells\n%Kdrop            = Number of UEs to be dropped in the square around a BS\n%B                = Bandwidth in Hz\n%noiseVariancedBm = Noise variance in dBm\n%Kmax             = Maximum number of UEs served by a BS\n%f                = Pilot reuse factor, giving pilot length Kmax*f\n%M                = Number of BS antennas\n%polarizations    = Select number of antenna polarizations (1 or 2)\n%\n%OUTPUT:\n%H         = M x 400 x K x L x L matrix with the channel realizations over\n%            400 subcarriers at one time instance\n%Rest      = M x M x K x L x L matrix with estimates of the spatial\n%            correlation matrices for all UEs in the network.\n%            Rest(:,:,k,j,l) is the correlation matrix for the channel\n%            between UE k in cell j and the BS in cell l.\n%activeUEs = Kmax x L with zeros and ones. activeUEs(k,l)==1 means that\n%            pilot k is used by a UE in cell l\n%\n%\n%This Matlab function was developed to generate simulation results to:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%% Create new Quadriga layout\n\n%Set irrelevant parameters\ns = simulation_parameters;\ns.sample_density = 1;\ns.use_absolute_delays = 1;\n\n%Set center frequency\ncenter_frequency = 2e9;\ns.center_frequency = center_frequency;\n\n%Number of subcarriers\nnbrOfSubcarriers = 400;\n\n%Create new layout from general parameters\nlay = layout(s);\n\n%Generate BSs\nlay.no_tx = L;\n\n%Set BS heights\nlay.tx_position(3,:) = 25;\n\n%Set the length in meters of the total square area\nsquareLength = 1000;\n\n%Number of BSs per dimension\nnbrBSsPerDim = sqrt(L);\n\n\n%% Deploy BSs\n\n%Minimum distance between BSs and UEs\nminDistance = 35;\n\n%Distance between BSs in vertical/horizontal direction\ninterSiteDistance = squareLength/nbrBSsPerDim;\n\n%Deploy BSs on the grid\nlocationsGridHorizontal = repmat(interSiteDistance/2:interSiteDistance:squareLength-interSiteDistance/2,[nbrBSsPerDim 1]);\nlocationsGridVertical = locationsGridHorizontal';\nBSpositions = locationsGridHorizontal(:) + 1i*locationsGridVertical(:);\n\nfor j = 1:length(BSpositions)\n    \n    lay.tx_position(1:2,j) = [real(BSpositions(j)); imag(BSpositions(j))];\n    \nend\n\n\n%% Create a circular antenna array for each BS\nM_V = 5; %Number of vertical antennas\nM_H = M/M_V; %Number of antennas on each horizontal circle\n\n%Define the antenna spacing (in number of wavelengths)\nantennaSpacing = 1/2; %Half wavelength distance\n\nif polarizations == 1\n    PolarizationIndicator = 1; %Single polarization antennas switching between vertical and horizontal\nelseif polarizations == 2\n    PolarizationIndicator = 3; %Dual +/-45deg polarized antennas\nend\n\n%Compute height of array\narrayHeight = (M_V-1)*antennaSpacing*3e8/center_frequency;\n\nif (PolarizationIndicator==1) %Single polarized elements\n    \n    circumference = M_H*antennaSpacing*3e8/center_frequency;\n    radius = circumference/(2*pi);\n    delta_angle = 2*pi/M_H;\n    \n    %Go through all BSs\n    for b = 1:L\n        \n        %Create rectangular array of size M_V x M_H\n        lay.tx_array(b).generate('3gpp-3d', 1, M_V, M_H, center_frequency, PolarizationIndicator, 0, antennaSpacing);\n        \n        %Place antennas on a circle and rotate radiation patters\n        for i = 1:M_V\n            for j = 1:M_H\n                indices = (i-1)*M_H + j;\n                angle = (j-1)*delta_angle;\n                lay.tx_array(b).element_position(1, indices) = radius*cos(angle);\n                lay.tx_array(b).element_position(2, indices) = radius*sin(angle);\n                lay.tx_array(b).element_position(3, indices) = (i-1)*antennaSpacing*3e8/center_frequency - arrayHeight/2;\n                lay.tx_array(b).rotate_pattern(rad2deg(angle), 'z', indices, 0);\n                \n                if mod(indices,2) == 0 %Switch between vertical and horizontal polarization\n                    lay.tx_array(b).rotate_pattern(90, 'y', indices, 2);\n                end\n            end\n        end\n    end\n    \nelseif (PolarizationIndicator==3) %Dual polarized elements\n    \n    circumference = M_H/2*antennaSpacing*3e8/center_frequency;\n    radius = circumference/(2*pi);\n    delta_angle = 2*pi/(M_H/2);\n    \n    %Go through all BSs\n    for b = 1:L\n        \n        %Create rectangular array of size M_V x M_H/2\n        lay.tx_array(b).generate('3gpp-3d', 1, M_V, M_H/2, center_frequency, PolarizationIndicator, 0, antennaSpacing);\n        \n        %Place antennas on a circle and rotate radiation patters (while keeping co-located antennas together)\n        for i = 1:M_V\n            for j = 1:M_H/2\n                indices = (i-1)*M_H + 2*j-1 : (i-1)*M_H + 2*j;\n                angle = (j-1)*delta_angle;\n                lay.tx_array(b).element_position(1, indices) = radius*cos(angle);\n                lay.tx_array(b).element_position(2, indices) = radius*sin(angle);\n                lay.tx_array(b).element_position(3, indices) = (i-1)*antennaSpacing*3e8/center_frequency - arrayHeight/2;\n                lay.tx_array(b).rotate_pattern(rad2deg(angle), 'z', indices, 0);\n            end\n        end\n    end\nend\n\n%Compute all nine alternatives of the BS locations when using wrap around\nwrapHorizontal = repmat([-squareLength 0 squareLength],[3 1]);\nwrapVertical = wrapHorizontal';\nwrapLocations = wrapHorizontal(:)' + 1i*wrapVertical(:)';\n\n%Compute the exact dimension of the square where the users are located\nmaxDistance = interSiteDistance;\n\n\n\n%Prepare to put out UEs in the cells\nUEpositions = zeros(Kdrop,L);\nUEpositionsWrapped = zeros(Kdrop,L,length(wrapLocations));\nperBS = zeros(L,1);\n\n%Go through all the cells\nfor l = 1:L\n    \n    %Put out K UEs in the cell, uniformly at random. The procedure is\n    %iterative since UEs that do not satisfy the minimum distance are\n    %replaced with new UEs\n    while perBS(l)<Kdrop\n        \n        %Put out users\n        UEremaining = Kdrop-perBS(l);\n        posX = rand(UEremaining,1)*maxDistance - maxDistance/2;\n        posY = rand(UEremaining,1)*maxDistance - maxDistance/2;\n        posXY = posX + 1i*posY;\n        \n        %Keep those that satisfy the minimum distance\n        posXY = posXY(abs(posXY)>=minDistance);\n        \n        %Store new UEs\n        UEpositions(perBS(l)+1:perBS(l)+length(posXY),l) = posXY + BSpositions(l);\n        perBS(l) = perBS(l)+length(posXY);\n        \n    end\n    \n    %Create alternative UE positions using wrap around\n    for k = 1:Kdrop\n        \n        UEpositionsWrapped(k,l,:) = UEpositions(k,l) + wrapLocations;\n        \n    end\n    \nend\n\n\n\n%% Configure UEs\n\nKtotal = Kdrop*L*length(wrapLocations); %Total number of UEs\n\n%Define UE heights\nUE_heights = 1.5*ones(Kdrop,L);\nUE_heightsWrapped = repmat(UE_heights,[1 1 length(wrapLocations)]);\n\n%Generate UEs\nlay.no_rx = Ktotal;\n\n%Define UE antennas\nlay.rx_array.generate('omni');\n\n\n%% Simulate channels\n\n% Randomly distribute UEs\nlay.rx_position =  [real(UEpositionsWrapped(:))'; imag(UEpositionsWrapped(:))'; UE_heightsWrapped(:)'];\n\n%Define tracks for each UE, assuming a fixed UE location\nfor k=1:Ktotal\n    lay.track(k).generate('linear',0,0) %Define a linear track consisting of only one position\n    lay.track(k).scenario = '3GPP_3D_UMi_NLOS'; %Select the Urban Microcell NLOS scenario\nend\n\n%Generate pilot patterns\nif f == 1\n    \n    pilotPattern = ones(L,1);\n    \nelseif f == 2 %Only works for 16 BSs\n    \n    pilotPattern = kron(ones(2,1),[1; 2; 1; 2; 2; 1; 2; 1]);\n    \nend\n\n\n%Randomize pilot allocation in each cell\nrandOrder = zeros(Kmax*f,L);\n\nfor j = 1:L\n    \n    randOrder(1+(pilotPattern(j)-1)*Kmax:pilotPattern(j)*Kmax,j) = randperm(Kmax)+(pilotPattern(j)-1)*Kmax;\n    \nend\n\n\n%Compute variance and standard deviation of the noise\nnoiseVar = 10^(noiseVariancedBm/10);\nnoiseStd = sqrt(noiseVar);\n\n\n%Prepare to store channel realizations\nH = zeros(M,nbrOfSubcarriers,Kmax,L,L);\nRest = zeros(M,M,Kmax,L,L);\nperBS = zeros(L,1);\nactiveUEs = zeros(Kmax,L);\n\n\n%% Go through all cells\nfor j = 1:L\n    \n    %Output simulation progress\n    disp([num2str(j) ' cells generated out of ' num2str(L)]);\n    \n    %Go through all UEs\n    for k = 1:Kdrop\n        \n        Huser = zeros(M,nbrOfSubcarriers,1,1,L);\n        Ruser = zeros(M,M,1,1,L);\n        \n        %Extract the channels to all BSs\n        for l = 1:L\n            \n            [~,minr] = min(abs(UEpositionsWrapped(k,j,:)-BSpositions(l)));\n            \n            userind = k+(j-1)*Kdrop+(minr-1)*Kdrop*L;\n            \n            [ h_channel, ~ ] = lay.get_channels_seg(l, userind);\n            Hextract = h_channel.fr(B, nbrOfSubcarriers);\n            \n            Huser(:,:,1,1,l) = reshape(Hextract,[M nbrOfSubcarriers])/noiseStd;\n            Ruser(:,:,1,1,l) = diag(mean(abs(Huser(:,:,1,1,l)).^2,2)/noiseVar);\n            \n        end\n        \n        %Determine which BS should serve the UE\n        [~,bestBS] = max(mean(sum(abs(Huser(:,:,1,1,:)).^2,1),2));\n        \n        %Check if the selected BS has pilots available\n        if perBS(bestBS)<Kmax\n            \n            %Add the UE to the cell of the selected BS\n            perBS(bestBS) = perBS(bestBS) + 1;\n            H(:,:,randOrder(perBS(bestBS)+(pilotPattern(bestBS)-1)*Kmax,bestBS),bestBS,:) = Huser;\n            Rest(:,:,randOrder(perBS(bestBS)+(pilotPattern(bestBS)-1)*Kmax,bestBS),bestBS,:) = Ruser;\n            activeUEs(randOrder(perBS(bestBS)+(pilotPattern(bestBS)-1)*Kmax,bestBS),bestBS) = 1;\n            \n        end\n        \n    end\n    \nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/functionExampleSetup_Quadriga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22314540306904537}}
{"text": "function varargout = process_scale( varargin )\n% PROCESS_SCALE: Sacle values by a constant factor.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'Scale values';\n    sProcess.FileTag     = 'scale';\n    sProcess.Category    = 'Filter';\n    sProcess.SubGroup    = 'Pre-process';\n    sProcess.Index       = 75;\n    sProcess.Description = '';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data', 'results', 'timefreq', 'raw', 'matrix'};\n    sProcess.OutputTypes = {'data', 'results', 'timefreq', 'raw', 'matrix'};\n    sProcess.nInputs     = 1;\n    sProcess.nMinFiles   = 1;\n    sProcess.isSeparator = 1;\n    % Default values for some options\n    sProcess.processDim  = 2;    % Process time by time\n    % === Factor\n    sProcess.options.factor.Comment = 'Multiplication factor: ';\n    sProcess.options.factor.Type    = 'value';\n    sProcess.options.factor.Value   = {1, '', 4};\n    % === Sensor types\n    sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): ';\n    sProcess.options.sensortypes.Type    = 'text';\n    sProcess.options.sensortypes.Value   = 'MEG, EEG';\n    sProcess.options.sensortypes.InputTypes = {'data', 'raw'};\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n    Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction sInput = Run(sProcess, sInput) %#ok<DEFNU>\n    % Get factor\n    factor = sProcess.options.factor.Value{1};\n    % Opposite values\n    sInput.A = factor * sInput.A;\n    % Do not keep the Std field in the output\n    if isfield(sInput, 'Std') && ~isempty(sInput.Std)\n        sInput.Std = [];\n    end\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22314539673029676}}
{"text": "function response = Golden(n,p)\n\npersistent mems\nif n==1; mems=0; end\n\n\nif p==0 || p==3 || n==1\n    response = 'cooperate';\nelse\n    response = 'defect';\nend\n\n\nif length(mems)>=4\n    if isequal( mems(end-3:end), [5 0 5 0] ); response = 'cooperate'; end\nend\nmems(n)=p;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27611-iterated-prisoners-dilemma/IPD/Ziggy/Golden.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22314539673029674}}
{"text": "function roi = dtiRoiFromImg(roiImg, imgXform, bb)\n% \n% roi = dtiRoiFromImg(roiImg, imgXform, bb)\n%\n% If not the identity matrix, imgXform is typically set to xformToAcpc. This\n% has the effect of forcing the roiImg to have the same voxel size as the \n% image that xformToAcpc is based on.\n%\n% bb is the bounding box, defined in the xformed spaced. Defaults to \n% [min(coords)-10; max(coords)+10].\n%\n% [roiImg, imgXform, bb] = dtiRoiToImg(roi);\n% % Do some processing on the ROI\n% perimImg = bwperim(roiImg);\n% perimRoi = dtiRoiFromImg(roiImg, imgXform, bb);\n%\n% HISTORY:\n% 2010.03.11 RFD wrote it.\n\n[coords(:,1), coords(:,2), coords(:,3)] = ind2sub(size(roiImg), find(roiImg));\ncoords(:,1) = coords(:,1) + bb(1,1) - 1;\ncoords(:,2) = coords(:,2) + bb(1,2) - 1;\ncoords(:,3) = coords(:,3) + bb(1,3) - 1;\ncoords = mrAnatXformCoords(inv(imgXform), coords);\nroi = dtiNewRoi('roiFromImg','g', coords);\n\nreturn;\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/roi/dtiRoiFromImg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22314539673029674}}
{"text": "function [input] = ft_apply_montage(input, montage, varargin)\n\n% FT_APPLY_MONTAGE changes the montage (i.e. linear combination) of a set of\n% electrode or gradiometer channels. A montage can be used for EEG rereferencing, MEG\n% synthetic gradients, MEG planar gradients or unmixing using ICA. This function not\n% only applies the montage to the EEG or MEG data, but also applies the montage to\n% the input EEG or MEG sensor array, which can subsequently be used for forward\n% computation and source reconstruction of the data.\n%\n% Use as\n%   [sens]    = ft_apply_montage(sens,     montage,  ...)\n%   [data]    = ft_apply_montage(data,     montage,  ...)\n%   [freq]    = ft_apply_montage(freq,     montage,  ...)\n%   [montage] = ft_apply_montage(montage1, montage2, ...)\n%\n% A montage is specified as a structure with the fields\n%   montage.tra      = MxN matrix\n%   montage.labelold = Nx1 cell-array\n%   montage.labelnew = Mx1 cell-array\n%\n% As an example, a bipolar montage could look like this\n%   bipolar.labelold  = {'1',   '2',   '3',   '4'}\n%   bipolar.labelnew  = {'1-2', '2-3', '3-4'}\n%   bipolar.tra       = [\n%     +1 -1  0  0\n%      0 +1 -1  0\n%      0  0 +1 -1\n%   ];\n%\n% The montage can optionally also specify the channel type and unit of the input\n% and output data with\n%   montage.chantypeold = Nx1 cell-array\n%   montage.chantypenew = Mx1 cell-array\n%   montage.chanunitold = Nx1 cell-array\n%   montage.chanunitnew = Mx1 cell-array\n%\n% Additional options should be specified in key-value pairs and can be\n%   'keepunused'    = string, 'yes' or 'no' (default = 'no')\n%   'inverse'       = string, 'yes' or 'no' (default = 'no')\n%   'balancename'   = string, name of the montage (default = '')\n%   'feedback'      = string, see FT_PROGRESS (default = 'text')\n%   'warning'       = boolean, whether to show warnings (default = true)\n%\n% If the first input is a montage, then the second input montage will be\n% applied to the first. In effect, the output montage will first do\n% montage1, then montage2.\n%\n% See also FT_READ_SENS, FT_DATATYPE_SENS\n\n% Copyright (C) 2008-2023, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif iscell(input)\n  % this represents combined EEG, ECoG and/or MEG\n  for i=1:numel(input)\n    input{i} = ft_apply_montage(input{i}, montage, varargin{:});\n  end\n  return\nend\n\n% use \"old/new\" instead of \"org/new\"\nmontage = fixoldorg(montage);\ninput   = fixoldorg(input); % the input might be a montage or a sensor array\n\n% get optional input arguments\nkeepunused    = ft_getopt(varargin, 'keepunused',  'no');\ninverse       = ft_getopt(varargin, 'inverse',     'no');\nfeedback      = ft_getopt(varargin, 'feedback',    'text');\nshowwarning   = ft_getopt(varargin, 'warning',     true);\nbname         = ft_getopt(varargin, 'balancename', '');\n\nif istrue(showwarning)\n  warningfun = @warning;\nelse\n  warningfun = @nowarning;\nend\n\n% ensure that the input montage is correct, see https://github.com/fieldtrip/fieldtrip/issues/1718\nassert(length(unique(montage.labelold))==length(montage.labelold), 'the montage is invalid');\nassert(length(unique(montage.labelnew))==length(montage.labelnew), 'the montage is invalid');\n\n% these are optional, at the end we will clean up the output in case they did not exist\nif ~istrue(inverse)\n  haschantype = (isfield(input, 'chantype') || isfield(input, 'chantypenew')) && all(isfield(montage, {'chantypeold', 'chantypenew'}));\n  haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitnew')) && all(isfield(montage, {'chanunitold', 'chanunitnew'}));\nelse\n  haschantype = (isfield(input, 'chantype') || isfield(input, 'chantypeold')) && all(isfield(montage, {'chantypeold', 'chantypenew'}));\n  haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitold')) && all(isfield(montage, {'chanunitold', 'chanunitnew'}));\nend\n\n% make sure they always exist to facilitate the remainder of the code\nif ~isfield(montage, 'chantypeold')\n  montage.chantypeold = repmat({'unknown'}, size(montage.labelold));\n  if isfield(input, 'chantype') && ~istrue(inverse)\n    ft_warning('copying input chantype to montage');\n    [sel1, sel2] = match_str(montage.labelold, input.label);\n    montage.chantypeold(sel1) = input.chantype(sel2);\n  end\nend\n\nif ~isfield(montage, 'chantypenew')\n  montage.chantypenew = repmat({'unknown'}, size(montage.labelnew));\n  if isfield(input, 'chantype') && istrue(inverse)\n    ft_warning('copying input chantype to montage');\n    [sel1, sel2] = match_str(montage.labelnew, input.label);\n    montage.chantypenew(sel1) = input.chantype(sel2);\n  end\nend\n\nif ~isfield(montage, 'chanunitold')\n  montage.chanunitold = repmat({'unknown'}, size(montage.labelold));\n  if isfield(input, 'chanunit') && ~istrue(inverse)\n    ft_warning('copying input chanunit to montage');\n    [sel1, sel2] = match_str(montage.labelold, input.label);\n    montage.chanunitold(sel1) = input.chanunit(sel2);\n  end\nend\n\nif ~isfield(montage, 'chanunitnew')\n  montage.chanunitnew = repmat({'unknown'}, size(montage.labelnew));\n  if isfield(input, 'chanunit') && istrue(inverse)\n    ft_warning('copying input chanunit to montage');\n    [sel1, sel2] = match_str(montage.labelnew, input.label);\n    montage.chanunitnew(sel1) = input.chanunit(sel2);\n  end\nend\n\nif ~isfield(input, 'label') && isfield(input, 'labelnew')\n  % the input data structure is also a montage\n  inputlabel = input.labelnew;\n  if isfield(input, 'chantypenew')\n    inputchantype = input.chantypenew;\n  else\n    inputchantype = repmat({'unknown'}, size(input.labelnew));\n  end\n  if isfield(input, 'chanunitnew')\n    inputchanunit = input.chanunitnew;\n  else\n    inputchanunit = repmat({'unknown'}, size(input.labelnew));\n  end\nelse\n  % the input should describe the channel labels, and optionally the type and unit\n  inputlabel = input.label;\n  if isfield(input, 'chantype')\n    inputchantype = input.chantype;\n  else\n    inputchantype = repmat({'unknown'}, size(input.label));\n  end\n  if isfield(input, 'chanunit')\n    inputchanunit = input.chanunit;\n  else\n    inputchanunit = repmat({'unknown'}, size(input.label));\n  end\nend\n\n% check the consistency of the montage\nif ~iscell(montage.labelold) || ~iscell(montage.labelnew)\n  ft_error('montage labels need to be specified in cell-arrays');\nend\n\n% check the consistency of the montage\nif ~all(isfield(montage, {'tra', 'labelold', 'labelnew'}))\n  ft_error('the second input argument does not correspond to a montage');\nend\n\n% check the consistency of the montage\nif size(montage.tra,1)~=length(montage.labelnew)\n  ft_error('the number of channels in the montage is inconsistent');\nelseif size(montage.tra,2)~=length(montage.labelold)\n  ft_error('the number of channels in the montage is inconsistent');\nend\n\n% use a default unit transfer from sensors to channels if not otherwise specified\nif ~isfield(input, 'tra') && isfield(input, 'label')\n  if     isfield(input, 'elecpos') && length(input.label)==size(input.elecpos, 1)\n    nchan = length(input.label);\n    input.tra = eye(nchan);\n  elseif isfield(input, 'coilpos') && length(input.label)==size(input.coilpos, 1)\n    nchan = length(input.label);\n    input.tra = eye(nchan);\n  elseif isfield(input, 'chanpos') && length(input.label)==size(input.chanpos, 1)\n    nchan = length(input.label);\n    input.tra = eye(nchan);\n  end\nend\n\nif istrue(inverse)\n  % swap the role of the old and new channels\n  tmp.labelnew    = montage.labelold;\n  tmp.labelold    = montage.labelnew;\n  tmp.chantypenew = montage.chantypeold;\n  tmp.chantypeold = montage.chantypenew;\n  tmp.chanunitnew = montage.chanunitold;\n  tmp.chanunitold = montage.chanunitnew;\n  % apply the inverse montage, this can be used to undo a previously applied montage\n  tmp.tra = full(montage.tra);\n  if rank(tmp.tra) < length(tmp.tra)\n    warningfun('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality');\n    tmp.tra = pinv(tmp.tra);\n  else\n    tmp.tra = inv(tmp.tra);\n  end\n  montage = tmp;\nend\n\n% keep only the columns that are not empty\nselcol = ~all(montage.tra==0, 1);\nif istrue(keepunused)\n  for i=find(selcol==false)\n    % don't remove the column if it corresponds to one of the output channels\n    selcol(i) = any(strcmp(montage.labelnew, montage.labelold{i}));\n  end\nend\nmontage.tra         = montage.tra(:,selcol);\nmontage.labelold    = montage.labelold(selcol);\nmontage.chantypeold = montage.chantypeold(selcol);\nmontage.chanunitold = montage.chanunitold(selcol);\nclear selcol\n\n% keep only the channels that are present in the input data\nremove = setdiff(montage.labelold, intersect(montage.labelold, inputlabel));\nselcol = match_str(montage.labelold, remove);\n% we cannot just remove the colums, all rows that depend on it should also be removed\nselrow = false(length(montage.labelnew),1);\nfor i=1:length(selcol)\n  selrow = selrow & (montage.tra(:,selcol(i))~=0);\nend\n% convert from indices to logical vector\nselcol = indx2logical(selcol, length(montage.labelold));\n% remove rows and columns\nmontage.labelold    = montage.labelold(~selcol);\nmontage.labelnew    = montage.labelnew(~selrow);\nmontage.chantypeold = montage.chantypeold(~selcol);\nmontage.chantypenew = montage.chantypenew(~selrow);\nmontage.chanunitold = montage.chanunitold(~selcol);\nmontage.chanunitnew = montage.chanunitnew(~selrow);\nmontage.tra         = montage.tra(~selrow, ~selcol);\nclear remove selcol selrow\n\n% add columns for channels present in the input data but that are not specified in the montage, stick to the original order in the data\n[dum, ix]   = setdiff(inputlabel, montage.labelold);\naddlabel    = inputlabel(sort(ix));\naddchantype = inputchantype(sort(ix));\naddchanunit = inputchanunit(sort(ix));\nm = size(montage.tra,1);\nn = size(montage.tra,2);\nk = length(addlabel);\n\n% % check for NaNs in unused channels; these will be mixed in with the rest\n% % of the channels and result in NaNs in the output even when multiplied\n% % with zeros or identity\n% if k > 0 && isfield(input, 'trial') % check for raw data now only\n%   cfg = [];\n%   cfg.channel = addlabel;\n%   cfg.showcallinfo = showcallinfo;\n%   data_unused = ft_selectdata(cfg, input);\n%   % use an anonymous function to test for the presence of NaNs in the input data\n%   hasnan = @(x) any(isnan(x(:)));\n%   if any(cellfun(hasnan, data_unused.trial))\n%     ft_error('FieldTrip:NaNsinInputData', ['Your input data contains NaNs in channels that are unused '...\n%       'in the supplied montage. This would result in undesired NaNs in the '...\n%       'output data. Please remove these channels from the input data (using '...\n%       'ft_selectdata) before attempting to apply the montage.']);\n%   end\n% end\n\nif istrue(keepunused)\n  % add the channels that are not rereferenced to the input and output of the montage\n  montage.tra((m+(1:k)),(n+(1:k))) = eye(k);\n  montage.labelold    = cat(1, montage.labelold(:), addlabel(:));\n  montage.labelnew    = cat(1, montage.labelnew(:), addlabel(:));\n  montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:));\n  montage.chantypenew = cat(1, montage.chantypenew(:), addchantype(:));\n  montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:));\n  montage.chanunitnew = cat(1, montage.chanunitnew(:), addchanunit(:));\nelse\n  % add the channels that are not rereferenced to the input of the montage only\n  montage.tra(:,(n+(1:k))) = zeros(m,k);\n  montage.labelold    = cat(1, montage.labelold(:), addlabel(:));\n  montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:));\n  montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:));\nend\nclear addlabel addchantype addchanunit m n k\n\n% determine whether all channels are unique\nm = size(montage.tra,1);\nn = size(montage.tra,2);\nif length(unique(montage.labelnew))~=m\n  ft_error('not all output channels of the montage are unique');\nend\nif length(unique(montage.labelold))~=n\n  ft_error('not all input channels of the montage are unique');\nend\n\n% determine whether all channels that have to be rereferenced are available\nif length(intersect(inputlabel, montage.labelold))~=length(montage.labelold)\n  ft_error('not all channels that are required in the montage are available in the data');\nend\n\n% reorder the columns of the montage matrix\n[selinput, selmontage] = match_str(inputlabel, montage.labelold);\nmontage.tra            = montage.tra(:,selmontage);\nmontage.labelold       = montage.labelold(selmontage);\nmontage.chantypeold    = montage.chantypeold(selmontage);\nmontage.chanunitold    = montage.chanunitold(selmontage);\n\n% ensure that the montage is double precision\nmontage.tra = double(montage.tra);\n\n% making the tra matrix sparse will speed up subsequent multiplications, but should not result in sparse output data\n% this only makes sense for matrices with a lot of zero elements; for dense matrices it is faster to keep it full\nif size(montage.tra,1)>1 && nnz(montage.tra)/numel(montage.tra) < 0.3\n  montage.tra = sparse(montage.tra);\nelse\n  montage.tra = full(montage.tra);\nend\n\n% update the channel scaling if the input has different units than the montage expects\nif isfield(input, 'chanunit') && ~isequal(input.chanunit, montage.chanunitold)\n  scale = ft_scalingfactor(input.chanunit, montage.chanunitold);\n  montage.tra = montage.tra * diag(scale);\n  montage.chanunitold = input.chanunit;\nelseif isfield(input, 'chanunitnew') && ~isequal(input.chanunitnew, montage.chanunitold)\n  scale = ft_scalingfactor(input.chanunitnew, montage.chanunitold);\n  montage.tra = montage.tra * diag(scale);\n  montage.chanunitold = input.chanunitnew;\nend\n\nif isfield(input, 'chantype') && ~isequal(input.chantype, montage.chantypeold)\n  ft_error('inconsistent chantype in data and montage');\nelseif isfield(input, 'chantypenew') && ~isequal(input.chantypenew, montage.chantypeold)\n  ft_error('inconsistent chantype in data and montage');\nend\n\nif isfield(input, 'labelold') && isfield(input, 'labelnew')\n  inputtype = 'montage';\nelseif isfield(input, 'tra')\n  inputtype = 'sens';\nelseif ft_datatype(input, 'raw')\n  inputtype = 'raw';\nelseif ft_datatype(input, 'timelock')\n  inputtype = 'timelock';\nelseif ft_datatype(input, 'freq') && isfield(input, 'fourierspctrm')\n  inputtype = 'freq';\nelseif ft_datatype(input, 'freq') && isfield(input, 'crsspctrm')\n  inputtype = 'freq_crsspctrm';\n\n  % attempt to convert to a chan-chan representation\n  input     = ft_checkdata(input, 'cmbstyle', 'full');\nelse\n  inputtype = 'unknown';\nend\n\nswitch inputtype\n  case 'montage'\n    % apply the montage on top of the other montage\n    if isa(input.tra, 'single')\n      % sparse matrices and single precision do not match\n      input.tra = full(montage.tra) * input.tra;\n    else\n      input.tra = montage.tra * input.tra;\n    end\n    input.labelnew    = montage.labelnew;\n    input.chantypenew = montage.chantypenew;\n    input.chanunitnew = montage.chanunitnew;\n\n  case 'sens'\n    % apply the montage to an electrode or gradiometer description\n    sens = input;\n    clear input\n\n    % apply the montage to the input\n    if isa(sens.tra, 'single')\n      % sparse matrices and single precision do not match\n      sens.tra = full(montage.tra) * sens.tra;\n    else\n      sens.tra = montage.tra * sens.tra;\n    end\n\n    % The montage operates on the coil weights in sens.tra, but the output channels can be different.\n    % If possible, we want to keep the old channel positions and orientations.\n    [sel1, sel2] = match_str(montage.labelnew, inputlabel);\n    keepchans = isequal(sel1(:)', 1:numel(montage.labelnew));\n\n    posweight = abs(montage.tra);\n    posweight = diag(1./sum(posweight,2)) * posweight;\n\n    if isfield(sens, 'chanpos')\n      if keepchans\n        sens.chanpos = sens.chanpos(sel2,:);\n      else\n        if ~isfield(sens, 'chanposold')\n          % add a chanposold only if it is not there yet\n          sens.chanposold  = sens.chanpos;\n          %  also keep the old label, type and unit for reference\n          sens.labelold    = inputlabel;\n          sens.chantypeold = inputchantype;\n          sens.chanunitold = inputchanunit;\n        end\n        % compute the new channel positions as a weighted sum of the old ones\n        sens.chanpos = posweight * sens.chanpos;\n      end\n    end\n\n    if isfield(sens, 'chanori')\n      if keepchans\n        sens.chanori = sens.chanori(sel2,:);\n      else\n        if ~isfield(sens, 'chanoriold')\n          sens.chanoriold = sens.chanori;\n        end\n        % compute the new channel orientations as a weighted sum of the old ones\n        sens.chanori = posweight * sens.chanori;\n      end\n    end\n\n    sens.label    = montage.labelnew;\n    sens.chantype = montage.chantypenew;\n    sens.chanunit = montage.chanunitnew;\n\n    % keep track of the order of the balancing and which one is the current one\n    if istrue(inverse)\n      if isfield(sens, 'balance')% && isfield(sens.balance, 'previous')\n        if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1\n          sens.balance.current  = sens.balance.previous{1};\n          sens.balance.previous = sens.balance.previous(2:end);\n        elseif isfield(sens.balance, 'previous')\n          sens.balance.current  = 'none';\n          sens.balance          = rmfield(sens.balance, 'previous');\n        else\n          sens.balance.current  = 'none';\n        end\n      end\n\n    elseif ~istrue(inverse) && ~isempty(bname)\n      if isfield(sens, 'balance')\n        % check whether a balancing montage with name bname already exist, and if so, how many\n        mnt = fieldnames(sens.balance);\n        sel = strmatch(bname, mnt);\n        if numel(sel)==0\n          % bname can stay the same\n        elseif numel(sel)==1\n          % the original should be renamed to 'bname1' and the new one should be 'bname2'\n          sens.balance.([bname, '1']) = sens.balance.(bname);\n          sens.balance                = rmfield(sens.balance, bname);\n          if isfield(sens.balance, 'current') && strcmp(sens.balance.current, bname)\n            sens.balance.current = [bname, '1'];\n          end\n          if isfield(sens.balance, 'previous')\n            sel2 = strmatch(bname, sens.balance.previous);\n            if ~isempty(sel2)\n              sens.balance.previous{sel2} = [bname, '1'];\n            end\n          end\n          bname = [bname, '2'];\n        else\n          bname = [bname, num2str(length(sel)+1)];\n        end\n      end\n\n      if isfield(sens, 'balance') && isfield(sens.balance, 'current')\n        if ~isfield(sens.balance, 'previous')\n          sens.balance.previous = {};\n        end\n        sens.balance.previous = [{sens.balance.current} sens.balance.previous];\n        sens.balance.current  = bname;\n        sens.balance.(bname)  = montage;\n      end\n    end\n\n    % rename the output variable\n    input = sens;\n    clear sens\n\n  case 'raw'\n    % apply the montage to the raw input data\n    data = input;\n    clear input\n\n    % there are two challenges to deal with\n    % 1) the input data can be single, and sparse(1) * single(0) fails\n    % 2) the input data can contain nans, and 0*nan returns a nan\n    % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3035 and https://github.com/fieldtrip/fieldtrip/issues/2169\n\n    Ntrials = numel(data.trial);\n    ft_progress('init', feedback, 'processing trials');\n    for i=1:Ntrials\n      ft_progress(i/Ntrials, 'processing trial %d from %d\\n', i, Ntrials);\n\n      if     ~isa(data.trial{i}, 'single') && ~any(isnan(data.trial{i}(:)))\n        data.trial{i} = montage.tra * data.trial{i};\n      elseif ~isa(data.trial{i}, 'single') &&  any(isnan(data.trial{i}(:)))\n        % do not multiply 0 in the montage with nan in the data\n        tmp = zeros(size(montage.tra,1), size(data.trial{i}, 2));\n        for j=1:size(montage.tra,1)\n          sel = montage.tra(j,:)~=0;\n          tmp(j,:) = montage.tra(j,sel) * data.trial{i}(sel,:);\n        end\n        data.trial{i} = tmp;\n      elseif  isa(data.trial{i}, 'single') && ~any(isnan(data.trial{i}(:)))\n        % sparse matrices and single precision do not match\n        data.trial{i} = full(montage.tra) * data.trial{i};\n      elseif  isa(data.trial{i}, 'single') &&  any(isnan(data.trial{i}(:)))\n        % sparse matrices and single precision do not match\n        % do not multiply 0 in the montage with nan in the data, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3035\n        tmp = zeros(size(montage.tra,1), size(data.trial{i}, 2));\n        for j=1:size(montage.tra,1)\n          sel = montage.tra(j,:)~=0;\n          tmp(j,:) = full(montage.tra(j,sel)) * data.trial{i}(sel,:);\n        end\n        data.trial{i} = tmp;\n      end\n    end % for Ntrials\n    ft_progress('close');\n\n    data.label    = montage.labelnew;\n    data.chantype = montage.chantypenew;\n    data.chanunit = montage.chanunitnew;\n\n    % rename the output variable\n    input = data;\n    clear data\n\n  case 'timelock'\n    % apply the montage to averaged data\n    timelock = input;\n    clear input\n\n    fn = {'avg', 'trial', 'individual', 'cov'};\n    for i=1:numel(fn)\n      if isfield(timelock, fn{i})\n        switch getdimord(timelock, fn{i})\n          case 'chan_time'\n            timelock.(fn{i}) = montage.tra * timelock.(fn{i});\n          case 'rpt_chan_time'\n            siz    = getdimsiz(timelock, fn{i});\n            nrpt   = siz(1);\n            nchan  = siz(2);\n            ntime  = siz(3);\n            output = zeros(nrpt, size(montage.tra,1), ntime);\n            for rptlop=1:nrpt\n              output(rptlop,:,:) = montage.tra * reshape(timelock.(fn{i})(rptlop,:,:), [nchan ntime]);\n            end\n            timelock.(fn{i}) = output; % replace the original field\n          case 'chan_chan'\n            timelock.(fn{i}) = montage.tra * timelock.(fn{i}) * montage.tra';\n          case 'rpt_chan_chan'\n            siz    = getdimsiz(timelock, fn{i});\n            nrpt   = siz(1);\n            nchan  = siz(2);\n            output = zeros(nrpt, size(montage.tra,1), size(montage.tra,1));\n            for rptlop=1:nrpt\n              output(rptlop,:,:) = montage.tra * reshape(timelock.(fn{i})(rptlop,:,:), [nchan nchan]) * montage.tra';\n            end\n            timelock.(fn{i}) = output; % replace the original field\n          otherwise\n            ft_error('unsupported dimord for %s', fn{i});\n        end % switch\n      end % if\n    end % for\n\n    timelock.label    = montage.labelnew;\n    timelock.chantype = montage.chantypenew;\n    timelock.chanunit = montage.chanunitnew;\n\n    % rename the output variable\n    input = timelock;\n    clear timelock\n\n  case 'freq'\n    % apply the montage to the spectrally decomposed data\n    freq = input;\n    clear input\n\n    switch getdimord(freq, 'fourierspctrm')\n      case 'rpttap_chan_freq'\n        siz    = [getdimsiz(freq, 'fourierspctrm') 1];\n        nrpt   = siz(1);\n        nchan  = siz(2);\n        nfreq  = siz(3);\n        output = zeros(nrpt, size(montage.tra,1), nfreq);\n        for foilop=1:nfreq\n          output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra';\n        end\n        freq.fourierspctrm = output; % replace the original Fourier spectrum\n\n      case 'rpttap_chan_freq_time'\n        siz    = getdimsiz(freq, 'fourierspctrm');\n        nrpt   = siz(1);\n        nchan  = siz(2);\n        nfreq  = siz(3);\n        ntime  = siz(4);\n        output = zeros(nrpt, size(montage.tra,1), nfreq, ntime);\n        for foilop=1:nfreq\n          for toilop = 1:ntime\n            output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra';\n          end\n        end\n        freq.fourierspctrm = output; % replace the original Fourier spectrum\n\n      otherwise\n        ft_error('unsupported dimord for fourierspctrm');\n    end % switch\n\n    freq.label    = montage.labelnew;\n    freq.chantype = montage.chantypenew;\n    freq.chanunit = montage.chanunitnew;\n\n    % rename the output variable\n    input = freq;\n    clear freq\n  case 'freq_crsspctrm'\n    % input freq data has a chan-chan crsspctrm, montage needs te be\n    % applied to both ends\n\n    freq = input;\n    clear input\n    if contains(getdimord(freq, 'crsspctrm'), 'rpt')\n      % first dimension is rpt-like, so the square is dimensions 2 and 3\n      siz   = [getdimsiz(freq, 'crsspctrm') 1];\n      nrpt  = siz(1);\n      nchan = siz(2);\n      nrest = prod(siz(4:end));\n      output = zeros([nrpt size(montage.tra,1).*[1 1] siz(4:end)]);\n      for rptlop = 1:nrpt\n        for restlop = 1:nrest\n          output(rptlop,:,:,restlop) = montage.tra*reshape(freq.crsspctrm(rptlop,:,:,restlop),[nchan nchan])*montage.tra';\n        end\n      end\n      freq.crsspctrm = output;\n    else\n      % the square is dimensions 1 and 2\n      siz   = [getdimsiz(freq, 'crsspctrm') 1];\n      nrest = prod(siz(4:end));\n      output = zeros([size(montage.tra,1).*[1 1] siz(4:end)]);\n      for restlop = 1:nrest\n        output(:,:,restlop) = montage.tra*freq.crsspctrm(:,:,restlop)*montage.tra';\n      end\n      freq.crsspctrm = output;\n    end\n\n    freq.label    = montage.labelnew;\n    freq.chantype = montage.chantypenew;\n    freq.chanunit = montage.chanunitnew;\n\n    % rename the output variable\n    input = freq;\n    clear freq\n  otherwise\n    ft_error('unrecognized input');\nend % switch inputtype\n\n% only retain the chantype and/or chanunit if they were present in the input\nif ~haschantype\n  input = removefields(input, {'chantype', 'chantypeold', 'chantypenew'});\nend\nif ~haschanunit\n  input = removefields(input, {'chanunit', 'chanunitold', 'chanunitnew'});\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% HELPER FUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = indx2logical(x, n)\ny = false(1,n);\ny(x) = true;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% HELPER FUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction nowarning(varargin)\nreturn\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/ft_apply_montage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2229919332879985}}
{"text": "function vis_topo(varargin)\n% handles:\n% handles.ics(1-8) has which ICs to plot\n\n% get the updated stream buffer\nW = evalin('base','W');\nsphere = evalin('base','sphere');\nWinv = inv(W*sphere);\nhandles = varargin{3};\n\nit = mod(get(varargin{1},'TasksExecuted')-1,8)+1;\nhstr = ['axesIC' int2str(it)];\nhand = get(handles.(hstr),'children');\n[map, cmin, cmax] = topoplotUpdate(Winv(:,handles.ics(it)), handles.chanlocs,'electrodes','off','gridscale',32);\nset(hand(end),'CData',map);\nset(handles.(hstr),'CLim',[cmin cmax]);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/functions/vis/vis_topo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22294176500283133}}
{"text": "function image = motionCompMeanImage(view, scans, frames)\n\n%    function image = motionCompMeanImage(view, [scans], [frames])\n% \n% gb 01/22/05\n% \n% Finds the image closest to the mean image across frames for all scans\n% Default : scans = current scan\n%           frames = all frames\n\n% Initilizes arguments and variables\n\nglobal dataTYPES\ncurType = viewGet(view, 'curdatatype');\n\nif ieNotDefined('scans')\n    scans = 1:length(dataTYPES(curType).scanParams);\nend\nif ieNotDefined('frames')\n    frames = 1:length(dataTYPES(curType).scanParams(scans(1)).nFrames);\nend\n\n% Computes the mean image\nmeanImage = motionCompComputeMean(view,scans,frames);\n\n% Finds the image closest to the mean image\n[scan,frame,mn] = motionCompNearestImage(view, scans, frames, meanImage);\n\n% Loads this image\nframe = frames(frame);\nimage = motionCompLoadImages(view,scan,frame);", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/MotionComp/MI/Common/motionCompMeanImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22279367514197138}}
{"text": "function [u,perm,gjc,g] = urotorder(u,K, maxu,permIN) %#ok\n% [u,perm,gjc,g] = urotorder(u,K, maxu,permIN)\n%\n% UROTORDER  Stable reORDERing of triu U-factor by Givens ROTations.\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\n%Indicate to the user Matlab cannot find the SeDuMi binaries\nsedumi_binary_error();", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/urotorder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22270471038272138}}
{"text": "function [throttle_factor, counter_out] = manage_clutchgearshift(trigger_gearshift, counter_in, throttle_shiftbreak_s, tSPhysics)\n%% Documentation       \n%\n% Author:       Leonhard Hermansdorfer (leo.hermansdorfer@tum.de)\n% \n% Start Date:   15.09.2021\n%\n% Description:  this function applies throttle lifting if a gear shift happend.\n%               This aims at increasing the vehicle stability during shifting. \n% \n% Inputs:\n%   - trigger_gearshift         gear shift trigger (1 if shift happend, otherwise 0)\n%   - counter_in                same value as counter_out from last timestep\n%   - throttle_shiftbreak_s     time duration of throttle lift after gear shift\n%\n% Outputs:\n%   - throttle_factor           multiply factor for throttle signal (either 1 or 0)\n%   - counter_out               counter which is fed back into the function in the next timestep\n\n    % detect gear shift (direction independent)\n    trigger_gearshift = min(1, abs(trigger_gearshift));\n\n    % start counter if a gear shift has happend\n    if trigger_gearshift == 1\n        counter_in = throttle_shiftbreak_s;\n    end\n\n    % count down to zero\n    counter_out = counter_in - tSPhysics;\n\n    % calculate throttle factor\n    if counter_out > 0\n        throttle_factor = 0;\n    else\n        throttle_factor = 1;\n    end\n\nend\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehiclesubsystems/powertrain/src/manage_clutchgearshift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2227047103827213}}
{"text": "function u = tora_control(x)\n\nload('tora_data', 'K', 'U', 'domain');\n\np = [x(3) x(4)];\nu = tpcontroller(p, x, K, U, domain);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25514-tp-tool/tptool/example/tora/tora_control.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.22266021582819523}}
{"text": "% The COBRAToolbox: testOptGene.m\n%\n% Purpose:\n%     - test the optGene function\n%\n% Authors:\n%     - Jacek Wachowiak\n\n% Check requirements\n\nrequiredToolboxes = {'gads_toolbox'};  % This is the Global optimization toolbox\nsolvers = prepareTest('needsLP', true, 'needsMILP', true, 'toolboxes', requiredToolboxes);\n% If we have more than one solver per type (LP/MILP), only use those that\n% are available for both.\nif numel(solvers.LP) > 1 && numel(solvers.MILP) > 1\n    commonSolvers = intersect(solvers.LP, solvers.MILP);\n    if ~isempty(commonSolvers)  % If there is any such solver\n        solvers.MILP = commonSolvers;\n        solvers.LP = commonSolvers;\n    else  % Use only one solver. otherwise we can get into troubles.\n        solvers.LP = solvers.LP(1);\n        solvers.MILP = solvers.MILP(1);\n    end\nend\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testOptGene'));\ncd(fileDir);\n\n% test variables\nmodel = getDistributedModel('ecoli_core_model.mat');\ntargetRxn = model.rxns{39};  % Succinate\nfructose_substrateRxn = model.rxns{26};  % Fructose, even though this has no incluence whatsoever.\ngenerxnList = model.rxns(setdiff([1:95], [11, 13, 26, 39]));  % Everything besides the ATP Maintenance, The biomass reaction and the substrate and target reactions.\n\nklt=min([length(solvers.LP),length(solvers.MILP)]);\nfor k = 1:klt\n    changeCobraSolver(solvers.LP{k}, 'LP', 0);\n    changeCobraSolver(solvers.MILP{k}, 'MILP', 0);\n    fprintf(' -- Running testOptGene using the solver interfaces: LP: %s ; MILP: %s... ', solvers.LP{k}, solvers.MILP{k});\n    basicsolution = optimizeCbModel(model);\n    % function outputs\n    % requires Global Optimization Toolbox\n    % Set the rng, for reproducability\n    rng(0);\n    [x, population, scores, optGeneSol] = optGene(model, targetRxn, fructose_substrateRxn, generxnList, 'StallTimeLimit', 15, 'TimeLimit', 30);\n    % Check, that we get the expected solution from a previous run.\n    optSols = population((optGeneSol.scores == min(optGeneSol.scores)), :);  % Get the set of optimal Solutions.\n    optReacs = optSols(1, :);\n    model2 = model;\n    model2.lb(ismember(model2.rxns, generxnList(optReacs))) = 0;\n    model2.ub(ismember(model2.rxns, generxnList(optReacs))) = 0;\n    sol = optimizeCbModel(model2);\n    % Lets only assert, that we have some improvement.\n    assert(sol.v(39) - basicsolution.v(39) > 0);\n\nend\n% close the open windows\nclose all\n\n% Remove the output, to keep the toolbox updateable.\ndelete([fileDir filesep 'MILPProblem.mat']);\n\nfprintf('Done.\\n');\n% change to old directory\ncd(currentDir);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/design/testOptGene.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2226602158281952}}
{"text": "function [hdr] = read_bucn_nirshdr(filename)\n\n% READ_BUCN_NIRSHDR reads the header information of ASCII-formatted NIRS\n% data acquired with the UCL-BIRKBECK machine and postprocessed by the\n% Paris group. The first line contains the channel labels and the rest of\n% the file contains per line a time sample. The first column specifies the\n% time axis.\n%\n% Use as\n%   [hdr] = read_bucn_nirshdr(filename)\n%\n% See also read_bucn_nirsdata, READ_BUCN_NIRSEVENT\n\n% Copyright (C) 2011, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id: read_bucn_nirshdr.m$\n\nfid = fopen_or_error(filename, 'r');\n\n% read the first line\nline1 = textscan(fid, '%[^\\n]',1);\n\n% field delimiter can be space or tab\nlabelspc = textscan(line1{1}{1}, '%[^ ]');\nlabeltab = textscan(line1{1}{1}, '%[^\\t]');\n\n% let tab as a delimiter prevail\nif numel(labeltab{1})>1\n  label = labeltab{1};\nelse\n  label = labelspc{1};\nend\nnchan = numel(label);\nFs    = str2num(strtok(strtok(label{1},'#Time.'),'Hz'));\n\n% test whether the channel labels are non-numeric\nlabelnumber = cellfun(@str2num, label, 'UniformOutput', false);\nlabelstring = cellfun(@isempty, labelnumber, 'UniformOutput', true);\nif ~any(labelstring)\n  ft_error('channel labels were not found in the first line of the file');\nend\n\n% read the rest\ndat = textscan(fid, '%f');\nfclose(fid);\n\ndat  = reshape(dat{1}, nchan, []);\nnsmp = size(dat,2);\n\n% create the output\nhdr          = [];\nhdr.Fs       = Fs;\nhdr.label    = label;\nhdr.nTrials  = 1;\nhdr.nSamples = nsmp;\nhdr.nSamplesPre = 0;\nhdr.nChans   = nchan;\nhdr.time     = dat(1,:); % events in the raw event file have both a sample and a time stamp\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/fileio/private/read_bucn_nirshdr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2226602158281952}}
{"text": "function resetTimeTicks(h, num, format)\n% reset function for setTimeTicks\n% SEE ALSO: setTimeTicks\n\n%--------------------------------------------------------------------------\n%               ___ ___ ___\n%     __ _ ___ / __| _ | __|\n%    / _` / _ \\ (_ |  _|__ \\\n%    \\__, \\___/\\___|_| |___/\n%    |___/                    v 1.0RC1\n%\n%--------------------------------------------------------------------------\n%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n%  Written by:       Andrea Gatti\n%  Contributors:     Andrea Gatti, ...\n%  A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n%    This program is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This program is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n    if (nargin == 1) \n        num = 4;\n        format = 'yyyy/mm/dd HH:MM';\n    end\n    if isa(h, 'matlab.ui.Figure')\n        h = get(h,'Children');\n    end\n    for i = 1 : numel(h)\n        try\n            h(i).TickLength = [0.005 0.01];\n            ax = double(axis(h(i)));            \n\n            step = (ax(2)-ax(1))/(num);\n            time_span = ax(2)-ax(1);\n\n            % depending on the time_span round ticks\n            round_val = 1 / 86400; % one second\n                        \n            if time_span > 8                 % greater than 20days\n                round_val =  1;               % round on 1 day\n            elseif time_span > 4              % greater than 5 days\n                round_val =  12 / 24;         % round on 12 hour\n            elseif time_span > 1              % greater than a day\n                round_val =  1 / 24;          % round on 1 hour\n            elseif time_span > 12 / 24        % greater than 12 hours\n                round_val =  30 / (24 * 60);  % round on 30 minutes\n            elseif time_span > 5 / 24         % greater than 5 hours\n                round_val =  15 / (24 * 60);  % round on 15 minutes\n            elseif time_span > 1 / 24         % greater than 1 hour\n                round_val =  5 / (24 * 60);   % round on 5 minutes\n            elseif time_span > 10 / (24 * 60) % greater than 10 minutes\n                round_val =  1 / (24 * 60);   % round on 1 minute\n            elseif time_span > 5 / (24 * 60)  % greater than 5 minutes\n                round_val =  30 / 86400;      % round on 30 seconds\n            elseif time_span > 1 / (24 * 60)  % greater than 1 minutes\n                round_val =  5 / 86400;       % round on 5 seconds\n            end\n\n            tick_pos = (ax(1) + (step/2)) : step : (ax(2) - (step/2));\n            \n            c_out = 0;\n            if round_val >= 1 / (24 * 60) % rounding is greater than 1 minute\n                c_out = 3;                % do not show seconds\n            elseif round_val >= 1 / 24    % rounding is greater than 1 hour\n                c_out = 6;                % do not show minutes\n            elseif round_val >= 1         % greater than 1 day\n                c_out = 9;                % do not show hours\n            end\n                \n            tick_pos = round(tick_pos ./ round_val) .* round_val; % round ticks\n            tick_pos((tick_pos < ax(1)) | (tick_pos > ax(2))) = []; % delete ticks outside figure;\n            tick_pos = unique(tick_pos);\n            \n            if all(mod(tick_pos, 1) == 0)\n                round_val = 1;\n            end\n            set(h(i), 'XTick', tick_pos);\n            if strcmp(format, 'auto')\n                last_date = [0 0 0 0 0 0];\n                h.XTickLabel = cell(size(tick_pos));\n\n                x_labels = cell(size(tick_pos));\n                for l = 1 : numel(tick_pos)\n                    str_time_format = 'HH:MM:SS';\n                    new_date = datevec(double(tick_pos(l)));\n                    if last_date(1) ~= new_date(1)        % if the year is different\n                        str_time_format = [char(32 * ones(1, floor(c_out/2) + 5)) str_time_format(1:end - c_out) '-newlinemmm dd, yyyy'];\n                    elseif last_date(2) ~= new_date(2)    % if the month is different \n                        str_time_format = [char(32 * ones(1, floor(c_out/2) + 5)) str_time_format(1:end - c_out) '-newlinemmm dd, yyyy'];\n                    elseif last_date(3) ~= new_date(3)    % if the day is different \n                        str_time_format = [char(32 * ones(1, floor(c_out/2) + 5)) str_time_format(1:end - c_out) '-newlinemmm dd, yyyy'];\n                    elseif last_date(4) ~= new_date(4)    % if the hour is different \n                        str_time_format = str_time_format(1:end - c_out);\n                    else % if last_date(5) ~= new_date(5)    % if the hour is different\n                        str_time_format = str_time_format(1:end - c_out);\n                    end                    \n                    if isempty(str_time_format)\n                        h.XTickLabel{l} = '';\n                    else\n                        if round_val == 1\n                            tmp = datestr(tick_pos(l), regexp(str_time_format, '(?<=line).*','match', 'once'));\n                        else\n                            tmp = datestr(tick_pos(l), str_time_format);\n                            tmp(tmp == '-') = '\\';\n                        end\n                        h.XTickLabel{l} = tmp;\n                    end\n                    last_date = new_date;\n                end\n            else\n                datetick(h(i),'x',format,'keepticks');\n            end\n            axis(h(i),ax);\n        catch ex\n            Core_Utils.printEx(ex);\n        end\n    end\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/plot/resetTimeTicks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2226602158281952}}
{"text": "function all_sal = computeSaliency(options)\n\n    if( ~exist( options.outfolder, 'dir' ) ), mkdir( options.outfolder ), end;\n    if( ~exist( fullfile( options.outfolder, 'intra-frame_saliency'), 'dir' ) )\n        mkdir(fullfile( options.outfolder, 'intra-frame_saliency'));\n    end\n    if( ~exist( fullfile( options.outfolder, 'inter-frame_saliency'), 'dir' ) )\n        mkdir(fullfile( options.outfolder, 'inter-frame_saliency'));\n    end\n    if( ~exist( fullfile( options.outfolder, 'final_saliency'), 'dir' ) )\n        mkdir(fullfile( options.outfolder, 'final_saliency'));\n    end\n    % Cache all frames in memory\n    [data.frames,data.names,height,width,nframe ]= readAllFrames( options );\n     % Load optical flow (or compute if file is not found)\n    data.flow = loadFlow( options );\n    if( isempty( data.flow ) )\n        data.flow = computeOpticalFlow( options, data.frames );\n    end\n    % Load superpixels (or compute if not found)\n    data.superpixels = loadSuperpixels( options );\n    if( isempty( data.superpixels ) )\n        data.superpixels = computeSuperpixels(  options, data.frames );\n    end\n    % Load Boundary (or compute if not found)\n    % computeBoundary\n    % \n    \n    [ superpixels, ~, bounds, labels ] = makeSuperpixelIndexUnique( data.superpixels );\n    [ colours, centres, ~ ] = getSuperpixelStats( data.frames(1:nframe-1), superpixels, double(labels) );%\n    valLAB = [];\n    for index = 1:nframe-1\n        valLAB = [valLAB;data.superpixels{index}.Sup1, data.superpixels{index}.Sup2, data.superpixels{index}.Sup3];     \n    end\n    \n    k =1:6:nframe-1;\n    k(end) = [];\n    global_saliency_track = zeros(height,width);\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%computing global and local location cues %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    for i = 1:size(k,2)\n        all_flowmagnitude = zeros(height,width);\n        if i > 1\n            for index = k(i):k(i)+5\n                flowgradient = getFlowGradient( data.flow{index} );\n                flowmagnitude = getMagnitude( flowgradient );\n                flowmagnitude = (0.5+saliency_trac).*reshape(flowmagnitude(:),height,width);\n                all_flowmagnitude = max(all_flowmagnitude,flowmagnitude);\n            end\n        else\n            for index = k(i):k(i)+5\n                flowgradient = getFlowGradient( data.flow{index} );\n                flowmagnitude = getMagnitude( flowgradient );\n                flowmagnitude = reshape(flowmagnitude(:),height,width);\n                all_flowmagnitude = max(all_flowmagnitude,flowmagnitude);\n            end\n        end\n        \n        all_flowmagnitude = imresize(all_flowmagnitude,0.1,'bilinear');\n        [h,w] = size(all_flowmagnitude);\n        all_flowmagnitudex = all_flowmagnitude(:);\n        all_flowmagnitudex(h*w+1)=0;\n        all_Label = zeros(h,w);\n        all_Label(:) = 1:size(all_flowmagnitude,1)*size(all_flowmagnitude,2);\n        all_Labelx = zeros(h+2,w+2);\n        all_Labelx(2:end-1,2:end-1) = all_Label;\n        all_Labelx(1,:)=h*w+1;\n        all_Labelx(end,:)=h*w+1;\n        all_Labelx(:,1)=h*w+1;\n        all_Labelx(:,end)=h*w+1;\n        [ConSPix,~]= find_connect_superpixel(all_Labelx, h*w+1, h+2 ,w+2 );             \n        ConSPix = ConSPix + eye(size(ConSPix,1));\n        all_fDistM = squareform(pdist(all_flowmagnitudex(:)));  \n        bdIds = GetBndPatchIds(all_Label,1);        \n        clipVal = EstimateDynamicParas(ConSPix,all_fDistM);\n        geoDist = GeodesicSaliency(ConSPix, double(bdIds), all_fDistM, clipVal,true,[]);\n        geoDist = geoDist(1:end-1);\n        saliency_trac = reshape(geoDist,h,w);\n        saliency_trac = imresize(saliency_trac,[height,width],'bilinear');\n        global_saliency_track = max(global_saliency_track,saliency_trac);       \n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%computing saliency via intra-frame graph %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    if( options.vocal )\n          disp( 'compute saliency via intra-frame graph:');\n    end\n    all_sal = cell(1,nframe-1);\n    for index = 1:nframe-1\n        if( options.vocal )\n                fprintf( 'Processing frame: %i of %i... \\n', ...\n                    index, nframe-1);\n        end\n        FGR = [];\n        frame = data.frames{index};        \n        frameName = data.names{index};    \n        nLabel = double(max(data.superpixels{index}.Label(:)));\n        Label = data.superpixels{index}.Label; \n        G = edge_detect(imfilter(uint8(frame),fspecial('average',3),'same','replicate'));\n        flowgradient = getFlowGradient( data.flow{index} );\n        flowmagnitude = getMagnitude( flowgradient );\n        gradBoundary = 1 - exp( -flowmagnitude); \n        flowmagnitude = G.*( gradBoundary +0.1);\n        flowmagnitude = reshape(flowmagnitude(:),height,width);\n        for  i = 1:nLabel\n             flowmagnitude_R = flowmagnitude(Label==i);\n             [flowmagnitude_R,~] = sort(flowmagnitude_R, 'descend');\n             FGR(i)=mean(flowmagnitude_R(1:10));\n             flowmagnitude(Label==i) = FGR(i);\n        end\n\n        [ConSPix,~]= find_connect_superpixel( Label, nLabel, height ,width );             \n        ConSPix = ConSPix + eye(nLabel);\n        FGRM = squareform(pdist(FGR'));\n        bdIds = GetBndPatchIds(Label,1);        \n        clipVal = EstimateDynamicParas(ConSPix,FGRM);\n        geoDist = GeodesicSaliency(ConSPix, double(bdIds), FGRM, clipVal,true,[]);\n        geo_sal = geoDist(data.superpixels{index}.Label);\n        all_sal{index}=geo_sal.*(global_saliency_track+0.3);\n        all_sal{index}=all_sal{index}/max(all_sal{index}(:));\n        \n        imwrite(all_sal{index}, [options.outfolder '\\intra-frame_saliency\\' frameName  '.bmp']);\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%computing saliency via inter-frame graph %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if( options.vocal )\n          disp( 'compute saliency via inter-frame graph:');\n    end\n    all_geoDist = cell(1,nframe-1);\n    for index = 1:nframe-2\n        if( options.vocal )\n                fprintf( 'Processing frame: %i of %i... \\n', ...\n                    index, nframe-1);\n        end\n        nLabel = double(max(data.superpixels{index}.Label(:)));\n        \n        colDistM = squareform(pdist(valLAB( bounds(index):bounds(index+2)-1,:)));\n        Conedge = [];   \n        Label_1 = data.superpixels{index}.Label;\n        [~,conedge]= find_connect_superpixel( Label_1, max(Label_1(:)), height ,width ); \n        Conedge = [Conedge;conedge];\n        \n        [x,y] = meshgrid(1:bounds(index+1)-bounds(index),1:bounds(index+2)-bounds(index+1));\n        conedge = [x(:),y(:)+bounds(index+1)-bounds(index)];\n        connect = sum((centres(conedge(:,1)+bounds(index)-1,:) - centres(conedge(:,2)+bounds(index)-1,:)).^2,2 );\n        cross_po_dis = conedge(connect<800,:);       \n        Conedge = [Conedge;cross_po_dis];\n        \n        Label_2 = data.superpixels{index+1}.Label;\n        [~,conedge]= find_connect_superpixel( Label_2, max(Label_2(:)), height ,width ); \n        Conedge = [Conedge;conedge + bounds(index+1)-bounds(index)];\n        ConSPix=sparse([Conedge(:,1);Conedge(:,2)],[Conedge(:,2);Conedge(:,1)], ...\n         [ones(size(Conedge(:,1)));ones(size(Conedge(:,1)))],bounds(index+2)-bounds(index),bounds(index+2)-bounds(index));\n        ConSPix = full(ConSPix);\n        ConSPix = ConSPix +eye(size(ConSPix));\n        \n        firstmap = all_sal{index}>mean(all_sal{index}(:));\n        str = strel('disk',1);  firstmap = imdilate(firstmap,str);\n        fd = int32(firstmap).*data.superpixels{index}.Label;\n        fd = unique(fd(:));\n        fd(fd==0) = [];\n        bd = setdiff(unique(data.superpixels{index}.Label(:)),fd);\n        \n        bdIds = bd;   \n        \n        secondmap = all_sal{index+1}>mean(all_sal{index+1}(:));\n        secondmap = ~((~secondmap).*(~firstmap));\n        str = strel('disk',1);  secondmap = imdilate(secondmap,str);\n        fd = int32(secondmap).*data.superpixels{index+1}.Label;\n        fd = unique(fd(:));\n        fd(fd==0) = [];\n        bd = setdiff(unique(data.superpixels{index+1}.Label(:)),fd);\n        bdIds = [bdIds;bd+bounds(index+1)-bounds(index)]; \n        \n        clipVal = EstimateDynamicParas(ConSPix,colDistM);\n        geoDist = GeodesicSaliency(ConSPix, double(bdIds), colDistM, clipVal, false,[]);\n        geoDist_1 = geoDist(1:bounds(index+1)-bounds(index));\n        geoDist_2 = geoDist(bounds(index+1)-bounds(index)+1:end);\n        \n        tmp = sort(geoDist_1, 'descend');\n        pos = round(options.topRate * length(tmp));\n        maxVal = tmp(pos);\n        geoDist_1 = geoDist_1 / maxVal; \n        geoDist_1(geoDist_1 > 1) = 1;\n        \n        tmp = sort(geoDist_2, 'descend');\n        pos = round(options.topRate * length(tmp));\n        maxVal = tmp(pos);\n        geoDist_2 = geoDist_2 / maxVal; \n        geoDist_2(geoDist_2 > 1) = 1;\n        \n        all_geoDist{index} = geoDist_1;\n        all_geoDist{index+1} = geoDist_2;\n        geo_sal = geoDist_1(data.superpixels{index}.Label);\n        \n\n        all_sal{index} = geo_sal*0.5+all_sal{index}*0.5;\n        all_sal{index} = all_sal{index}./max( all_sal{index}(:));\n\n        L{1} = uint32(data.superpixels{index}.Label);\n        S{1} = repmat(all_sal{index},[1 3]);\n        [ R, ~, ~ ] = getSuperpixelStats(S(1:1),L, nLabel );\n        R = double(R(:,1));\n        sR = sort(R);\n        t = sum(sR(end-9:end))/10;\n        R = (R-min(R))/(t-min(R));\n        R(R>1)=1;\n        all_geoDist{index} = R';\n     \n        geo_sal = geoDist_2(data.superpixels{index+1}.Label);\n        \n        all_sal{index+1} = geo_sal*0.5+all_sal{index+1}*0.5;\n        all_sal{index+1} = all_sal{index+1}./max( all_sal{index+1}(:)); \n\n        nLabel = double(max(data.superpixels{index+1}.Label(:)));\n        L{1} = uint32(data.superpixels{index+1}.Label);\n        S{1} = repmat(all_sal{index+1},[1 3]);\n        [ R, ~, ~ ] = getSuperpixelStats(S(1:1),L, nLabel );\n        R = double(R(:,1));\n        sR = sort(R);\n        t = sum(sR(end-9:end))/10;\n        R = (R-min(R))/(t-min(R));\n        R(R>1)=1;\n        all_geoDist{index+1} = R';  \n\n    end\n          \n    RegionSal = [];\n    for index = 1:nframe-1\n        nLabel = double(max(data.superpixels{index}.Label(:)));\n        all_sal{index} = all_sal{index}.*(global_saliency_track+0.1);\n        all_sal{index} = all_sal{index}/max(all_sal{index}(:));        \n        \n        sal = reshape( all_sal{index},height*width,1);\n        L{1} = uint32(data.superpixels{index}.Label);\n        S{1} = repmat(sal,[1 3]);\n        [ R, ~, ~ ] = getSuperpixelStats(S(1:1),L, nLabel );\n        R = double(R(:,1));\n        sR = sort(R);\n        t = sum(sR(end-9:end))/10;\n        R = (R-min(R))/(t-min(R));\n        R(R>1)=1;\n        all_geoDist{index} = R';\n        RegionSal = [RegionSal;all_geoDist{index}(:)];\n        all_sal{index} = double(R(data.superpixels{index}.Label));\n        imwrite(all_sal{index}, [options.outfolder '\\inter-frame_saliency\\' data.names{index} '.bmp']);\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Spatio-temporal consistance optimization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%you can uncomment this part for computation efficiency %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if( options.vocal )\n          disp( 'spatio-temporal consistance optimization');\n    end\n    Conedge = [];      \n    for index = 1:nframe-1\n        Label = data.superpixels{index}.Label;\n        [~,conedge]= find_connect_superpixel( Label, max(Label(:)), height ,width );      \n        Conedge = [Conedge;conedge + bounds(index)-1];\n    end\n    intralength = size(Conedge,1);\n    for index = 1:nframe-2\n        [x,y] = meshgrid(1:bounds(index+1)-bounds(index),1:bounds(index+2)-bounds(index+1));\n        conedge = [x(:)+bounds(index)-1,y(:)+bounds(index+1)-1];\n        connect = sum((centres(conedge(:,1),:) - centres(conedge(:,2),:)).^2,2 );\n        Conedge = [Conedge;conedge(connect<800,:)];\n    end\n    valDistances=sqrt(sum((valLAB(Conedge(:,1),:)-valLAB(Conedge(:,2),:)).^2,2));\n    valDistances(intralength+1:end)=valDistances(intralength+1:end)/5;\n    valDistances=normalize(valDistances);\n    weights=exp(-options.valScale*valDistances)+ 1e-5;\n    weights=sparse([Conedge(:,1);Conedge(:,2)],[Conedge(:,2);Conedge(:,1)], ...\n    [weights;weights],labels,labels);\n    E = sparse(1:labels,1:labels,ones(labels,1)); iD = sparse(1:labels,1:labels,1./sum(weights));\n    P = iD*weights;\n    RegionSal = (E-P+10*options.alpha*E)\\RegionSal;\n    for index = 1:nframe-1\n        R = RegionSal(bounds(index):bounds(index+1)-1);\n        sR = sort(R);\n        t = sum(sR(end-9:end))/10;\n        R = (R-min(R))/(t-min(R));\n        R(R>1)=1;\n        all_geoDist{index} = R';\n        all_sal{index} = 0.6*double(R(data.superpixels{index}.Label))+0.4*all_sal{index};\n        imwrite(all_sal{index}, [options.outfolder '\\final_saliency\\' data.names{index}  '.bmp']);\n    end\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/Saliency-Aware-Video-Object-Segmentation-old--master/code/computeSaliency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.22262229726642005}}
{"text": "function outstruct=memmapstream(bytes, format, varargin)\n%\n%    outstruct=memmapstream(bytes, format)\n%\n%    Map a byte-array (in char array or uint8/int8 array) into a structure\n%    using a dictionary (format is compatible with memmapfile in MATLAB)\n%\n%    This function is compatible with both MATLAB and GNU Octave. \n%\n%    author: Qianqian Fang (q.fang <at> neu.edu)\n%\n%    input:\n%        bytes: a char, int8 or uint8 vector or array\n%        format: a 3-column cell array in the format compatible with the\n%              'Format' parameter of memmapfile in MATLAB. It has the\n%              following structure\n%\n%             column 1: data type string, it can be one of the following\n%                'int8','int16','int32','int64',\n%                'uint8','uint16','uint32','uint64',\n%                'single','double','logical'\n%             column 2: an integer vector denoting the size of the data\n%             column 3: a string denoting the fieldname in the output struct\n%\n%             For example format={'int8',[1,8],'key'; 'float',[1,1],'value'}\n%             reads the first 8 bytes from 'bytes' as the first subfield\n%             'key' and the following 4 bytes as the floating point 'value'\n%             subfield.\n%\n%    output:\n%        outstruct: a structure containing the required field\n%\n%    example:\n%        bytestream=['Andy' 5 'JT'];\n%        format={'uint8', [1,4], 'name',\n%              'uint8', [1,1], 'age',\n%              'uint8', [1,2], 'school'};\n%        data=memmapstream(bytestream,format);\n%\n%    this file is part of JNIfTI specification: https://github.com/fangq/jnifti\n%\n%    License: Apache 2.0, see https://github.com/fangq/jnifti for details\n%\n\nif(nargin<2)\n   error('must provide bytes and format as inputs');\nend\n\nif(~ischar(bytes) && ~isa(bytes,'int8') && ~isa(bytes,'uint8') || isempty(bytes))\n   error('first input, bytes, must be a char-array or uint8/int8 vector');\nend\n\nif(~iscell(format) || size(format,2)<3 || size(format,1)==0 || ~ischar(format{1,1}))\n   error('second input, format, must be a 3-column cell array, in a format described by the memmapfile Format field.');\nend\n\nbytes=bytes(:)';\n\ndatatype=struct('int8',1,'int16',2,'int32',4,'int64',8,'uint8',1,'uint16',2,'uint32',4,'uint64',8,'single',4,'double',8);\n\nopt=varargin2struct(varargin{:});\nopt.usemap=jsonopt('usemap',0,opt) && exist('containers.Map');\n\nif(opt.usemap)\n    outstruct=containers.Map();\nelse\n    outstruct=struct();\nend\nlen=1;\nfor i=1:size(format,1)\n    bytelen=datatype.(format{i,1})*prod(format{i,2});\n    if(opt.usemap)\n        outstruct(format{i,3})=reshape(typecast(uint8(bytes(len:bytelen+len-1)),format{i,1}),format{i,2});\n    else\n        outstruct.(format{i,3})=reshape(typecast(uint8(bytes(len:bytelen+len-1)),format{i,1}),format{i,2});\n    end\n    len=len+bytelen;\n    if(len>length(bytes))\n        break;\n    end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/jnifti/memmapstream.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22256175291053032}}
{"text": "% ----------------------------------------------------------------------------------------------------------------\nfunction net = vid_create_net(varargin)\n% Very similar to vanilla AlexNet from MatConvNet examples,\n% but with smaller stride at conv1 and no padding\n% Used to generate the network described in  the paper\n% \"Fully-Convolutional Siamese Networks for Object Tracking\"\n% ----------------------------------------------------------------------------------------------------------------\n    opts.exemplarSize = [127 127];\n    opts.instanceSize = [255 255];\n    opts.scale = 1 ;\n    opts.initBias = 0.1 ;\n    opts.weightDecay = 1 ;\n    %opts.weightInitMethod = 'xavierimproved' ;\n    opts.weightInitMethod = 'gaussian';\n    opts.batchNormalization = false ;\n    opts.networkType = 'simplenn' ;\n    opts.strides = [2, 2, 1, 2] ;\n    opts.cudnnWorkspaceLimit = 1024*1024*1024 ; % 1GB\n    opts = vl_argparse(opts, varargin) ;\n\n    if numel(opts.exemplarSize) == 1\n        opts.exemplarSize = [opts.exemplarSize, opts.exemplarSize];\n    end\n    if numel(opts.instanceSize) == 1\n        opts.instanceSize = [opts.instanceSize, opts.instanceSize];\n    end\n\n    net = modified_alexnet(struct(), opts) ;\n\n    % Meta parameters\n    net.meta.normalization.interpolation = 'bicubic' ;\n    net.meta.normalization.averageImage = [] ;\n    net.meta.normalization.keepAspect = true ;\n    net.meta.augmentation.rgbVariance = zeros(0,3) ;\n    net.meta.augmentation.transformation = 'stretch' ;\n\n    % Fill in default values\n    net = vl_simplenn_tidy(net) ;\n\n    % Switch to DagNN if requested\n    switch lower(opts.networkType)\n      case 'simplenn'\n        % done\n      case 'dagnn'\n        net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;\n        net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...\n                     {'prediction','label'}, 'top1err') ;\n        net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...\n                                           'opts', {'topK',5}), ...\n                     {'prediction','label'}, 'top5err') ;\n      otherwise\n        assert(false) ;\n    end\n\nend\n\n% --------------------------------------------------------------------\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad, init_bias)\n% --------------------------------------------------------------------\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n  name = 'fc' ;\nelse\n  name = 'conv' ;\nend\nconvOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...\n                           'weights', {{init_weight(opts, h, w, in, out, 'single'), zeros(out, 1, 'single')}}, ...\n                           'stride', stride, ...\n                           'pad', pad, ...\n                           'learningRate', [1 2], ...\n                           'weightDecay', [opts.weightDecay 0], ...\n                           'opts', {convOpts}) ;\nif opts.batchNormalization\n  net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%s',id), ...\n                             'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single'), zeros(out, 2, 'single')}}, ...\n                             'learningRate', [2 1 0.05], ...\n                             'weightDecay', [0 0]) ;\nend\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = add_block_conv_only(net, opts, id, h, w, in, out, stride, pad, init_bias)\n% --------------------------------------------------------------------\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n  name = 'fc' ;\nelse\n  name = 'conv' ;\nend\nconvOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...\n                           'weights', {{init_weight(opts, h, w, in, out, 'single'), zeros(out, 1, 'single')}}, ...\n                           'stride', stride, ...\n                           'pad', pad, ...\n                           'learningRate', [1 2], ...\n                           'weightDecay', [opts.weightDecay 0], ...\n                           'opts', {convOpts}) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = add_norm(net, opts, id)\n% --------------------------------------------------------------------\nif ~opts.batchNormalization\n  net.layers{end+1} = struct('type', 'normalize', ...\n                             'name', sprintf('norm%s', id), ...\n                             'param', [5 1 0.0001/5 0.75]) ;\nend\nend\n\n% --------------------------------------------------------------------\nfunction net = add_dropout(net, opts, id)\n% --------------------------------------------------------------------\nif ~opts.batchNormalization\n  net.layers{end+1} = struct('type', 'dropout', ...\n                             'name', sprintf('dropout%s', id), ...\n                             'rate', 0.5) ;\nend\nend\n\n% --------------------------------------------------------------------\nfunction net = modified_alexnet(net, opts)\n% --------------------------------------------------------------------\n\n    strides = ones(1, 7);\n    strides(1:numel(opts.strides)) = opts.strides(:);\n\n    net.layers = {} ;\n\n    net = add_block(net, opts, '1', 11, 11, 3, 96, strides(1), 0) ;\n    net = add_norm(net, opts, '1') ;\n    net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n                               'method', 'max', ...\n                               'pool', [3 3], ...\n                               'stride', strides(2), ...\n                               'pad', 0) ;\n\n    net = add_block(net, opts, '2', 5, 5, 48, 256, strides(3), 0) ;\n    net = add_norm(net, opts, '2') ;\n    net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n                               'method', 'max', ...\n                               'pool', [3 3], ...\n                               'stride', strides(4), ...\n                               'pad', 0) ;\n\n    net = add_block(net, opts, '3', 3, 3, 256, 384, strides(5), 0) ;\n    net = add_block(net, opts, '4', 3, 3, 192, 384, strides(6), 0) ;\n    net = add_block_conv_only(net, opts, '5', 3, 3, 192, 256, strides(7), 0) ;\n\n    % Check if the receptive field covers full image\n\n    [ideal_exemplar, ~] = ideal_size(net, opts.exemplarSize);\n    [ideal_instance, ~] = ideal_size(net, opts.instanceSize);\n    assert(sum(opts.exemplarSize==ideal_exemplar)==2, 'exemplarSize is not ideal.');\n    assert(sum(opts.instanceSize==ideal_instance)==2, 'instanceSize is not ideal.');\nend\n", "meta": {"author": "bertinetto", "repo": "siamese-fc", "sha": "e86eb64d6f146b51135232c1d46a29f64c63678a", "save_path": "github-repos/MATLAB/bertinetto-siamese-fc", "path": "github-repos/MATLAB/bertinetto-siamese-fc/siamese-fc-e86eb64d6f146b51135232c1d46a29f64c63678a/training/vid_create_net.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.2225453258532728}}
{"text": "classdef TankMassConstraint < AbstractConstraint\n    %TankMassConstraint Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        normFact = 1;\n        tank LaunchVehicleTank\n        event LaunchVehicleEvent\n        eventNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n        \n        lb(1,1) double = 0;\n        ub(1,1) double = 0;\n        \n        evalType(1,1) ConstraintEvalTypeEnum = ConstraintEvalTypeEnum.FixedBounds;\n        stateCompType(1,1) ConstraintStateComparisonTypeEnum = ConstraintStateComparisonTypeEnum.Equals;\n        stateCompEvent LaunchVehicleEvent\n        stateCompNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n    end\n    \n    methods\n        function obj = TankMassConstraint(tank, event, lb, ub)\n            obj.tank = tank;\n            obj.event = event;\n            obj.lb = lb;\n            obj.ub = ub;   \n            \n             obj.id = rand();\n        end\n        \n        function [lb, ub] = getBounds(obj)\n            lb = obj.lb;\n            ub = obj.ub;\n        end\n        \n        function [c, ceq, value, lwrBnd, uprBnd, type, eventNum, valueStateComp] = evalConstraint(obj, stateLog, celBodyData)           \n            type = obj.getConstraintType();\n            \n            switch obj.eventNode\n                case ConstraintStateComparisonNodeEnum.FinalState\n                    stateLogEntry = stateLog.getLastStateLogForEvent(obj.event);\n                    \n                case ConstraintStateComparisonNodeEnum.InitialState\n                    stateLogEntry = stateLog.getFirstStateLogForEvent(obj.event);\n                \n                otherwise\n                    error('Unknown event node.');\n            end\n                    \n            value = lvd_TankMassTasks(stateLogEntry, 'tankMass', obj.tank);\n\n            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n                switch obj.stateCompNode\n                    case ConstraintStateComparisonNodeEnum.FinalState\n                        stateLogEntryStateComp = stateLog.getLastStateLogForEvent(obj.stateCompEvent);\n\n                    case ConstraintStateComparisonNodeEnum.InitialState\n                        stateLogEntryStateComp = stateLog.getFirstStateLogForEvent(obj.stateCompEvent);\n\n                    otherwise\n                        error('Unknown event node.');\n                end\n\n                valueStateComp = lvd_TankMassTasks(stateLogEntryStateComp, 'tankMass', obj.tank);\n            else\n                valueStateComp = NaN;\n            end\n            \n            [c, ceq] = obj.computeCAndCeqValues(value, valueStateComp);  \n            \n            lwrBnd = obj.lb;\n            uprBnd = obj.ub;\n            \n            eventNum = obj.event.getEventNum();\n        end\n        \n        function sF = getScaleFactor(obj)\n            sF = obj.normFact;\n        end\n        \n        function setScaleFactor(obj, sF)\n            obj.normFact = sF;\n        end\n        \n        function tf = usesStage(obj, stage)\n            tf = false;\n        end\n        \n        function tf = usesEngine(obj, engine)\n            tf = false;\n        end\n        \n        function tf = usesTank(obj, tank)\n            tf = obj.tank == tank;\n        end\n        \n        function tf = usesEngineToTankConn(obj, engineToTank)\n            tf = false;\n        end\n        \n        function tf = usesEvent(obj, event)\n            tf = obj.event == event;\n            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n                tf = tf || obj.stateCompEvent == event;\n            end\n        end\n        \n        function tf = usesStopwatch(obj, stopwatch)\n            tf = false;\n        end\n        \n        function tf = usesExtremum(obj, extremum)\n            tf = false;\n        end\n        \n        function tf = usesGroundObj(obj, grdObj)\n            tf = false;\n        end\n        \n        function tf = canUseSparseOutput(obj)\n            tf = true;\n        end\n        \n        function event = getConstraintEvent(obj)\n            event = obj.event;\n        end\n        \n        function type = getConstraintType(obj)\n            type = 'Tank Mass';\n        end\n        \n        function [unit, lbLim, ubLim, usesLbUb, usesCelBody, usesRefSc] = getConstraintStaticDetails(obj)\n            unit = 'mT';\n            lbLim = 0;\n            ubLim = Inf;\n            usesLbUb = true;\n            usesCelBody = false;\n            usesRefSc = false;\n        end\n        \n        function addConstraintTf = openEditConstraintUI(obj, lvdData)\n            [~, tanks] = lvdData.launchVehicle.getTanksListBoxStr();\n            if(numel(tanks) >= 1)\n%                 addConstraintTf = lvd_EditTankConstraintGUI(obj, lvdData);\n                \n                output = AppDesignerGUIOutput({false});\n                lvd_EditTankConstraintGUI_App(obj, lvdData, output);\n                addConstraintTf = output.output{1};\n            else\n                errordlg('There are currently no tanks assigned to the launch vehicle in this scenario.  Add at least one tank first.');\n                \n                addConstraintTf = false;\n            end\n        end\n    end\n    \n    methods(Static)\n        function constraint = getDefaultConstraint(~, ~)            \n            constraint = TankMassConstraint(LaunchVehicleTank.empty(1,0), LaunchVehicleEvent.empty(1,0), 0, 0);\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/constraints/@TankMassConstraint/TankMassConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22241572285236277}}
{"text": "function [gKern, gVarmeans, gVarcovars, gInd] = rbfardjitVardistPsi1Gradient(rbfard2Kern, vardist, Z, covGrad, learnInducing)\n\n% RBFARDJITVARDISTPSI1GRADIENT description.\n  \n% VARGPLVM\n  \nif nargin < 5\n    learnInducing = 1;\nend\n\n [gKern, gVarmeans, gVarcovars, gInd] = rbfard2VardistPsi1Gradient(rbfard2Kern, vardist, Z, covGrad, learnInducing);\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/rbfardjitVardistPsi1Gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22241572285236277}}
{"text": "%% Feature homography based planar tracking\n%\n% Example of using features2d framework for interactive video homography\n% matching. ORB features and FLANN matcher are used. The actual tracking is\n% implemented by |PlaneTracker| class.\n%\n% Inspired by <http://www.youtube.com/watch?v=-ZNYoL8rzPY>\n%\n% Video: <http://www.youtube.com/watch?v=FirtmYcC0Vc>\n%\n% Select a textured planar object to track by drawing a box with a mouse.\n%\n% Sources:\n%\n% * <https://github.com/opencv/opencv/blob/3.3.1/samples/python/feature_homography.py>\n%\n\nfunction feature_homography_track_demo(vid)\n    % video file, and a default target to track [x,y,w,h]\n    win = [];\n    if nargin < 1\n        vid = fullfile(mexopencv.root(), 'test', 'blais.mp4');\n        assert(exist(vid, 'file') == 2, 'Missing video file');\n        if true\n            win = [135 165 285 175];  % face\n        else\n            win = [136 0 366 433];    % book\n        end\n    elseif isempty(vid)\n        vid = 0;\n    end\n\n    % open video feed, and get first frame\n    cap = cv.VideoCapture(vid);\n    pause(1);\n    assert(cap.isOpened(), 'Failed to open video');\n    frame = cap.read();\n    assert(~isempty(frame), 'Failed to read frames');\n\n    % prepare plot\n    paused = false;\n    tframe = zeros(size(frame), class(frame));  % target frame + drawings\n    hImg = imshow([frame, tframe]);\n\n    % create and initialize tracker\n    tracker = PlaneTracker();\n    if ~isempty(win)\n        onRect(win);\n    end\n\n    % create ROI region selector\n    if ~mexopencv.isOctave()\n        onHelp();\n        roi = RectSelector(hImg);\n        roi.clip = true;\n        roi.callback = @onRect;\n    else\n        %HACK: RectSelector not Octave compatible\n        %HACK: function handle to nested function not supported in Octave\n        roi = struct('isDragging',@()false);\n    end\n\n    % listen to keyboard input\n    if ~mexopencv.isOctave()\n        %HACK: function handle to nested function not supported in Octave\n        set(ancestor(hImg,'figure'), 'WindowKeyPressFcn',@onType);\n    end\n\n    % main loop\n    while ishghandle(hImg)\n        playing = ~paused && ~roi.isDragging();\n        if playing\n            % read new frame\n            frame = cap.read();\n            if isempty(frame), break; end\n        end\n        out = [frame, tframe];\n\n        % track and draw keypoints and boundary of target in new frame\n        if playing\n            tracked = tracker.track(frame);\n            if ~isempty(tracked)\n                tr = tracked(1);\n                out = cv.circle(out, tr.pt1, 2, 'Color',[255 0 0]);\n                out = cv.polylines(out, tr.quad, 'Closed',true, ...\n                    'Color',[0 255 0], 'Thickness',2);\n                % draw matches\n                out = cv.line(out, ...\n                    bsxfun(@plus, tr.pt0, [size(frame,2) 0]), tr.pt1, ...\n                    'Color',[0 0 255]);\n            end\n        end\n\n        % display result\n        set(hImg, 'CData',out);\n        if playing\n            drawnow;\n        else\n            pause(0.1);  % slow down a bit if paused\n        end\n    end\n    cap.release();\n    if isobject(roi), delete(roi); end\n\n    % --- Callback functions ---\n\n    function onRect(rect)\n        %ONRECT  Callback for ROI selector\n        %\n        %     onRect(rect)\n        %\n        % ## Input\n        % * __rect__ selected rectangle [x,y,w,h], or empty\n        %\n\n        if isempty(rect), return; end\n\n        % selection must be made in left image (current frame)\n        rect = cv.Rect.intersect(rect, [0 0 size(frame,2) size(frame,1)]);\n        if cv.Rect.area(rect) < 1, return; end\n\n        % track new target\n        disp('New target...')\n        tracker.clear();\n        tracker.addTarget(frame, rect);\n\n        % draw keypoints and boundary in target frame\n        if ~isempty(tracker.targets)\n            t = tracker.targets(1);\n            tframe = cv.drawKeypoints(t.image, t.kpts, 'Color',[255 0 0]);\n            tframe = cv.rectangle(tframe, t.rect(1:2), t.rect(3:4), ...\n                'Color',[0 255 0], 'Thickness',2);\n        else\n            tframe(:) = 0;\n        end\n\n        % un-pause\n        paused = false;\n    end\n\n    function onType(hfig, e)\n        %ONTYPE  Event handler for key press on figure\n\n        switch e.Key\n            case {'q', 'escape'}\n                close(hfig);\n\n            case 'h'\n                onHelp();\n\n            case {'space', 'p'}\n                disp('Toggle pause...');\n                paused = ~paused;\n\n            case {'c', 'r'}\n                disp('Clearing tracker...');\n                tracker.clear();\n                tframe(:) = 0;\n        end\n    end\n\n    function onHelp()\n        %ONHELP  Display usage help dialog\n\n        h = helpdlg({\n            'Select object(s) to track using the mouse.'\n            'Hot keys:'\n            '  q - quit'\n            '  h - help'\n            '  p - pause'\n            '  c - clear targets'\n        });\n\n        % wait for user to accept dialog\n        set(h, 'WindowStyle','modal');\n        waitfor(h);\n    end\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/feature_homography_track_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22241571663760065}}
{"text": "%  internal function\n\n%  'xform_nii.m' is an internal function called by \"load_nii.m\", so\n%  you do not need run this program by yourself. It does simplified\n%  NIfTI sform/qform affine transform, and supports some of the\n%  affine transforms, including translation, reflection, and\n%  orthogonal rotation (N*90 degree).\n%\n%  For other affine transforms, e.g. any degree rotation, shearing\n%  etc. you will have to use the included 'reslice_nii.m' program\n%  to reslice the image volume. 'reslice_nii.m' is not called by\n%  any other program, and you have to run 'reslice_nii.m' explicitly\n%  for those NIfTI files that you want to reslice them.\n%\n%  Since 'xform_nii.m' does not involve any interpolation or any\n%  slice change, the original image volume is supposed to be\n%  untouched, although it is translated, reflected, or even\n%  orthogonally rotated, based on the affine matrix in the\n%  NIfTI header.\n%\n%  However, the affine matrix in the header of a lot NIfTI files\n%  contain slightly non-orthogonal rotation. Therefore, optional\n%  input parameter 'tolerance' is used to allow some distortion\n%  in the loaded image for any non-orthogonal rotation or shearing\n%  of NIfTI affine matrix. If you set 'tolerance' to 0, it means\n%  that you do not allow any distortion. If you set 'tolerance' to\n%  1, it means that you do not care any distortion. The image will\n%  fail to be loaded if it can not be tolerated. The tolerance will\n%  be set to 0.1 (10%), if it is default or empty.\n%\n%  Because 'reslice_nii.m' has to perform 3D interpolation, it can\n%  be slow depending on image size and affine matrix in the header.\n%\n%  After you perform the affine transform, the 'nii' structure\n%  generated from 'xform_nii.m' or new NIfTI file created from\n%  'reslice_nii.m' will be in RAS orientation, i.e. X axis from\n%  Left to Right, Y axis from Posterior to Anterior, and Z axis\n%  from Inferior to Superior.\n%\n%  NOTE: This function should be called immediately after load_nii.\n%\n%  Usage: [ nii, idem? ] = xform_nii(nii, [tolerance], [preferredForm])\n%\n%  nii\t- NIFTI structure (returned from load_nii)\n%\n%  tolerance (optional) - distortion allowed for non-orthogonal rotation\n%\tor shearing in NIfTI affine matrix. It will be set to 0.1 (10%),\n%\tif it is default or empty.\n%\n%  preferredForm (optional)  -  selects which transformation from voxels\n%\tto RAS coordinates; values are s,q,S,Q.  Lower case s,q indicate\n%\t\"prefer sform or qform, but use others if preferred not present\".\n%\tUpper case indicate the program is forced to use the specificied\n%\ttransform or fail loading.  'preferredForm' will be 's', if it is\n%\tdefault or empty.\t- Jeff Gunter\n%\n%  NIFTI data format can be found on: http://nifti.nimh.nih.gov\n%\n%  - Jimmy Shen (jimmy@rotman-baycrest.on.ca)\n%\nfunction [nii, idem] = xform_nii(nii, tolerance, preferredForm)\n\n%  save a copy of the header as it was loaded.  This is the\n%  header before any sform, qform manipulation is done.\n%\nnii.original.hdr = nii.hdr;\n\nif ~exist('tolerance','var') | isempty(tolerance)\n    tolerance = 0.1;\nelseif(tolerance<=0)\n    tolerance = eps;\nend\n\nif ~exist('preferredForm','var') | isempty(preferredForm)\n    preferredForm= 's';\t\t\t\t% Jeff\nend\n\n%  if scl_slope field is nonzero, then each voxel value in the\n%  dataset should be scaled as: y = scl_slope * x + scl_inter\n%  I bring it here because hdr will be modified by change_hdr.\n%\nif nii.hdr.dime.scl_slope ~= 0 && ...\n        ismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768]) && ...\n        (nii.hdr.dime.scl_slope ~= 1 | nii.hdr.dime.scl_inter ~= 0)\n    \n    nii.img = ...\n        nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;\n    \n    if nii.hdr.dime.datatype == 64\n        \n        nii.hdr.dime.datatype = 64;\n        nii.hdr.dime.bitpix = 64;\n    else\n        nii.img = single(nii.img);\n        \n        nii.hdr.dime.datatype = 16;\n        nii.hdr.dime.bitpix = 32;\n    end\n    \n    nii.hdr.dime.glmax = max(double(nii.img(:)));\n    nii.hdr.dime.glmin = min(double(nii.img(:)));\n    \n    %  set scale to non-use, because it is applied in xform_nii\n    %\n    nii.hdr.dime.scl_slope = 0;\n    \nend\n\n%  However, the scaling is to be ignored if datatype is DT_RGB24.\n\n%  If datatype is a complex type, then the scaling is to be applied\n%  to both the real and imaginary parts.\n%\nif nii.hdr.dime.scl_slope ~= 0 && ...\n        ismember(nii.hdr.dime.datatype, [32,1792])\n    \n    nii.img = ...\n        nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;\n    \n    if nii.hdr.dime.datatype == 32\n        nii.img = single(nii.img);\n    end\n    \n    nii.hdr.dime.glmax = max(double(nii.img(:)));\n    nii.hdr.dime.glmin = min(double(nii.img(:)));\n    \n    %  set scale to non-use, because it is applied in xform_nii\n    %\n    nii.hdr.dime.scl_slope = 0;\n    \nend\n\n%  There is no need for this program to transform Analyze data\n%\nif nii.filetype == 0 && exist([nii.fileprefix '.mat'],'file')\n    load([nii.fileprefix '.mat']);\t% old SPM affine matrix\n    R=M(1:3,1:3);\n    T=M(1:3,4);\n    T=R*ones(3,1)+T;\n    M(1:3,4)=T;\n    nii.hdr.hist.qform_code=0;\n    nii.hdr.hist.sform_code=1;\n    nii.hdr.hist.srow_x=M(1,:);\n    nii.hdr.hist.srow_y=M(2,:);\n    nii.hdr.hist.srow_z=M(3,:);\nelseif nii.filetype == 0\n    nii.hdr.hist.rot_orient = [];\n    nii.hdr.hist.flip_orient = [];\n    return;\t\t\t\t% no sform/qform for Analyze format\nend\n\nhdr = nii.hdr;\n\n[hdr,orient]=change_hdr(hdr,tolerance,preferredForm);\n\n%  flip and/or rotate image data\n%\nif ~isequal(orient, [1 2 3])\n    idem=false;\n    old_dim = hdr.dime.dim([2:4]);\n    \n    %  More than 1 time frame\n    %\n    if ndims(nii.img) > 3\n        pattern = 1:prod(old_dim);\n    else\n        pattern = [];\n    end\n    \n    if ~isempty(pattern)\n        pattern = reshape(pattern, old_dim);\n    end\n    \n    %  calculate for rotation after flip\n    %\n    rot_orient = mod(orient + 2, 3) + 1;\n    \n    %  do flip:\n    %\n    flip_orient = orient - rot_orient;\n    \n    for i = 1:3\n        if flip_orient(i)\n            if ~isempty(pattern)\n                pattern = flipdim(pattern, i);\n            else\n                nii.img = flipdim(nii.img, i);\n            end\n        end\n    end\n    \n    %  get index of orient (rotate inversely)\n    %\n    [tmp rot_orient] = sort(rot_orient);\n    \n    new_dim = old_dim;\n    new_dim = new_dim(rot_orient);\n    hdr.dime.dim([2:4]) = new_dim;\n    \n    new_pixdim = hdr.dime.pixdim([2:4]);\n    new_pixdim = new_pixdim(rot_orient);\n    hdr.dime.pixdim([2:4]) = new_pixdim;\n    \n    %  re-calculate originator\n    %\n    tmp = hdr.hist.originator([1:3]);\n    tmp = tmp(rot_orient);\n    flip_orient = flip_orient(rot_orient);\n    \n    for i = 1:3\n        if flip_orient(i) && ~isequal(tmp(i), 0)\n            tmp(i) = new_dim(i) - tmp(i) + 1;\n        end\n    end\n    \n    hdr.hist.originator([1:3]) = tmp;\n    hdr.hist.rot_orient = rot_orient;\n    hdr.hist.flip_orient = flip_orient;\n    \n    %  do rotation:\n    %\n    if ~isempty(pattern)\n        pattern = permute(pattern, rot_orient);\n        pattern = pattern(:);\n        \n        if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...\n                hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n            \n            tmp = reshape(nii.img(:,:,:,1), [prod(new_dim) hdr.dime.dim(5:8)]);\n            tmp = tmp(pattern, :);\n            nii.img(:,:,:,1) = reshape(tmp, [new_dim       hdr.dime.dim(5:8)]);\n            \n            tmp = reshape(nii.img(:,:,:,2), [prod(new_dim) hdr.dime.dim(5:8)]);\n            tmp = tmp(pattern, :);\n            nii.img(:,:,:,2) = reshape(tmp, [new_dim       hdr.dime.dim(5:8)]);\n            \n            if hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n                tmp = reshape(nii.img(:,:,:,3), [prod(new_dim) hdr.dime.dim(5:8)]);\n                tmp = tmp(pattern, :);\n                nii.img(:,:,:,3) = reshape(tmp, [new_dim       hdr.dime.dim(5:8)]);\n            end\n            \n        else\n            nii.img = reshape(nii.img, [prod(new_dim) hdr.dime.dim(5:8)]);\n            nii.img = nii.img(pattern, :);\n            nii.img = reshape(nii.img, [new_dim       hdr.dime.dim(5:8)]);\n        end\n    else\n        if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...\n                hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n            \n            nii.img(:,:,:,1) = permute(nii.img(:,:,:,1), rot_orient);\n            nii.img(:,:,:,2) = permute(nii.img(:,:,:,2), rot_orient);\n            \n            if hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n                nii.img(:,:,:,3) = permute(nii.img(:,:,:,3), rot_orient);\n            end\n        else\n            nii.img = permute(nii.img, rot_orient);\n        end\n    end\nelse\n    idem=true;\n    hdr.hist.rot_orient = [];\n    hdr.hist.flip_orient = [];\n    \nend\n\nnii.hdr = hdr;\n\nreturn;\t\t\t\t\t% xform_nii\n\n\n%-----------------------------------------------------------------------\nfunction [hdr, orient] = change_hdr(hdr, tolerance, preferredForm)\n\norient = [1 2 3];\naffine_transform = 1;\n\n%  NIFTI can have both sform and qform transform. This program\n%  will check sform_code prior to qform_code by default.\n%\n%  If user specifys \"preferredForm\", user can then choose the\n%  priority.\t\t\t\t\t- Jeff\n%\nuseForm=[];\t\t\t\t\t% Jeff\n\nif isequal(preferredForm,'S')\n    if isequal(hdr.hist.sform_code,0)\n        error('User requires sform, sform not set in header');\n    else\n        useForm='s';\n    end\nend\t\t\t\t\t\t% Jeff\n\nif isequal(preferredForm,'Q')\n    if isequal(hdr.hist.qform_code,0)\n        error('User requires qform, qform not set in header');\n    else\n        useForm='q';\n    end\nend\t\t\t\t\t\t% Jeff\n\nif isequal(preferredForm,'s')\n    if hdr.hist.sform_code > 0\n        useForm='s';\n    elseif hdr.hist.qform_code > 0\n        useForm='q';\n    end\nend\t\t\t\t\t\t% Jeff\n\nif isequal(preferredForm,'q')\n    if hdr.hist.qform_code > 0\n        useForm='q';\n    elseif hdr.hist.sform_code > 0\n        useForm='s';\n    end\nend\t\t\t\t\t\t% Jeff\n\nif isequal(useForm,'s')\n    R = [hdr.hist.srow_x(1:3)\n        hdr.hist.srow_y(1:3)\n        hdr.hist.srow_z(1:3)];\n    \n    T = [hdr.hist.srow_x(4)\n        hdr.hist.srow_y(4)\n        hdr.hist.srow_z(4)];\n    \n    if det(R) == 0 || ~isequal(R(find(R)), sum(R)')\n        hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];\n        R_sort = sort(abs(R(:)));\n        if tolerance ==1\n            R(2:3,1) = 0; R([1,3],2) = 0; R(1:2,3) = 0;\n        else\n            R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;\n        end\n        hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];\n        \n        if det(R) == 0 || ~isequal(R(find(R)), sum(R)')\n            msg = [char(10) char(10) '   Non-orthogonal rotation or shearing '];\n            msg = [msg 'found inside the affine matrix' char(10)];\n            msg = [msg '   in this NIfTI file. You have 3 options:' char(10) char(10)];\n            msg = [msg '   1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];\n            msg = [msg '      file. I strongly recommand this, because it will not cause' char(10)];\n            msg = [msg '      negative effect, as long as you remember not to do slice' char(10)];\n            msg = [msg '      time correction after using ''reslice_nii.m''.' char(10) char(10)];\n            msg = [msg '   2. Using included ''load_untouch_nii.m'' program to load image' char(10)];\n            msg = [msg '      without applying any affine geometric transformation or' char(10)];\n            msg = [msg '      voxel intensity scaling. This is only for people who want' char(10)];\n            msg = [msg '      to do some image processing regardless of image orientation' char(10)];\n            msg = [msg '      and to save data back with the same NIfTI header.' char(10) char(10)];\n            msg = [msg '   3. Increasing the tolerance to allow more distortion in loaded' char(10)];\n            msg = [msg '      image, but I don''t suggest this.' char(10) char(10)];\n            msg = [msg '   To get help, please type:' char(10) char(10) '   help reslice_nii.m' char(10)];\n            msg = [msg '   help load_untouch_nii.m' char(10) '   help load_nii.m'];\n            error(msg);\n        end\n    end\n    \nelseif isequal(useForm,'q')\n    b = hdr.hist.quatern_b;\n    c = hdr.hist.quatern_c;\n    d = hdr.hist.quatern_d;\n    \n    if 1.0-(b*b+c*c+d*d) < 0\n        if abs(1.0-(b*b+c*c+d*d)) < 1e-5\n            a = 0;\n        else\n            error('Incorrect quaternion values in this NIFTI data.');\n        end\n    else\n        a = sqrt(1.0-(b*b+c*c+d*d));\n    end\n    \n    qfac = hdr.dime.pixdim(1);\n    if qfac==0, qfac = 1; end\n    i = hdr.dime.pixdim(2);\n    j = hdr.dime.pixdim(3);\n    k = qfac * hdr.dime.pixdim(4);\n    \n    R = [a*a+b*b-c*c-d*d     2*b*c-2*a*d        2*b*d+2*a*c\n        2*b*c+2*a*d         a*a+c*c-b*b-d*d    2*c*d-2*a*b\n        2*b*d-2*a*c         2*c*d+2*a*b        a*a+d*d-c*c-b*b];\n    \n    T = [hdr.hist.qoffset_x\n        hdr.hist.qoffset_y\n        hdr.hist.qoffset_z];\n    \n    %  qforms are expected to generate rotation matrices R which are\n    %  det(R) = 1; we'll make sure that happens.\n    %\n    %  now we make the same checks as were done above for sform data\n    %  BUT we do it on a transform that is in terms of voxels not mm;\n    %  after we figure out the angles and squash them to closest\n    %  rectilinear direction. After that, the voxel sizes are then\n    %  added.\n    %\n    %  This part is modified by Jeff Gunter.\n    %\n    if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n        \n        %  det(R) == 0 is not a common trigger for this ---\n        %  R(find(R)) is a list of non-zero elements in R; if that\n        %  is straight (not oblique) then it should be the same as\n        %  columnwise summation. Could just as well have checked the\n        %  lengths of R(find(R)) and sum(R)' (which should be 3)\n        %\n        hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];\n        R_sort = sort(abs(R(:)));\n        if tolerance ==1\n            R(2:3,1) = 0; R([1,3],2) = 0; R(1:2,3) = 0;\n        else\n            R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;\n        end\n        R = R * diag([i j k]);\n        hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];\n        \n        if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n            msg = [char(10) char(10) '   Non-orthogonal rotation or shearing '];\n            msg = [msg 'found inside the affine matrix' char(10)];\n            msg = [msg '   in this NIfTI file. You have 3 options:' char(10) char(10)];\n            msg = [msg '   1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];\n            msg = [msg '      file. I strongly recommand this, because it will not cause' char(10)];\n            msg = [msg '      negative effect, as long as you remember not to do slice' char(10)];\n            msg = [msg '      time correction after using ''reslice_nii.m''.' char(10) char(10)];\n            msg = [msg '   2. Using included ''load_untouch_nii.m'' program to load image' char(10)];\n            msg = [msg '      without applying any affine geometric transformation or' char(10)];\n            msg = [msg '      voxel intensity scaling. This is only for people who want' char(10)];\n            msg = [msg '      to do some image processing regardless of image orientation' char(10)];\n            msg = [msg '      and to save data back with the same NIfTI header.' char(10) char(10)];\n            msg = [msg '   3. Increasing the tolerance to allow more distortion in loaded' char(10)];\n            msg = [msg '      image, but I don''t suggest this.' char(10) char(10)];\n            msg = [msg '   To get help, please type:' char(10) char(10) '   help reslice_nii.m' char(10)];\n            msg = [msg '   help load_untouch_nii.m' char(10) '   help load_nii.m'];\n            error(msg);\n        end\n        \n    else\n        R = R * diag([i j k]);\n    end\t\t\t\t\t% 1st det(R)\n    \nelse\n    affine_transform = 0;\t% no sform or qform transform\nend\n\nif affine_transform == 1\n    voxel_size = abs(sum(R,1));\n    inv_R = inv(R);\n    originator = inv_R*(-T)+1;\n    orient = get_orient(inv_R);\n    \n    %  modify pixdim and originator\n    %\n    %hdr.dime.pixdim(2:4) = voxel_size;\n    hdr.hist.originator(1:3) = originator;\n    \n    %  set sform or qform to non-use, because they have been\n    %  applied in xform_nii\n    %\n    hdr.hist.qform_code = 0;\n    hdr.hist.sform_code = 0;\nend\n\n%  apply space_unit to pixdim if not 1 (mm)\n%\nspace_unit = get_units(hdr);\n\nif space_unit ~= 1\n    hdr.dime.pixdim(2:4) = hdr.dime.pixdim(2:4) * space_unit;\n    \n    %  set space_unit of xyzt_units to millimeter, because\n    %  voxel_size has been re-scaled\n    %\n    hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,1,0));\n    hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,2,1));\n    hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,3,0));\nend\n\nhdr.dime.pixdim = abs(hdr.dime.pixdim);\n\nreturn;\t\t\t\t\t% change_hdr\n\n\n%-----------------------------------------------------------------------\nfunction orient = get_orient(R)\n\norient = [];\n\nfor i = 1:3\n    switch find(R(i,:)) * sign(sum(R(i,:)))\n        case 1\n            orient = [orient 1];\t\t% Left to Right\n        case 2\n            orient = [orient 2];\t\t% Posterior to Anterior\n        case 3\n            orient = [orient 3];\t\t% Inferior to Superior\n        case -1\n            orient = [orient 4];\t\t% Right to Left\n        case -2\n            orient = [orient 5];\t\t% Anterior to Posterior\n        case -3\n            orient = [orient 6];\t\t% Superior to Inferior\n    end\nend\n\nreturn;\t\t\t\t\t% get_orient\n\n\n%-----------------------------------------------------------------------\nfunction [space_unit, time_unit] = get_units(hdr)\n\nswitch bitand(hdr.dime.xyzt_units, 7)\t% mask with 0x07\n    case 1\n        space_unit = 1e+3;\t\t% meter, m\n    case 3\n        space_unit = 1e-3;\t\t% micrometer, um\n    otherwise\n        space_unit = 1;\t\t\t% millimeter, mm\nend\n\nswitch bitand(hdr.dime.xyzt_units, 56)\t% mask with 0x38\n    case 16\n        time_unit = 1e-3;\t\t\t% millisecond, ms\n    case 24\n        time_unit = 1e-6;\t\t\t% microsecond, us\n    otherwise\n        time_unit = 1;\t\t\t% second, s\nend\n\nreturn;\t\t\t\t\t% get_units\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NIfTI_20140122/xform_nii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22228497944320313}}
{"text": "function [sift, SIFTparam] = LMdenseSift(D, HOMEIMAGES, SIFTparam, HOMESIFT)\n%\n% Computes dense SIFT features.\n% The SIFT grid will be defined by the parameters:\n%    SIFTparam.grid_spacing = 1; % distance between grid centers\n%    SIFTparam.patch_size = 16;  % size of patch from which to compute SIFT\n%    descriptor (it has to be a factor of 4)\n%\n% Run demoSIFT.m to see an example of how it works.\n%\n% The SIFT descriptor at each location has 128 dimensions.\n%\n% This function can be called as:\n%\n% [sift, param] = LMdenseSift(D(n), HOMEIMAGES, param);\n% [sift, param] = LMdenseSift(filename, HOMEIMAGES, param);\n% [sift, param] = LMdenseSift(filename, HOMEIMAGES, param, HOMESIFT);\n% LMdenseSift(D, HOMEIMAGES, param, HOMESIFT);\n%\n% 'sift' corresponds to the features of the last image. So, call it passing\n% just one image. But you can precompute the SIFT features for a set of\n% images: When calling LMdenseSift with a fourth argument it will store the sift descriptors in a\n% new folder structure mirroring the folder structure of the images. Then,\n% when called again, if the sift files already exist, it will just read\n% them without recomputing them.\n%\n% Antonio Torralba, 2008\n\n\nif nargin==4\n    precomputed = 1;\n    % get list of folders and create non-existing ones\n    %listoffolders = {D(:).annotation.folder};\nelse\n    precomputed = 0;\n    HOMESIFT = '';\nend\n\nif nargin<3\n    % Default parameters\n    SIFTparam.grid_spacing = 1; % distance between grid centers\n    SIFTparam.patch_size = 16; % size of patch from which to compute SIFT descriptor (it has to be a factor of 4)\nend\nSIFTparam.w = SIFTparam.patch_size/2; % boundary\nNfeatures = 128;\n\nif isstruct(D)\n    % [gist, param] = LMdenseSift(D, HOMEIMAGES, param);\n    Nscenes = length(D);\n    typeD = 1;\nend\n\nif iscell(D)\n    % [gist, param] = LMdenseSift(filename, HOMEIMAGES, param);\n    Nscenes = length(D);\n    typeD = 2;\nend\n\nif isnumeric(D)\n    % [gist, param] = LMdenseSift(img, HOMEIMAGES, param);\n    Nscenes = size(D,4);\n    typeD = 3;\nend\n\nif Nscenes >1\n    fig = figure;\nend\n\n% Loop: Compute SIFT features for all scenes\nsift = zeros([Nscenes Nfeatures], 'single');\nfor n = 1:Nscenes\n    g = [];\n    todo = 1;\n    \n    % if SIFT has already been computed, just read the file\n    if precomputed==1\n        filesift = fullfile(HOMESIFT, D(n).annotation.folder, [D(n).annotation.filename(1:end-4) '.mat']);\n        if exist(filesift, 'file')\n            load(filesift, 'sift', 'SIFTparam');\n            todo = 0;\n        end\n    end\n    \n    % otherwise compute SIFT\n    if todo==1\n        disp([n Nscenes])\n\n        % load image\n        try\n            switch typeD\n                case 1\n                    img = LMimread(D, n, HOMEIMAGES);\n                case 2\n                    img = imread(fullfile(HOMEIMAGES, D{n}));\n                case 3\n                    img = D(:,:,:,n);\n            end\n        catch\n            disp(D(n).annotation.folder)\n            disp(D(n).annotation.filename)\n            rethrow(lasterror)\n        end        \n        \n        % get SIFT descriptors\n        [sift, SIFTparam.grid_x, SIFTparam.grid_y] = dense_sift(img, SIFTparam);\n        \n        if isfield(SIFTparam, 'edges')\n            % 'dont-compute': default if field not present\n            % 'siftrepeat'\n            w = SIFTparam.w-1;\n            switch lower(SIFTparam.edges)\n                case 'siftrepeat'\n                    sift = [repmat(sift(1,:,:),[w 1 1]); sift; repmat(sift(end,:,:),[w 1 1])];\n                    sift = [repmat(sift(:,1,:),[1 w 1]), sift, repmat(sift(:,end,:),[1 w 1])];\n                otherwise\n                    error('Unknown edges method')\n            end\n        end\n        \n        % save SIFT if a HOMESIFT file is provided\n        if precomputed\n            mkdir(fullfile(HOMESIFT, D(n).annotation.folder))\n            save (filesift, 'sift', 'SIFTparam')\n        end\n\n        if Nscenes >1\n            figure(fig);\n            subplot(121)\n            imshow(uint8(img))\n            subplot(122)\n            showColorSIFT(sift)\n        end\n    end\n\n    drawnow\nend\n\n\n\n\nfunction [sift_arr, grid_x, grid_y] = dense_sift(I, SIFTparam)\n% Original script by Svetlana Lazebnick\n% Antonio Torralba: modified using convolutions to speed up the\n% computations.\n\ngrid_spacing = SIFTparam.grid_spacing;\npatch_size = SIFTparam.patch_size;\n\nI = double(I);\nI = mean(I,3);\nI = I /max(I(:));\n\n% parameters\nnum_angles = 8;\nnum_bins = 4;\nnum_samples = num_bins * num_bins;\nalpha = 9; %% parameter for attenuation of angles (must be odd)\n\nif nargin < 5\n    sigma_edge = 1;\nend\n\nangle_step = 2 * pi / num_angles;\nangles = 0:angle_step:2*pi;\nangles(num_angles+1) = []; % bin centers\n\n[hgt wid] = size(I);\n\n[G_X,G_Y]=gen_dgauss(sigma_edge);\n\n% add boundary:\nI = [I(2:-1:1,:,:); I; I(end:-1:end-1,:,:)];\nI = [I(:,2:-1:1,:) I I(:,end:-1:end-1,:)];\n\nI = I-mean(I(:));\nI_X = filter2(G_X, I, 'same'); % vertical edges\nI_Y = filter2(G_Y, I, 'same'); % horizontal edges\n\nI_X = I_X(3:end-2,3:end-2,:);\nI_Y = I_Y(3:end-2,3:end-2,:);\n\nI_mag = sqrt(I_X.^2 + I_Y.^2); % gradient magnitude\nI_theta = atan2(I_Y,I_X);\nI_theta(find(isnan(I_theta))) = 0; % necessary????\n\n% grid \ngrid_x = patch_size/2:grid_spacing:wid-patch_size/2+1;\ngrid_y = patch_size/2:grid_spacing:hgt-patch_size/2+1;\n\n% make orientation images\nI_orientation = zeros([hgt, wid, num_angles], 'single');\n\n% for each histogram angle\ncosI = cos(I_theta);\nsinI = sin(I_theta);\nfor a=1:num_angles\n    % compute each orientation channel\n    tmp = (cosI*cos(angles(a))+sinI*sin(angles(a))).^alpha;\n    tmp = tmp .* (tmp > 0);\n\n    % weight by magnitude\n    I_orientation(:,:,a) = tmp .* I_mag;\nend\n\n% Convolution formulation:\nweight_kernel = zeros(patch_size,patch_size);\nr = patch_size/2;\ncx = r - 0.5;\nsample_res = patch_size/num_bins;\nweight_x = abs((1:patch_size) - cx)/sample_res;\nweight_x = (1 - weight_x) .* (weight_x <= 1);\n\nfor a = 1:num_angles\n    %I_orientation(:,:,a) = conv2(I_orientation(:,:,a), weight_kernel, 'same');\n    I_orientation(:,:,a) = conv2(weight_x, weight_x', I_orientation(:,:,a), 'same');\nend\n\n% Sample SIFT bins at valid locations (without boundary artifacts)\n% find coordinates of sample points (bin centers)\n[sample_x, sample_y] = meshgrid(linspace(1,patch_size+1,num_bins+1));\nsample_x = sample_x(1:num_bins,1:num_bins); sample_x = sample_x(:)-patch_size/2;\nsample_y = sample_y(1:num_bins,1:num_bins); sample_y = sample_y(:)-patch_size/2;\n\nsift_arr = zeros([length(grid_y) length(grid_x) num_angles*num_bins*num_bins], 'single');\nb = 0;\nfor n = 1:num_bins*num_bins\n    sift_arr(:,:,b+1:b+num_angles) = I_orientation(grid_y+sample_y(n), grid_x+sample_x(n), :);\n    b = b+num_angles;\nend\nclear I_orientation\n\n\n% Outputs:\n[grid_x,grid_y] = meshgrid(grid_x, grid_y);\n[nrows, ncols, cols] = size(sift_arr);\n\n% normalize SIFT descriptors\n\n%sift_arr = reshape(sift_arr, [nrows*ncols num_angles*num_bins*num_bins]);\n%sift_arr = normalize_sift(sift_arr);\n%sift_arr = reshape(sift_arr, [nrows ncols num_angles*num_bins*num_bins]);\n\n\nct = .1;\nsift_arr = sift_arr + ct;\ntmp = sqrt(sum(sift_arr.^2, 3));\nsift_arr = sift_arr ./ repmat(tmp, [1 1 size(sift_arr,3)]);\n\nfunction [GX,GY]=gen_dgauss(sigma)\n\n% laplacian of size sigma\n%f_wid = 4 * floor(sigma);\n%G = normpdf(-f_wid:f_wid,0,sigma);\n%G = G' * G;\nG = gen_gauss(sigma);\n[GX,GY] = gradient(G); \n\nGX = GX * 2 ./ sum(sum(abs(GX)));\nGY = GY * 2 ./ sum(sum(abs(GY)));\n\n\nfunction G=gen_gauss(sigma)\n\nif all(size(sigma)==[1, 1])\n    % isotropic gaussian\n\tf_wid = 4 * ceil(sigma) + 1;\n    G = fspecial('gaussian', f_wid, sigma);\n%\tG = normpdf(-f_wid:f_wid,0,sigma);\n%\tG = G' * G;\nelse\n    % anisotropic gaussian\n    f_wid_x = 2 * ceil(sigma(1)) + 1;\n    f_wid_y = 2 * ceil(sigma(2)) + 1;\n    G_x = normpdf(-f_wid_x:f_wid_x,0,sigma(1));\n    G_y = normpdf(-f_wid_y:f_wid_y,0,sigma(2));\n    G = G_y' * G_x;\nend\n\n\n\n\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/features/LMdenseSift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22228497944320313}}
{"text": "function view = motionCompNestaresWithin1st(view, tgtScans, baseScan, baseFrame, smoothing);\n%\n% view = motionCompNestaresFull(view, <tgtScans=all>, <baseScan=1>, , <baseFrame=1>, <temporalSmoothing = 1 frame>);\n%\n% Call both between and within scan motion compensation, back-to-back, on\n% an inplane view. Right now just a simple wrapper. \n%\n% Note that these are the older, rigid-body only motion compensation tools\n% based around the code originally developed by Nestares and Heeger.\n%\n%\n% DY 09/2008 based on motionCompNestaresFull\nif notDefined('view'), view = getSelectedInplane; end\nif notDefined('tgtScans'), tgtScans = 1:numScans(view); end\nif notDefined('baseScan'), baseScan = 1; end\nif notDefined('baseFrame'), baseFrame = 1; end\nif notDefined('smoothing'), smoothing = 1; end\n\nif ~isequal(view.viewType, 'Inplane')\n    myErrorDlg('Can only run motion compensation on Inplane data.');\nend\n\n% first do within scans motion compensation:\nnewDataType = 'MotionComp';\nview = motionCompSelScan(view, newDataType, tgtScans, baseFrame, smoothing);\n\n% then run between scans motion compensation:\nview = selectDataType(view, newDataType);\nnewnewDataType=['MotionComp_RefScan' num2str(baseScan)];\nview = betweenScanMotComp(view, newnewDataType, baseScan, tgtScans);\n\n\ndisp('Finished all motion compensation. Final results in MotionComp_RefScan# data type.')\n\nreturn\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/MotionComp/motionCompNestaresWithin1st.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220688215258025}}
{"text": "function [data_train, labels_train, data_devel, labels_devel, raw_devel, PC, means_norm, stds_norm, devel_ids, devel_success] = ...\n    Prepare_HOG_AU_data_dynamic(train_users, devel_users, au_train, rest_aus, UNBC_dir, features_dir)\n\n%%\naddpath(genpath('../data extraction/'));\n\n% First extracting the labels\n[ labels_train, valid_ids_train, filenames ] = extract_UNBC_labels(UNBC_dir, train_users, au_train);\n\n[ labels_other, ~, ~ ] = extract_UNBC_labels(UNBC_dir, train_users, rest_aus);\nlabels_other = cat(1, labels_other{:});\n\n% Reading in the HOG data (of only relevant frames)\n[train_appearance_data, valid_ids_train_hog, vid_ids_train_string] = Read_HOG_files_dynamic(train_users, features_dir);\n\n[train_geom_data] = Read_geom_files_dynamic(train_users,  features_dir);\n\n% Subsample the data to make training quicker\nlabels_train = cat(1, labels_train{:});\nvalid_ids_train = logical(cat(1, valid_ids_train{:}));\n\nif(numel(train_users) > 0)\n    reduced_inds = false(size(labels_train,1),1);\n    reduced_inds(labels_train > 0) = true;\n\n    % make sure the same number of positive and negative samples is taken\n    pos_count = sum(labels_train > 0);\n    neg_count = sum(labels_train == 0);\n\n    num_other = floor(pos_count / (size(labels_other, 2)));\n\n    inds_all = 1:size(labels_train,1);\n\n    for i=1:size(labels_other, 2)+1\n   \n        if(i > size(labels_other, 2))\n            % fill the rest with a proportion of neutral\n            inds_other = inds_all(sum(labels_other,2)==0 & ~labels_train );   \n                num_other_i = min(numel(inds_other), pos_count - sum(labels_train(reduced_inds,:)==0));     \n        else\n                % take a proportion of each other AU\n            inds_other = inds_all(labels_other(:, i) & ~labels_train );      \n            num_other_i = min(numel(inds_other), num_other);        \n        end\n        inds_other_to_keep = inds_other(round(linspace(1, numel(inds_other), num_other_i)));\n        reduced_inds(inds_other_to_keep) = true;\n\n    end\n\n    % Remove invalid ids based on CLM failing or AU not being labelled\n    reduced_inds(~valid_ids_train) = false;\n    reduced_inds(~valid_ids_train_hog) = false;\n\n    labels_other = labels_other(reduced_inds, :);\n    labels_train = labels_train(reduced_inds,:);\n    train_appearance_data = train_appearance_data(reduced_inds,:);\n    train_geom_data = train_geom_data(reduced_inds,:);\n    vid_ids_train_string = vid_ids_train_string(reduced_inds,:);\nend\n%% Extract devel data\n\n% First extracting the labels\n[ labels_devel, valid_ids_devel, vid_ids_devel ] = extract_UNBC_labels(UNBC_dir, devel_users, au_train);\n\n% Reading in the HOG data (of only relevant frames)\n[devel_appearance_data, valid_ids_devel_hog, vid_ids_devel_string] = Read_HOG_files_dynamic(devel_users, features_dir);\ndevel_success = valid_ids_devel_hog;\ndevel_ids = vid_ids_devel_string;\n\n[devel_geom_data] = Read_geom_files_dynamic(devel_users, features_dir);\n\nlabels_devel = cat(1, labels_devel{:});\n\n% Peforming zone specific masking\nif(au_train < 8 || au_train == 43 || au_train == 45) % upper face AUs ignore bottom face\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_upper.mat';\n    load(pca_file);\nelseif(au_train > 9) % lower face AUs ignore upper face and the sides\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_lower.mat';\n    load(pca_file);\nelseif(au_train == 9) % Central face model\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_rigid.mat';\n    load(pca_file);\nend\n\n% Grab all data for validation as want good params for all the data\nraw_devel = cat(2, devel_appearance_data, devel_geom_data);\n\ndevel_appearance_data = bsxfun(@times, bsxfun(@plus, devel_appearance_data, -means_norm), 1./stds_norm);\n\ndata_devel = devel_appearance_data * PC;\n\ndata_devel = cat(2, data_devel, devel_geom_data);\n\nif(numel(train_users) > 0)\n    train_appearance_data = bsxfun(@times, bsxfun(@plus, train_appearance_data, -means_norm), 1./stds_norm);\n\n    data_train = train_appearance_data * PC;\n    data_train = cat(2, data_train, train_geom_data);\nelse\n    data_train = [];\nend\n\ngeom_size = max(size(train_geom_data, 2), size(devel_geom_data, 2));\n\nPC_n = zeros(size(PC)+geom_size);\nPC_n(1:size(PC,1), 1:size(PC,2)) = PC;\nPC_n(size(PC,1)+1:end, size(PC,2)+1:end) = eye(geom_size);\nPC = PC_n;\n\nmeans_norm = cat(2, means_norm, zeros(1, geom_size));\nstds_norm = cat(2, stds_norm, ones(1, geom_size));\n\nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/AU_training/experiments/UNBC/Prepare_HOG_AU_data_dynamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.22220497510891904}}
{"text": "\n\nfunction my_net_backward(net_info, work_info_batch, data_info, net_run_config)\n\n    gpu_mode=net_run_config.use_gpu;\n      \n    if gpu_mode\n      if ~net_info.ref.net_on_gpu\n           my_move_net(net_info, 'gpu') ;\n      end\n      data_info.ref.output_info_layers{end}=...\n          move_output_info_gpu(data_info.ref.output_info_layers{end});\n    else\n      assert(~net_info.ref.net_on_gpu);\n      data_info.ref.output_info_layers{end}=...\n          move_output_info_cpu(data_info.ref.output_info_layers{end});\n    end\n    \n    do_backward(net_info, work_info_batch, data_info, net_run_config);\n    \n    if gpu_mode\n        if ~net_info.ref.net_stay_on_gpu\n            my_move_net(net_info, 'cpu') ;\n        end\n    end\n      \nend\n\n\n\n\nfunction do_backward(net_info, work_info_batch, data_info, net_run_config)\n\n\none_optimizer_param=work_info_batch.ref.gen_optimizer_param_fn(work_info_batch, net_info);\nnet_info.ref.current_lr=one_optimizer_param.learning_rate;\n\n\nbp_start_layer=net_info.ref.bp_start_layer;\nlayer_num = numel(net_info.ref.layers) ;\nassert(bp_start_layer<=layer_num);\n\n\ngpu_mode=net_run_config.use_gpu;\n\nif gpu_mode && net_run_config.sync\n    wait(gpuDevice) ;\nend\n\n\nif gpu_mode\n    if ~net_info.ref.data_stay_on_gpu\n        data_info.ref.output_info_layers{end}=move_output_info_gpu(...\n            data_info.ref.output_info_layers{end});\n    end\nend\n    \n\n\nfor layer_idx=layer_num:-1:bp_start_layer\n    \n    input_info=data_info.ref.output_info_layers{layer_idx};\n    output_info=data_info.ref.output_info_layers{layer_idx+1};\n        \n    if gpu_mode && ~net_info.ref.data_stay_on_gpu\n        input_info=move_output_info_gpu(input_info);\n    end\n\n    l = net_info.ref.layers{layer_idx} ;\n    is_simple_layer= ~strcmp(l.type, 'my_custom');\n    \n    if is_simple_layer\n        assert(~input_info.is_group_data);\n        assert(~output_info.is_group_data);\n        switch l.type\n          case 'conv'\n\n            one_dzdw=cell(2, 1);\n            [input_info.dzdx, one_dzdw{1}, one_dzdw{2}] = ...\n                vl_nnconv(input_info.x, l.filters, l.biases, ...\n                          output_info.dzdx, ...\n                          'pad', l.pad, 'stride', l.stride) ;\n            input_info.dzdw=one_dzdw;\n\n          case 'pool'\n            input_info.dzdx = vl_nnpool(input_info.x, l.pool, output_info.dzdx, ...\n              'pad', l.pad, 'stride', l.stride, 'method', l.method) ;\n          case 'normalize'\n            input_info.dzdx = vl_nnnormalize(input_info.x, l.param, output_info.dzdx) ;\n          case 'softmax'\n            input_info.dzdx = vl_nnsoftmax(input_info.x, output_info.dzdx) ;\n          case 'relu'\n            input_info.dzdx = vl_nnrelu(input_info.x, output_info.dzdx) ;\n          case 'noffset'\n            input_info.dzdx = vl_nnnoffset(input_info.x, l.param, output_info.dzdx) ;\n          case 'dropout'\n              input_info.dzdx = vl_nndropout(input_info.x, output_info.dzdx, 'mask', output_info.aux) ;\n        end\n    else\n        if ~check_valid_net_output(output_info)\n            break;\n        end\n        input_info = l.backward_fn(input_info, l, work_info_batch, output_info);\n    end\n    \n    \n    if gpu_mode && net_run_config.sync\n      wait(gpuDevice) ;\n    end\n    \n    input_info.bp_finished=true;\n    data_info.ref.output_info_layers{layer_idx}=input_info;\n    do_bp_update_one_layer(net_info, work_info_batch, input_info, layer_idx, one_optimizer_param);\n        \n    data_info.ref.output_info_layers{layer_idx+1}=[];\n\n    if gpu_mode && net_run_config.sync\n      wait(gpuDevice) ;\n    end\nend\n\n\n\nend\n\n\n \n\n\n\n\nfunction do_bp_update_one_layer(net_info, work_info_batch, input_info, layer_idx, one_optimizer_param)\n\n    bp_start_layer=net_info.ref.bp_start_layer;\n    if layer_idx<bp_start_layer\n        return;\n    end\n           \n\n      ly=net_info.ref.layers{layer_idx} ;\n                         \n\n      if strcmp(ly.type, 'conv') \n          \n          lr=one_optimizer_param.learning_rate;\n          momentum_param=one_optimizer_param.momentum;\n          weightDecay_param=one_optimizer_param.weightDecay;\n\n          ly.filtersMomentum = momentum_param * ly.filtersMomentum ...\n              - weightDecay_param * ly.filtersWeightDecay ...\n                  * lr * ly.filtersLearningRate * ly.filters ...\n              - lr * ly.filtersLearningRate * input_info.dzdw{1} ;\n\n          ly.biasesMomentum = momentum_param * ly.biasesMomentum ...\n              - weightDecay_param * ly.biasesWeightDecay ...\n                  * lr * ly.biasesLearningRate * ly.biases ...\n              - lr * ly.biasesLearningRate * input_info.dzdw{2} ;\n\n          ly.filters = ly.filters + ly.filtersMomentum ;\n          ly.biases = ly.biases + ly.biasesMomentum ;\n          net_info.ref.layers{layer_idx} = ly ;\n      end\n\n\n      if strcmp(ly.type, 'my_custom') \n          layer_update_fn=ly.layer_update_fn;\n          if ~isempty(layer_update_fn)\n\n              update_info=[];\n              update_info.input_info=input_info;\n              update_info.work_info_batch=work_info_batch;\n\n              ly=layer_update_fn('bp_update', ly, net_info, update_info);\n              net_info.ref.layers{layer_idx} = ly ;\n          end\n      end\n\n\nend\n\n\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/my_net_backward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.22220497093841038}}
{"text": "%{\n * Copyright (C) 2020-2030, The Regents of The University of Michigan.\n * All rights reserved.\n * This software was developed in the Biped Lab (https://www.biped.solutions/) \n * under the direction of Jessy Grizzle, grizzle@umich.edu. This software may \n * be available under alternative licensing terms; contact the address above.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the Regents of The University of Michigan.\n * \n * AUTHOR: Bruce JK Huang (bjhuang[at]umich.edu)\n * WEBSITE: https://www.brucerobot.com/\n%}\n\n\nfunction cost = checkCost(point, cons1, cons2)\n    if point >= cons1 && point <= cons2\n        cost = 0;\n    else\n        dis = min(abs(point-cons2), abs(point-cons1));\n        cost = getCost(dis);\n    end\nend", "meta": {"author": "UMich-BipedLab", "repo": "extrinsic_lidar_camera_calibration", "sha": "d423c81e95c6de595e1dff79871385348b1c68f4", "save_path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration", "path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration/extrinsic_lidar_camera_calibration-d423c81e95c6de595e1dff79871385348b1c68f4/checkCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "function validJunctionMets = findMetabolicJunctions(model, nRxnsJnc)\n% Finds metabolic branchpoints with different numbers of branches\n%\n% USAGE:\n%\n%    validJunctionMets = findMetabolicJunctions(model, nRxnsJnc)\n%\n% INPUTS:\n%    model:                COBRA model structure\n%    nRxnJnc:              Number of reactions to be considered a junction\n%\n% OUTPUT:\n%    validJunctionMets:    List of junction metabolites\n%\n% .. Author: - Markus Herrgard 12/14/06\n\nif (isfield(model,'c'))\n    selRxnsC = (model.c == 0);\nelse\n    selRxnsC = true(length(model.rxns),1);\nend\n\n%rxnGeneMat is a required field for this function, so if it does not exist,\n%build it.\nif ~isfield(model,'rxnGeneMat')\n    model = buildRxnGeneMat(model);\nend\n\n[baseMetNames,compSymbols,uniqueMetNames,uniqueCompSymbols] = parseMetNames(model.mets);\nuniqueMetNames = uniqueMetNames';\nfor i = 1:length(uniqueMetNames)\n    sel = ismember(baseMetNames,uniqueMetNames{i});\n    nRxnsMetUni(i) = sum(any(model.S(sel,selRxnsC) ~= 0,1));\nend\nnRxnsMetUni = full(nRxnsMetUni');\njunctionMets = uniqueMetNames(nRxnsMetUni >= nRxnsJnc);\n\nvalidJunctionMets = {};\nfor i = 1:length(junctionMets)\n    sel = ismember(baseMetNames,junctionMets{i});\n    if (length(unique(compSymbols(sel))) == 1)\n        selRxns = any(model.S(sel,:) ~= 0,1) & selRxnsC';\n        thisRxns = model.rxns(selRxns);\n        geneMap = model.rxnGeneMat(findRxnIDs(model,thisRxns),:);\n        selNonZero = any(geneMap,2);\n        if (sum(selNonZero) == nRxnsJnc & ...\n            size(unique(geneMap(selNonZero,:),'rows'),1) == nRxnsJnc)\n            validJunctionMets{end+1} = junctionMets{i};\n            if (verbFlag)\n                fprintf('*** %s ***\\n',junctionMets{i});\n                for j = 1:length(thisRxns)\n                    %fprintf('%s\\t',thisRxns{j});\n                    geneInd = find(model.rxnGeneMat(findRxnIDs(model,thisRxns{j}),:));\n                    if (~isempty(geneInd))\n                        thisGenes = model.genes(geneInd);\n                        for k = 1:length(thisGenes)\n                            fprintf('%s ',thisGenes{k});\n                        end\n                    end\n                    fprintf('\\n');\n                end\n            end\n        end\n    end\nend\n\nvalidJunctionMets = validJunctionMets';\nfor i = 1:length(validJunctionMets)\n    validJunctionMets{i} = [validJunctionMets{i} '(c)'];\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/exploration/findMetabolicJunctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "classdef GeometricVectorZConstraint < AbstractGeometricVectorConstraint\n    %GeometricVectorMagConstraint Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n\n    end\n    \n    methods\n        function obj = GeometricVectorZConstraint(vector, event, lb, ub)\n            obj.vector = vector;\n            obj.event = event;\n            obj.lb = lb;\n            obj.ub = ub;   \n\n            obj.type = 'VectorZ';\n            \n            obj.id = rand();\n        end\n\n        function type = getConstraintType(obj)\n            type = 'Geometric Vector Z Component';\n        end\n    end\n    \n    methods(Static)\n        function constraint = getDefaultConstraint(~, ~)            \n            constraint = GeometricVectorZConstraint(AbstractGeometricVector.empty(1,0), LaunchVehicleEvent.empty(1,0), 0, 0);\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/constraints/@GeometricVectorZConstraint/GeometricVectorZConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%% UPDATE PROCEDURES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% UPDATE THE GLOBAL STATE VECTORS FROM ENTITY.VIRTUAL\nfunction [METAObjUpdate]\t= OMAS_updateGlobalStates(SIM,objectID,globalVelocity_k,quaternion_k,idleStatus_k)\n% This function reallocates the global properties of each entity to the \n% META.OBJECT series to allow faster reference and increased independance\n% of the main cycle from the object cycles.\n\n% CONFIRM OBJECT VARIABLES\nassert(isa(objectID,'uint16')   == 1,'The objectID must be a uint16 type');\nassert(islogical(idleStatus_k)  == 1,'The idle agent status must be reported as a logical');\nassert(size(globalVelocity_k,1) == 3 && isnumeric(globalVelocity_k),'Object velocity update must be given as a column vector [3x1].');\nassert(size(quaternion_k,1)     == 4 && isnumeric(quaternion_k),'Object quaternion update must be given as a column vector [4x1].');\nassert(any(isnan(quaternion_k)) == 0,sprintf('Quaternion for objectID %d is invalid; q = [%f %f %f %f]',int8(objectID),quaternion_k(1),quaternion_k(2),quaternion_k(3),quaternion_k(4)));\n\n% IDENTIFY THE ASSOCIATED META OBJECT \nlogicalIndices = SIM.globalIDvector == objectID;                           % The logical position of the ID\nindex = inf;\nfor i = 1:numel(logicalIndices)\n   if logicalIndices(i)\n      index = i; \n      break\n   end\nend\n\n% EXTRACT THE META STRUCTURE TO BE UPDATED \nMETAObjUpdate = SIM.OBJECTS(1,index);                                      % Get the current META object associated with 'entity'\n\n% //////////////////////// UPDATE META.OBJECT /////////////////////////////\n% UPDATE THE META ROTATION DEFINING FIXED LOCAL >> ROTATED IN THE GLOBAL\nMETAObjUpdate.R = OMAS_geometry.quaternionToRotationMatrix(quaternion_k);\n% UPDATE THE GLOBAL POSITION\nglobalPosition_k = METAObjUpdate.globalState(1:3) + globalVelocity_k*SIM.TIME.dt; % Calculate the new global position\n% REBUILD GLOBAL STATES (ENTITY & META)\nMETAObjUpdate.globalState = [globalPosition_k;globalVelocity_k;quaternion_k]; \n% DETERMINE IF ENTITY HAS INDICATED THAT TASK IS COMPLETE\nMETAObjUpdate.idleStatus = idleStatus_k;\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/OMAS_updateGlobalStates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2220699179146683}}
{"text": "function [data_train, labels_train, data_test, labels_test, raw_test, PC, means_norm, stds_norm, vid_ids_test, success_test] = ...\n    Prepare_HOG_AU_data_generic_dynamic(train_users, test_users, au_train, rest_aus, root, features_dir)\n\n%% This should be a separate function?\n\ninput_train_label_files = cell(numel(train_users),1);\ninput_test_label_files = cell(numel(test_users),1);\n\n% This is for loading the labels\nfor i=1:numel(train_users)   \n    input_train_label_files{i} = [root, '/ActionUnit_Labels/', train_users{i}, '/', train_users{i}];\nend\n\n% This is for loading the labels\nfor i=1:numel(test_users)   \n    input_test_label_files{i} = [root, '/ActionUnit_Labels/', test_users{i}, '/', test_users{i}];\nend\n\n% First extracting the labels\n[train_geom_data] = Read_geom_files_dynamic(train_users, features_dir);\n[test_geom_data] = Read_geom_files_dynamic(test_users, features_dir);\n\n% Reading in the HOG data\n[train_data, tracked_inds_hog, vid_ids_train] = Read_HOG_files_dynamic(train_users, features_dir);\n[test_data, success_test, vid_ids_test] = Read_HOG_files_dynamic(test_users, features_dir);\n\ntrain_data = cat(2, train_data, train_geom_data);\nraw_test = cat(2, test_data, test_geom_data);\n\n% Extracting the labels\nlabels_train = extract_au_labels(input_train_label_files, au_train);\nlabels_test = extract_au_labels(input_test_label_files, au_train);\n\nlabels_other = zeros(size(labels_train,1), numel(rest_aus));\n\n% This is used to pick up activity of other AUs for a more 'interesting'\n% data split and not only neutral expressions for negative samples    \nif(numel(input_train_label_files) > 0)\n    for i=1:numel(rest_aus)\n        labels_other(:,i) = extract_au_labels(input_train_label_files, rest_aus(i));\n    end\n\n    % can now extract the needed training labels (do not rebalance validation\n    % data)\n\n    % make sure the same number of positive and negative samples is taken\n    reduced_inds = false(size(labels_train,1),1);\n    reduced_inds(labels_train > 0) = true;\n\n    % make sure the same number of positive and negative samples is taken\n    pos_count = sum(labels_train > 0);\n    neg_count = sum(labels_train == 0);\n\n    % pos_count = pos_count * 8;\n\n    num_other = floor(pos_count / (size(labels_other, 2)));\n\n    inds_all = 1:size(labels_train,1);\n\n    for i=1:size(labels_other, 2)+1\n\n        if(i > size(labels_other, 2))\n            % fill the rest with a proportion of neutral\n            inds_other = inds_all(sum(labels_other,2)==0 & ~labels_train);   \n            num_other_i = min(numel(inds_other), pos_count - sum(labels_train(reduced_inds,:)==0));     \n        else\n            % take a proportion of each other AU\n            inds_other = inds_all(labels_other(:, i) & ~labels_train);      \n            num_other_i = min(numel(inds_other), num_other);        \n        end\n        inds_other_to_keep = inds_other(round(linspace(1, numel(inds_other), num_other_i)));\n        reduced_inds(inds_other_to_keep) = true;\n\n    end\n\n    % Remove invalid ids based on CLM failing or AU not being labelled\n    reduced_inds(~tracked_inds_hog) = false;\n\n    labels_train = labels_train(reduced_inds);\n    train_data = train_data(reduced_inds,:);\n    \nend\n     \ngeom_size = max(size(train_geom_data,2), size(test_geom_data,2));\n\n% Peforming zone specific masking\nif(au_train < 8 || au_train == 43 || au_train == 45) % upper face AUs ignore bottom face\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_upper.mat';\n    load(pca_file);\nelseif(au_train > 9) % lower face AUs ignore upper face and the sides\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_lower.mat';\n    load(pca_file);\nelseif(au_train == 9) % Central face model\n    % normalise the data\n    pca_file = '../../pca_generation/generic_face_rigid.mat';\n    load(pca_file);\nend\n\nPC_n = zeros(size(PC)+geom_size);\nPC_n(1:size(PC,1), 1:size(PC,2)) = PC;\nPC_n(size(PC,1)+1:end, size(PC,2)+1:end) = eye(geom_size);\nPC = PC_n;\n\nmeans_norm = cat(2, means_norm, zeros(1, geom_size));\nstds_norm = cat(2, stds_norm, ones(1, geom_size));\n\ndata_test = bsxfun(@times, bsxfun(@plus, raw_test, -means_norm), 1./stds_norm);\ndata_test = data_test * PC;\n\nif(numel(train_data > 0))\n    data_train = bsxfun(@times, bsxfun(@plus, train_data, -means_norm), 1./stds_norm);\n    data_train = data_train * PC;\nelse\n   data_train = []; \nend\n\nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/AU_training/experiments/DISFA/Prepare_HOG_AU_data_generic_dynamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22206991217031663}}
{"text": "%% MKL Numerical Jacobian Install for OPTI Toolbox\n% Supplied binaries are built from MKL 10.3 Release 11\n\n%   Copyright (C) 2011 Jonathan Currie (I2C2)\n\n% This file will help you compile the Intel Math Kernel Library (MKL) \n% djacobi function for use with MATLAB. NOTE you must NOT link the threaded\n% MKL libraries as the MATLAB callback function is not thread safe!\n\n% My build platform:\n% - Windows 7 SP1 x64\n% - Visual Studio 2010\n% - Intel Math Kernel Library 10.3 \n\n% To recompile you will need to get / do the following:\n\n% 1) Get and Install Intel MKL\n% http://software.intel.com/en-us/articles/intel-mkl/\n\n% 2) MKL JAC MEX Interface\n% The MKL JAC MEX Interface is a simple MEX interface I wrote to use this\n% function and is supplied in the Utilities\\NumDiff folder.\n\n% 6) Compile the MEX File\n% The code below will automatically include all required libraries and\n% directories to build the MKL JAC MEX file. Once you have completed all \n% the above steps, simply run this file to compile! You MUST BE in the \n% base directory of OPTI!\n\nclear mklJac\n\n% Modify below function if it cannot find Intel MKL on your system.\nmkl_link = opti_FindMKL('seq'); %NOTE sequential only build!\n\nfprintf('\\n------------------------------------------------\\n');\nfprintf('MKL JAC MEX FILE INSTALL\\n\\n');\n\n%Get MKL Includes & MKL Libraries (for DJACOBI)\npost = mkl_link;\n\n%CD to Source Directory\ncdir = cd;\ncd 'Utilities/Differentiation/Numerical/Source';\n\n%Compile & Move\npre = 'mex -v -largeArrayDims mklJac.c';\ntry\n    eval([pre post])\n    movefile(['mklJac.' mexext],'../','f')\n    fprintf('Done!\\n');\ncatch ME\n    cd(cdir);\n    error('opti:mkljac','Error Compiling MKL JAC!\\n%s',ME.message);\nend\ncd(cdir);\nfprintf('------------------------------------------------\\n');\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Utilities/Differentiation/Numerical/opti_MKLJAC_Install.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2216837463375855}}
{"text": "function normalise = spm_cfg_normalise\n% SPM Configuration file for toolbox 'Old Normalise'\n%__________________________________________________________________________\n% Copyright (C) 2005-2012 Wellcome Trust Centre for Neuroimaging\n\n% $Id: spm_cfg_normalise.m 7155 2017-08-17 10:55:05Z john $\n\nif ~isdeployed, addpath(fullfile(spm('dir'),'toolbox','OldNorm')); end\n\n%--------------------------------------------------------------------------\n% source Source Image\n%--------------------------------------------------------------------------\nsource         = cfg_files;\nsource.tag     = 'source';\nsource.name    = 'Source Image';\nsource.help    = {'The image that is warped to match the template(s).  The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};\nsource.filter  = 'image';\nsource.ufilter = '.*';\nsource.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% wtsrc Source Weighting Image\n%--------------------------------------------------------------------------\nwtsrc         = cfg_files;\nwtsrc.tag     = 'wtsrc';\nwtsrc.name    = 'Source Weighting Image';\nwtsrc.val     = {''};\nwtsrc.help    = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains.  These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};\nwtsrc.filter  = 'image';\nwtsrc.ufilter = '.*';\nwtsrc.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% subj Subject\n%--------------------------------------------------------------------------\nsubj         = cfg_branch;\nsubj.tag     = 'subj';\nsubj.name    = 'Subject';\nsubj.val     = {source wtsrc };\nsubj.help    = {'Data for this subject.  The same parameters are used within subject.'};\n\n%--------------------------------------------------------------------------\n% esubjs Data\n%--------------------------------------------------------------------------\nesubjs         = cfg_repeat;\nesubjs.tag     = 'esubjs';\nesubjs.name    = 'Data';\nesubjs.help    = {'List of subjects. Images of each subject should be warped differently.'};\nesubjs.values  = {subj };\nesubjs.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% template Template Image\n%--------------------------------------------------------------------------\ntemplate         = cfg_files;\ntemplate.tag     = 'template';\ntemplate.name    = 'Template Image';\ntemplate.help    = {'Specify a template image to match the source image with. The contrast in the template must be similar to that of the source image in order to achieve a good registration.  It is also possible to select more than one template, in which case the registration algorithm will try to find the best linear combination of these images in order to best model the intensities in the source image.'};\ntemplate.filter  = 'image';\ntemplate.ufilter = '.*';\ntemplate.dir     = fileparts(mfilename('fullpath'));\ntemplate.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% weight Template Weighting Image\n%--------------------------------------------------------------------------\nweight         = cfg_files;\nweight.tag     = 'weight';\nweight.name    = 'Template Weighting Image';\nweight.val     = {''};\nweight.help    = {\n                  'Applies a weighting mask to the template(s) during the parameter estimation.  With the default brain mask, weights in and around the brain have values of one whereas those clearly outside the brain are zero.  This is an attempt to base the normalisation purely upon the shape of the brain, rather than the shape of the head (since low frequency basis functions can not really cope with variations in skull thickness).'\n                  ''\n                  'The option is now available for a user specified weighting image. This should have the same dimensions and mat file as the template images, with values in the range of zero to one.'\n}';\nweight.filter  = 'image';\nweight.ufilter = '.*';\nweight.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% smosrc Source Image Smoothing\n%--------------------------------------------------------------------------\nsmosrc         = cfg_entry;\nsmosrc.tag     = 'smosrc';\nsmosrc.name    = 'Source Image Smoothing';\nsmosrc.help    = {'Smoothing to apply to a copy of the source image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};\nsmosrc.strtype = 'e';\nsmosrc.num     = [1 1];\nsmosrc.def     = @(val)spm_get_defaults('old.normalise.estimate.smosrc', val{:});\n\n%--------------------------------------------------------------------------\n% smoref Template Image Smoothing\n%--------------------------------------------------------------------------\nsmoref         = cfg_entry;\nsmoref.tag     = 'smoref';\nsmoref.name    = 'Template Image Smoothing';\nsmoref.help    = {'Smoothing to apply to a copy of the template image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};\nsmoref.strtype = 'e';\nsmoref.num     = [1 1];\nsmoref.def     = @(val)spm_get_defaults('old.normalise.estimate.smoref', val{:});\n\n%--------------------------------------------------------------------------\n% regtype Affine Regularisation\n%--------------------------------------------------------------------------\nregtype         = cfg_menu;\nregtype.tag     = 'regtype';\nregtype.name    = 'Affine Regularisation';\nregtype.help    = {'Affine registration into a standard space can be made more robust by regularisation (penalising excessive stretching or shrinking).  The best solutions can be obtained by knowing the approximate amount of stretching that is needed (e.g. ICBM templates are slightly bigger than typical brains, so greater zooms are likely to be needed). If registering to an image in ICBM/MNI space, then choose the first option.  If registering to a template that is close in size, then select the second option.  If you do not want to regularise, then choose the third.'};\nregtype.labels  = {\n                  'ICBM space template'\n                  'Average sized template'\n                  'No regularisation'\n}';\nregtype.values  = {\n                  'mni'\n                  'subj'\n                  'none'\n}';\nregtype.def     = @(val)spm_get_defaults('old.normalise.estimate.regtype', val{:});\n\n%--------------------------------------------------------------------------\n% cutoff Nonlinear Frequency Cutoff\n%--------------------------------------------------------------------------\ncutoff         = cfg_entry;\ncutoff.tag     = 'cutoff';\ncutoff.name    = 'Nonlinear Frequency Cutoff';\ncutoff.help    = {'Cutoff of DCT bases.  Only DCT bases of periods longer than the cutoff are used to describe the warps. The number used will depend on the cutoff and the field of view of the template image(s).'};\ncutoff.strtype = 'e';\ncutoff.num     = [1 1];\ncutoff.def     = @(val)spm_get_defaults('old.normalise.estimate.cutoff', val{:});\n\n%--------------------------------------------------------------------------\n% nits Nonlinear Iterations\n%--------------------------------------------------------------------------\nnits         = cfg_entry;\nnits.tag     = 'nits';\nnits.name    = 'Nonlinear Iterations';\nnits.help    = {'Number of iterations of nonlinear warping performed.'};\nnits.strtype = 'w';\nnits.num     = [1 1];\nnits.def     = @(val)spm_get_defaults('old.normalise.estimate.nits', val{:});\n\n%--------------------------------------------------------------------------\n% reg Nonlinear Regularisation\n%--------------------------------------------------------------------------\nreg         = cfg_entry;\nreg.tag     = 'reg';\nreg.name    = 'Nonlinear Regularisation';\nreg.help    = {'The amount of regularisation for the nonlinear part of the spatial normalisation. Pick a value around one.  However, if your normalised images appear distorted, then it may be an idea to increase the amount of regularisation (by an order of magnitude) - or even just use an affine normalisation. The regularisation influences the smoothness of the deformation fields.'};\nreg.strtype = 'e';\nreg.num     = [1 1];\nreg.def     = @(val)spm_get_defaults('old.normalise.estimate.reg', val{:});\n\n%--------------------------------------------------------------------------\n% eoptions Estimation Options\n%--------------------------------------------------------------------------\neoptions      = cfg_branch;\neoptions.tag  = 'eoptions';\neoptions.name = 'Estimation Options';\neoptions.val  = {template weight smosrc smoref regtype cutoff nits reg };\neoptions.help = {'Various settings for estimating warps.'};\n\n%--------------------------------------------------------------------------\n% est Old Normalise: Estimate\n%--------------------------------------------------------------------------\nest         = cfg_exbranch;\nest.tag     = 'est';\nest.name    = 'Old Normalise: Estimate';\nest.val     = {esubjs eoptions };\nest.help    = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to a file imagename''_sn.mat''.'};\nest.prog    = @spm_run_normalise;\nest.vout    = @vout_estimate;\n\n%--------------------------------------------------------------------------\n% matname Parameter File\n%--------------------------------------------------------------------------\nmatname         = cfg_files;\nmatname.tag     = 'matname';\nmatname.name    = 'Parameter File';\nmatname.help    = {'Select the ''_sn.mat'' file containing the spatial normalisation parameters for that subject.'};\nmatname.filter  = 'mat';\nmatname.ufilter = '.*_sn\\.mat$';\nmatname.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% resample Images to Write\n%--------------------------------------------------------------------------\nresample         = cfg_files;\nresample.tag     = 'resample';\nresample.name    = 'Images to Write';\nresample.help    = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the \"source\" image used to generate the parameters.'};\nresample.filter  = 'image';\nresample.ufilter = '.*';\nresample.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% subj Subject\n%--------------------------------------------------------------------------\nsubj         = cfg_branch;\nsubj.tag     = 'subj';\nsubj.name    = 'Subject';\nsubj.val     = {matname resample };\nsubj.help    = {'Data for this subject.  The same parameters are used within subject.'};\n\n%--------------------------------------------------------------------------\n% wsubjs Data\n%--------------------------------------------------------------------------\nwsubjs         = cfg_repeat;\nwsubjs.tag     = 'wsubjs';\nwsubjs.name    = 'Data';\nwsubjs.help    = {'List of subjects. Images of each subject should be warped differently.'};\nwsubjs.values  = {subj };\nwsubjs.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% preserve Preserve\n%--------------------------------------------------------------------------\npreserve         = cfg_menu;\npreserve.tag     = 'preserve';\npreserve.name    = 'Preserve';\npreserve.help    = {\n                    'Preserve Concentrations: Spatially normalised images are not \"modulated\". The warped images preserve the intensities of the original images.'\n                    ''\n                    'Preserve Total: Spatially normalised images are \"modulated\" in order to preserve the total amount of signal in the images. Areas that are expanded during warping are correspondingly reduced in intensity.'\n}';\npreserve.labels = {\n                   'Preserve Concentrations'\n                   'Preserve Amount'\n}';\npreserve.values = {0 1};\npreserve.def     = @(val)spm_get_defaults('old.normalise.write.preserve', val{:});\n\n%--------------------------------------------------------------------------\n% bb Bounding box\n%--------------------------------------------------------------------------\nbb         = cfg_entry;\nbb.tag     = 'bb';\nbb.name    = 'Bounding box';\nbb.help    = {'The bounding box (in mm) of the volume which is to be written (relative to the anterior commissure).'};\nbb.strtype = 'e';\nbb.num     = [2 3];\nbb.def     = @(val)spm_get_defaults('old.normalise.write.bb', val{:});\n\n%--------------------------------------------------------------------------\n% vox Voxel sizes\n%--------------------------------------------------------------------------\nvox         = cfg_entry;\nvox.tag     = 'vox';\nvox.name    = 'Voxel sizes';\nvox.help    = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'};\nvox.strtype = 'e';\nvox.num     = [1 3];\nvox.def     = @(val)spm_get_defaults('old.normalise.write.vox', val{:});\n\n%--------------------------------------------------------------------------\n% interp Interpolation\n%--------------------------------------------------------------------------\ninterp         = cfg_menu;\ninterp.tag     = 'interp';\ninterp.name    = 'Interpolation';\ninterp.help    = {\n                  ['The method by which the images are sampled when ' ...\n                  'being written in a different space. ' ...\n                  '(Note that Inf or NaN values are treated as zero, ' ...\n                  'rather than as missing data)']\n                  '    Nearest Neighbour:'\n                  '      - Fastest, but not normally recommended.'\n                  '    Trilinear Interpolation:'\n                  '      - OK for PET, realigned fMRI, or segmentations'\n                  '    B-spline Interpolation:'\n                  ['      - Better quality (but slower) interpolation' ...\n                  '/* \\cite{thevenaz00a}*/, especially with higher ' ...\n                  'degree splines. Can produce values outside the ' ...\n                  'original range (e.g. small negative values from an ' ...\n                  'originally all positive image).']\n}';\ninterp.labels = {\n                 'Nearest neighbour'\n                 'Trilinear'\n                 '2nd Degree B-spline'\n                 '3rd Degree B-Spline '\n                 '4th Degree B-Spline '\n                 '5th Degree B-Spline'\n                 '6th Degree B-Spline'\n                 '7th Degree B-Spline'\n}';\ninterp.values = {0 1 2 3 4 5 6 7};\ninterp.def     = @(val)spm_get_defaults('old.normalise.write.interp', val{:});\n\n%--------------------------------------------------------------------------\n% wrap Wrapping\n%--------------------------------------------------------------------------\nwrap         = cfg_menu;\nwrap.tag     = 'wrap';\nwrap.name    = 'Wrapping';\nwrap.help    = {\n                'These are typically:'\n                '    No wrapping: for PET or images that have already been spatially transformed. '\n                '    Wrap in  Y: for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).'\n}';\nwrap.labels  = {\n               'No wrap'\n               'Wrap X'\n               'Wrap Y'\n               'Wrap X & Y'\n               'Wrap Z'\n               'Wrap X & Z'\n               'Wrap Y & Z'\n               'Wrap X, Y & Z'\n}';\nwrap.values  = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]...\n               [1 1 1]};\nwrap.def     = @(val)spm_get_defaults('old.normalise.write.wrap', val{:});\n\n%--------------------------------------------------------------------------\n% prefix Filename Prefix\n%--------------------------------------------------------------------------\nprefix         = cfg_entry;\nprefix.tag     = 'prefix';\nprefix.name    = 'Filename Prefix';\nprefix.help    = {'Specify the string to be prepended to the filenames of the normalised image file(s). Default prefix is ''w''.'};\nprefix.strtype = 's';\nprefix.num     = [1 Inf];\nprefix.def     = @(val)spm_get_defaults('old.normalise.write.prefix', val{:});\n\n%--------------------------------------------------------------------------\n% roptions Writing Options\n%--------------------------------------------------------------------------\nroptions      = cfg_branch;\nroptions.tag  = 'roptions';\nroptions.name = 'Writing Options';\nroptions.val  = {preserve bb vox interp wrap prefix };\nroptions.help = {'Various options for writing normalised images.'};\n\n%--------------------------------------------------------------------------\n% write Old Normalise: Write\n%--------------------------------------------------------------------------\nwrite         = cfg_exbranch;\nwrite.tag     = 'write';\nwrite.name    = 'Old Normalise: Write';\nwrite.val     = {wsubjs roptions };\nwrite.help    = {'Allows previously estimated warps (stored in imagename''_sn.mat'' files) to be applied to series of images.'};\nwrite.prog    = @spm_run_normalise;\nwrite.vout    = @vout_write;\n\n%--------------------------------------------------------------------------\n% source Source Image\n%--------------------------------------------------------------------------\nsource         = cfg_files;\nsource.tag     = 'source';\nsource.name    = 'Source Image';\nsource.help    = {'The image that is warped to match the template(s).  The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};\nsource.filter  = 'image';\nsource.ufilter = '.*';\nsource.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% wtsrc Source Weighting Image\n%--------------------------------------------------------------------------\nwtsrc         = cfg_files;\nwtsrc.tag     = 'wtsrc';\nwtsrc.name    = 'Source Weighting Image';\nwtsrc.val     = {''};\nwtsrc.help    = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains.  These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};\nwtsrc.filter  = 'image';\nwtsrc.ufilter = '.*';\nwtsrc.num     = [0 1];\n\n%--------------------------------------------------------------------------\n% resample Images to Write\n%--------------------------------------------------------------------------\nresample         = cfg_files;\nresample.tag     = 'resample';\nresample.name    = 'Images to Write';\nresample.help    = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the \"source\" image used to generate the parameters.'};\nresample.filter  = 'image';\nresample.ufilter = '.*';\nresample.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% subj Subject\n%--------------------------------------------------------------------------\nsubj         = cfg_branch;\nsubj.tag     = 'subj';\nsubj.name    = 'Subject';\nsubj.val     = {source wtsrc resample };\nsubj.help    = {'Data for this subject.  The same parameters are used within subject.'};\n\n%--------------------------------------------------------------------------\n% ewsubjs Data\n%--------------------------------------------------------------------------\newsubjs         = cfg_repeat;\newsubjs.tag     = 'ewsubjs';\newsubjs.name    = 'Data';\newsubjs.help    = {'List of subjects. Images of each subject should be warped differently.'};\newsubjs.values  = {subj };\newsubjs.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% estwrite Old Normalise: Estimate & Write\n%--------------------------------------------------------------------------\nestwrite      = cfg_exbranch;\nestwrite.tag  = 'estwrite';\nestwrite.name = 'Old Normalise: Estimate & Write';\nestwrite.val  = {ewsubjs eoptions roptions };\nestwrite.help = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to the file imagename''_sn.mat''. This option also allows the contents of the imagename''_sn.mat'' files to be applied to a series of images.'};\nestwrite.prog = @spm_run_normalise;\nestwrite.vout = @vout_estwrite;\n\n%--------------------------------------------------------------------------\n% oldnorm Old Normalise\n%--------------------------------------------------------------------------\nnormalise         = cfg_choice;\nnormalise.tag     = 'oldnorm';\nnormalise.name    = 'Old Normalise';\nnormalise.help    = {\n                     'This very ancient module /* \\cite{ashburner97b,ashburner99a} */ spatially (stereotactically) normalises MRI, PET or SPECT images into a standard space defined by some ideal model or template image[s].  The template images supplied with SPM conform to the space defined by the ICBM, NIH P-20 project, and approximate that of the the space described in the atlas of Talairach and Tournoux (1988). The transformation can also be applied to any other image that has been coregistered with these scans. A few researchers may wish to continue using this strategy, but (when good quality anatomical MRI scans are available) the DARTEL approach is now generally recommended instead.'\n                     ''\n                     'Generally, the algorithms work by minimising the sum of squares difference between the image which is to be normalised, and a linear combination of one or more template images.  For the least squares registration to produce an unbiased estimate of the spatial transformation, the image contrast in the templates (or linear combination of templates) should be similar to that of the image from which the spatial normalisation is derived.  The registration simply searches for an optimum solution.  If the starting estimates are not good, then the optimum it finds may not find the global optimum.'\n                     ''\n                     'The first step of the normalisation is to determine the optimum 12-parameter affine transformation.  Initially, the registration is performed by matching the whole of the head (including the scalp) to the template.  Following this, the registration proceeded by only matching the brains together, by appropriate weighting of the template voxels.  This is a completely automated procedure (that does not require ``scalp editing'') that discounts the confounding effects of skull and scalp differences.   A Bayesian framework is used, such that the registration searches for the solution that maximises the a posteriori probability of it being correct /* \\cite{ashburner97b} */.  i.e., it maximises the product of the likelihood function (derived from the residual squared difference) and the prior function (which is based on the probability of obtaining a particular set of zooms and shears).'\n                     ''\n                     'The affine registration is followed by estimating nonlinear deformations, whereby the deformations are defined by a linear combination of three dimensional discrete cosine transform (DCT) basis functions /* \\cite{ashburner99a} */.  The default options result in each of the deformation fields being described by 1176parameters, where these represent the coefficients of the deformations in three orthogonal directions.  The matching involved simultaneously minimising the membrane energies of the deformation fields and the residual squared difference between the images and template(s).'\n                     ''\n                     'The primarily use is for stereotactic normalisation to facilitate inter-subject averaging and precise characterisation of functional anatomy /* \\cite{ashburner97bir} */.  It is not necessary to spatially normalise the data (this is only a pre-requisite  for  inter-subject averaging or reporting in the Talairach space).  If you wish to circumnavigate this step  (e.g. if you have single slice data or do not have an appropriate high resolution MRI scan) simply specify where you think the  anterior commissure  is  with  the  ORIGIN in the header of the first scan (using the ''Display'' facility) and proceed directly  to ''Smoothing''or ''Statistics''.'\n                     ''\n                     'All normalised images are written to the same subdirectory as the original images, prefixed with a ''w''.  The details of the transformations are displayed in the results window, and the parameters are saved in the \"*_sn.mat\" file.'\n}';\nnormalise.values   = {est write estwrite};\n\n%==========================================================================\nfunction dep = vout_estimate(job)\nfor k=1:numel(job.subj)\n    dep(k)            = cfg_dep;\n    dep(k).sname      = sprintf('Norm Params File (Subj %d)',k);\n    dep(k).src_output = substruct('()',{k},'.','params');\n    dep(k).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\nend\n\n%==========================================================================\nfunction dep = vout_write(job)\nfor k=1:numel(job.subj)\n    dep(k)            = cfg_dep;\n    dep(k).sname      = sprintf('Normalised Images (Subj %d)',k);\n    dep(k).src_output = substruct('()',{k},'.','files');\n    dep(k).tgt_spec   = cfg_findspec({{'filter','image','strtype','e'}});\nend\n\n%==========================================================================\nfunction dep = vout_estwrite(job)\ndepe = vout_estimate(job);\ndepw = vout_write(job);\ndep = [depe depw];\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/OldNorm/spm_cfg_normalise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22168374633758547}}
{"text": "% params\ntotalNum = 6159264;\nbValue = 1000;\nlamda = 0;\nqFile = '/home/yinhuan/Data/mapModel/yq/weightVector.txt';\nvisFilesDir = '/home/yinhuan/Data/mapModel/yq/visMatrix/';\nmaxQ = 179;\nminQ = 1;\n\nsplitLength_0 = 50;\nsaveResultsDir_0 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/0/';\nsaveReIndexFile_0 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/0.txt';\nsaveNewQFile_0 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/0.txt';\n\nsplitLength_1 = 100;\nsaveResultsDir_1 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/1/';\nsaveReIndexFile_1 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/1.txt';\nsaveNewQFile_1 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/1.txt';\n\nsplitLength_2 = 200;\nsaveResultsDir_2 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/2/';\nsaveReIndexFile_2 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/2.txt';\nsaveNewQFile_2 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/2.txt';\n\nsplitLength_3 = 400;\nsaveResultsDir_3 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/3/';\nsaveReIndexFile_3 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/3.txt';\nsaveNewQFile_3 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/3.txt';\n\nsplitLength_4 = 800; \nsaveResultsDir_4 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/4/';\nsaveReIndexFile_4 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/4.txt';\nsaveNewQFile_4 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/4.txt';\n\nsplitLength_5 = 1600;\nsaveResultsDir_5 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/5/';\nsaveReIndexFile_5 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/5.txt';\nsaveNewQFile_5 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/5.txt';\n\nsplitLength_6 = 3200;\nsaveResultsDir_6 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/6/';\nsaveReIndexFile_6 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/index/6.txt';\nsaveNewQFile_6 = '/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/weight/6.txt';\n\n%% iteration of optimization\n\nvisCells_origin = fromVisDirToCells(visFilesDir);\n\n[ epsilon_soft_0, time_sum_0  ] = Uniform_loopCompress_Cells( lamda, qFile, visCells_origin, splitLength_0, totalNum, bValue, saveResultsDir_0 );\nmin_cost_0 = get_min_cost(minQ, maxQ, saveResultsDir_0, qFile, lamda, epsilon_soft_0);\n[totalNum_0, visCells_0] = deleteZeroPoints_Cells( qFile, visCells_origin, saveResultsDir_0, saveReIndexFile_0, saveNewQFile_0 );\n\n[ epsilon_soft_1, time_sum_1  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_0, visCells_0, splitLength_1, totalNum_0, bValue, saveResultsDir_1 );\nmin_cost_1 = get_min_cost(minQ, maxQ, saveResultsDir_1, saveNewQFile_0, lamda, epsilon_soft_1);\n[totalNum_1, visCells_1] = deleteZeroPoints_Cells( saveNewQFile_0, visCells_0, saveResultsDir_1, saveReIndexFile_1, saveNewQFile_1 );\n\n[ epsilon_soft_2, time_sum_2  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_1, visCells_1, splitLength_2, totalNum_1, bValue, saveResultsDir_2 );\nmin_cost_2 = get_min_cost(minQ, maxQ, saveResultsDir_2, saveNewQFile_1, lamda, epsilon_soft_2);\n[totalNum_2, visCells_2] = deleteZeroPoints_Cells( saveNewQFile_1, visCells_1, saveResultsDir_2, saveReIndexFile_2, saveNewQFile_2 );\n\n\n\n\n\n[ epsilon_soft_3, time_sum_3  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_2, visCells_2, splitLength_3, totalNum_2, bValue, saveResultsDir_3 );\nmin_cost_3 = get_min_cost(minQ, maxQ, saveResultsDir_3, saveNewQFile_2, lamda, epsilon_soft_3);\n[totalNum_3, visCells_3] = deleteZeroPoints_Cells( saveNewQFile_2, visCells_2, saveResultsDir_3, saveReIndexFile_3, saveNewQFile_3 );\n\n[ epsilon_soft_4, time_sum_4  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_3, visCells_3, splitLength_4, totalNum_3, bValue, saveResultsDir_4 );\nmin_cost_4 = get_min_cost(minQ, maxQ, saveResultsDir_4, saveNewQFile_3, lamda, epsilon_soft_4);\n[totalNum_4, visCells_4] = deleteZeroPoints_Cells( saveNewQFile_3, visCells_3, saveResultsDir_4, saveReIndexFile_4, saveNewQFile_4 );\n\n\n\n\n[ epsilon_soft_5, time_sum_5  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_4, visCells_4, splitLength_5, totalNum_4, bValue, saveResultsDir_5 );\nmin_cost_5 = get_min_cost(minQ, maxQ, saveResultsDir_5, saveNewQFile_4, lamda, epsilon_soft_5);\n[totalNum_5, visCells_5] = deleteZeroPoints_Cells( saveNewQFile_4, visCells_4, saveResultsDir_5, saveReIndexFile_5, saveNewQFile_5 );\n\n[ epsilon_soft_6, time_sum_6  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_5, visCells_5, splitLength_6, totalNum_5, bValue, saveResultsDir_6 );\nmin_cost_6 = get_min_cost(minQ, maxQ, saveResultsDir_6, saveNewQFile_5, lamda, epsilon_soft_6);\n[totalNum_6, visCells_6] = deleteZeroPoints_Cells( saveNewQFile_5, visCells_5, saveResultsDir_6, saveReIndexFile_6, saveNewQFile_6 );\n\n\n\n\n\n\n% save the results\n\ncompressIndex_5 = anal_reindex_last(saveResultsDir_6, saveReIndexFile_5);\ncompressIndex_4 = anal_reindex_middle(compressIndex_5, saveReIndexFile_4);\ncompressIndex_3 = anal_reindex_middle(compressIndex_4, saveReIndexFile_3);\ncompressIndex_2 = anal_reindex_middle(compressIndex_3, saveReIndexFile_2);\ncompressIndex_1 = anal_reindex_middle(compressIndex_2, saveReIndexFile_1);\ncompressIndex_0 = anal_reindex_middle(compressIndex_1, saveReIndexFile_0);\n\ndlmwrite('/home/yinhuan/Data/mapModel/yq/iter_b_1000_0/compressIndex_final.txt', compressIndex_0, 'precision', '%d');\n\n\n\n\n\n\n\n\n", "meta": {"author": "HuanYin94", "repo": "map_compression", "sha": "3c126a5cc832bf51f0c313c6ad8aa58a2930312c", "save_path": "github-repos/MATLAB/HuanYin94-map_compression", "path": "github-repos/MATLAB/HuanYin94-map_compression/map_compression-3c126a5cc832bf51f0c313c6ad8aa58a2930312c/gurobi/q_ILP_lamda/iter_run/yq_lamda/run_yq_1000_0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22158186035846725}}
{"text": "function stage_time_struct = timesStruct(N, nt)\nstage_time_struct = ocl.types.Structure();\nstage_time_struct.addRepeated({'states', 'integrator', 'controls'}, ...\n  {ocl.types.Matrix([1,1]), ocl.types.Matrix([nt,1]), ocl.types.Matrix([1,1])}, N);\nstage_time_struct.add('states', ocl.types.Matrix([1,1]));", "meta": {"author": "OpenOCL", "repo": "OpenOCL", "sha": "348fc31929791ddc8ed15a15733cf060a2e4674c", "save_path": "github-repos/MATLAB/OpenOCL-OpenOCL", "path": "github-repos/MATLAB/OpenOCL-OpenOCL/OpenOCL-348fc31929791ddc8ed15a15733cf060a2e4674c/+ocl/+simultaneous/timesStruct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22148315733699372}}
{"text": "function [F1,Se,PPV,Nb] = run_sqi(refqrs,testqrs,thres,margin,windowlen,fs)\n% sqi = run_sqi(refqrs,testqrs,thres,margin,windowlen,fs)\n% compare two sets of annotation with one as the reference (refqrs) and one\n% as the test (testqrs)\n%\n% inputs\n%     refqrs:       reference qrs annotation (in sec)\n%     testqrs:      test qrs annotations (in sec)\n%     thres:        threshold (in sec,default 0.05s)\n%     margin:       margin time not include in comparison (in sec,default 2s)\n%     windowlen:    length of the comparison window (in sec,default 60s)\n%     fs:           sampling frequency\n%\n% output\n%     sqi: match proportion according to some criteria you can change\n%     depending on what you are looking for (can be Se, PPV or F1 measure).\n%     See at the end of the function.\n%\n% When using this work, then please cite [1] and [2]:\n%     [1] Behar Joachim, Oster Julien, Qiao Li, Clifford Gari D. Signal Quality\n%     During Arrhythmia and its Application to False Alarm Reduction. \n%     IEEE Transactions on Biomedical Engineering. 60(6). 1660-6. 2013.\n%\n%     [2] Li, Qiao, Roger G. Mark, and Gari D. Clifford. \"Robust heart rate estimation \n%     from multiple asynchronous noisy sources using signal quality indices and \n%     a Kalman filter.\" Physiological measurement 29.1 (2008): 15.\n%\n% PCinCC2014, version 1.0, June 2014\n% Released under the GNU General Public License\n%\n% Copyright (C) 2014  Joachim Behar\n% Oxford university, Intelligent Patient Monitoring Group - Oxford 2014\n% joachim.behar@gmail.com\n%\n% Updates: \n% 07-02-2014\n% JB- testes with Octave -> running OK \n%\n% 02-10-2014\n% Bug fix: Dealing with annotations close to the border of the search\n% window. Lines 70 - 100\n% David Springer\n%\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\n% == managing inputs\nif nargin<2; error('bsqi: wrong number of input arguments \\n'); end;\nif nargin<3; thres=0.05; end;\nif nargin<4; margin=2; end;\nif nargin<5; windowlen=60; end;\nif nargin<6; fs=1000; end;\n\nif size(refqrs,1)>size(refqrs,2); refqrs=refqrs';end\nif size(testqrs,1)>size(testqrs,2); testqrs=testqrs';end\n\nstart = margin*fs;\nstop = (windowlen-margin)*fs;\nrefqrs = refqrs.*fs; % convert into samples from time\ntestqrs = testqrs.*fs; % convert into samples from time\n\ntry\n    refqrs  = refqrs(refqrs>start & refqrs<stop)'; % reference annotations\n    testqrs = testqrs(testqrs>start & testqrs<stop)'; % test annotations\n    \n    if ~isempty(refqrs)\n    \n        NB_REF  = length(refqrs);\n        NB_TEST = length(testqrs);\n\n        % == removing borders problems\n        indbord = find(refqrs<thres*fs | refqrs>(windowlen-thres)*fs); % reference QRS at the border\n        if ~isempty(indbord)\n            [IndMatchBord,DistQRSbord] = dsearchn(testqrs,refqrs(indbord));\n            Indeces_below_threshold = DistQRSbord<thres*fs; %Added line to find indices of annotation of interest (refqrs) below threshold (02-10-14)\n            IndMatchBord = IndMatchBord(Indeces_below_threshold);\n            NB_QRS_BORD = length(indbord); % QRS at the border of the window (0,1,2)\n            NB_MATCHING = length(IndMatchBord); % nb of corresponding mathing QRS (0,1,2)\n            if isempty(IndMatchBord); \n                refqrs(indbord) = []; \n            elseif NB_MATCHING<NB_QRS_BORD\n                refqrs(indbord(~Indeces_below_threshold)) = []; %Removing other indices not below threshold (02-10-14)\n            end\n        end\n\n        indbord = find(testqrs<thres*fs | testqrs>(windowlen-thres)*fs); % reference QRS at the border\n        if ~isempty(indbord)\n            [IndMatchBord,DistQRSbord] = dsearchn(refqrs,testqrs(indbord));\n            Indeces_below_threshold = DistQRSbord<thres*fs; %Added line to find indices of annotation of interest (testqrs) below threshold (02-10-14)\n            IndMatchBord = IndMatchBord(Indeces_below_threshold);\n            NB_QRS_BORD = length(indbord); % QRS at the border of the window (0,1,2)\n            NB_MATCHING = length(IndMatchBord); % nb of corresponding mathing QRS (0,1,2)\n            if isempty(IndMatchBord); \n                testqrs(indbord) = []; \n            elseif NB_MATCHING<NB_QRS_BORD\n                testqrs(indbord(~Indeces_below_threshold)) = []; %Removing other indices not below threshold (02-10-14)\n            end\n        end    \n\n        % == core function\n        [IndMatch,Dist] = dsearchn(refqrs,testqrs);         % closest ref for each point in test qrs\n        IndMatchInWindow = IndMatch(Dist<thres*fs);         % keep only the ones within a certain window\n        NB_MATCH_UNIQUE = length(unique(IndMatchInWindow)); % how many unique matching\n        TP = NB_MATCH_UNIQUE;                               % number of identified ref QRS\n        FN = NB_REF-TP;                                     % number of missed ref QRS\n        FP = NB_TEST-TP;                                    % how many extra detection?\n        Se  = TP/(TP+FN);\n        PPV = TP/(FP+TP);\n        F1 = 2*Se*PPV/(Se+PPV);                             % accuracy measure\n\n        Nb.TP = TP;\n        Nb.FN = FN;\n        Nb.FP = FP;\n    else\n        F1=[];Se=[];PPV=[];Nb=[];\n    end\ncatch \n    F1=[];Se=[];PPV=[];Nb=[];\nend\n\nend\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/PeakDetection_SQI/run_sqi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.22145539729145516}}
{"text": "function  [ons_secs, VOLLOCS, LOCS, verbose] = tapas_physio_create_scan_timing(...\n    log_files, scan_timing, ons_secs, verbose)\n% Extracts slice and volume scan onsets (triggers) from different vendor formats\n%\n%   [ons_secs, VOLLOCS, LOCS, verbose] = tapas_physio_create_scan_timing(...\n%            log_files, scan_timing, ons_secs, verbose);\n%\n%\n% IN\n%   NOTE: The detailed description of all input structures can be found as\n%   comments in tapas_physio_new\n%\n%   log_files    - file names (physiology and scan timing) and sampling rates\n%\n%   ons_secs     -  structure for time-dependent variables, i.e. onsets,\n%                   specified in seconds, in particular\n%                   .t          - time vector of phys time course\n%\n%   scan_timing         -  Parameters for sequence timing & synchronization\n%   scan_tming.sqpar    -  slice and volume acquisition starts, TR,\n%                          number of scans etc.\n%   scan_timing.sync    -  synchronization options\n%                          (e.g. from gradients, trigger, tics phys\n%                           logfile to scan acquisition)\n%\n%       sqpar           - sequence timing parameters, used for computation\n%                         of scan events from 'nominal' timing\n%           .Nslices        - number of slices per volume in fMRI scan\n%           .TR             - repetition time in seconds\n%           .Ndummies       - number of dummy volumes\n%           .Nscans         - number of full volumes saved (volumes in nifti file,\n%                             usually rows in your design matrix)\n%           .Nprep          - number of non-dummy, volume like preparation pulses\n%                             before 1st dummy scan. If set, logfile is read from beginning,\n%                             otherwise volumes are counted from last detected volume in the logfile\n%           .time_slice_to_slice - time between the acquisition of 2 subsequent\n%                             slices; typically TR/Nslices or\n%                             minTR/Nslices, if minimal temporal slice\n%                             spacing was chosen\n%\n%   verbose                 - defines output level (which graphics to plot\n%                             and whether to save them)\n%\n% OUT\n%   ons_secs    -  structure for time-dependent variables, i.e. onsets,\n%                  specified in seconds, updated fields\n%                   .spulse     - scan slice trigger events\n%                   .svolpulse  - scan volume trigger events\n%                   .spulse_per_vol\n%                               - cell(nVolumes,1) of slice triggers per\n%                                 volume\n%                   .acq_codes  - acquisition codes (e.g. triggers) within\n%                                 phys log files (e.g. Philips, Biopac)\n%\n%   VOLLOCS     - index locations in time vector (of physiological recordings),\n%                             when volume scan events started\n%   LOCS        - locations in time vector, when slice or volume scan\n%                             events started\n%\n%   See also tapas_physio_new tapas_physio_main_create_regresssors\n\n% Author: Lars Kasper\n% Created: 2013-08-23\n% Copyright (C) 2016 Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\nsqpar   = scan_timing.sqpar;\n\n% TODO: introduce auto that takes time stamps from default locations\n% for different vendors\nswitch lower(scan_timing.sync.method)\n    case 'nominal'\n        [VOLLOCS, LOCS] = ...\n            tapas_physio_create_scan_timing_nominal(ons_secs.t + ...\n                    ons_secs.t_start, sqpar, log_files.align_scan);\n    case {'gradient', 'gradient_log'}\n        [VOLLOCS, LOCS, verbose] = ...\n            tapas_physio_create_scan_timing_from_gradients_philips( ...\n            log_files, scan_timing, verbose);\n    case {'gradient_auto', 'gradient_log_auto'}\n        [VOLLOCS, LOCS, verbose] = ...\n            tapas_physio_create_scan_timing_from_gradients_auto_philips( ...\n            log_files, scan_timing, verbose);\n    case 'scan_timing_log'\n        switch lower(log_files.vendor)\n            case 'siemens'\n                % for alignScan = 'last', in case logfile lasts longer than end of last scan\n                % assuming t = 0 is already start of first scan\n                durationPhyslogAfterEndOfLastScan = ons_secs.t(end) + ...\n                    ons_secs.t_start - sqpar.Nscans*sqpar.TR;\n                [VOLLOCS, LOCS] = ...\n                    tapas_physio_create_scan_timing_nominal(ons_secs.t + ...\n                    ons_secs.t_start, sqpar, log_files.align_scan, ...\n                    durationPhyslogAfterEndOfLastScan);\n            case 'siemens_tics'\n                [VOLLOCS, LOCS, verbose] = ...\n                    tapas_physio_create_scan_timing_from_tics_siemens( ...\n                    ons_secs.t, ons_secs.t_start, log_files, verbose);\n            case {'biopac_mat', 'biopac_txt', 'bids'}\n                [VOLLOCS, LOCS, verbose] = ...\n                    tapas_physio_create_scan_timing_from_acq_codes( ...\n                    ons_secs.t + ons_secs.t_start, ons_secs.acq_codes, ...\n                    sqpar, log_files.align_scan, verbose);\n        end\n    otherwise\n        verbose = tapas_physio_log(...\n            sprintf('unknown scan_timing.sync.method: %s', ...\n            scan_timing.sync.method), verbose, 2);\nend\n\n\n% remove arbitrary offset in time vector now, since all timings have now\n% been aligned to ons_secs.t\n% ons_secs.t = ons_secs.t - ons_secs.t(1);\n\n[ons_secs.svolpulse, ons_secs.spulse, ons_secs.spulse_per_vol, verbose] = ...\n    tapas_physio_get_onsets_from_locs(...\n    ons_secs.t, VOLLOCS, LOCS, sqpar, verbose);\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/sync/tapas_physio_create_scan_timing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.22139522108804444}}
{"text": "function cellInfo = Extended_States_Bus(varargin) \n% EXTENDED_STATES_BUS returns a cell array containing bus object information \n% \n% Optional Input: 'false' will suppress a call to Simulink.Bus.cellToObject \n%                 when the MATLAB file is executed. \n% The order of bus element attributes is as follows:\n%   ElementName, Dimensions, DataType, SampleTime, Complexity, SamplingMode, DimensionsMode, Min, Max, DocUnits, Description \n\nsuppressObject = false; \nif nargin == 1 && islogical(varargin{1}) && varargin{1} == false \n    suppressObject = true; \nelseif nargin > 1 \n    error('Invalid input argument(s) encountered'); \nend \n\ncellInfo = { ... \n  { ... \n    'AirSpeed_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'diff_pressure', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('Pa'), ''}; ...\n{'temperature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degC'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'Auto_Cmd_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'p_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate x command in body frame')}; ...\n{'q_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate y command in body frame')}; ...\n{'r_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate z command in body frame')}; ...\n{'phi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('roll command')}; ...\n{'theta_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('pitch command')}; ...\n{'psi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'psi_rate_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command')}; ...\n{'x_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'y_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'z_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'lat_cmd', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'lon_cmd', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'alt_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'u_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity x command in control frame')}; ...\n{'v_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity y command in control frame')}; ...\n{'w_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity z command in control frame')}; ...\n{'ax_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'ay_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'az_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'throttle_cmd', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('throttle command')}; ...\n{'frame', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Coordinate Frame:\\n0:FRAME_GLOBAL_NED\\n1:FRAME_LOCAL_FRD\\n2:FRAME_BODY_FRD')}; ...\n{'reserved', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'cmd_mask', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Type mask for auto command:\\n  1: p_cmd valid\\n  2: q_cmd valid\\n  3: r_cmd valid\\n  4: phi_cmd valid\\n  5: theta_cmd valid\\n  6: psi__cmd_valid\\n  7: psi_rate_cmd_valid\\n  8: x_cmd valid\\n  9: y_cmd valid\\n10: z_cmd valid\\n11: lat_cmd valid\\n12: lon_cmd valid\\n13: alt_cmd valid\\n14: u_cmd valid\\n15: v_cmd valid\\n16: w_cmd valid\\n17: ax_cmd valid\\n18: ay_cmd valid\\n19: ax_cmd valid\\n20: throttle_cmd valid')}; ...\n    } ...\n  } ...\n  { ... \n    'Barometer_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'pressure', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('Pa'), ''}; ...\n{'temperature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('deg'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'Commander_In_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'sp_waypoint', 3, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'cur_waypoint', 3, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'offboard_psi_0', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('The psi value when offboard mode entered, \\nwhich is used for FRAME_LOCAL_FRD')}; ...\n    } ...\n  } ...\n  { ... \n    'Control_Out_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'actuator_cmd', 16, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'Extended_States_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'temprature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('deg'), ''}; ...\n{'prop_vel', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'quat', 4, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'M_BO', [3 3], 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'M_OB', [3 3], 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'Va', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('Airspeed in body frame')}; ...\n    } ...\n  } ...\n  { ... \n    'FMS_Out_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), sprintf('fms output timestamp')}; ...\n{'p_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('roll rate command in body frame')}; ...\n{'q_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('pitch rate command in body frame')}; ...\n{'r_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command in body frame')}; ...\n{'phi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('roll command in body frame')}; ...\n{'theta_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('pitch command in body frame')}; ...\n{'psi_rate_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command in body frame')}; ...\n{'u_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity x command in control frame')}; ...\n{'v_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity y command in control frame')}; ...\n{'w_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity z command in control frame')}; ...\n{'ax_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration x command in control frame')}; ...\n{'ay_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration y command in control frame')}; ...\n{'az_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration z command in control frame')}; ...\n{'actuator_cmd', 16, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('actuator command')}; ...\n{'throttle_cmd', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('throttle command')}; ...\n{'cmd_mask', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Type mask for offboard mode:\\n  1: p_cmd valid\\n  2: q_cmd valid\\n  3: r_cmd valid\\n  4: phi_cmd valid\\n  5: theta_cmd valid\\n  6: psi_rate_cmd_valid\\n  7: u_cmd valid\\n  8: v_cmd valid\\n  9: w_cmd valid\\n10: ax_cmd valid\\n11: ay_cmd valid\\n12: ax_cmd valid\\n13: throttle_cmd valid')}; ...\n{'status', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum VehicleStatus\\n\\nvehicle status:\\n0: None\\n1: Disarm\\n2: Standby\\n3: Arm')}; ...\n{'state', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum VehicleState\\n\\nvehicle state:\\n0: None\\n1: Disarm\\n2: Standby\\n3: Offboard\\n4: Mission\\n5: InvalidAutoMode\\n6: Hold\\n7: Acro\\n8: Stabilize\\n9: Altitude\\n10: Position\\n11: InvalidAssistMode\\n12: Manual\\n13: InvalidManualMode\\n14: InvalidArmMode\\n15: Land\\n16: Return\\n17: Takeoff')}; ...\n{'ctrl_mode', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum ControlMode\\n\\ncontrol mode:\\n0: None\\n1: Manual\\n2: Acro\\n3: Stabilize\\n4: ALTCTL\\n5: POSCTL')}; ...\n{'mode', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum PilotMode\\n\\npilot mode:\\n0: None\\n1: Manual\\n2: Acro\\n3: Stabilize\\n4: Altitude\\n5: Position\\n6: Mission\\n7: Offboard')}; ...\n{'reset', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('reset the controller')}; ...\n{'wp_consume', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('consumed waypoints')}; ...\n{'wp_current', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('current waypoint')}; ...\n{'reserved', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum of PilotMode')}; ...\n    } ...\n  } ...\n  { ... \n    'GCS_Cmd_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'cmd_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 1')}; ...\n{'cmd_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 2')}; ...\n    } ...\n  } ...\n  { ... \n    'GPS_uBlox_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'iTOW', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'year', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'month', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'day', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'hour', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'min', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'sec', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'valid', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'tAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'nano', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'fixType', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'flags', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved1', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'numSV', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'lon', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'lat', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'height', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'hMSL', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'hAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'vAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'velN', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'velE', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'velD', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'gSpeed', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'heading', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'sAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'headingAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'pDOP', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved2', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'IMU_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'gyr_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'gyr_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'gyr_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'acc_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'acc_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'acc_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'INS_Out_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'phi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'theta', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'psi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'quat', 4, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('unified'), ''}; ...\n{'p', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'q', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'r', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'ax', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'ay', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'az', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'vn', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'ve', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'vd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'airspeed', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'lat', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...\n{'lon', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...\n{'alt', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'lat_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...\n{'lon_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...\n{'alt_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'x_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'y_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'h_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'h_AGL', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'flag', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'status', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'MAG_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'mag_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...\n{'mag_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...\n{'mag_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'Mission_Data_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'valid_items', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'seq', 8, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Start from 0')}; ...\n{'command', 8, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'frame', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'current', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'autocontinue', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'mission_type', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'param1', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'param2', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'param3', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'param4', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'x', 8, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'y', 8, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'z', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'Optical_Flow_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'vx', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'vy', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'quality', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved1', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'reserved2', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'Pilot_Cmd_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'stick_yaw', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of yaw channel')}; ...\n{'stick_throttle', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of throttle channel')}; ...\n{'stick_roll', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of roll chanel')}; ...\n{'stick_pitch', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of pitch channel')}; ...\n{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'cmd_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 1')}; ...\n{'cmd_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 2')}; ...\n    } ...\n  } ...\n  { ... \n    'Plant_States_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'phi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'theta', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'psi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'rot_x_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'rot_y_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'rot_z_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...\n{'acc_x_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'acc_y_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'acc_z_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...\n{'vel_x_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'vel_y_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'vel_z_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...\n{'x_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'y_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'h_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'lat', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'lon', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'alt', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n{'lat_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'lon_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...\n{'alt_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'Rangefinder_Bus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...\n{'distance', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...\n    } ...\n  } ...\n  { ... \n    'StatesBus', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'V_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'Omega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'Euler', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'Accel_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'dOmega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'V_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'X_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n{'LLA', [1 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Latitude, Longitude, Altitude')}; ...\n{'DCM_be', [3 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...\n    } ...\n  } ...\n  { ... \n    'mavlink_fmt_pilot_cmd_t', ... \n    '', ... \n    '', ... \n    'Auto', ... \n    '-1', {... \n{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('timestamp in milliseconds')}; ...\n{'ls_lr', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Left stick left/right')}; ...\n{'ls_ud', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Left stick up/down')}; ...\n{'rs_lr', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Right stick left/right')}; ...\n{'rs_ud', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Right stick up/down')}; ...\n{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Control Mode')}; ...\n{'command_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Pilot command 1')}; ...\n{'command_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Pilot command 2')}; ...\n    } ...\n  } ...\n}'; \n\nif ~suppressObject \n    % Create bus objects in the MATLAB base workspace \n    Simulink.Bus.cellToObject(cellInfo) \nend \n", "meta": {"author": "Firmament-Autopilot", "repo": "FMT-Model", "sha": "adb85b9379cb4268f60bd8414f35aacfbdf8dec1", "save_path": "github-repos/MATLAB/Firmament-Autopilot-FMT-Model", "path": "github-repos/MATLAB/Firmament-Autopilot-FMT-Model/FMT-Model-adb85b9379cb4268f60bd8414f35aacfbdf8dec1/bus/Extended_States_Bus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2211475296636529}}
{"text": "classdef PowerNetChargeRateTermCondition < AbstractEventTerminationCondition\n    %PowerNetChargeRateTermCondition Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        netChargeRate(1,1) double = 0; %km\n        initialStateLogEntry LaunchVehicleStateLogEntry\n    end\n    \n    methods\n        function obj = PowerNetChargeRateTermCondition(netChargeRate)\n            obj.netChargeRate = netChargeRate;\n        end\n        \n        function evtTermCondFcnHndl = getEventTermCondFuncHandle(obj)            \n            evtTermCondFcnHndl = @(t,y) obj.eventTermCond(t,y);\n        end\n        \n        function initTermCondition(obj, initialStateLogEntry)\n            obj.initialStateLogEntry = initialStateLogEntry;\n        end\n        \n        function name = getName(obj)\n            name = sprintf('Power Net Charge Rate (%.3f EC)', obj.netChargeRate);\n        end\n        \n        function tf = shouldBeReinitOnRestart(obj)\n            tf = true;\n        end\n        \n        function params = getTermCondUiStruct(obj)\n            params = struct();\n            \n            params.paramName = 'Net Charge Rate';\n            params.paramUnit = 'EC/s';\n            params.useParam = 'on';\n            params.useStages = 'off';\n            params.useTanks = 'off';\n            params.useEngines = 'off';\n            params.useStopwatches = 'off';\n            \n            params.value = obj.netChargeRate;\n            params.refStage = LaunchVehicleStage.empty(1,0);\n            params.refTank = LaunchVehicleEngine.empty(1,0);\n            params.refEngine = LaunchVehicleEngine.empty(1,0);\n            params.refStopwatch = LaunchVehicleStopwatch.empty(1,0);\n        end\n        \n        function optVar = getNewOptVar(obj)\n            optVar = NetChargeRateOptimizationVariable(obj);\n        end\n        \n        function optVar = getExistingOptVar(obj)\n            optVar = obj.optVar;\n        end\n        \n        function tf = usesStage(obj, stage)\n            tf = false;\n        end\n        \n        function tf = usesEngine(obj, engine)\n            tf = false;\n        end\n        \n        function tf = usesTank(obj, tank)\n            tf = false;\n        end\n        \n        function tf = usesEngineToTankConn(obj, engineToTank)\n            tf = false;\n        end\n        \n        function tf = usesStopwatch(obj, stopwatch)\n            tf = false;\n        end\n    end\n    \n    methods(Static)\n        function termCond = getTermCondForParams(paramValue, stage, tank, engine, stopwatch)\n            termCond = PowerNetChargeRateTermCondition(paramValue);\n        end\n    end\n    \n    methods(Access=private)\n        function [value,isterminal,direction] = eventTermCond(obj, t,y)\n            initStateLogEntry = obj.initialStateLogEntry;\n            \n            powerStorageStates = initStateLogEntry.getAllActivePwrStorageStates();\n\n            numTankStates = initStateLogEntry.getNumActiveTankStates();\n            numPwrStorageStates = initStateLogEntry.getNumActivePwrStorageStates();\n            [~, ~, ~, ~, storageSoCs] = AbstractPropagator.decomposeIntegratorTandY(t,y, numTankStates, numPwrStorageStates);\n            \n            stgStates = initStateLogEntry.stageStates;\n            \n            ut = initStateLogEntry.time;\n            rVect = initStateLogEntry.position(:);\n            vVect = initStateLogEntry.velocity(:);\n            bodyInfo = initStateLogEntry.centralBody;\n            \n            steeringModel = initStateLogEntry.steeringModel;\n            \n            storageRates = LaunchVehicleStateLogEntry.getStorageChargeRatesDueToSourcesSinks(storageSoCs, powerStorageStates, stgStates, ut, rVect, vVect, bodyInfo, steeringModel);\n            actualNetStorageRate = sum(storageRates);\n            \n            value = actualNetStorageRate - obj.netChargeRate;\n            isterminal = 1;\n            direction = 0;\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Events/termConditions/@PowerNetChargeRateTermCondition/PowerNetChargeRateTermCondition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114752338165658}}
{"text": "function [dat] =  test(algo,dat,lossType)\n% \n%               [res]=test(algo,data,loss) \n%   An algorihm algo is trained on the training set data. If a loss\n%   function is supplied, it will be calculated.\n%   It returns a data object containing the results.\n%   If no loss function is supplied, the data object will contain the loss\n%   on the training set. If not, it usually contain the label estimates in\n%   the X part and the true labels in the Y part of the data object.\n%\n%   It is also possible to call test(algo), where the emtpy data set is passed \n%   into the algorithm to test it. This is useful for methods that generate their\n%   own data.\n%   \n%   Note: \n%               test(algo) <=> test(algo,[]).\n\n%% Programming note:\n% It is used to call testing.m function which doesn't include loss\n% function calculations in a child object \n\n    \nif nargin==1 \n    dat=[];% <--- data is optional\nend; \n\nif nargin<3 \n    lossType=[]; \nend; \n\nif iscell(dat) \n    dat=group(dat); \nend;\n%%<<----test data---->>\nif ~isempty(dat) \n    if ~am_i_data(dat)  \n        dat=test(dat); %% <--- i.e generate data \n    end\nend\n\n%%%% SGE support (note sightly different behaviour from algorithm/train)\nif isdeferred(algo)\n\tif submitted(algo.deferred)\n\t\t[algo jobfailed] = waitcollect(algo);\n\t\tif jobfailed, return, end\n\telse\n\t\tdat.deferred = qsub(algo.deferred, max(nargout,1), mfilename, algo, dat, lossType);\n\t\treturn\n\tend\nend\nif ~isempty(dat)\nif isdeferred(dat)\n\t[dat jobfailed] = waitcollect(dat);\n\tif jobfailed, return, end\nend \nend\n%%%%\n\ne=struct(dat);\n%%<<------ if there are multiple datasets as input ---->>\nif isa(dat,'group')  & strcmp(e.group,'separate') \n  dat=e.child; % dat seen as @algorithm object => so it is not possible to access child directly\n  dat=make_cell(dat);\n  res=[];\n  for i=1:length(dat)\n      [r]=test(algo,dat{i},lossType); \n      res{i}=r;\n  end\n  dat=group(res);  %% <--- return data/res as set of group\nelse\n    [dat]=testing(algo,dat);\n    if ~isempty(lossType) \n      if isa(lossType,'loss')\n\tdat=train(lossType,dat);\n      else\n\tdat=loss(dat,lossType);\n      end\n    end;    \n    if iscell(dat) \n        dat=group(dat); \n    end;  %%  <--- return data/res as set of group\nend\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/basic/@algorithm/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114752338165658}}
{"text": "function process_scores_Tex(conf, scores, nr)\n\nfprintf('Writing results to Tex summary...\\n');\n\nvalid_id = [2 3 4 5 6 7 8 9 11];\nfprintf('\\n');\n\n    for j = 1:length(conf.desc)\n        if sum(valid_id==j)==0\n            continue;\n        end;\n        fprintf('& \\\\multicolumn{2}{|c|}{%s}', conf.desc{j});        \n    end\n    fprintf('\\\\\\\\\\n');\n\nfprintf('image');\n    for j = 1:length(conf.desc)\n        if sum(valid_id==j)==0\n            continue;\n        end;\n        fprintf('& PSNR & Time');        \n    end\n    fprintf('\\\\\\\\\\n');\n\nfor i =1:nr\n    [p, f, x] = fileparts(conf.filenames{i});\n    fprintf('%s',f);\n    for j = 1:length(conf.desc)\n        if sum(valid_id==j)==0\n            continue;\n        end;\n        \n        fprintf(' & %.1f & %.1f', scores(i,j), conf.countedtime(j-1,i));\n    end\n    fprintf('\\\\\\\\\\n');\nend\n\nfprintf('average');\nfor j = 1:11\n    if sum(valid_id==j)==0\n       continue;\n    end;\n     \n    fprintf(' & %.2f & %.2f', mean(scores(:,j)), mean(conf.countedtime(j-1,:)));\nend\nfprintf('\\\\\\\\\\n\\n\\n');\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/Aplus/process_scores_Tex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22114752338165655}}
{"text": "function spp_demo()\nclear mex;\n\nspp_model_file = '.\\data\\spp_model\\VOC2007\\spp_model.mat';\nif ~exist(spp_model_file, 'file')\n  error('%s not exist ! \\n', spp_model_file);\nend\ntry\n    load(spp_model_file);\ncatch err\n    fprintf('load spp_model_file : %s\\n', err.message);\nend\ncaffe_net_file     = fullfile(pwd, 'data\\cnn_model\\Zeiler_conv5\\Zeiler_conv5');\ncaffe_net_def_file = fullfile(pwd, 'data\\cnn_model\\Zeiler_conv5\\Zeiler_spm_scale224_test_conv5.prototxt');\n\nuse_gpu = true;\ngpu_id = 1;\nif use_gpu\n    gpuDevice(gpu_id);\nend\n\ncaffe('init', caffe_net_def_file, caffe_net_file);\ncaffe('set_phase_test');\nif use_gpu\n    spp_model.cnn.layers = spp_layers_in_gpu(spp_model.cnn.layers);\n    caffe('set_mode_gpu');\nelse\n    caffe('set_mode_cpu');\nend\n\nspm_im_size = [480 576 688 874 1200];\n% spm_im_size = [ 688 ];\n\nim = imread('.\\datasets\\VOCdevkit2007\\VOC2007\\JPEGImages\\000015.jpg');\n\ndets = spp_detect(im, spp_model, spm_im_size, use_gpu);\n\nclasses = spp_model.classes;\nboxes = cell(length(classes), 1);\nthres = -0.5;\nfor i = 1:length(boxes)\n    I = dets{i}(:, 5) >= thres;\n    boxes{i} = dets{i}(I, :);\nend\nshowboxes_new(im, boxes, classes);\n\ncaffe('release');\n\nif use_gpu\n    gpuDevice([]);\nend\n", "meta": {"author": "ShaoqingRen", "repo": "SPP_net", "sha": "ca9675907f8af6c02773571bc91147b3a2ddfcc1", "save_path": "github-repos/MATLAB/ShaoqingRen-SPP_net", "path": "github-repos/MATLAB/ShaoqingRen-SPP_net/SPP_net-ca9675907f8af6c02773571bc91147b3a2ddfcc1/spp_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770903}}
{"text": "function [doseHandle,cMap,window] = matRad_plotDoseSlice3D(axesHandle,ct,doseCube,plane,slice,threshold,alpha,cMap,window)\n% matRad function that generates a dose plot of a selected slice in 3D view\n%\n% call\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,alpha)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,cMap)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,window)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,alpha,cMap)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,alpha,window)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,cMap,window)\n%   [doseHandle,cMap,window] = matRad_plotDose3DSlice(axesHandle, doseCube,plane,slice,threshold,alpha,cMap,window)\n%\n% input\n%   axesHandle  handle to axes the slice should be displayed in\n%   ct          matRad CT struct which contains resolution\n%   doseCube    3D array of the dose to select the slice from\n%   plane       plane view (coronal=1,sagittal=2,axial=3)\n%   slice       slice in the selected plane of the 3D cube\n%   threshold   threshold above which the dose shall be displayed\n%               for negative values (i.e. difference maps), also the values\n%               smaller than the negative threshold will be displayed\n%               if empty, no threshold will be applied\n%   alpha       optional argument defining the alpha value, default is 0.6.\n%               To use the default when providing a custom culormap, put in\n%               an empty array by [].\n%   cMap        optional argument defining the colormap, default is jet\n%               if you want to use the default map with the window argument\n%               you can use an empty array []\n%   window      optional argument defining the displayed range. default is\n%               [min(doseCube(:)) max(doseCube(:))]\n%\n% output\n%   doseHandle: handle of the plotted dose axes\n%   cMap        used colormap (same as input if set)\n%   window      used window (same as input if set)\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmatRad_cfg = MatRad_Config.instance();\n\n%Use default colormap?\nif nargin < 8 || isempty(cMap)\n    cMap = jet(64);\nend\nif nargin < 7 || isempty(alpha)\n    alpha = 0.6;\nend\nif nargin < 9 || isempty(window)\n    window = [min(doseCube(:)) max(doseCube(:))];\nend\n\ncMapScale = size(cMap,1) - 1;\nmaxDose = max(doseCube(:));\n\n%Create the coordinates\ncoords{1} = ct.resolution.x * (1:ct.cubeDim(2));\ncoords{2} = ct.resolution.y * (1:ct.cubeDim(1));\ncoords{3} = ct.resolution.z * (1:ct.cubeDim(3));\n\nif plane == 1  % Coronal plane\n    [xMesh,zMesh] = meshgrid(coords{2},coords{3});\n    yMesh = slice*ct.resolution.x*ones(size(xMesh));\n    %dose_slice = uint8(cMapScale*(squeeze(doseCube(slice,:,:)) - window(1))/(window(2)-window(1)));\n    doseSlice = permute(squeeze(doseCube(slice,:,:)),[2 1]);\nelseif plane == 2 % sagittal plane\n    [yMesh,zMesh] = meshgrid(coords{1},coords{3});\n    xMesh = slice*ct.resolution.y*ones(size(yMesh));\n    %dose_slice = uint8(cMapScale*(squeeze(doseCube(:,slice,:)) - window(1))/(window(2)-window(1)));\n    dose_slice = permute(squeeze(doseCube(:,slice,:)),[2 1]);\nelseif plane == 3 % Axial plane\n    [xMesh,yMesh] = meshgrid(coords{2},coords{1});\n    zMesh = slice*ct.resolution.z*ones(size(xMesh)); \n    %dose_slice = uint8(cMapScale*(squeeze(doseCube(:,:,slice)) - window(1))/(window(2)-window(1)));\n    dose_slice = squeeze(doseCube(:,:,slice));\nend\n\nif ~isempty(threshold)\n    dose_mask = alpha * (dose_slice < window(2) & dose_slice > window(1) & dose_slice > threshold*maxDose);\nelse\n    dose_mask = alpha * (dose_slice < window(2) & dose_slice > window(1));\nend\n\ndose_slice = uint8(cMapScale* (dose_slice - window(1))/(window(2)-window(1)));\n\n%This circumenvents a bug in Octave when the index in the image hase the maximum value of uint8\nif matRad_cfg.isOctave\n\tdose_slice(dose_slice == 255) = 254;\nend\n\ndose_rgb = ind2rgb(dose_slice,cMap);\n% slice plot with surface(...), colormapping can be done by texture\n% mapping, this is why we use surface instead of slice\ndoseHandle = surface('XData',xMesh, 'YData',yMesh, 'ZData',zMesh,'AlphaData',dose_mask, ...\n        'CData',dose_rgb, 'CDataMapping','direct', ...\n        'EdgeColor','none', 'FaceColor','texturemap', 'BackFaceLighting','unlit','FaceLighting','flat','FaceAlpha','texture','Parent',axesHandle);\n\nend\n\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/plotting/matRad_plotDoseSlice3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770903}}
{"text": "classdef unimodalComponent\n% This class is obsolet since MTEX 5.9. Use the class @SO3FunRBF instead.\n% Anyway the class is preserved, so that saved @ODFs can be loaded.\n\nmethods (Static = true, Hidden=true)\n  function odf = loadobj(s)\n    psi = s.psi;\n    if isempty(psi)\n      psi = SO3DeLaValleePoussinKernel; \n      warning(['MTEX is not able to load the SO3Kernel of the unimodalODF, ' ...\n        'because its class has been deleted. A standard kernel is used instead.'])\n    end\n    odf = SO3FunRBF(s.center,psi,s.weights);\n  end\nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/ODFAnalysis/OldClasses/unimodalComponent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.2210405306873272}}
{"text": "function [imo,rois,labels,targets] = fast_rcnn_train_get_batch(images, imdb, batch, opts)\n% FAST_RCNN_GET_BATCH_TRAIN  Generates mini-batches for Fast-RCNN train\n\n% opts.numFgRoisPerImg = 128;\n% opts.numRoisPerImg = 64;\n% opts.maxScale = 1000;\n% opts.bgLabel = 21;\n% opts.visualize = 0;\n% opts.scale = 600;\n% opts.interpolation = 'bicubic';\n% opts.averageImage = [];\n% opts.numThreads = 2;\n% opts.prefetch = true;\n%\n% Copyright (C) 2016 Hakan Bilen.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif isempty(images)\n  imo = [] ;\n  rois = [] ;\n  labels = [] ;\n  targets = [] ;\n  return ;\nend\n\n% fetch is true if images is a list of filenames (instead of\n% a cell array of images)\nfetch = ischar(images{1}) ;\n\n% prefetch is used to load images in a separate thread\nprefetch = fetch & opts.prefetch ;\n\n\nif prefetch\n  vl_imreadjpeg(images, 'numThreads',opts.numThreads,'prefetch') ;\n  imo = [] ;\n  rois = [] ;\n  labels = [] ;\n  targets = [] ;\n  return ;\nend\n\nif fetch\n  ims = vl_imreadjpeg(images,'numThreads',opts.numThreads) ;\nelse\n  ims = images ;\nend\n\nmaxW = 0;\nmaxH = 0;\n\n% labels = imdb.images.label(:,batch);\n\npboxes   = cell(1,numel(batch));\nplabels  = cell(1,numel(batch));\nptargets = cell(1,numel(batch));\n\n% get fg and bg rois\nfor b=1:numel(batch)\n  pbox   = imdb.boxes.pbox{batch(b)};\n  plabel = imdb.boxes.plabel{batch(b)};\n  ptarget = imdb.boxes.ptarget{batch(b)};\n\n  if size(pbox,2)~=4\n    error('wrong box size');\n  end\n\n  % get pos boxes\n  pos = find((plabel~=opts.bgLabel) & (plabel > 0)) ;\n  npos = numel(pos);\n  % get neg boxes\n  neg = find((plabel==opts.bgLabel)) ;\n  nneg = numel(neg);\n\n    bbox = [];\n    label = [];\n    target = [];\n\n    opts.numFgRoisPerImg = min(npos,opts.numFgRoisPerImg);\n    nBneg = min(nneg,opts.numRoisPerImg-opts.numFgRoisPerImg);\n\n    if npos>0\n      r = randperm(npos);\n      p = pos(r(1:opts.numFgRoisPerImg));\n      bbox = pbox(p,:);\n      label = plabel(p);\n      target = ptarget(p,:);\n    end\n    if nneg>0\n      r = randperm(nneg);\n\n      n = neg(r(1:nBneg));\n      bbox = [bbox ; pbox(n,:)];\n      label = [label ; plabel(n)];\n      target = [target ; ones(size(ptarget(n,:)))];\n    end\n  pboxes{b} = bbox;\n  plabels{b} = label;\n  ptargets{b} = target;\nend\n\nif isempty(pboxes)\n  warning('No gt box\\n');\nend\n\nlabels = vertcat(plabels{:});\ntargets = vertcat(ptargets{:});\n\n% rescale images and rois\nrois = [];\nimre = cell(1,numel(batch));\nfor b=1:numel(batch)\n  imSize = size(ims{b});\n\n  h = imSize(1);\n  w = imSize(2);\n\n  factor = max(opts.scale(1)/h,opts.scale(1)/w);\n\n  if any([h*factor,w*factor]>opts.maxScale)\n    factor = min(opts.maxScale/h,opts.maxScale/w);\n  end\n\n  if abs(factor-1)>1e-3\n    imre{b} = imresize(ims{b},factor,'Method',opts.interpolation);\n  else\n    imre{b} = ims{b};\n  end\n\n  if imdb.boxes.flip(batch(b))\n    im = imre{b};\n    imre{b} = im(:,end:-1:1,:);\n  end\n\n  imreSize = size(imre{b});\n\n  maxH = max(imreSize(1),maxH);\n  maxW = max(imreSize(2),maxW);\n\n  % adapt bounding boxes into new coord\n  bbox = pboxes{b};\n  if any(bbox(:)<=0)\n    error('bbox error');\n  end\n\n  nB = size(bbox,1);\n  tbbox = bbox_scale(bbox,factor,[imreSize(2) imreSize(1)]);\n  if any(tbbox(:)<=0)\n    error('tbbox error');\n  end\n\n  rois = [rois [b*ones(1,nB) ; tbbox' ] ];\nend\n\nimo = zeros(maxH,maxW,size(imre{1},3),numel(batch),'single');\nfor b=1:numel(batch)\n  % subtract mean\n  if ~isempty(opts.averageImage)\n    imre{b} = single(bsxfun(@minus,imre{b},opts.averageImage));\n  end\n  sz = size(imre{b});\n  imo(1:sz(1),1:sz(2),:,b) = single(imre{b});\nend\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/libs/matconvnet/examples/fast_rcnn/fast_rcnn_train_get_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.2210405256160936}}
{"text": "%--- help for dsge/bvar_dsge ---\n%\n%  INTERNAL FUNCTION: intermediary file for computing key elements for dsge-var\n% \n%  ::\n% \n%    [obj,retcode] = bvar_dsge(obj,varargin)\n% \n%  Args:\n% \n%     obj (rise | dsge): model object\n%     varargin : ususal dsge options. The most important of which are:\n% \n%       - **dsgevar_lag** [integer|{4}]: number of lags in the VAR\n%       - **dsgevar_constant** [false|{true}]: flag for having a constant in\n%         the VAR\n%       - **dsgevar_var_regime** [false|{true}]: use the VAR in simulations.\n%         Otherwise use the DSGE\n%       - **dsgevar_inner_param_uncertainty** [true|{false}]: make random draws\n%         for the parameters around the mode for each simulation\n% \n%  Returns:\n%     :\n% \n%     - **obj** [rise|dsge]: model object\n% \n%  Note:\n% \n%     - Because the BVAR-DSGE will have fewer variables than the DSGE, in\n%       simulations, the missing variables will be stored as 0+1i in time series.\n%       This is true for forecast, irf and simulate\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/models/@dsge/bvar_dsge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.22089948107245475}}
{"text": "function dispScanStats(scanBinsV, volHistV, name, nameVol, planC, indexS, opt)\n%Command line display of basic scan statistics\n%scanBinsV is a vector of the midpoint scanBin values.\n%volHistV is either a histogram of volumes or surface areas.\n%LM: 14 Oct 02, JOD.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n% ESPEZI OCT 2014 added nameVol, changed order of printed items and added dose name\n\nud = get(findobj('Tag', 'IVHGui'),'userdata');\nscanNum = get(ud.af.handles.scan,'value');\nimageType = planC{indexS.scan}(scanNum).scanInfo(1).imageType;\n\nif strcmpi(imageType,'CT')\n    units = 'HU';\nelseif strcmpi(imageType,'PET')\n    units = 'SUV';\nelse\n    units = '';\nend\n\nswitch lower(opt)\n\n  case 'standardscan'\n    disp('-----------------------')\n    disp('')\n    disp(['Structure is:  ' name])\n\n    totalVol = sum(volHistV);\n    disp(['Total volume is:  ' num2str(totalVol) ' cubic cm.'])\n\n    disp(['Scan name is:  ' nameVol])\n\n    meanD = sum(scanBinsV.*volHistV)/sum(volHistV);\n    disp(['Mean ' imageType ' ' units ' is:  ' num2str(meanD)])\n\n    ind = max(find([volHistV~=0]));\n    maxD = scanBinsV(ind);\n    disp(['Max' imageType ' ' units ' is:  ' num2str(maxD)])\n\n    ind = min(find([volHistV~=0]));\n    minD = scanBinsV(ind);\n    disp(['Min ' imageType ' ' units ' is:  ' num2str(minD)])\n    disp('')\n    disp('-----------------------')\n\n  case 'dshscan'\n\n    disp('-----------------------')\n    disp('')\n    disp(['Structure is:  ' name])\n\n    areaV = volHistV;  %actually areas, not volumes.\n    scansV = scanBinsV;\n\n    totalArea = sum(areaV);\n    disp(['Total surface area is:  ' num2str(totalArea) ' square cm.'])\n\n    disp(['Scan name is:  ' nameVol])\n\n    meanD = sum(scansV.*areaV)/sum(areaV);\n    disp(['Mean surface ' imageType ' ' units ' is:  ' num2str(meanD)])\n\n    maxScan = max(scansV);\n    disp(['Max ' imageType ' ' units ' is:  ' num2str(maxScan)])\n\n    minScan = min(scansV);\n    disp(['Min ' imageType ' ' units ' is:  ' num2str(minScan)])\n    disp('')\n    disp('-----------------------')\n\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/IntensityVolumeHistograms/dispScanStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.22089947560963297}}
{"text": "function output = callsparsecolo(interfacedata)\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc       = interfacedata.c;\nK       = interfacedata.K;\nx0      = interfacedata.x0;\nub      = interfacedata.ub;\nlb      = interfacedata.lb;\n\n% Bounded variables converted to constraints\nif ~isempty(ub)\n    [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\nA = -F_struc(:,2:end)';\nC = F_struc(:,1);\nb = -c;\n\nif options.savedebug\n    ops = options.sparsecolo;\n    save sparsecolodebug K A C b\nend\n\nops = options.sparsecolo;\nops.SDPsolver = lower(interfacedata.solver.sdpsolver.tag);\nops.SDPAoptions = options.sdpa;\nops.sedumipar = options.sedumi;\nops.sdpt3OPTIONS = options.sdpt3;\nops.sdpt3OPTIONS.printlevel = options.verbose;\nops.printlevel = options.verbose;\nif options.verbose==0\n    ops.SDPAoptions.print = 'no';\nelse\n    ops.SDPAoptions.print = 'display';\nend\n\nif options.savedebug\n    save sparsecolodebug K A C b ops\nend\n\nif options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end\nsolvertime = tic;\nif options.verbose==0 % Sparsecolo does not run silent\n    evalc('[x,y,infoCoLO,cliqueDomain,cliqueRange,LOP] = sparseCoLO(A,b,C,K,[],ops);');\nelse    \n    [x,y,infoCoLO,cliqueDomain,cliqueRange,LOP] = sparseCoLO(A,b,C,K,[],ops);\nend\nsolvertime = toc(solvertime);\n\n% Create YALMIP dual variable and slack\nDual = x;\nPrimal = y;\n\n\nswitch  lower(interfacedata.solver.sdpsolver.tag)\n    case 'sdpt3'\n        switch infoCoLO.SDPsolver.termcode\n            case 0\n                problem = 0; % No problems detected\n            case {-1,-5}\n                problem = 5; % Lack of progress\n            case {-2,-3,-4,-7}\n                problem = 4; % Numerical problems\n            case -6\n                problem = 3; % Maximum iterations exceeded\n            case -10\n                problem = 7; % YALMIP sent incorrect input to solver\n            case 1\n                problem = 2; % Dual feasibility\n            case 2\n                problem = 1; % Primal infeasibility\n            otherwise\n                problem = -1; % Unknown error\n        end\n    case 'sedumi'\n        problem = sedumicode(infoCoLO.SDPsolver,options);\n        \n    case 'sdpa'\n        switch (infoCoLO.SDPsolver.phasevalue)\n            case 'pdOPT'\n                problem = 0;\n            case {'noINFO','pFEAS','dFEAS','pdFEAS'}\n                problem = 3;\n            case 'pFEAS_dINF'\n                problem = 2;\n            case 'pINF_dFEAS'\n                problem = 1;\n            case 'pUNBD'\n                problem = 2;\n            case 'dUNBD'\n                problem = 1;\n            case 'pdINF'\n                problem = 12;\n            otherwise\n                problem = -1;\n        end\n        \nend\n\nif options.savesolveroutput\n    solveroutput.obj = obj;\n    solveroutput.X = X;\n    solveroutput.y = y;\n    solveroutput.Z = Z;\n    solveroutput.info = info;\n    solveroutput.runhist = runhist;\nelse\n    solveroutput = [];\nend\n\nif options.savesolverinput\n    solverinput.blk = blk;\n    solverinput.A   = A;\n    solverinput.C   = C;\n    solverinput.b   = b;\n    solverinput.X0   = [];\n    solverinput.y0   = x0;\n    solverinput.Z0   = [];\n    solverinput.options   = options.sdpt3;\nelse\n    solverinput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(Primal,Dual,[],problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);\n\n\nfunction problem = sedumicode(info,options)\ntemp = info.pinf;\npinf = info.dinf;\ndinf = temp;\n\n% Check for reported errors\nif (pinf==0) &  (dinf==0)\n    problem = 0; % No problems\nend\n\n% We can only report one error, use priorities\nif (problem==0) & (pinf==1)\n    problem = 1; % Primal infeasability\nend\n\nif (problem==0) & (dinf==1)\n    problem = 2; % Dual infeasability\nend\n\nif (problem==0) & (info.numerr==1) | (info.numerr==2)\n    problem = 4; %Numerical problems\nend\n\nif (problem==0) & (info.iter >= options.sedumi.maxiter)\n    % Did we need exactly maxiter iterations to find optimum\n    if (pinf==0) & (dinf==0) & (info.numerr==0)\n        problem = 0; % Yes\n    else\n        problem = 3; % No, we are not optimal yet\n    end\nend\n\nif (problem==0) & (info.feasratio<0.98)\n    problem = 4;\nend\n\n% Fix for cases not really explained in documentation of sedumi?\nif (abs(info.feasratio+1)<0.1) & (pinf==0) &  (dinf==0)\n    problem = 1;\nend\nif (abs(info.feasratio+1)<0.1) & (pinf==0) &  (dinf==0) & (c'*y_s<-1e10)\n    problem = 2;\nend\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callsparsecolo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.22081469573284188}}
{"text": "function [ output ] = tapas_rdcm_store_parameters(DCM, mN_cut, sN, aN, bN, logF, logF_term, idx_x, z_cut, args)\n% [ output ] = tapas_rdcm_store_parameters(DCM, mN_cut, sN, aN, bN, logF, logF_term, idx_x, z_cut, args)\n% \n% Wraps parameters to the output structure.\n% \n%   Input:\n%   \tDCM             - model structure\n%       mN_cut          - posterior means of connectivity parameters\n%       sN              - posterior covaraince of connectivity parameters\n%       aN              - posterior shape parameter of measurement noise\n%       bN              - posterior rate parameter of measurement noise\n%       logF            - negative free energy\n%       logF_term       - seperate terms of the negative free energy\n%       idx_x           - regressor/parameter index\n%       z_cut           - posterior binary indicators\n%       args            - arguments\n%\n%   Output:\n%       output          - output structure\n%\n \n% ----------------------------------------------------------------------\n% \n% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina\n% \n% Copyright (C) 2016-2022 Translational Neuromodeling Unit\n%                         Institute for Biomedical Engineering\n%                         University of Zurich & ETH Zurich\n%\n% This file is part of the TAPAS rDCM Toolbox, which is released under the \n% terms of the GNU General Public License (GPL), version 3.0 or later. You\n% can redistribute and/or modify the code under the terms of the GPL. For\n% further see COPYING or <http://www.gnu.org/licenses/>.\n% \n% Please note that this toolbox is in an early stage of development. Changes \n% are likely to occur in future releases.\n% \n% ----------------------------------------------------------------------\n\n\n% remove confound regressors\nNc = size(DCM.U.X0,2);\nDCM.b = DCM.b(:,:,1:end-Nc);\nDCM.c = DCM.c(:,1:end-Nc);\n\n% get number of regions and inputs\n[nr, nu] = size(DCM.c);\n\n% get the posterior parameter estimates\nif min(size(idx_x)) == 1\n    mN = zeros(nr,length(idx_x));\n    mN(repmat(idx_x,nr,1)) = mN_cut;\nelse\n    mN = mN_cut;\nend\n\n\n%% mean\n\n% get mean for connectivity parameters\noutput.Ep          = tapas_rdcm_empty_par(DCM);\noutput.Ep.A        = mN(1:nr,1:nr);\noutput.Ep.B        = reshape(mN(1:nr,nr+1:nr+nr*nu),[nr nr nu]);\noutput.Ep.C        = mN(1:nr,end-Nc-nu+1:end-Nc);\noutput.Ep.baseline = mN(1:nr,end-Nc+1:end);\n\n% modify driving inputs\nif ( strcmp(args.type,'r') )\n    output.Ep.C        = output.Ep.C*16;\nend\n\n\n%% variance\n\n% get the number of potential connections\nD = numel(output.Ep.A) + numel(output.Ep.C);\n\n% create the covariance matrix (for computational reasons, only recommended for small DCMs)\nif ( isempty(z_cut) && args.evalCp == 1 )\n    \n    % empty covariance matrix\n    output.Cp = sparse(D,D);\n    \n    % get the number of entries\n    nr_A    = numel(output.Ep.A);\n    nr_C    = numel(output.Ep.C);\n    nr_A_B  = numel(output.Ep.A(1,:))+numel(output.Ep.B(1,:,:))+numel(output.Ep.B(1,:,1));\n    \n    \n    % define an index matrix for endogenous connections\n    indexA = reshape(1:nr_A,nr,nr);\n    \n    % get the (co)variances of the endogenous connections\n    for k = 1:nr\n        for int = 1:nr\n            for int2 = 1:nr\n                output.Cp(indexA(k,int),indexA(k,int2)) = sN{k}(int,int2);\n            end\n        end\n    end\n    \n    % define an index matrix for driving input parameters\n    indexC = reshape(1:nr_C,nr,nu);\n    \n    % get the (co)variances of the driving input parameters\n    for k = 1:nr\n        for int = 1:nu\n            for int2 = 1:nu\n                output.Cp(nr_A+indexC(k,int),nr_A+indexC(k,int2)) = sN{k}(nr_A_B+int,nr_A_B+int2);\n            end\n        end\n    end\n    \n    % get the covariances between endogeous and driving input parameters\n    for k = 1:nr\n        for int = 1:nr\n            for int2 = 1:nu\n                output.Cp(indexA(k,int),nr_A+indexC(k,int2)) = sN{k}(int,nr_A_B+int2);\n                output.Cp(nr_A+indexC(k,int2),indexA(k,int)) = sN{k}(int,nr_A_B+int2);\n            end\n        end\n    end\nend\n\n\n% store the regions-wise posterior covariance matrices\noutput.sN = sN;\n\n\n\n%% precision\n\n% store precision parameters\noutput.t  = aN./bN;\noutput.aN = aN;\noutput.bN = bN;\n\n\n%% connection probabilities\n\n% store connection probabilities\nif ( ~isempty(z_cut) )\n    if min(size(idx_x)) == 1\n        z = zeros(nr,length(idx_x));\n        z(repmat(idx_x,nr,1)) = z_cut;\n    else\n        z = z_cut;\n    end\n    \n    output.Ip   = tapas_rdcm_empty_par(DCM);\n    output.Ip.A = z(1:nr,1:nr);\n    output.Ip.B = reshape(z(1:nr,nr+1:nr+nr*nu),[nr nr nu]);\n    output.Ip.C = z(1:nr,end-nu:end-1);\nelse\n    output.Ip   = tapas_rdcm_empty_par(DCM);\n    output.Ip.A = DCM.a;\n    output.Ip.B = DCM.b;\n    output.Ip.C = DCM.c;\nend\n\n\n%% free energy\n\n% store free energy\noutput.logF   = sum(logF);\noutput.logF_r = logF;\n\n% store the components of the free energy\nif ( ~isempty(logF_term) )\n    output.logF_term.log_lik        = sum(logF_term.log_lik);\n    output.logF_term.log_p_weight   = sum(logF_term.log_p_weight);\n    output.logF_term.log_p_prec     = sum(logF_term.log_p_prec);\n    output.logF_term.log_p_z        = sum(logF_term.log_p_z);\n    output.logF_term.log_q_weight   = sum(logF_term.log_q_weight);\n    output.logF_term.log_q_prec     = sum(logF_term.log_q_prec);\n    output.logF_term.log_q_z        = sum(logF_term.log_q_z);\nend\n\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/rDCM/code/tapas_rdcm_store_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.22081469275559}}
{"text": "function test_tutorial_natmeg2014_preprocessing\n\n% WALLTIME 00:20:00\n% MEM 5gb\n% DEPENDENCY\n\n% this script executes the MATLAB content from\n% http://www.fieldtriptoolbox.org/tutorial/natmeg2014/timefrequency\n%\n% it corresponds to the wiki version of 7 October 2014\n\nclear all\nclose all\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/workshop/natmeg2014'));\n\ncfg = [];\ncfg.dataset    = 'oddball1_mc_downsampled.fif';\ncfg.continuous = 'yes';\ncfg.channel    = 'MEG*1';\ncfg.viewmode   = 'vertical';\ncfg.blocksize  = 1; % Length of data to display, in seconds\nft_databrowser(cfg);\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\ncfg.channel = {'MEG*2', 'MEG*3'};\ncfg.viewmode = 'vertical';\ncfg.blocksize = 1;                             % Length of data to display, in seconds\nft_databrowser(cfg);\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\ncfg.channel = 'EEG';\ncfg.viewmode = 'vertical';\ncfg.blocksize = 1;                             % Length of data to display, in seconds\ncfg.preproc.demean = 'yes';                    % Demean the data before display\ncfg.ylim = [-4e-6 4e-6];\nft_databrowser(cfg);\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\n\ncfg.trialdef.prestim        = 1;\ncfg.trialdef.poststim       = 1;\ncfg.trialdef.std_triggers   = 1;\ncfg.trialdef.stim_triggers  = [1 2]; % 1 for standard, 2 for deviant\ncfg.trialdef.odd_triggers   = 2;\ncfg.trialdef.rsp_triggers   = [256 4096];\ncfg.trialfun                = 'trialfun_oddball_stimlocked';\ncfg                         = ft_definetrial(cfg);\n\ncfg.continuous              = 'yes';\ncfg.hpfilter                = 'no';\ncfg.detrend                 = 'no';\ncfg.continuous              = 'yes';\ncfg.demean                  = 'yes';\ncfg.dftfilter               = 'yes';\ncfg.dftfreq                 = [50 100];\ncfg.channel                 = 'MEG';\ndata_MEG                    = ft_preprocessing(cfg);\n\nif false\n  % skip the interactive section\n  % separately for magnetometers\n  cfg               = [];\n  cfg.metric        = 'zvalue';\n  cfg.layout        = 'neuromag306all.lay';\n  cfg.channel       = 'MEG*1';\n  cfg.keepchannel   = 'yes';  % This keeps those channels that are not displayed in the data\n  data_MEG_clean    = ft_rejectvisual(cfg,data_MEG);\n  % separately for gradiometers\n  cfg.channel = {'MEG*2','MEG*3'};\n  data_MEG_clean    = ft_rejectvisual(cfg,data_MEG_clean);\nelse\n  % simply copy it over\n  data_MEG_clean = data_MEG;\nend\n\ncfg = [];\ncfg.lpfilter        = 'yes';\ncfg.lpfreq          = 25;\ncfg.demean          = 'yes';\ncfg.baselinewindow  = [-0.5 0];\ndata_MEG_filt       = ft_preprocessing(cfg,data_MEG_clean);\n\n\ncfg = [];\ncfg.trials          = find(data_MEG_filt.trialinfo(:,1) == 1);\nERF_standard        = ft_timelockanalysis(cfg,data_MEG_filt);\n\ncfg.trials          = find(data_MEG_filt.trialinfo(:,1) == 2);\nERF_oddball         = ft_timelockanalysis(cfg,data_MEG_filt);\n\ncfg = [];\ncfg.operation = 'x1 - x2';\ncfg.parameter = 'avg';\nERF_diff = ft_math(cfg, ERF_oddball, ERF_standard);\n\ncfg = [];\ncfg.fontsize = 6;\ncfg.layout = 'neuromag306mag.lay';\ncfg.ylim = [-2.5e-13 2.5e-13];\ncfg.xlim = [-0.2 0.6];\n\nfigure;\nft_multiplotER(cfg, ERF_standard, ERF_oddball, ERF_diff );\nlegend({'Standard';'Oddball';'Difference'});\n\ncfg = [];\ncfg.fontsize = 6;\ncfg.layout   = 'neuromag306mag.lay';\ncfg.xlim     = [-0.2 0.6];\ncfg.ylim     = [-3e-13 3e-13];\ncfg.channel  = 'MEG0211';\n\nfigure;\nft_singleplotER(cfg, ERF_standard, ERF_oddball, ERF_diff);\nlegend({'Standard';'Oddball';'Difference'});\n\ncfg                 = [];\ncfg.layout          = 'neuromag306mag.lay'; % name will change\ncfg.zlim            = [-3e-13 3e-13];\ncfg.xlim            = [0.08 0.15];\ncfg.style           = 'straight';\ncfg.comment         = 'no';\ncfg.marker          = 'off';\ncfg.colorbar        = 'southoutside';\n\nfigure;\nsubplot(1,3,1);\nft_topoplotER(cfg, ERF_standard);\ntitle('Standard');\naxis tight\n\nsubplot(1,3,2);\nft_topoplotER(cfg, ERF_oddball);\ntitle('Oddball');\naxis tight\n\nsubplot(1,3,3);\nft_topoplotER(cfg, ERF_diff);\ntitle('Difference');\naxis tight\n\n% Combine planar\ncfg = [];\nERF_standard_cmb    = ft_combineplanar(cfg, ERF_standard);\nERF_oddball_cmb     = ft_combineplanar(cfg, ERF_oddball);\nERF_diff_cmb        = ft_combineplanar(cfg, ERF_diff);\n\ncfg = [];\ncfg.fontsize = 6;\ncfg.layout   = 'neuromag306cmb.lay';\ncfg.ylim     = [0 8e-12];\ncfg.xlim     = [-0.2 0.6];\n\nfigure;\nft_multiplotER(cfg, ERF_standard_cmb, ERF_oddball_cmb, ERF_diff_cmb);\nlegend({'Standard?, ?Oddball?, ?Difference'});\n\ncfg = [];\ncfg.showlabels = 'yes';\ncfg.fontsize   = 6;\ncfg.layout     = 'neuromag306cmb.lay';\ncfg.xlim       = [-0.2 0.6];\ncfg.ylim       = [0 8e-12];\ncfg.channel    = 'MEG0222+0223';\n\nfigure;\nft_singleplotER(cfg, ERF_standard_cmb, ERF_oddball_cmb, ERF_diff_cmb);\nlegend({'Standard?, ?Oddball?, ?Difference'});\n\ncfg                 = [];\ncfg.layout          = 'neuromag306cmb.lay'; % name will change\ncfg.zlim            = 'zeromax';\ncfg.xlim            = [0.08 0.15];\ncfg.style           = 'straight';\ncfg.comment         = 'no';\ncfg.marker          = 'off';\ncfg.colorbar        = 'southoutside';\n\nfigure;\nsubplot(1,3,1);\nft_topoplotER(cfg, ERF_standard_cmb);\ntitle('Standard');\naxis tight\n\nsubplot(1,3,2);\nft_topoplotER(cfg, ERF_oddball_cmb);\ntitle('Deviant');\naxis tight\n\nsubplot(1,3,3);\nft_topoplotER(cfg, ERF_diff_cmb);\ntitle('Difference');\naxis tight\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\n\ncfg.trialdef.prestim        = 1;\ncfg.trialdef.poststim       = 1;\ncfg.trialdef.std_triggers   = 1;\ncfg.trialdef.stim_triggers  = [1 2];\ncfg.trialdef.odd_triggers   = 2;\ncfg.trialdef.rsp_triggers   = [256 4096];\ncfg.trialfun                = 'trialfun_oddball_stimlocked';\ncfg                         = ft_definetrial(cfg);\n\ncfg.continuous              = 'yes';\ncfg.hpfilter                = 'no';\ncfg.detrend                 = 'no';\ncfg.continuous              = 'yes';\ncfg.demean                  = 'yes';\ncfg.dftfilter               = 'yes';\ncfg.dftfreq                 = [50 100];\ncfg.channel                 = 'EEG';\n\ncfg.reref                   = 'yes'; % recorded with left mastoid\ncfg.refchannel              = 'all';\ndata_EEG                    = ft_preprocessing(cfg);\n\nif false\n  % skip the interactive section\n  cfg               = [];\n  cfg.metric        = 'zvalue';\n  cfg.layout        = 'natmeg_customized_eeg1005.lay';\n  data_EEG_clean    = ft_rejectvisual(cfg,data_EEG);\nelse\n  % simply copy the data over\n  data_EEG_clean = data_EEG;\nend\n\ncfg = [];\ncfg.lpfilter        = 'yes';\ncfg.lpfreq          = 25;\ncfg.demean          = 'yes';\ncfg.baselinewindow  = [-0.5 0];\ndata_EEG_filt       = ft_preprocessing(cfg,data_EEG_clean);\n\ncfg = [];\ncfg.trials          = find(data_EEG_filt.trialinfo(:,1) == 1);\nERP_standard        = ft_timelockanalysis(cfg, data_EEG_filt);\ncfg.trials          = find(data_EEG_filt.trialinfo(:,1) == 2);\nERP_oddball         = ft_timelockanalysis(cfg, data_EEG_filt);\n\ncfg = [];\ncfg.operation = 'x1 - x2';\ncfg.parameter = 'avg';\nERP_diff = ft_math(cfg, ERP_oddball, ERP_standard);\n\ncfg          = [];\ncfg.fontsize = 6;\ncfg.layout   = 'natmeg_customized_eeg1005.lay';\ncfg.ylim     = [-3e-6 3e-6];\ncfg.xlim     = [-0.2 0.6];\n\nfigure;\nft_multiplotER(cfg, ERP_standard, ERP_oddball, ERP_diff);\n\ncfg            = [];\ncfg.showlabels = 'yes';\ncfg.fontsize   = 6;\ncfg.layout     = 'natmeg_customized_eeg1005.lay';\ncfg.xlim       = [-0.2 0.6];\ncfg.ylim       = [-8e-6 8e-6];\ncfg.channel    = 'EEG020';\n\nfigure;\nft_singleplotER(cfg, ERP_standard, ERP_oddball, ERP_diff);\nlegend({'Standard';'Oddball';'Difference'});\n\n% Topo\ncfg                 = [];\ncfg.layout          = 'natmeg_customized_eeg1005.lay';\ncfg.zlim            = [-3e-6 3e-6];\ncfg.xlim            = [0.08 0.15];\ncfg.style           = 'straight';\ncfg.comment         = 'no';\ncfg.marker          = 'off';\ncfg.colorbar        = 'southoutside';\n\nfigure;\nsubplot(1,3,1);\nft_topoplotER(cfg,ERP_standard);\ntitle('Standard');\naxis tight\n\nsubplot(1,3,2);\nft_topoplotER(cfg,ERP_oddball);\ntitle('Deviant');\naxis tight\n\nsubplot(1,3,3);\nft_topoplotER(cfg,ERP_diff);\ntitle('Difference');\naxis tight\n\ncfg                 = [];\ncfg.method          = 'finite';\ncfg.elec            = ERP_standard.elec;\n\nscd_ERP_standard    = ft_scalpcurrentdensity(cfg, ERP_standard);\nscd_ERP_oddball     = ft_scalpcurrentdensity(cfg, ERP_oddball);\nscd_ERP_diff        = ft_scalpcurrentdensity(cfg, ERP_diff);\n\ncfg                 = [];\ncfg.layout          = 'natmeg_customized_eeg1005.lay'; % name will change\ncfg.zlim            = 'maxabs';\ncfg.xlim            = [0.08 0.15];\ncfg.style           = 'straight';\ncfg.comment         = 'no';\ncfg.marker          = 'off';\ncfg.colorbar        = 'southoutside';\n\nfigure;\nsubplot(1,3,1);\nft_topoplotER(cfg,scd_ERP_standard);\ntitle('Standard');\naxis tight;\n\nsubplot(1,3,2);\nft_topoplotER(cfg,scd_ERP_oddball);\ntitle('Oddball');\naxis tight;\n\nsubplot(1,3,3);\nft_topoplotER(cfg,scd_ERP_diff);\ntitle('Difference');\naxis tight;\n\ncfg      = [];\ndata_all = ft_appenddata(cfg, data_MEG, data_EEG);\n\nif false\n  % skip the interactive section\n  cfg = [];\n  cfg.channel    = 'EEG';\n  cfg.metric     = 'zvalue';\n  cfg.keepchannel= 'yes';\n  cfg.layout     = 'neuromag306all.lay';\n  data_all_clean = ft_rejectvisual(cfg, data_all);\n  \n  cfg.channel    = 'MEGMAG';\n  data_all_clean = ft_rejectvisual(cfg, data_all_clean);\n  \n  cfg.channel    = 'MEGGRAD';\n  data_all_clean = ft_rejectvisual(cfg, data_all_clean);\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_tutorial_natmeg2014_preprocessing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22078580481165838}}
{"text": "function [metrics, emphysema_mask] = PTKComputeEmphysemaFromMask(roi_data, mask)\n    % PTKComputeEmphysemaFromMask. Computes emphysema percentage and percentile\n    % density\n    %\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n    %     Author: Tom Doel, 2013.  www.tomdoel.com\n    %     Distributed under the GNU GPL v3 licence. Please see website for details.\n    \n    emphysema_threshold_value_hu_1 = -950;\n    emphysema_threshold_value_hu_2 = -910;\n    \n    emphysema_threshold_value_1 = roi_data.HounsfieldToGreyscale(emphysema_threshold_value_hu_1);\n    emphysema_threshold_value_2 = roi_data.HounsfieldToGreyscale(emphysema_threshold_value_hu_2);\n    emphysema_threshold_value_percentile = 15;\n    lower_threshold = (roi_data.RawImage <= emphysema_threshold_value_1) & (mask.RawImage > 0);\n    upper_threshold = (roi_data.RawImage <= emphysema_threshold_value_2) & (mask.RawImage > 0);\n    emphysema_mask_raw = uint8(upper_threshold);\n    emphysema_mask_raw(lower_threshold) = 3;\n    emphysema_mask = mask.BlankCopy;\n    emphysema_mask.ChangeRawImage(emphysema_mask_raw);\n    \n    number_of_voxels_in_mask = sum(mask.RawImage(:));\n    emphysema_voxels_in_mask = sum(lower_threshold(:)); % We only count voxels in the lower threshold\n    emphysema_percentage = 100*emphysema_voxels_in_mask/number_of_voxels_in_mask;\n    \n    if ~mask.ImageExists\n        emphysema_percentile_density = NaN;\n        emphysema_percentile_density_hu = NaN;\n    else\n        emphysema_percentile_density = prctile(roi_data.RawImage(mask.RawImage(:)), emphysema_threshold_value_percentile);\n        emphysema_percentile_density_hu = roi_data.GreyscaleToHounsfield(emphysema_percentile_density);\n    end\n    \n    metrics = PTKMetrics;\n    metrics.AddMetric('EmphysemaPercentage', emphysema_percentage, '% of emphysema');\n    metrics.AddMetric('EmphysemaPercentileDensityHU', emphysema_percentile_density_hu, 'Emphysema percentile density (HU)');\nend", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Analysis/PTKComputeEmphysemaFromMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22078579859121045}}
{"text": "function [fx,dfdx,dfdp] = f_AR(x,theta,u,in)\n% AR(1) evolution function\nfx = x;\ndfdx = eye(length(x));\ndfdp = [];", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/f_AR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22064539581352366}}
{"text": "function v = rotate_outer(m,rot,varargin)\n% rotate crystal directions\n%\n% Input\n%  m - @Miller\n%  ori - @orientation\n%\n% Output\n%  v - vector3d\n%\n\n% ensure that the rotations have the right reference frame\nif isa(rot,'orientation') && nargin == 2\n  rot = m.CS.ensureCS(rot);\nend\n\nv = rotate_outer@vector3d(m,rot);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@Miller/rotate_outer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22064539581352363}}
{"text": "function [im, im_scale] = prep_im_for_blob(im, im_means, target_size, max_size)\n    im = single(im);\n    if size(im,3) < 3\n      im = im(:,:,[1 1 1]);\n    end\n    if ~isa(im, 'gpuArray')\n        try\n            im = bsxfun(@minus, im, im_means);\n        catch\n            im_means = imresize(im_means, [size(im, 1), size(im, 2)], 'bilinear', 'antialiasing', false);\n            if  size(im,3)>3 && size(im,3) ~= size(im_means,3)\n              im(:,:,1:3,:) = bsxfun(@minus, im(:,:,1:3,:), im_means);\n            else\n              im = bsxfun(@minus, im, im_means);\n            end\n        end\n        im_scale = prep_im_for_blob_size(size(im), target_size, max_size);\n\n        target_size = round([size(im, 1), size(im, 2)] * im_scale);\n        im = imresize(im, target_size, 'bilinear', 'antialiasing', false);\n    else\n        % for im as gpuArray\n        try\n            im = bsxfun(@minus, im, im_means);\n        catch\n            im_means_scale = max(double(size(im, 1)) / size(im_means, 1), double(size(im, 2)) / size(im_means, 2));\n            im_means = imresize(im_means, im_means_scale);    \n            y_start = floor((size(im_means, 1) - size(im, 1)) / 2) + 1;\n            x_start = floor((size(im_means, 2) - size(im, 2)) / 2) + 1;\n            im_means = im_means(y_start:(y_start+size(im, 1)-1), x_start:(x_start+size(im, 2)-1));\n            im = bsxfun(@minus, im, im_means);\n        end\n        \n        im_scale = prep_im_for_blob_size(size(im), target_size, max_size);\n        im = imresize(im, im_scale);\n    end\nend", "meta": {"author": "feichtenhofer", "repo": "Detect-Track", "sha": "e013785dc229ff3d60e7cad69858ae0a4e384fe2", "save_path": "github-repos/MATLAB/feichtenhofer-Detect-Track", "path": "github-repos/MATLAB/feichtenhofer-Detect-Track/Detect-Track-e013785dc229ff3d60e7cad69858ae0a4e384fe2/utils/prep_im_for_blob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22062196280627974}}
{"text": "function out = times( a,b )\n%TIMES (element-wise) for nested cells\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\n% determine input types\ninType = {class(a), class(b)};\nif(strcmp(inType{1},'TRAFO') && strcmp(inType{2},'TRAFO'))  \n    [outA, idx] = flattenCellMatrix(a.data);\n    [outB, idxB] = flattenCellMatrix(b.data);\n    meta = a.meta;\n    meta_b = b.meta;\n    clear 'a' 'b'\n\n    if(~isempty(idx) && ~isempty(idxB) && ~all(cellfun(@(x,y) isequal(x,y), idx, idxB)))\n        error('TRAFO::times: Nested cells must have the same size');\n    end\n    if (iscell(meta) && iscell(meta_b))\n        if(~isempty(meta) && ~isempty(meta_b))\n            if(iscell(meta{1}) && iscell(meta_b{1}))\n                if(~all(cellfun(@(x,y) isequal(x,y), flattenCellMatrix(meta), flattenCellMatrix(meta_b))))\n                    error('TRAFO::times: Unequal reconstruction information');\n                end\n            else\n                if(~all(cellfun(@(x,y) isequal(x,y), meta, meta_b)))\n                    % happens in kernelMult for kernel .* zpad(W) -> take kernel\n                    % meta information (meta) => corrected\n                    [ST, ~] = dbstack;\n                    if(~strcmp(ST(2,1).name,'kernelMult'))\n                        error('TRAFO::times: Unequal reconstruction information');\n                    end\n                end\n            end\n        end\n    else \n        if ~isequal(meta, meta_b)\n            error('TRAFO::times: Unequal reconstruction information');\n        end\n    end\n    \n%     try\n        out = cellfun(@(x,y) x.*y, outA, outB, 'UniformOutput', false);\n%     catch msg\n%         out = cell(size(outA));\n%         for i=1:length(out)\n%             out{i} = outA{i} .* outB{i};\n%         end\n%     end\n\nelseif(strcmp(inType{1},'TRAFO')) % assume b is double/uint/int\n    [out, idx] = flattenCellMatrix(a.data);\n    meta = a.meta;\n    clear 'a'\n    \n    out = cellfun(@(x) x .* b, out, 'UniformOutput', false);\n    \nelseif(strcmp(inType{2},'TRAFO'))\n    [out, idx] = flattenCellMatrix(b.data);\n    meta = b.meta;\n    clear 'b'\n    \n    out = cellfun(@(x) a .* x, out, 'UniformOutput', false);\n    \nelse\n    error('TRAFO::times: Impossible constellation!');\nend\n\nout = reconFlatCellMatrix(out,idx);\nout = TRAFO(out,meta); % return TRAFO object again without modifying input\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@TRAFO/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22056254635197067}}
{"text": "function run_test_single_model\n% Copyright (c) 2014-present University of Illinois at Urbana-Champaign\n% All rights reserved.\n% \t\t\n% Developed by:     Po-Sen Huang, Paris Smaragdis\n%                   Department of Electrical and Computer Engineering\n%                   Department of Computer Science\n%\n% Given a model, evaluate the performance.\n    baseDir = '../../../';\n    addpath([baseDir, filesep, 'codes']);\n    addpath([baseDir, filesep, 'tools', filesep, 'bss_eval']);\n    addpath([baseDir, filesep, 'tools', filesep, 'bss_eval_3']);\n    addpath([baseDir, filesep, 'tools', filesep, 'labrosa']);\n    addpath([baseDir, filesep, 'codes', filesep, 'TSP']);\n    \n    ModelPath=[baseDir, filesep, 'codes',filesep, 'TSP', filesep, 'model_demo'];\n\n    global SDR;\n    SDR.deviter=0;   SDR.devmax=0;   SDR.testmax=0;\n    SDR.devsar=0; SDR.devsir=0; SDR.testsar=0; SDR.testsir=0;\n\n    j=7650;\n\n    % Load model\n    load model_RNN1_win1_h300_l2_r0_64ms_1000000_softabs_linearout_RELU_logmel_trn0_c1e-10_c0.001_bsz100000_miter10_bf50_c0_d0_7650.mat\n    eI.writewav=1;\n    eI.bss3=1;\n    eI.DataPath=[baseDir, filesep, 'codes', filesep, 'TSP', ...\n        filesep, 'Data', filesep];\n    eI.saveDir = [baseDir, filesep, 'codes', filesep, 'TSP', ...\n        filesep, 'demo', filesep, 'results', filesep];\n    eI.CFGPath = [baseDir, filesep, 'tools', filesep, 'htk_features', filesep];\n    test_TSP_general_kl_recurrent(eI.modelname, theta, eI, 'done', j);\nend\n", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/codes/TSP/demo/run_test_single_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22056254635197062}}
{"text": "background.marker_pos(:,1+mod(background.smax:background.smax+size(background_marker_pos,2)-1,background.buffer_len)) = background_marker_pos+logical(background_marker_pos)*background.mmax;\nbackground.mmax = background.mmax + nnz(background_marker_pos);", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/temp/update__background_marker_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2203981558891963}}
{"text": "function path=VMR2mrGray(VMRfile,mmPerPix);\n% function path=VMR2mrGray(VMRfile,mmPerPix);\n% Function to convert between Brainvoyager VMR file format and mrGray\n% Last edited : $Date: 2007/07/05 19:51:58 $\n% ARW 100300\nif ~exist('mmPerPix','var')\n   mmPerPix = [240/256 240/256 1.2];\n   disp(['mmPerPix defaulting to [ ' num2str(mmPerPix,'%.4f ') ...\n         \t'].  I hope this is correct!']);\nend\n\nfid=fopen(VMRfile,'r');\nheader=fread(fid,3,'int16');\nmainImg=fread(fid,'uchar');\nfclose(fid);\nmainImg=reshape(mainImg,[header(1),header(2),header(3)]);\ndisp('Flipping images...');\n\nfor thisIm=1:header(3)\n   mainImg(:,:,thisIm)=rot90(fliplr(mainImg(:,:,thisIm)));\nend\n\npath = writeVolAnat(mainImg, mmPerPix);", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/VMR2mrGray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22039815588919626}}
{"text": "function fns_elec_write(pnt, vsize, dimpos, elecfile)\n%\n% This function write the electrodes locations on disk and other\n% information\n%   1. pnt is the location of the electrodes [NX3]\n%   3. voxel_sizes is the dimension of a voxel in the cartesian coordinates in mm [3X1]\n%   4. nodes_sizes is the dimension of the dipoles grid [NX NY NZ]\n\n% $Copyright (C) 2010 by Hung Dang$\n\nhdf5write(elecfile, '/electrodes/locations', pnt);\n\nhdf5write(elecfile, '/electrodes/gridlocs', int32(pnt), ...\n          'WriteMode', 'append');       % Assume the electrodes\n                                        % locations are mm and the\n                                        % voxel sizes is 1mm x 1mm\n                                        % x 1mm.\n\nhdf5write(elecfile, '/electrodes/voxel_sizes', vsize, ...\n          'WriteMode','append');\n\nhdf5write(elecfile, '/electrodes/node_sizes', int32(dimpos), ...\n          'WriteMode', 'append');\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/fns/fns_elec_write.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038093670468767}}
{"text": "s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nhash = java.util.Hashtable;\nC = {};\nfor i = 1:100\n    key = randsample(s,20,true);\n    value = randsample(s,40,true);\n    hash.put(key, value);\n    C{end+1} = {key, value};\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Workspace/Generic/test_hashtable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.22038093670468764}}
{"text": "function model = ivmOptimise(model, options);\n\n% IVMOPTIMISE Optimise the IVM.\n% FORMAT\n% DESC optimises an IVM by iterating between selecting points and\n% optimising kernel and noise parameters.\n% ARG model : the model to be optimised.\n% ARG options : options structure as returned by ivmOptions.\n%\n% SEEALSO : ivmOptimiseIvm, ivmOptimiseKernel, ivmOptimiseNoise\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n \n% IVM\n\nfor i = 1:options.extIters\n  if options.kernIters\n    % Update the kernel if required.\n    model = ivmOptimiseIvm(model, options.display);\n    model = ivmOptimiseKernel(model, options.display, options.kernIters);\n  end\n  if options.noiseIters\n    % Update the noise model if required.\n    model = ivmOptimiseIvm(model, options.display);\n    model = ivmOptimiseNoise(model, options.display, options.noiseIters);\n  end\n  if options.display\n    ivmDisplay(model);\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ivm/ivmOptimise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2201525381752258}}
{"text": "function output = callbonmin(model)\n\nmodel = yalmip2nonlinearsolver(model);\noptions = [];\ntry\n    options.bonmin = optiRemoveDefaults(model.options.bonmin,bonminset());\ncatch\n    options.bonmin = model.options.bonmin;\nend\noptions.ipopt = model.options.ipopt;\noptions.display = model.options.verbose;  \n\nif ~model.derivative_available\n    disp('Derivate-free call to bonmin/ipopt not yet implemented')\n    error('Derivate-free call to bonmin/ipopt not yet implemented')\nend\n\nif model.options.savedebug\n    save bonmindebug model\nend\n\nFupp = [ repmat(0,length(model.bnonlinineq)+length(model.K.q)*(model.K.q(1)>0),1);\n    repmat(0,length(model.bnonlineq),1);\n    repmat(0,length(model.b),1);\n    repmat(0,length(model.beq),1)];\n\nFlow = [ repmat(-inf,length(model.bnonlinineq)+length(model.K.q)*(model.K.q(1)>0),1);\n    repmat(0,length(model.bnonlineq),1);\n    repmat(-inf,length(model.b),1);\n    repmat(0,length(model.beq),1)];\n\nif isempty(Flow)\n    Flow = [];\n    Fupp = [];\nend\n\n% Since ipopt react strangely on lb>ub, we should bail if that is detected\n% (ipopt creates an exception)\nif ~isempty(model.lb)\n    if any(model.lb>model.ub)\n        problem = 1;   \n        solverinput = [];\n        solveroutput = [];  \n        output = createoutput(model.lb*0,[],[],problem,'BONMIN',solverinput,solveroutput,0);\n        return\n    end\nend\n\n% These are needed to avoid recomputation due to ipopts double call to get\n% f and df, and g and dg\nglobal latest_x_f\nglobal latest_x_g\nglobal latest_df\nglobal latest_f\nglobal latest_G\nglobal latest_g\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_G= [];\nlatest_g = [];\nlatest_x_f = [];\nlatest_x_g = [];\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\nfuncs.objective = @(x)ipopt_callback_f(x,model);\nfuncs.gradient = @(x)ipopt_callback_df(x,model);\nif ~isempty(Fupp)\n    funcs.constraints = @(x)ipopt_callback_g(x,model);\n    funcs.jacobian  = @(x)ipopt_callback_dg(x,model);\nend\n\noptions.lb = model.lb(:)';\noptions.ub = model.ub(:)';\nif ~isempty(Fupp)\n    options.cl = Flow;\n    options.cu = Fupp;\nend\n\nif ~isempty(Fupp)\n    m = length(model.lb);    \n    allA=[model.Anonlinineq];\n    if size(model.F_struc,1) > 0\n        % These are SOCP cones\n        top = 1;\n        for i = 1:length(model.K.q)\n            rows = model.F_struc(top:top + model.K.q(i)-1,2:end)\n            allA = [allA;any(rows,1)];\n        end\n    end\n    allA = [allA;model.Anonlineq];\n    jacobianstructure = spalloc(size(allA,1),m,0);    \n    depends = allA | allA;   \n    for i = 1:size(depends,1)\n        vars = find(depends(i,:));\n        [ii,vars] = find(model.deppattern(vars,:));\n        vars = unique(vars);\n        s = size(jacobianstructure,1);\n        for j = 1:length(vars)            \n            jacobianstructure(i,find(vars(j) == model.linearindicies)) = 1; \n        end      \n    end\n    allA=[model.A; model.Aeq];\n    depends = allA | allA;\n    jacobianstructure = [jacobianstructure;depends];\n    \n    Z = sparse(jacobianstructure);\n    funcs.jacobianstructure = @() Z;\nend\n\nif ~model.options.usex0\n    model.x0 = (options.lb+options.ub)/2;\n    model.x0(isinf(options.ub)) = options.lb(isinf(options.ub))+1;\n    model.x0(isinf(options.lb)) = options.ub(isinf(options.lb))-1;\n    model.x0(isinf(model.x0)) = 0;\nend\n\nif ~isempty(model.binary_variables) | ~isempty(model.integer_variables)\n    options.var_type = zeros(length(model.linearindicies),1);\n    options.var_type(model.binary_variables) = -1;\n    options.var_type(model.integer_variables) = 1;\nend\n\nshowprogress('Calling BONMIN',model.options.showprogress);\nsolvertime = tic;\n[xout,info] = bonmin(model.x0,funcs,options);\nsolvertime = toc(solvertime);\n\nx = RecoverNonlinearSolverSolution(model,xout);\n\nswitch info.status\n    case {0,2}\n        problem = 0;\n    case 1\n        problem = 1;\n    case {-1}\n        problem = 3;\n    case {3}\n        problem = 15;\n    otherwise\n        problem = -1;\nend\n\n% Duals currently not supported\nD_struc = [];\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n    solverinput.x0 = model.x0;\n    solverinput.model = model;\n    solverinput.options = options;\nelse\n    solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n    solveroutput.x = xout;  \n    solveroutput.info = info;\nelse\n    solveroutput = [];\nend\n\n% Standard interface\noutput = createoutput(x,D_struc,[],problem,'BONMIN',solverinput,solveroutput,solvertime);\n\n\n% Code supplied by Jonatan Currie\nfunction opts = removeDefaults(opts,defs)\noFn = fieldnames(opts);\nfor i = 1:length(oFn)\n    label = oFn{i};\n    if(isfield(defs,label))\n        if(ischar(opts.(label)))\n            if(strcmpi(defs.(label),opts.(label)))\n                opts = rmfield(opts,label);\n            end\n        else\n            if(defs.(label) == opts.(label))\n                opts = rmfield(opts,label);\n            end\n        end\n    end\nend\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/callbonmin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2201525326310721}}
{"text": "function specific_vortal_plots(up)\n\nsave_name = up.paths.filenames.hr_rr_scatter;\nsavepath = [up.paths.plots_save_folder, up.paths.filenames.hr_rr_scatter, '.eps'];\nif ~up.analysis.redo_stats\n    exist_log = check_exists(savepath, save_name);\n    if exist_log\n        return\n    end\nend\n\n%% Make plot of feature vs filter resp sigs\nif ~isempty(strfind(up.paths.paper_figures_folder, 'pc13')) & ...\n        isempty(strfind(up.paths.data_save_folder, 'REC')) & isempty(strfind(up.paths.data_save_folder, 'WALK')) ...\n        & isempty(strfind(up.paths.data_save_folder, 'EX'))\n    % Load resp sigs\n    subj = 2;\n    load_path = [strrep(up.paths.data_save_folder, 'rest_and_rec', 'rest'), num2str(subj), up.paths.filenames.respSigs];\n    resp_sigs = load(load_path);\n    if sum(strcmp(fieldnames(resp_sigs), 'ppg_flt_Wam'))\n        % Load raw sig\n        load_path = [up.paths.data_save_folder, num2str(subj), up.paths.filenames.int_respSigs];\n        int_resp_sigs = load(load_path);\n        % Load annotated breaths\n        up.paths.root_ann_folder = 'C:\\Documents\\Data\\VORTAL\\Manual_breath_annotations\\';\n        up.paths.observers = {'TB', 'DV'};\n        up.paths.ann_folder = '_annotations\\';\n        obs_no = 1;\n        data_folder = [up.paths.root_ann_folder, up.paths.observers{obs_no}, up.paths.ann_folder];\n        % find SID\n        temp = num2str(subj);\n        if length(temp) == 1\n            SID = ['00', temp];\n        elseif length(temp) == 2\n            SID = ['0', temp];\n        end\n        % Load annotated breaths\n        rel_name = ['VORTAL' SID 'rest' up.paths.observers{obs_no} '-paw_an'];\n        anns = load([data_folder, rel_name]); t = anns.PKS.t;\n        % Load s ref time\n        up.paths.s_ref_time_folder = 'C:\\Documents\\Data\\VORTAL\\Analysis_files\\Processed_Data\\';\n        loadpath = [up.paths.s_ref_time_folder, SID, 's_con_rest'];\n        load(loadpath, 'Sreftime', 'Send', 'Sstart');\n        load(up.paths.db_data, 'db_data');\n        bst_time = db_data.bst_log(db_data.sid == subj)/(24);\n        % find t, measured in seconds since the start of the period\n        t = 60*60*24*(t/(60*60*24) - floor( t/(60*60*24) ) - Sreftime + bst_time) - Sstart; % As the times are in seconds since 1970\n        % Identify relevant section\n        start_t = 92;\n        rel_t = [start_t, start_t+up.paramSet.winLeng];\n        rel_feat = int_resp_sigs.ppg_FMeam_FPt_PDtIMS_EHF;\n        rel_filt = resp_sigs.ppg_flt_Wam;\n        rel_sig = int_resp_sigs.ppg_EHF;\n        rel_els = rel_feat.t >= rel_t(1) & rel_feat.t <= rel_t(2);\n        rel_data.feat.t = rel_feat.t(rel_els);\n        rel_data.feat.v = rel_feat.v(rel_els);\n        rel_els = rel_filt.t >= rel_t(1) & rel_filt.t <= rel_t(2);\n        rel_data.filt.t = rel_filt.t(rel_els);\n        rel_data.filt.v = rel_filt.v(rel_els);\n        rel_els = rel_sig.t >= rel_t(1) & rel_sig.t <= rel_t(2);\n        rel_data.sig.t = rel_sig.t(rel_els);\n        rel_data.sig.v = rel_sig.v(rel_els);\n        \n        % Make Figure\n        h_fig = figure('Position', [200, 200, 600, 300]);\n        \n        % Plot\n        ftsize = 12; lwidth = 2;\n        h1 = plot(rel_data.sig.t-rel_t(1), detrend(rel_data.sig.v), 'b', 'LineWidth',1);\n        hold on\n        plot(rel_data.filt.t-rel_t(1), detrend(rel_data.filt.v), 'k', 'LineWidth',lwidth+2)\n        h2 = plot(rel_data.filt.t-rel_t(1), detrend(rel_data.filt.v), 'c', 'LineWidth',lwidth);\n        h3 = plot(rel_data.feat.t-rel_t(1), detrend(rel_data.feat.v), '-r', 'LineWidth',lwidth);\n        h4 = plot(t-start_t, -0.05+zeros(length(t),1), '.k','MarkerSize',30);\n        plot(rel_data.feat.t-rel_t(1), detrend(rel_data.feat.v), '.r', 'LineWidth',lwidth,'MarkerSize',20)\n        xlim(rel_t-rel_t(1))\n        temp = range(rel_data.sig.v);\n        ylim([min(rel_data.sig.v)-0.05*temp, max(rel_data.sig.v)+0.05*temp])\n        xlabel('Time [s]', 'FontSize', ftsize)\n        ylabel('PPG', 'FontSize', ftsize)\n        legend([h1, h2, h3, h4], {'PPG', 'Filter', 'Feature', 'Breaths'},'Location','northoutside','Orientation','horizontal')\n        set(gca, 'FontSize', ftsize)\n        set(gca, 'YTick', [])\n        % Save\n        set(gcf,'PaperUnits','inches');\n        set(gcf,'PaperSize', [6, 3]);\n        set(gcf,'PaperPosition',[0 0 6 3]);\n        save_name = up.paths.filenames.feat_filt_plot;\n        savepath = [up.paths.plots_save_folder, save_name];\n        print(h_fig,'-depsc',savepath)\n        close all\n    end\nend\n\n\nif strfind(up.paths.data_save_folder, 'REST_AND_REC_TEMP')\n    %% Create plot of improved precision with no of windows\n    fprintf('\\n--- Plot of improvement in precision with no of windows ');\n    \n    %% Load alg names\n    load_name = up.paths.filenames.alg_names;\n    loadpath = [up.paths.data_save_folder, up.paths.filenames.alg_names, '.mat'];\n    load(loadpath, load_name);\n    \n    %% Load BA data\n    load_name = 'BA_results';\n    loadpath = [up.paths.data_save_folder, up.paths.filenames.global_BA, '.mat'];\n    load(loadpath, load_name);\n    rel_BA_res = BA_results.young;\n    \n    rel_els = find(strcmp(alg_names.sigs, 'ECG'));\n    no_wins = alg_names.no_wins(rel_els);\n    rel_prec = rel_BA_res.prec.val(rel_els);\n    \n    % Make Figure\n    h_fig = figure('Position', [200, 200, 600, 300]);\n    \n    % Plot\n    ftsize = 12; lwidth = 2;\n    f2 = fit(no_wins,rel_prec,'exp2');\n    coeffs = coeffvalues(f2);\n    fitexp = ( coeffs(1)*exp(coeffs(2)*no_wins) ) + ( coeffs(3)*exp(coeffs(4)*no_wins) );\n    plot(no_wins,rel_prec, 'mx', 'LineWidth',lwidth,'MarkerEdgeColor','k','MarkerFaceColor','k',...\n        'MarkerSize',10)\n    hold on\n    plot(no_wins, fitexp, 'r', 'LineWidth', lwidth)\n    ylim([8 12])\n    xlim([1 max(no_wins)])\n    xlabel('Number of windows used to estimate RR', 'FontSize', ftsize)\n    ylabel('LOA interval [bpm]', 'FontSize', ftsize)\n    set(gca, 'FontSize', ftsize)\n    set(gca, 'YTick', 8:12)\n    set(gcf,'PaperUnits','inches');\n    set(gcf,'PaperSize', [6, 3]);\n    set(gcf,'PaperPosition',[0 0 6 3]);\n    save_name = up.paths.filenames.temp_prec_plot;\n    savepath = [up.paths.plots_save_folder, save_name];\n    print(h_fig,'-depsc',savepath)\n    close all\nend\n\nfprintf('\\n--- Making B-A Plots ');\n\n%% Load data from entire study\nload_name = up.paths.filenames.win_data;\nloadpath = [up.paths.data_save_folder, up.paths.filenames.win_data, '.mat'];\nload(loadpath, load_name);\n\n%% Load algorithms names\nload_name = up.paths.filenames.alg_names;\nloadpath = [up.paths.data_save_folder, up.paths.filenames.alg_names, '.mat'];\nload(loadpath, load_name);\n\n%% Load relevant algorithm els\nload_name = 'vortal_results';\nloadpath = [up.paths.data_save_folder, up.paths.filenames.vortal_results, '.mat'];\nload(loadpath, load_name);\n\n%% Identify the most precise algorithm(s) to make plots for\nno_plots_per_sig = 1;\nfor sig = {'ekg', 'ppg'}\n    eval([sig{1,1}, '_els = vortal_results.top_ten.' sig{1,1}, '.alg_nos(1:no_plots_per_sig);']);\n    eval([sig{1,1}, '_bias = vortal_results.top_ten.' sig{1,1}, '.bias.val(1:no_plots_per_sig);']);\n    eval([sig{1,1}, '_lloa = vortal_results.top_ten.' sig{1,1}, '.lloa.val(1:no_plots_per_sig);']);\n    eval([sig{1,1}, '_uloa = vortal_results.top_ten.' sig{1,1}, '.uloa.val(1:no_plots_per_sig);']);\nend\n\nrel_els = [ekg_els(:); ppg_els(:)];\nrel_bias = [ekg_bias(:); ppg_bias(:)];\nrel_lloa = [ekg_lloa(:); ppg_lloa(:)];\nrel_uloa = [ekg_uloa(:); ppg_uloa(:)];\n\nrel_names = alg_names.names(rel_els);\nrel_sigs = alg_names.sigs(rel_els);\n\n%% Generate plots for each algorithm\nfor rel_el_no = 1 : length(rel_els)\n    \n    alg_no = rel_els(rel_el_no);\n    \n    % identify data for this algorithm\n    curr_els = win_data.alg_no == alg_no & win_data.snr_log;\n    curr_est = win_data.est(curr_els);\n    curr_ref = win_data.ref(curr_els);\n    curr_bias = rel_bias(rel_el_no);\n    curr_lloa = rel_lloa(rel_el_no);\n    curr_uloa = rel_uloa(rel_el_no);\n    curr_data.ave = nanmean([curr_est(:), curr_ref(:)],2);\n    curr_data.error = [curr_est(:) - curr_ref(:)];\n    \n    % setup figure\n    ftsize = 13;\n    min_ave_val = 0;            % xlims\n    max_ave_val = 36;\n    min_error_val = -10;        % ylims\n    max_error_val = 10;\n    x_edge_int = 0.2;           % resolution of BA plot\n    y_edge_int = 0.2;\n    edges1 = [min_ave_val : x_edge_int : max_ave_val];       % locations of individual pixels\n    edges2 = [min_error_val : y_edge_int : max_error_val];\n    \n    % Make color plot\n    h_fig = figure('Position', [200 200 700 350]);\n    A2=hist3([curr_data.ave,curr_data.error],'Edges',{edges1 edges2});\n    h = fspecial('gaussian', [10 10], 2);\n    y = filter2(h, A2');\n    y = y./(max(max(y)));\n    imagesc(y),\n    c_han = colorbar;\n    set(c_han,'YTickMode','manual')\n    set(c_han, 'YTick',[0,1], 'YTickLabel', {'Min','Max'})\n    \n    % mymap = repmat(-1*[-1:0.01:0]', 1,3); colormap(mymap)\n    hold on\n    \n    % X Ticks\n    x_tick_int = 10/x_edge_int;\n    x_label_int = (edges1(end)-edges1(1))*x_tick_int/length(edges1);\n    xlims = xlim;\n    edges1_labels = round( edges1(1) : x_label_int : edges1(end) )';\n    \n    x_spec.axis_lims = xlims;\n    x_spec.real_lims = [edges1(1), edges1(end)];\n    edges1_ticks = convert_real_to_axis_units(edges1_labels, x_spec);\n    \n    current_top_of_x_axis = xlims(1) + (0.5*(edges1(2)-edges1(1)));\n    % adjust = - current_top_of_x_axis;\n    set(gca, 'XTick', edges1_ticks, 'XTickLabel', num2str(edges1_labels))\n    \n    % Y Ticks\n    y_tick_int = 10/y_edge_int;\n    y_label_int = (edges2(end)-edges2(1))*y_tick_int/length(edges2);\n    ylims = ylim;\n    edges2_labels = round( edges2(1) : y_label_int : edges2(end) )';\n    \n    y_spec.axis_lims = ylims;\n    y_spec.real_lims = [edges2(1), edges2(end)];\n    edges2_ticks = convert_real_to_axis_units(edges2_labels, y_spec);\n    \n    current_top_of_y_axis = ylims(1) - (0.5*(edges2(2)-edges2(1)));\n    %adjust = - current_top_of_y_axis;\n    set(gca, 'YTick', edges2_ticks, 'YTickLabel', num2str(edges2_labels))\n    \n    % Axis Labels\n    \n    xlabel('Mean: 0.5(RR^{est} + RR^{ref}),  bpm', 'FontSize', ftsize);\n    ylabel('Difference:  (RR^{est} - RR^{ref}),  bpm', 'FontSize', ftsize);\n    \n    % Bias and LOA Labels\n    \n    % xlim([min_ave_val, max_ave_val]), ylim([min_error_val, max_error_val])\n    %xlims = xlim;\n    %bias_adj = BA_data.bias + adjust;\n    %loa_adj = [BA_data.lloa, BA_data.uloa] + adjust;\n    axis_bias = convert_real_to_axis_units(curr_bias, y_spec);\n    axis_lloa = convert_real_to_axis_units(curr_lloa, y_spec);\n    axis_uloa = convert_real_to_axis_units(curr_uloa, y_spec);\n    plot(xlims, [axis_bias, axis_bias], 'r')\n    plot(xlims, [axis_lloa, axis_lloa], '--r')\n    plot(xlims, [axis_uloa, axis_uloa], '--r')\n    text(mean(xlims),0.5*axis_lloa,['Lower LOA = ' num2str(curr_lloa,2)],'HorizontalAlignment','center','BackgroundColor',[1 1 1], 'FontSize', ftsize);\n    text(mean(xlims),1.2*axis_uloa,['Upper LOA = ' num2str(curr_uloa,2)],'HorizontalAlignment','center','BackgroundColor',[1 1 1], 'FontSize', ftsize);\n    text(xlims(2),0.8*axis_bias,['Bias = ' num2str(curr_bias,2)],'HorizontalAlignment','right','BackgroundColor',[1 1 1], 'FontSize', ftsize);\n    set(gca, 'FontSize', ftsize)\n    \n    set(gcf,'PaperUnits','inches');\n    set(gcf,'PaperSize', [6, 3]);\n    set(gcf,'PaperPosition',[0 0 6 3]);\n    save_name = ['BA_' rel_sigs{rel_el_no}, rel_names{rel_el_no}];\n    savepath = [up.paths.plots_save_folder, save_name];\n    print(h_fig,'-depsc',savepath)\n    close all\n    \nend\n\n\n% %% CDF of abs errors plot\n% fprintf('\\n--- Making CDF Error Plot');\n% \n% % Load data (Best alg)\n% load_name = up.paths.filenames.win_data;\n% loadpath = [up.paths.data_save_folder, up.paths.filenames.win_data, '.mat'];\n% load(loadpath, load_name);\n% good_els = win_data.sqi & win_data.snr_log & win_data.alg_no == 203 & ~isnan(win_data.est);\n% alg.est = win_data.est(good_els);\n% alg.ref = win_data.ref(good_els);\n% alg.error = alg.est - alg.ref;\n% \n% % Load data (Moderate alg)\n% load_name = up.paths.filenames.win_data;\n% loadpath = [up.paths.data_save_folder, up.paths.filenames.win_data, '.mat'];\n% load(loadpath, load_name);\n% good_els = win_data.sqi & win_data.snr_log & win_data.alg_no == 281 & ~isnan(win_data.est);\n% mod_alg.est = win_data.est(good_els);\n% mod_alg.ref = win_data.ref(good_els);\n% mod_alg.error = mod_alg.est - mod_alg.ref;\n% \n% % Load data (Imp)\n% load_name = up.paths.filenames.win_data;\n% loadpath = [up.paths.data_save_folder, up.paths.filenames.win_data_imp, '.mat'];\n% load(loadpath, load_name);\n% good_els = win_data.sqi & win_data.snr_log & ~isnan(win_data.est) & ~isnan(win_data.est);\n% imp.est = win_data.est(good_els);\n% imp.ref = win_data.ref(good_els);\n% imp.error = imp.est - imp.ref;\n% \n% % Normal data\n% norm.error = normrnd(0,2.5,1,1000);\n% \n% % Make Figure\n% ftsize = 12;\n% h_fig = figure('Position', [200, 200, 1200, 550]);\n% plot(sort(abs(alg.error)),linspace(0,1,length(alg.error))), hold on\n% plot(sort(abs(imp.error)),linspace(0,1,length(imp.error)))\n% plot(sort(abs(norm.error)),linspace(0,1,length(norm.error)))\n% plot(sort(abs(mod_alg.error)),linspace(0,1,length(mod_alg.error)))\n% title('Empirical CDF', 'FontSize', ftsize)\n% xlabel('Absolute difference (bpm)', 'FontSize', ftsize)\n% ylabel('F(x)', 'FontSize', ftsize)\n% xlim([0 40])\n% set(gca, 'XTick', [0:10, 15:5:40], 'YTick', [0:0.1:0.9, 0.95, 1.0], 'XTickLabel', {'0','','','','','5','','','','','10','15', '20', '25', '30', '35', '40'});\n% legend({'a203', 'impedance', 'normal distribution', 'a281'}, 'Location', 'Best')\n% grid on\n% \n% set(gca, 'FontSize', ftsize)\n% save_name = 'Errors CDF';\n% savepath = [up.paths.plots_save_folder, save_name];\n% savefig(h_fig,savepath)\n% close all\n\n\nfprintf('\\n--- Making HR / RR Scatter Plot');\n\n%% Load data from entire study\nload_name = up.paths.filenames.win_data;\nloadpath = [up.paths.data_save_folder, up.paths.filenames.win_data, '.mat'];\nload(loadpath, load_name);\nhr = win_data.hr(win_data.comb_log & win_data.ecg_log & win_data.young_log & win_data.alg_no == 1);\nrr = win_data.ref(win_data.comb_log & win_data.ecg_log & win_data.young_log & win_data.alg_no == 1);\n\n% Make Figure\nh_fig = figure('Position', [200, 200, 900, 400]);\n\n% Plot Histograms\n[counts,centers] = hist(rr,20); hold on\ncounts = counts/max(counts);\nscale = 40;\nbar(centers,scale*counts, 'c')\n[counts,centers] = hist(hr,20);\ncounts = counts/max(counts);\nscale = 5;\nbarh(centers,scale*counts, 'c')\nrr_new = rr; hr_new = hr;\n\nftsize = 14;\nplot(rr_new,hr_new, 'xk')\nxlabel('Respiratory Rate [bpm]', 'FontSize', ftsize)\nylabel('Heart Rate [beats per minute]', 'FontSize', ftsize)\nset(gca, 'FontSize', ftsize)\nset(gca, 'YTick', 0:20:150)\nset(gcf,'PaperUnits','inches');\nset(gcf,'PaperSize', [9, 4]);\nset(gcf,'PaperPosition',[0 0 9 4]);\nsave_name = up.paths.filenames.hr_rr_scatter;\nsavepath = [up.paths.plots_save_folder, save_name];\nprint(h_fig,'-depsc',savepath)\nclose all\n\n%% Precision and prop of algs using filter / feature\n\nfprintf('\\n--- Making Prop of algs, filt/feat plot');\n\nfor plot_type = {'est_techs', 'sigs', 'comps'}\n    % Load BA data for algs\n    if ~strcmp(up.paths.root_data_folder, 'C:\\Documents\\Data\\VORTAL_REST_AND_REC\\')\n        loadpath = [up.paths.data_save_folder, up.paths.filenames.global_BA, '.mat'];\n        load(loadpath);\n        rel_res = BA_results.young.prec;\n        [~, orders] = sort(rel_res.val);\n        rel_res.val = rel_res.val(orders); rel_res.val = rel_res.val(:)';\n        rel_res.uci = rel_res.uci(orders); rel_res.uci = rel_res.uci(:)';\n        rel_res.lci = rel_res.lci(orders); rel_res.lci = rel_res.lci(:)';\n        if strcmp(plot_type{1,1}, 'est_techs')\n            rel_els = alg_names.meths.ef(orders)>0;\n            rel_res.pos_label = 'Frequency';\n            rel_res.neg_label = 'Time';\n        elseif strcmp(plot_type{1,1}, 'sigs')\n            rel_els = strcmp(alg_names.sigs(orders), 'ECG');\n            rel_res.pos_label = 'ECG';\n            rel_res.neg_label = 'PPG';\n        elseif strcmp(plot_type{1,1}, 'comps')\n            rel_res.label1 = 'None';\n            rel_res.label2 = 'X_{A1}';\n            rel_res.label3 = 'X_{A4}';\n            rel_res.label4 = 'E_{F3}';\n            rel_els1 = alg_names.meths.xa~= 1 & alg_names.meths.xa~= 4 & alg_names.meths.ef~= 3;\n            rel_els2 = alg_names.meths.xa== 1;\n            rel_els3 = alg_names.meths.xa== 4;\n            rel_els4 = alg_names.meths.ef== 3;\n        end\n        \n    else\n        loadpath = 'C:\\Users\\pc13\\Dropbox\\VORTAL\\VORTAL_theoret_lims_yhvs\\2016_Jan_Submission_to_Phys_Meas\\Data\\Complete_results_table.csv';\n        [num, txt, raw] = xlsread(loadpath);\n        headers = raw(1,:);\n        % Eliminate IP\n        rel_col = find(strcmp(headers, 'Signal'));\n        bad_row = find(strcmp(raw(:,rel_col),'IP'));\n        raw = raw([1:(bad_row-1), (bad_row+1):length(raw(:,1))], :);\n        % Eliminate ones which had a problem with the random effects model (failed to converge)\n        rel_col = find(strcmp(headers, 'Problems with Random Effects Model'));\n        good_rows = ismember(raw(:,rel_col),'.'); good_rows(1) = 1;\n        raw = raw(good_rows,:);\n        % Extract relevant data\n        rel_col = find(strcmp(headers, 'Overall Rank'));\n        ranks = cell2mat(raw(2:end, rel_col));\n        [~, rel_res.order] = sort(ranks);\n        rel_col = find(strcmp(headers, 'Signal'));\n        rel_res.sigs = raw(2:end, rel_col);\n        rel_col = find(strcmp(headers, 'Algorithm'));\n        rel_res.algs = raw(2:end, rel_col);\n        rel_col = find(strcmp(headers, '2SD [bpm]'));\n        rel_res.val = cell2mat(raw(2:end, rel_col));\n        if strcmp(plot_type{1,1}, 'est_techs')\n            rel_els = strfind(rel_res.algs, 'Ef');\n            rel_els = not(cellfun('isempty', rel_els));\n            rel_res.pos_label = 'Frequency';\n            rel_res.neg_label = 'Time';\n        elseif strcmp(plot_type{1,1}, 'sigs')\n            rel_els = strcmp(rel_res.sigs(rel_res.order), 'ECG');\n            rel_res.pos_label = 'ECG';\n            rel_res.neg_label = 'PPG';\n        elseif strcmp(plot_type{1,1}, 'comps')\n            rel_res.label1 = 'None';\n            rel_res.label2 = 'X_{A1}';\n            rel_res.label3 = 'X_{A4}';\n            rel_res.label4 = 'E_{F4}';\n            temp = strfind(rel_res.algs, 'Xa1'); rel_els2 = ~cellfun(@isempty,temp);\n            temp = strfind(rel_res.algs, 'Xa4'); rel_els3 = ~cellfun(@isempty,temp);\n            temp = strfind(rel_res.algs, 'Ef4'); rel_els4 = ~cellfun(@isempty,temp);\n            rel_els1 = ~rel_els2 & ~rel_els3 & ~rel_els4;\n        end\n        \n    end\n    orank = 1 : length(rel_res.val); orank = orank(:)';\n    \n    % data for hist\n    tot = length(orank)+1;\n    if strcmp(plot_type{1,1}, 'comps')\n        bin_width = (tot/5);\n    else\n        bin_width = (tot/5);\n    end\n    bin_ends = 0:bin_width:tot;\n    bin_starts = bin_ends(1:(end-1))+1;\n    bin_ends = bin_ends(2:end);\n    bin_mids = mean([bin_starts(:)'; bin_ends(:)']);\n    clear prop*\n    if ~strcmp(plot_type{1,1}, 'comps')\n        for bin_no = 1 : length(bin_starts)\n            prop1(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n        end\n        prop2 = 100 - prop1;\n        y_vals = [prop1; prop2];\n    else\n        for bin_no = 1 : length(bin_starts)\n            prop1(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els1(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n            prop2(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els2(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n            prop3(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els3(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n            prop4(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els4(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n        end\n        y_vals = [prop1; prop2; prop3; prop4];\n    end\n    \n    % setup fig\n    h_fig = figure('Position', [200 200 900 550]);\n    fontsize = 16;\n    \n    % upper plot\n    xlims = [min(orank), max(orank)];\n    if xlims(2) == 439\n        xlims(2) = 440;\n    end\n    ylims = [0 50];\n    h_prec = subplot(2,1,1, 'Position', [0.2 0.61 0.76 0.38]); hold on\n    % fill([orank, fliplr(orank)], [rel_res.lci(:)', fliplr(rel_res.uci(:)')], 0.5*[1,1,1]);\n    % hold on,\n    plot(orank, rel_res.val, 'k', 'LineWidth', 3),\n    ylab = ylabel({'2SD', '[bpm]'}, 'FontSize', fontsize, 'Rotation', 0);\n    set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.3, 0]);\n    xlim(xlims)\n    ylim(ylims)\n    set(gca, 'XTick', [1, 50:50:tot, tot]);\n    xlabel('Overall Rank', 'FontSize', fontsize)\n    \n    % lower plot (stacked bar)\n    h_bar = subplot(2,1,2, 'Position', [0.2 0.10 0.76 0.38]); hold on\n    h_bars = bar(bin_mids, y_vals', 'stacked');\n    h_bars(1).FaceColor = 0.1*[1,1,1];\n    h_bars(2).FaceColor = 0.5*[1,1,1];\n    xlim(xlims),\n    if ~strcmp(plot_type{1,1}, 'comps')\n        ylim([0 100])\n    else\n        ylim([0 120])\n    end\n    if strcmp(plot_type{1,1}, 'est_techs')\n        ylabel({'% using Frequency- and', 'Time-domain RR estimation'}, 'FontSize', fontsize)\n    elseif strcmp(plot_type{1,1}, 'sigs')\n        ylabel('% using ECG and PPG', 'FontSize', fontsize)\n    elseif strcmp(plot_type{1,1}, 'comps')\n        ylab = ylabel({'% using X_{A1},', 'X_{A4}, E_{F4}, or', 'none of these'}, 'FontSize', fontsize, 'Rotation', 0);\n        set(ylab, 'Units', 'Normalized', 'Position', [-0.16, 0.33, 0]);\n    end\n    xlabel('Overall Rank', 'FontSize', fontsize)\n    starts = strread(num2str(ceil(bin_starts)),'%s');\n    mids = strread(num2str(ceil(bin_mids)),'%s');\n    ends = strread(num2str(ceil(bin_ends)),'%s');\n    quintiles = strread(num2str(1:length(bin_ends)),'%s');\n    for s = 1 : length(ends)\n        xtickstr{s} = [starts{s} ' - ' ends{s}];\n        %xtickstr{s} = [quintiles{s}, ' (' starts{s} ' - ' ends{s} ')'];\n    end\n    set(h_bar, 'XTick', bin_mids, 'XTickLabel', xtickstr)\n    \n    allAxesInFigure = findall(h_fig,'type','axes');\n    set(allAxesInFigure, 'Fontsize', fontsize-4, 'xgrid','on')\n    \n    % annotate\n    if ~strcmp(plot_type{1,1}, 'comps')\n        text(bin_mids(5),15, rel_res.pos_label, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n        text(bin_mids(5),87, rel_res.neg_label, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    else\n        text(bin_mids(1),50, rel_res.label1, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n        text(bin_mids(5),22, rel_res.label2, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n        text(bin_mids(5),62, rel_res.label3, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n        text(bin_mids(5),95, rel_res.label4, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    end\n    \n    % add (a) and (b)\n    dim = [.01 .91 .1 .1]; str = '(a)';\n    annotation('textbox',dim,'String',str,'FitBoxToText','on','FontSize',fontsize,'LineStyle','none');\n    dim = [.01 .43 .1 .1]; str = '(b)';\n    annotation('textbox',dim,'String',str,'FitBoxToText','on','FontSize',fontsize,'LineStyle','none');\n    \n    set(gcf,'color','w');\n    \n    set(gcf,'PaperUnits','inches');\n    set(gcf,'PaperSize', [9, 5.5]);\n    set(gcf,'PaperPosition',[0 0 9 5.5]);\n    save_name = [up.paths.filenames.stacked_bar, '_', plot_type{1,1}];\n    savepath = [up.paths.plots_save_folder, save_name];\n    print(h_fig,'-depsc',savepath)\n    \n    close all\n    \nend\n\n%% New joint stacked bar plot\n\nplot_type = {'comps_est_techs'};\n% Load BA data for algs\nif strcmp(up.paths.root_data_folder, 'C:\\Documents\\Data\\VORTAL_REST_AND_REC\\')\n    loadpath = 'C:\\Users\\pc13\\Dropbox\\VORTAL\\VORTAL_theoret_lims_yhvs\\2016_Jan_Submission_to_Phys_Meas\\Data\\Complete_results_table.csv';\n    [num, txt, raw] = xlsread(loadpath);\n    headers = raw(1,:);\n    % Eliminate IP\n    rel_col = find(strcmp(headers, 'Signal'));\n    bad_row = find(strcmp(raw(:,rel_col),'IP'));\n    raw = raw([1:(bad_row-1), (bad_row+1):length(raw(:,1))], :);\n    % Eliminate ones which had a problem with the random effects model (failed to converge)\n    rel_col = find(strcmp(headers, 'Problems with Random Effects Model'));\n    good_rows = ismember(raw(:,rel_col),'.'); good_rows(1) = 1;\n    raw = raw(good_rows,:);\n    % Extract relevant data\n    rel_col = find(strcmp(headers, 'Overall Rank'));\n    ranks = cell2mat(raw(2:end, rel_col));\n    [~, rel_res.order] = sort(ranks);\n    rel_col = find(strcmp(headers, 'Signal'));\n    rel_res.sigs = raw(2:end, rel_col);\n    rel_col = find(strcmp(headers, 'Algorithm'));\n    rel_res.algs = raw(2:end, rel_col);\n    rel_col = find(strcmp(headers, '2SD [bpm]'));\n    rel_res.val = cell2mat(raw(2:end, rel_col));\n    rel_els = strfind(rel_res.algs, 'Ef');\n    rel_els = not(cellfun('isempty', rel_els));\n    rel_res.pos_label = 'Frequency';\n    rel_res.neg_label = 'Time';\n    rel_res.label1 = 'None';\n    rel_res.label2 = 'X_{A1}';\n    rel_res.label3 = 'X_{A4}';\n    rel_res.label4 = 'E_{F4}';\n    temp = strfind(rel_res.algs, 'Xa1'); rel_els2 = ~cellfun(@isempty,temp);\n    temp = strfind(rel_res.algs, 'Xa4'); rel_els3 = ~cellfun(@isempty,temp);\n    temp = strfind(rel_res.algs, 'Ef4'); rel_els4 = ~cellfun(@isempty,temp);\n    rel_els1 = ~rel_els2 & ~rel_els3 & ~rel_els4;\n    orank = 1 : length(rel_res.val); orank = orank(:)';\n    \n    % Create first histogram\n    tot = length(orank)+1;\n    if strcmp(plot_type{1,1}, 'comps')\n        bin_width = (tot/5);\n    else\n        bin_width = (tot/5);\n    end\n    bin_ends = 0:bin_width:tot;\n    bin_starts = bin_ends(1:(end-1))+1;\n    bin_ends = bin_ends(2:end);\n    bin_mids = mean([bin_starts(:)'; bin_ends(:)']);\n    clear prop*\n    for bin_no = 1 : length(bin_starts)\n        prop1(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els1(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n        prop2(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els2(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n        prop3(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els3(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n        prop4(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els4(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n    end\n    y_vals = [prop1; prop2; prop3; prop4];\n    \n    % setup fig\n    h_fig = figure('Position', [200 200 900 800]);\n    fontsize = 16;\n    \n    % upper plot\n    xlims = [min(orank), max(orank)];\n    if xlims(2) == 439\n        xlims(2) = 440;\n    end\n    ylims = [0 50];\n    h_prec = subplot(3,1,1, 'Position', [0.2 0.74 0.76 0.25]); hold on\n    plot(orank, rel_res.val, 'k', 'LineWidth', 3),\n    ylab = ylabel({'2SD', '[bpm]'}, 'FontSize', fontsize, 'Rotation', 0);\n    set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.3, 0]);\n    xlim(xlims)\n    ylim(ylims)\n    set(gca, 'XTick', [1, 50:50:tot, tot]);\n    xlabel('Overall Rank', 'FontSize', fontsize)\n    \n    % mid plot (stacked bar)\n    h_bar = subplot(3,1,2, 'Position', [0.2 0.41 0.76 0.25]); hold on\n    h_bars = bar(bin_mids, y_vals', 'stacked');\n    h_bars(1).FaceColor = 0.1*[1,1,1];\n    h_bars(2).FaceColor = 0.5*[1,1,1];\n    xlim(xlims),\n    ylim([0 120])\n    ylab = ylabel({'% using X_{A1},', 'X_{A4}, E_{F4}, or', 'none of these'}, 'FontSize', fontsize, 'Rotation', 0);\n    set(ylab, 'Units', 'Normalized', 'Position', [-0.16, 0.33, 0]);\n    xlabel('Overall Rank', 'FontSize', fontsize)\n    starts = strread(num2str(ceil(bin_starts)),'%s');\n    mids = strread(num2str(ceil(bin_mids)),'%s');\n    ends = strread(num2str(ceil(bin_ends)),'%s');\n    quintiles = strread(num2str(1:length(bin_ends)),'%s');\n    for s = 1 : length(ends)\n        xtickstr{s} = [starts{s} ' - ' ends{s}];\n    end\n    set(h_bar, 'XTick', bin_mids, 'XTickLabel', xtickstr)\n    % annotate\n    text(bin_mids(1),50, rel_res.label1, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    text(bin_mids(5),25, rel_res.label2, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    text(bin_mids(5),65, rel_res.label3, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    text(bin_mids(5),96, rel_res.label4, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    \n    % lower plot (stacked bar)\n    for bin_no = 1 : length(bin_starts)\n        prop1(bin_no) = 100*sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no) & rel_els(:))/sum(orank(:)>= bin_starts(bin_no) & orank(:)< bin_ends(bin_no));\n    end\n    prop2 = 100 - prop1;\n    y_vals = [prop1; prop2];\n    h_bar = subplot(3,1,3, 'Position', [0.2 0.08 0.76 0.25]); hold on\n    h_bars = bar(bin_mids, y_vals', 'stacked');\n    h_bars(1).FaceColor = 0.1*[1,1,1];\n    h_bars(2).FaceColor = 0.5*[1,1,1];\n    xlim(xlims),\n    ylim([0 100])\n    ylab = ylabel({'% using', 'Frequency- or', 'Time-domain', 'RR estimation'}, 'FontSize', fontsize, 'Rotation', 0);\n    set(ylab, 'Units', 'Normalized', 'Position', [-0.16, 0.28, 0]);\n    xlabel('Overall Rank', 'FontSize', fontsize)\n    starts = strread(num2str(ceil(bin_starts)),'%s');\n    mids = strread(num2str(ceil(bin_mids)),'%s');\n    ends = strread(num2str(ceil(bin_ends)),'%s');\n    quintiles = strread(num2str(1:length(bin_ends)),'%s');\n    for s = 1 : length(ends)\n        xtickstr{s} = [starts{s} ' - ' ends{s}];\n    end\n    set(h_bar, 'XTick', bin_mids, 'XTickLabel', xtickstr)\n    % annotate\n    text(bin_mids(5),15, rel_res.pos_label, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    text(bin_mids(5),87, rel_res.neg_label, 'HorizontalAlignment', 'Center', 'FontSize', fontsize-4, 'Backgroundcolor', 'w')\n    \n    % add (a) and (b) and (c)\n    dim = [.01 .91 .1 .1]; str = '(a)';\n    annotation('textbox',dim,'String',str,'FitBoxToText','on','FontSize',fontsize,'LineStyle','none');\n    dim = [.01 .58 .1 .1]; str = '(b)';\n    annotation('textbox',dim,'String',str,'FitBoxToText','on','FontSize',fontsize,'LineStyle','none');\n    dim = [.01 .25 .1 .1]; str = '(c)';\n    annotation('textbox',dim,'String',str,'FitBoxToText','on','FontSize',fontsize,'LineStyle','none');\n    \n    allAxesInFigure = findall(h_fig,'type','axes');\n    set(allAxesInFigure, 'Fontsize', fontsize-4, 'xgrid','on')\n    \n    set(gcf,'color','w');    \n    set(gcf,'PaperUnits','inches');\n    set(gcf,'PaperSize', [9, 8.0]);\n    set(gcf,'PaperPosition',[0 0 9 8.0]);\n    save_name = [up.paths.filenames.stacked_bar, '_', plot_type{1,1}];\n    savepath = [up.paths.plots_save_folder, save_name];\n    print(h_fig,'-depsc',savepath)\n    close all\n    \nend\n\nend\n\nfunction axis_units = convert_real_to_axis_units(real_units, spec)\n\naxis_units = spec.axis_lims(1) + ( (real_units - spec.real_lims(1)) * (spec.axis_lims(end) - spec.axis_lims(1))/ (spec.real_lims(end)-spec.real_lims(1)));\n\nend", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v2.0/Algorithms/calc_stats/specific_vortal_plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.22015252451136505}}
{"text": "function test_suite = test_interval_neighborhood()\n% tests for cosmo_interval_neighborhood\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n    try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n        test_functions=localfunctions();\n    catch % no problem; early Matlab versions can use initTestSuite fine\n    end\n    initTestSuite;\n\n\nfunction test_interval_neighborhood_basis()\n    ds_full=cosmo_synthetic_dataset('type','meeg','size','big');\n    ds_full=cosmo_slice(ds_full,ds_full.fa.chan<3,2);\n    ds_full=cosmo_dim_prune(ds_full);\n\n    sliceargs={1:7,[1 4 7],[2 6]};\n    radii=[0 1 2];\n    for k=1:numel(sliceargs)\n        slicearg=sliceargs{k};\n        narg=numel(slicearg);\n\n        ds=cosmo_slice(ds_full,cosmo_match(ds_full.fa.time,slicearg),2);\n        ds=cosmo_dim_prune(ds);\n        nf=size(ds.samples,2);\n        ds=cosmo_slice(ds,randperm(nf),2);\n\n        for j=1:numel(radii)\n            ds=cosmo_slice(ds,randperm(nf),2);\n            fa_time=ds.fa.time;\n\n            radius=radii(j);\n\n            nh=cosmo_interval_neighborhood(ds,'time','radius',radius);\n            assert(numel(nh.neighbors)==narg);\n            assertEqual(nh.fa.time,1:narg);\n            assertEqual(nh.a.fdim.values,...\n                            {ds_full.a.fdim.values{2}(slicearg)});\n\n            assertEqual(nh.origin.a.fdim,ds.a.fdim);\n            assertEqual(nh.origin.fa,ds.fa);\n\n            for m=1:narg\n                msk=m-radius<=fa_time & ...\n                        fa_time <= m+radius;\n                assertEqual(find(msk),nh.neighbors{m});\n            end\n\n            % should properly deal with permutations\n            ds2=cosmo_slice(ds,randperm(nf),2);\n            ds2.a.fdim.values=cellfun(@transpose,ds2.a.fdim.values,...\n                                        'UniformOutput',false)';\n            nh2=cosmo_interval_neighborhood(ds2,'time','radius',radius);\n            assertEqual(nh.fa,nh2.fa);\n            assertEqual(nh.a,nh2.a);\n            mp=cosmo_align(ds.fa,ds2.fa);\n            for m=1:numel(nh.neighbors)\n                assertEqual(sort(mp(nh2.neighbors{m})),nh.neighbors{m});\n            end\n        end\n    end\n\n    % test exceptionsclc\n    aet=@(x,i)assertExceptionThrown(@()...\n                        cosmo_interval_neighborhood(x{:}),i);\n\n\n    aet({ds},'');\n    aet({ds,'time'},'');\n    aet({ds,'x',2},'');\n    aet({ds,'time',-1},'');\n    aet({ds,'time',[2 3]},'');\n    aet({ds,'time','radius'},'');\n    aet({ds,'time','radius',-1},'');\n\nfunction test_interval_neighborhood_sa()\n    ds=cosmo_synthetic_dataset('type','meeg');\n    ds_tr=cosmo_dim_transpose(ds,'time');\n    ds_tr=cosmo_slice(ds_tr,randperm(12));\n    for radius=0:1\n        nbrhood=cosmo_interval_neighborhood(ds_tr,'time','radius',radius);\n        unq_time=unique(ds_tr.sa.time);\n        for k=1:numel(unq_time)\n            msk=abs(ds_tr.sa.time-unq_time(k))<=radius;\n            assertEqual(nbrhood.neighbors{k},find(msk)');\n        end\n    end\n\n\nfunction test_interval_neighborhood_fa()\n    ds=cosmo_synthetic_dataset('type','meeg','size','big');\n    nf=size(ds.samples,2);\n    rp=randperm(nf);\n    dsp=cosmo_slice(ds,rp,2);\n\n    for radius=0:10\n        nhp=cosmo_interval_neighborhood(dsp,'time','radius',radius);\n        assertEqual(nhp.a.fdim.values{1},ds.a.fdim.values{2});\n\n        for k=1:numel(nhp.neighbors)\n            idx=find(abs(nhp.fa.time(k)-dsp.fa.time)<=radius);\n            assertEqual(nhp.neighbors{k},idx);\n        end\n    end\n\nfunction test_sparse_interval_neighborhood\n    ds=cosmo_synthetic_dataset('size','big');\n\n    % make some holes\n    ds=cosmo_slice(ds,ds.fa.i>=4 & ds.fa.i<=16,2);\n    ds=cosmo_slice(ds,mod(ds.fa.i,3)<=1,2);\n\n    for radius=0:5\n        nh=cosmo_interval_neighborhood(ds,'i','radius',radius);\n\n        n_nbrs=numel(nh.neighbors);\n\n        assert(n_nbrs==numel(ds.a.fdim.values{1}));\n        for j=1:n_nbrs\n            nbrs=nh.neighbors{j};\n\n            idx=find(j-radius <= ds.fa.i & ds.fa.i <= j+radius);\n            assertEqual(nbrs(:),idx(:),sprintf(['not equal with '...\n                                        'radius=%d, index=%d'],...\n                                        radius,j))\n        end\n    end\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_interval_neighborhood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22013924011468547}}
{"text": "%CODEGENERATOR.GENSLBLOCKFKINE Generate Simulink block for forward kinematics\n%\n% cGen.genslblockfkine() generates a robot-specific Simulink block to compute\n% forward kinematics.\n%\n% Notes::\n% - Is called by CodeGenerator.genfkine if cGen has active flag genslblock.\n% - The Simulink blocks are generated and stored in a robot specific block \n%   library cGen.slib in the directory cGen.basepath.\n% - Blocks are created for intermediate transforms T0, T1 etc. as well.\n%\n% Author::\n%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)\n%\n% See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine.\n\n% Copyright (C) 2012-2014, by Joern Malzahn\n%\n% This file is part of The Robotics Toolbox for Matlab (RTB).\n%\n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n%\n% The code generation module emerged during the work on a project funded by\n% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully \n% acknowledge the financial support.\n\nfunction genslblockfkine(CGen)\n \n%% Open or create block library\nbdclose('all')                                                              % avoid problems with previously loaded libraries\nload_system('simulink');\nif ~(exist([CGen.slibpath,simulinkext]) == 2)                                  % Create new block library if none exists\n CGen.createnewblocklibrary;\nend\nopen_system(CGen.slibpath);\nset_param(CGen.slib,'lock','off');\n\nq = CGen.rob.gencoords;\n\n%% Forward kinematics up to tool center point\nCGen.logmsg([datestr(now),'\\tGenerating forward kinematics Simulink block up to the end-effector frame']);\nsymname = 'fkine';\nfname = fullfile(CGen.sympath,[symname,'.mat']);\n\nif exist(fname,'file')\n    tmpStruct = load(fname);\nelse\n    error ('genslblockfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')\nend\n\nblockaddress = [CGen.slib,'/',symname];          % treat intermediate transformations separately\nif ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname))                    % Delete previously generated block\n    delete_block(blockaddress);\n    save_system;\nend\n\nsymexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q});\n\nCGen.logmsg('\\t%s\\n',' done!');\n\n%% Individual joint forward kinematics\nCGen.logmsg([datestr(now),'\\tGenerating forward kinematics Simulink block up to joint']);\nfor iJoints=1:CGen.rob.n\n    \n    CGen.logmsg(' %i ',iJoints);\n    symname = ['T0_',num2str(iJoints)];\n    fname = fullfile(CGen.sympath,[symname,'.mat']);\n    \n    tmpStruct = struct;\n    tmpStruct = load(fname);\n    \n    funFileName = fullfile(CGen.robjpath,[symname,'.m']);\n    q = CGen.rob.gencoords;\n    \n    \n    blockaddress = [CGen.slib,'/',symname];          % treat intermediate transformations separately\n    if doesblockexist(CGen.slib,symname)\n        delete_block(blockaddress);\n        save_system;\n    end\n    \n    symexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q});\n    \nend\nCGen.logmsg('\\t%s\\n',' done!');\n\n%% Cleanup\n% Arrange blocks\ndistributeblocks(CGen.slib);\n\n% Lock, save and close library\nset_param(CGen.slib,'lock','on');\nsave_system(CGen.slib,CGen.slibpath);\nclose_system(CGen.slib);\n\nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/@CodeGenerator/genslblockfkine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.22013923421806056}}
{"text": "%FeatureMatch Feature correspondence object\n%\n% This class represents the correspondence between two PointFeature\n% objects.  A vector of FeatureMatch objects can represent the \n% correspondence between sets of points.\n%\n% Methods::\n% plot       Plot corresponding points\n% show       Show summary statistics of corresponding points\n%\n% ransac     Determine inliers and outliers\n% inlier     Return inlier matches\n% outlier    Return outlier matches\n% subset     Return a subset of matches\n% remove\n%\n% display    Display value of match\n% char       Convert value of match to string\n% \n% Properties::\n% p1         Point coordinates in view 1 (2x1)\n% p2         Point coordinates in view 2 (2x1)\n% p          Point coordinates in view 1 and 2 (4x1)\n% distance   Match strength between the points\n%\n% Properties of a vector of FeatureMatch objects are returned as a vector.\n% If F is a vector (Nx1) of FeatureMatch objects then F.p1 is a 2xN matrix\n% with each column the corresponding view 1 point coordinate.\n%\n% Note::\n%  - FeatureMatch is a reference object.\n%  - FeatureMatch objects can be used in vectors and arrays\n%  - Operates with all objects derived from PointFeature, such as \n%    ScalePointFeature, SurfPointFeature and SiftPointFeature.\n%\n% See also PointFeature, SurfPointFeature, SiftPointFeature.\n\n% TODO:\n% distance, strength should be converted to similarity\n% p should be p12\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.\n\nclassdef FeatureMatch < handle\n\n    properties\n        % the trailing underscore is to distinguish these properties from the methods\n        % of almost similar name.  Finding the property of a vector of objects\n        % F.x results in a list rather than a vector.  You need to write [F.x] so we\n        % create methods to provide this.  Using dependent properties does not work.\n        xy_          % x1 y1 x2 y2 of corresponding points\n        distance_    % strength of match\n        inlier_      % NaN - indeterminate\n                    % true - inlier\n                    % false - outlier\n    end\n\n    methods\n\n        function m = FeatureMatch(f1, f2, s)\n        %FeatureMatch.FeatureMatch Create a new FeatureMatch object\n        %\n        % M = FeatureMatch(F1, F2, S) is a new FeatureMatch object describing a \n        % correspondence between point features F1 and F2 with a strength of S.\n        %\n        % M = FeatureMatch(F1, F2) as above but the strength is set to NaN.\n        %\n        % Notes::\n        % - Only the coordinates of the PointFeature are kept.\n        %\n        % See also PointFeature, SurfPointFeature, SiftPointFeature.\n\n            if nargin == 0\n                m.xy_ = [];\n                m.distance_ = [];\n                m.inlier_ = [];\n                return;\n            end\n\n            m.xy_ = [f1.u_ f1.v_ f2.u_ f2.v_]';\n            if nargin < 3\n                m.distance = NaN;\n            else\n                m.distance_ = s;\n            end\n            m.inlier_ = NaN;\n        end\n\n        function v = inlier(m)\n        %FeatureMatch.inlier Inlier features\n        %\n        % M2 = M.inlier() is a subset of the FeatureMatch vector M that are\n        % considered to be inliers.\n        %\n        % Notes::\n        % - Inliers are not determined until after RANSAC is run.\n        %\n        % See also FeatureMatch.outlier, FeatureMatch.ransac.\n            v = m([m.inlier_] == true);\n        end\n\n        function v = outlier(m)\n        %FeatureMatch.outlier Outlier features\n        %\n        % M2 = M.outlier() is a subset of the FeatureMatch vector M that are\n        % considered to be outliers.\n        %\n        % Notes::\n        % - Outliers are not determined until after RANSAC is run.\n        %\n        % See also FeatureMatch.inlier, FeatureMatch.ransac.\n            v = m([m.inlier_] == false);\n        end\n\n        function v = distance(m)\n            v = [m.distance_];\n        end\n        \n        function v = inlierx(m)\n            v = find([m.inlier_]);\n        end\n\n        function display(m)\n        %FeatureMatch.display Display value\n        %\n        % M.display() displays a compact human-readable representation of the \n        % feature pair.  If M is a vector then the elements are printed one per line.\n        %\n        % Notes::\n        % - This method is invoked implicitly at the command line when the result\n        %   of an expression is a FeatureMatch object and the command has no trailing\n        %   semicolon.\n        %\n        % See also FeatureMatch.char.\n\n            disp(' ');\n            disp([inputname(1), ' = '])\n            disp(' ');\n            if length(m) > 20\n                fprintf('%d corresponding points (listing suppressed)\\n', length(m));\n            else\n                disp( char(m) );\n            end\n        end % display()\n\n        function s = char(matches)\n        %FeatureMatch.char Convert to string\n        %\n        % S = M.char() is a compact string representation of the match object.\n        % If M is a vector then the string has multiple lines, one per element.\n\n            s = '';\n            for m=matches\n                ss = sprintf('(%g, %g) <-> (%g, %g), dist=%f', ...\n                    m.xy_, m.distance_);\n                switch m.inlier_\n                case true\n                    ss = [ss ' +'];\n                case false\n                    ss = [ss ' -'];\n                end\n                s = strvcat(s, ss);\n            end\n        end\n        \n        function s = show(m)\n        %FeatureMatch.show Display summary statistics of the FeatureMatch vector\n        %\n        % M.show() is a compact summary of the FeatureMatch vector M that gives\n        % the number of matches, inliers and outliers (and their percentages).\n            s = sprintf('%d corresponding points\\n', length(m));\n            in = [m.inlier_];\n            s = [s sprintf('%d inliers (%.1f%%)\\n', ...\n                sum(in==true), sum(in==true)/length(m)*100)];\n            s = [s sprintf('%d outliers (%.1f%%)\\n', ...\n                sum(in==false), sum(in==false)/length(m)*100) ];\n        end\n        \n        function v = subset(m, n, varargin)\n        %FeatureMatch.subset Subset of matches\n        %\n        % M2 = M.subset(N) is a FeatureMatch vector with no more than N elements\n        % sampled uniformly from M.\n        \n            opt.random = false;\n            opt = tb_optparse(opt, varargin);\n\n            if opt.random\n                i = randi(length(m), n);\n            else\n                i = round(linspace(1, length(m), n));\n            end\n            v = m(i);\n        end\n\n        \n        function s = p1(m, k)\n        %FeatureMatch.p1 Feature point coordinates from view 1\n        %\n        % P = M.p1() is a 2xN matrix containing the feature points coordinates\n        % from view 1.  These are the (u,v) properties of the feature F1 passed\n        % to the constructor.\n        %\n        % See also FeatureMatch.FeatureMatch, FeatureMatch.p2, FeatureMatch.p.\n            xy = [m.xy_];\n            s = xy(1:2,:);\n        end\n        \n        function s = p2(m, k)\n        %FeatureMatch.p2 Feature point coordinates from view 2\n        %\n        % P = M.p2() is a 2xN matrix containing the feature points coordinates\n        % from view 1.  These are the (u,v) properties of the feature F2 passed\n        % to the constructor.\n        %\n        % See also FeatureMatch.FeatureMatch, FeatureMatch.p1, FeatureMatch.p.\n\n            xy = [m.xy_];\n            xy = [m.xy_];\n            s = xy(3:4,:);\n        end\n        \n        function s = p(m, k)\n        %FeatureMatch.p Feature point coordinate pairs\n        %\n        % P = M.p() is a 4xN matrix containing the feature point coordinates.\n        % Each column contains the coordinates of a pair of corresponding \n        % points [u1,v1,u2,v2].\n        %\n        % See also FeatureMatch.p1, FeatureMatch.p2.\n            s = [m.xy_];\n        end\n        \n        function plot(m, varargin)       \n        %FeatureMatch.plot Show corresponding points\n        %\n        % M.plot() overlays the correspondences in the FeatureMatch vector M\n        % on the current figure.  The figure must comprise views 1 and 2 side\n        % by side, for example by:\n        %\n        %      idisp({im1,im2})\n        %      m.plot()\n        %\n        % M.plot(LS) as above but the optional line style arguments LS are\n        % passed to plot.\n        %\n        % Notes::\n        % - Using IDISP as above adds UserData to the figure, and an error is \n        %   created if this UserData is not found.\n        % See also IDISP.\n\n            opt.offset = [];\n            [opt,args] = tb_optparse(opt, varargin);\n            \n            if isempty(opt.offset)\n            try\n                ud = get(gca, 'UserData');\n                u0 = ud.u0;\n            catch\n                error('Current image is not a pair displayed by idisp');\n            end\n            opt.offset = [0 u0(2) 0 0];\n            end\n            \n            xy = [m.xy_];\n            hold on\n            for k=1:numcols(xy),\n                plot([xy(1,k)+opt.offset(1) xy(3,k)+opt.offset(2)], ...\n                    [xy(2,k)+opt.offset(3), xy(4,k)+opt.offset(4)],  args{:});\n            end\n            hold off\n            figure(gcf);\n        end % plot\n        \n        function [MM,rr] = ransac(m, func, varargin)\n        %FeatureMatch.ransac Apply RANSAC\n        %\n        % M.ransac(FUNC, OPTIONS) applies the RANSAC algorithm to fit the point\n        % correspondences to the model described by the function FUNC.  The \n        % OPTIONS are passed to the RANSAC() function.  Elements of the \n        % FeatureMatch vector have their status updated in place to indicate \n        % whether they are inliers or outliers.\n        %\n        % Example::\n        %      f1 = isurf(im1);\n        %      f2 = isurf(im2);\n        %      m = f1.match(f2);\n        %      m.ransac( @fmatrix, 1e-4);\n        %\n        % See also FMATRIX, HOMOGRAPHY, RANSAC.\n        \n            opt.retry = 1;\n            [opt,args] = tb_optparse(opt, varargin);\n            if opt.verbose\n                args = [args 'verbose'];\n            end\n            \n            while true\n                try\n                    [M,in,resid] = ransac(func, [m.xy_], args{:});\n                    break;\n                catch err\n                    opt.retry = opt.retry - 1;\n                    if opt.retry > 0\n                        continue;\n                    else\n                        rethrow(err);\n                    end\n                end\n            end\n            \n            % mark all as outliers\n            for i=1:length(m)\n                m(i).inlier_ = false;\n            end\n            for i=in\n                m(i).inlier_ = true;\n            end\n\n            if nargout >= 1\n                MM = M;\n            end\n            if nargout >= 2\n                rr = resid;\n            end\n        end\n    end\n\nend\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/FeatureMatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22013922832143554}}
{"text": "function err = err_fit(params, sample, tes)\n% return residual\n\n%size(sample)\n%size(signal(params, tes))\n\nerr = sample - signal(params, tes);\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/MWF/met2_eva/err_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2201135407408466}}
{"text": "function [gp, indA] = passgp(gp, x, y, varargin)\n%PASSGP   Optimize active set and hyperparameters of PASS-GP \n%\n%  Description\n%    [GP, INDA] = PASSGP(GP, X, Y, OPTIONS)\n%    Returns GP structure with hyperparameters optimized according to\n%    PASS-GP routine (Henao & Winther, 2012) and active set indices \n%    INDA for X and Y\n%\n%   OPTIONS is optional parameter-value pair\n%      npass - Number of passes the algorithm takes over the whole training\n%              data set\n%      ninit - Initial active set size\n%      nsub  - Number of subsets we process at each pass (in how many\n%              parts we divide the whole data)\n%      pinc  - Predictive density threshold for inclusion in active set.\n%      pdel  - LOO-predictive density threshold for deletion from active\n%              set\n%      pexc  - Exchange proportion for fixed PASS-GP\n%      opt   - Options structure for optimizer\n%      fixed - Whether we use fixed size of active set or not. Default\n%               'off'\n%      display - Whether to display additional info or not. Default 'off'\n%      optimn - Whether to optimize always or only after every nth\n%               deletion/addition to active set. Default 1 (every time). If\n%               given e.g. value 3, optimizes after every 3rd\n%               addition/deletion.\n%\n%  See also\n%    GP_SET, LIK_*\n%\n%  Reference:\n%    Ricardo Henao & Ole Winther (2012). Preditive active set selection\n%    methods for Gaussian processes. Neurocomputing 80 (2012), 10-18.\n\n% Copyright (c) 2013 Ville Tolvanen\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n  ip=inputParser;\n  ip.FunctionName = 'PASSGP';\n  ip.addRequired('gp',@(x) isstruct(x) || iscell(x));\n  ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('npass', 3, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('ninit', 100, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('nsub', 10, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('pinc', 0.5, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('pdel', 0.99, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('pexc', 0.1, @(x) isscalar(x) && x > 0)\n  ip.addParamValue('opt', [], @(x) isstruct(x))\n  ip.addParamValue('fixed', 'off', @(x) ismember(x,{'on','off'}))\n  ip.addParamValue('display', 'off', @(x) ismember(x,{'on','off'}))\n  ip.addParamValue('optimn', 1', @(x) isscalar(x) && x > 0 && rem(10*x,2)==0)\n  ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n  ip.parse(gp, x, y, varargin{:});\n  opt=ip.Results.opt;\n  fixed=ip.Results.fixed;\n  options.z = ip.Results.z;\n  npass=ip.Results.npass;\n  ninit=ip.Results.ninit;\n  nsub=ip.Results.nsub;\n  pinc=ip.Results.pinc;\n  pdel=ip.Results.pdel;\n  pexc=ip.Results.pexc;\n  display=ip.Results.display;\n  optimn=ip.Results.optimn;\n  \n  if isequal(display,'on')\n    display=1;\n  else\n    display=0;\n  end\n  if isequal(fixed, 'on')\n    fixed=1;\n  else\n    fixed=0;\n  end  \n  \n  if ninit > size(x,1)\n    error('Initial active set must be subset of original data');\n  end\n  if nsub > (size(x,1) - ninit)\n    error('nsub must be lower than size(x,1) - ninit');\n  end\n  \n  [n,nin]=size(x);\n  \n  % Initial active set\n  \n  indA=sort(randperm(n, ninit),'ascend');\n  % Inclusions/deletions per iteration for fixed pass-gp\n  nexc=floor(ninit*pexc);\n  iter=optimn-1;\n  for i=1:npass\n    if display\n      fprintf('Pass %d / %d.\\n', i, npass)\n    end\n    [tmp,indSub]=cvit(n, nsub, floor(10*rand(1)));\n    for j=1:nsub      \n      iter=iter+1;\n      inds=indSub{j};\n      % Remove indices that are already in active set\n      inds(ismember(inds,indA))=[];\n      \n      if iter==optimn\n        % Optimize hyperparameters\n        gp = gp_optim(gp, x(indA,:), y(indA), 'opt', opt, options);\n        iter=0;\n      end\n      \n      % Calculate weights for active set inputs (loo predictive densities)\n      [tmp,tmp,lpyt]=gp_loopred(gp,x(indA,:),y(indA), options);\n      \n      % Remove active set indices according to removal rule      \n      if ~fixed\n        indA(find(exp(lpyt)>pdel))=[];\n      else\n        [tmp,ii]=sort(lpyt, 'descend');\n        indA(ii(1:nexc))=[];\n      end\n      % Calculate weights for inputs not in active set (predictive density)\n      [tmp,tmp,lpyt]=gp_pred(gp, x(indA,:), y(indA), x(inds,:), 'yt', y(inds), options);\n      \n      % Add indices to active set according to addition rule\n      if ~fixed\n        ind=find(exp(lpyt)<pinc)';\n      else\n        [tmp,ii]=sort(lpyt, 'ascend');\n        ind=ii(1:nexc);\n      end\n      indA=[indA inds(ind)];\n        \n    end\n    \n      \n  end\n  \nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/passgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2201135407408466}}
{"text": "function g = gpTimeDynamicsLogLikeGradients(model)\n\n% GPTIMEDYNAMICSLOGLIKEGRADIENTS Gradients of the GP dynamics wrt parameters.\n% FORMAT\n% DESC Computes the gradients with respect to the log likelihood of\n% the GP dynamics in a GP-LVM model.\n% ARG model : the GP model for which log likelihood is to be\n% computed.\n% RETURN g : the gradients of the log likelihood with respect to\n% the latent points and (optionally) parameters.\n%\n% SEEALSO : gpLogLikeGradients, gpTimeDynamicsCreate, gpTimeDynamicsLogLikelihood, modelLogLikelihood\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2009\n\n% FGPLVM\n\nif model.k ==0 & ~model.learn & ~model.learnScales\n  g = [];\n  return\nend\n\ng = gpLogLikeGradients(model);\n\nif ~model.learn\n  % If we aren't learning model parameters extract only X_u;\n  % this is inefficient (but neater in the code) as we have also computed parameters \n  if ~model.learnScales\n    if isfield(model, 'fixInducing') & model.fixInducing\n      g = [];\n    else\n      g = g(1:model.k*model.q);\n    end\n  else\n    switch model.approx\n     case 'ftc'\n      g =  [g(end-model.d + 1:end)];\n     case {'dtc', 'dtcvar', 'fitc', 'pitc'}\n      if isfield(model, 'fixInducing') & model.fixInducing\n        g = g(end-model.d:end-1);\n      else\n        g =  [g(1:model.k*model.q) g(end-model.d:end-1)];\n      end\n    end\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/gpTimeDynamicsLogLikeGradients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.22005602639255092}}
{"text": "function CrossCutter(img, cb_name, cb_format)\n%\n%        CrossCutter(img, cb_name, cb_format)\n%\n%\n%        Input:\n%           -img: input environment map encoded as a cubemap\n%           -name: a string representing the prefix name for each face of\n%            the cubemap. For example: 'output_cubemap' (default)\n%           -format: the output format of each face of the cubemap. For\n%           example: 'hdr' (default)\n%        Output:\n%           -ret: it is set to 1 if the function succeeded\n%\n%     Copyright (C) 2011  Francesco Banterle\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n\nif(~exist('cb_name', 'var'))\n    cb_name = 'output_cube_map';\nend\n\nif(~exist('cb_format', 'var'))\n    cb_name = 'hdr';\nend\n\nc = size(img, 2);\n\ncubeSize = round(c / 3);\n\n%CUBE_POS_Y\nimgPosY = img(1:cubeSize,(cubeSize+1):(2*cubeSize),:);\nimgPosY = imrotate(imgPosY, -270);\nhdrimwrite(imgPosY,[cb_name,'_POS_Y.',cb_format]);\n\n%CUBE_POS_X\nhdrimwrite(img((cubeSize+1)    :(2*cubeSize),(cubeSize+1):(2*cubeSize),:),[cb_name,'_POS_X.',cb_format]);\n\n%CUBE_NEG_Y\nimgNegY = img((2*cubeSize+1):(3*cubeSize),(cubeSize+1):(2*cubeSize),:);\nhdrimwrite(imrotate(imgNegY,-90),[cb_name,'_NEG_Y.',cb_format]);\n\n%CUBE_NEG_X\nimgNegX = img((3*cubeSize+1):(4*cubeSize),(cubeSize+1):(2*cubeSize),:); \nfor i=1:3\n    imgNegX(:,:,i) = flipud(imgNegX(:,:,i));\n    imgNegX(:,:,i) = fliplr(imgNegX(:,:,i));\nend\nhdrimwrite(imgNegX,[cb_name,'_NEG_X.',cb_format]);\n\n%CUBE_POS_Z\nhdrimwrite(img((cubeSize+1):(2*cubeSize),1:cubeSize,:),[cb_name,'_POS_Z.',cb_format]);\n\n%CUBE_NEG_Z\nhdrimwrite(img((cubeSize+1):(2*cubeSize),(2*cubeSize+1):(3*cubeSize),:),[cb_name,'_NEG_Z.', cb_format]);\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/EnvironmentMaps/CrossCutter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21998477402161074}}
{"text": "function OBJ=read_wobj(fullfilename)\n% Read the objects from a Wavefront OBJ file\n%\n% OBJ=read_wobj(filename);\n%\n% OBJ struct containing:\n%\n% OBJ.vertices : Vertices coordinates\n% OBJ.vertices_texture: Texture coordinates\n% OBJ.vertices_normal : Normal vectors\n% OBJ.vertices_point  : Vertice data used for points and lines\n% OBJ.material : Parameters from external .MTL file, will contain parameters like\n%           newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,\n%           example of an entry from the material object:\n%       OBJ.material(i).type = newmtl\n%       OBJ.material(i).data = 'vase_tex'\n% OBJ.objects  : Cell object with all objects in the OBJ file,\n%           example of a mesh object:\n%       OBJ.objects(i).type='f'\n%       OBJ.objects(i).data.vertices: [n x 3 double]\n%       OBJ.objects(i).data.texture:  [n x 3 double]\n%       OBJ.objects(i).data.normal:   [n x 3 double]\n%\n% Example,\n%   OBJ=read_wobj('examples\\example10.obj');\n%   FV.vertices=OBJ.vertices;\n%   FV.faces=OBJ.objects(3).data.vertices;\n%   figure, patch(FV,'facecolor',[1 0 0]); camlight\n%\n% Function is written by D.Kroon University of Twente (June 2010)\n\nverbose=true;\n\nif(exist('fullfilename','var')==0)\n    [filename, filefolder] = uigetfile('*.obj', 'Read obj-file');\n    fullfilename = [filefolder filename];\nend\nfilefolder = fileparts( fullfilename);\nif(verbose),disp(['Reading Object file : ' fullfilename]); end\n\n\n% Read the DI3D OBJ textfile to a cell array\nfile_words = file2cellarray( fullfilename);\n% Remove empty cells, merge lines split by \"\\\" and convert strings with values to double\n[ftype fdata]= fixlines(file_words);\n\n% Vertex data\nvertices=[]; nv=0;\nvertices_texture=[]; nvt=0;\nvertices_point=[]; nvp=0;\nvertices_normal=[]; nvn=0;\nmaterial=[];\n\n% Surface data\nno=0;\n\n% Loop through the Wavefront object file\nfor iline=1:length(ftype)\n    if(mod(iline,10000)==0),\n        if(verbose),disp(['Lines processed : ' num2str(iline)]); end\n    end\n    \n    type=ftype{iline}; data=fdata{iline};\n    \n    % Switch on data type line\n    switch(type)\n        case{'mtllib'}\n            if(iscell(data))\n                datanew=[];\n                for i=1:length(data)\n                    datanew=[datanew data{i}];\n                    if(i<length(data)), datanew=[datanew ' ']; end\n                end\n                data=datanew;\n            end\n            \n            filename_mtl=fullfile(filefolder,data);\n            material=readmtl(filename_mtl,verbose);\n        case('v') % vertices\n            nv=nv+1;\n            if(length(data)==3)\n                % Reserve block of memory\n                if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:3)=0; end\n                % Add to vertices list X Y Z\n                vertices(nv,1:3)=data;\n            else\n                % Reserve block of memory\n                if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:4)=0; end\n                % Add to vertices list X Y Z W\n                vertices(nv,1:4)=data;\n            end\n        case('vp')\n            % Specifies a point in the parameter space of curve or surface\n            nvp=nvp+1;\n            if(length(data)==1)\n                % Reserve block of memory\n                if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1)=0; end\n                % Add to vertices point list U\n                vertices_point(nvp,1)=data;\n            elseif(length(data)==2)\n                % Reserve block of memory\n                if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:2)=0; end\n                % Add to vertices point list U V\n                vertices_point(nvp,1:2)=data;\n            else\n                % Reserve block of memory\n                if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:3)=0; end\n                % Add to vertices point list U V W\n                vertices_point(nvp,1:3)=data;\n            end\n        case('vn')\n            % A normal vector\n            nvn=nvn+1; if(mod(nvn,10000)==1),  vertices_normal(nvn+1:nvn+10001,1:3)=0; end\n            % Add to vertices list I J K\n            vertices_normal(nvn,1:3)=data;\n        case('vt')\n            % Vertices Texture Coordinate in photo\n            % U V W\n            nvt=nvt+1;\n            if(length(data)==1)\n                % Reserve block of memory\n                if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1)=0; end\n                % Add to vertices texture list U\n                vertices_texture(nvt,1)=data;\n            elseif(length(data)==2)\n                % Reserve block of memory\n                if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:2)=0; end\n                % Add to vertices texture list U V\n                vertices_texture(nvt,1:2)=data;\n            else\n                % Reserve block of memory\n                if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:3)=0; end\n                % Add to vertices texture list U V W\n                vertices_texture(nvt,1:3)=data;\n            end\n        case('l')\n            no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end\n            array_vertices=[];\n            array_texture=[];\n            for i=1:length(data),\n                switch class(data)\n                    case 'cell'\n                        tvals=str2double(stringsplit(data{i},'/'));\n                    case 'string'\n                        tvals=str2double(stringsplit(data,'/'));\n                    otherwise\n                        tvals=data(i);\n                end\n                val=tvals(1);\n                if(val<0), val=val+1+nv; end\n                array_vertices(i)=val;\n                if(length(tvals)>1),\n                    val=tvals(2);\n                    if(val<0), val=val+1+nvt; end\n                    array_texture(i)=val;\n                end\n            end\n            objects(no).type='l';\n            objects(no).data.vertices=array_vertices;\n            objects(no).data.texture=array_texture;\n        case('f')\n            no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end\n            array_vertices=[];\n            array_texture=[];\n            array_normal=[];\n            for i=1:length(data);\n                switch class(data)\n                    case 'cell'\n                        tvals=str2double(stringsplit(data{i},'/'));\n                    case 'string'\n                        tvals=str2double(stringsplit(data,'/'));\n                    otherwise\n                        tvals=data(i);\n                end\n                val=tvals(1);\n                \n                if(val<0), val=val+1+nv; end\n                array_vertices(i)=val;\n                if(length(tvals)>1),\n                    if(isfinite(tvals(2)))\n                        val=tvals(2);\n                        if(val<0), val=val+1+nvt; end\n                        array_texture(i)=val;\n                    end\n                end\n                if(length(tvals)>2),\n                    val=tvals(3);\n                    if(val<0), val=val+1+nvn; end\n                    array_normal(i)=val;\n                end\n            end\n            \n            % A face of more than 3 indices is always split into\n            % multiple faces of only 3 indices.\n            objects(no).type='f';\n            findex=1:min (3,length(array_vertices));\n           \n            objects(no).data.vertices=array_vertices(findex);\n            if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end\n            if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end\n            for i=1:length(array_vertices)-3;\n                no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end\n                findex=[1 2+i 3+i];\n                findex(findex>length(array_vertices))=findex(findex>length(array_vertices))-length(array_vertices);\n                objects(no).type='f';\n                objects(no).data.vertices=array_vertices(findex);\n                if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end\n                if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end\n            end\n        case{'#','$'}\n            % Comment\n            tline='  %'; \n            if(iscell(data))\n                for i=1:length(data), tline=[tline ' ' data{i}]; end\n            else\n                tline=[tline data];\n            end\n            if(verbose), disp(tline); end\n        case{''}\n        otherwise\n            no=no+1;\n            if(mod(no,10000)==1), objects(no+10001).data=0; end\n            objects(no).type=type;\n            objects(no).data=data;\n    end\nend\n\n% Initialize new object list, which will contain the \"collapsed\" objects\nobjects2(no).data=0;\n\nindex=0;\n\ni=0;\nwhile (i<no), i=i+1;\n    type=objects(i).type;\n    % First face found\n    if((length(type)==1)&&(type(1)=='f'))\n        % Get number of faces\n        for j=i:no\n            type=objects(j).type;\n            if((length(type)~=1)||(type(1)~='f'))\n                j=j-1; break;\n            end\n        end\n        numfaces=(j-i)+1;\n        \n        index=index+1;\n        objects2(index).type='f';\n        % Process last face first to allocate memory\n        objects2(index).data.vertices(numfaces,:)= objects(i).data.vertices;\n        if(isfield(objects(i).data,'texture'))\n            objects2(index).data.texture(numfaces,:) = objects(i).data.texture;\n        else\n            objects2(index).data.texture=[];\n        end\n        if(isfield(objects(i).data,'normal'))\n            objects2(index).data.normal(numfaces,:)  = objects(i).data.normal;\n        else\n            objects2(index).data.normal=[];\n        end\n        % All faces to arrays\n        for k=1:numfaces\n            objects2(index).data.vertices(k,:)= objects(i+k-1).data.vertices;\n            if(isfield(objects(i).data,'texture'))\n                objects2(index).data.texture(k,:) = objects(i+k-1).data.texture;\n            end\n            if(isfield(objects(i).data,'normal'))\n                objects2(index).data.normal(k,:)  = objects(i+k-1).data.normal;\n            end\n        end\n        i=j;\n    else\n        index=index+1;\n        objects2(index).type=objects(i).type;\n        objects2(index).data=objects(i).data;\n    end\nend\n\n% Add all data to output struct\nOBJ.objects=objects2(1:index);\nOBJ.material=material;\nOBJ.vertices=vertices(1:nv,:);\nOBJ.vertices_point=vertices_point(1:nvp,:);\nOBJ.vertices_normal=vertices_normal(1:nvn,:);\nOBJ.vertices_texture=vertices_texture(1:nvt,:);\nif(verbose),disp('Finished Reading Object file'); end\n\n\nfunction twords=stringsplit(tline,tchar)\n% Get start and end position of all \"words\" separated by a char\ni=find(tline(2:end-1)==tchar)+1; i_start=[1 i+1]; i_end=[i-1 length(tline)];\n% Create a cell array of the words\ntwords=cell(1,length(i_start)); for j=1:length(i_start), twords{j}=tline(i_start(j):i_end(j)); end\n\nfunction file_words=file2cellarray(filename)\n% Open a DI3D OBJ textfile\nfid=fopen(filename,'r');\nfile_text=fread(fid, inf, 'uint8=>char')';\nfclose(fid);\nfile_lines = regexp(file_text, '\\n+', 'split');\nfile_words = regexp(file_lines, '\\s+', 'split');\n\nfunction [ftype fdata]=fixlines(file_words)\nftype=cell(size(file_words));\nfdata=cell(size(file_words));\n\niline=0; jline=0;\nwhile(iline<length(file_words))\n    iline=iline+1;\n    twords=removeemptycells(file_words{iline});\n    if(~isempty(twords))\n        % Add next line to current line when line end with '\\'\n        while(strcmp(twords{end},'\\')&&iline<length(file_words))\n            iline=iline+1;\n            twords(end)=[];\n            twords=[twords removeemptycells(file_words{iline})];\n        end\n        % Values to double\n        \n        type=twords{1};\n        stringdold=true;\n        j=0;\n        switch(type)\n            case{'#','$'}\n                for i=2:length(twords)\n                    j=j+1; twords{j}=twords{i};                    \n                end    \n            otherwise    \n                for i=2:length(twords)\n                    str=twords{i};\n                    val=str2double(str);\n                    stringd=~isfinite(val);\n                    if(stringd)\n                        j=j+1; twords{j}=str;\n                    else\n                        if(stringdold)\n                            j=j+1; twords{j}=val;\n                        else\n                            twords{j}=[twords{j} val];    \n                        end\n                    end\n                    stringdold=stringd;\n                end\n        end\n        twords(j+1:end)=[];\n        jline=jline+1;\n        ftype{jline}=type;\n        if(length(twords)==1), twords=twords{1}; end\n        fdata{jline}=twords;\n    end\nend\nftype(jline+1:end)=[];\nfdata(jline+1:end)=[];\n\nfunction b=removeemptycells(a)\nj=0; b={};\nfor i=1:length(a);\n    if(~isempty(a{i})),j=j+1; b{j}=a{i}; end;\nend\n\nfunction  objects=readmtl(filename_mtl,verbose)\nif(verbose),disp(['Reading Material file : ' filename_mtl]); end\nfile_words=file2cellarray(filename_mtl);\n% Remove empty cells, merge lines split by \"\\\" and convert strings with values to double\n[ftype fdata]= fixlines(file_words);\n\n% Surface data\nobjects.type(length(ftype))=0; \nobjects.data(length(ftype))=0; \nno=0;\n% Loop through the Wavefront object file\nfor iline=1:length(ftype)\n  type=ftype{iline}; data=fdata{iline};\n    \n    % Switch on data type line\n    switch(type)\n        case{'#','$'}\n            % Comment\n            tline='  %'; \n            if(iscell(data))\n                for i=1:length(data), tline=[tline ' ' data{i}]; end\n            else\n                tline=[tline data];\n            end\n            if(verbose), disp(tline); end\n        case{''}\n        otherwise\n            no=no+1;\n            if(mod(no,10000)==1), objects(no+10001).data=0; end\n            objects(no).type=type;\n            objects(no).data=data;\n    end\nend\nobjects=objects(1:no);\nif(verbose),disp('Finished Reading Material file'); end\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/objToolbox2b/objRead.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21996501191674728}}
{"text": "function GammaExposureTMOv(hdrv, filenameOutput, tmo_gamma, tmo_fstop, tmo_quality, tmo_video_profile)\n%\n%\n%       GammaExposureTMOv(hdrv, filenameOutput, tmo_gamma, tmo_fstop, tmo_quality, tmo_video_profile)\n%\n%       This function applies gamma + exposure correction for each frame of the HDR stream\n%\n%       Input:\n%           -hdrv: a HDR video structure; use hdrvread to create a hdrv\n%           structure\n%           -filenameOutput: output filename (if it has an image extension,\n%           single files will be generated)\n%           -tmo_gamma: gamma for encoding the frame. If it is negative,\n%           sRGB econding is applied\n%           -tmo_fstop: f-stop value\n%           -tmo_quality: the output quality in [1,100]. 100 is the best quality\n%           1 is the lowest quality.%\n%           -tmo_video_profile: the compression profile (encoder) for compressing the stream.\n%           Please have a look to the profile of VideoWriter from the MATLAB\n%           help. Depending on the version of MATLAB some profiles may be not\n%           be present.\n%\n%       Output:\n%           -frameOut: the tone mapped frame\n%\n%     Copyright (C) 2016  Francesco Banterle\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n%\n%     This function applies a static TMO to an operator without taking into\n%     account for temporal coherency\n%\n\nif(~exist('filenameOutput', 'var'))\n    date_str = strrep(datestr(now()), ' ', '_');\n    date_str = strrep(date_str, ':', '_');\n    filenameOutput = ['static_tmo_output_', date_str, '.avi'];\nend\n\nif(~exist('tmo_gamma', 'var'))\n    tmo_gamma = 2.2;\nend\n\nif(~exist('tmo_fstop', 'var'))\n    tmo_fstop = 0.0;\nend\n\nif(~exist('tmo_quality', 'var'))\n    tmo_quality = 95;\nend\n\nif(~exist('tmo_video_profile', 'var'))\n    tmo_video_profile = 'MPEG-4';\nend\n\nif(tmo_gamma < 0)\n    bsRGB = 1;\nelse\n    bsRGB = 0;\nend\n\nname = RemoveExt(filenameOutput);\next = fileExtension(filenameOutput);\n\nbVideo = 0;\nwriterObj = 0;\n\nif(strcmp(ext, 'avi') == 1 | strcmp(ext, 'mp4') == 1)\n    bVideo = 1;\n    writerObj = VideoWriter(filenameOutput, tmo_video_profile);\n    writerObj.FrameRate = hdrv.FrameRate;\n    writerObj.Quality = tmo_quality;\n    open(writerObj);\nend\n\nhdrv = hdrvopen(hdrv);\n\nexposure = 2^tmo_fstop;\n\ndisp('Tone Mapping...');\nfor i=1:hdrv.totalFrames\n    disp(['Processing frame ',num2str(i)]);\n    [frame, hdrv] = hdrvGetFrame(hdrv, i);\n    \n    %only physical values\n    frame = RemoveSpecials(frame);\n    frame(frame < 0) = 0;    \n            \n    %gamma/sRGB encoding\n    if(bsRGB)\n        frameOut = ClampImg(ConvertRGBtosRGB(frame * exposure, 0), 0, 1);\n    else\n        frameOut = ClampImg(GammaTMO(frame, tmo_gamma, tmo_fstop, 0), 0, 1);\n    end\n    \n    if(bVideo)\n        writeVideo(writerObj, frameOut);\n    else\n        nameOut = [name, sprintf('%.10d',i), '.', ext];\n        imwrite(frameOut, nameOut);\n    end\n    \nend\ndisp('OK');\n\nif(bVideo)\n    close(writerObj);\nend\n\nhdrvclose(hdrv);\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo_video/GammaExposureTMOv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21996500622684406}}
{"text": "function [ResultsAllCellLines,OverViewResults] = setQuantConstraints(model, samples, tol, minGrowth, obj, no_secretion, no_uptake, medium, addExtraExch, addExtraExch_value, path)\n% This function takes a model and quantitative extracellular metabolomic data and returns a model in which the data is integrated as constraints described\n% in \"MetaboTools: A Comprehensive Toolbox for Analysis of Genome-Scale Metabolic Models\", 2016, Front. Physiol., and the supplemental data \"Tutorial II: Workflow for the integration \n% of quantitative extracellular metabolomic data into the network context.\" (Data Sheet 3.pdf)\n%\n% USAGE:\n%\n%    [ResultsAllCellLines, OverViewResults] = setQuantConstraints(model, samples, tol, minGrowth, obj, no_secretion, no_uptake, medium, addExtraExch, addExtraExch_value, path, epsilon)\n%\n% INPUTS:\n%       model:                Global metabolic model (Recon)\n%       samples:              Vector specifying the samples used (there must be an output file of function .... for each sample)\n%       tol:                  Cutoff value for small numbers (e.g., -1e-8). All number smaller than tol will be treated as zero\n%       minGrowth:            Will be the lower bound of the objective function (e.g., 0.008). Forces the output model(s) to be able to produce a minimal objective value\n%       obj:                  Objective function, e.g. `biomass_reaction2`\n%       no_secretion:         Define metabolites that should not be secreted (e.g., {`EX_o2(e)`})\n%       no_uptake:            Define metabolites that should not be consumed (e.g., {`EX_o2s(e)`, `EX_h2o2(e)`})\n%       medium:               Define if certain exchanges should be excluded from minimization of exchanges (e.g., {}, if no medium except the exometabolomic data has been defined)\n%       addExtraExch:         After adding secretions, models are still not growing, this variable allows one to recover exchanges with a defined small value\n%       addExtraExch_value:   e.g. 1 as arbitrary small flux value / the resulting ub = 1, lb = -1.\n%       path:                 Location of the .mat files for samples.\n%       \n%\n% OUTPUTS:\n%       ResultsAllCellLines:  Structure that contains pruned and unpruned model, Vector of the Exchange_reactions, the exchange reactions added by `minExCard`, `minFLux` and `maxFlux` of the added reactions, maximal objective value, and the results of the gene deletion\n%       OverViewResults:      Overview of model statistics, e.g., number of reactions, metabolites, genes, number of essential genes, min and max objective values for easy comparison between sets of models\n%\n%\n% Depends on `changeRxnBounds`, `fluxVariability`, `optimizeCbModel`, `generateCompactExchModel` as well its dependent functions `pruneModel`, `findMinCardModel`, `findOptExchRxns`\n%\n% .. Author: - Maike K. Aurich 18/02/15\n\ncntO=1;\n% Set overview variable\nOverViewResults{1,cntO} ='cell line';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num Added Rxns';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num rxns pruned model';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num mets pruned model';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num genes pruned model';cntO = cntO+1;\nOverViewResults{1,cntO} = 'max growth rate';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num exch rxns';cntO = cntO+1;\nOverViewResults{1,cntO} = 'O2 requirement';cntO = cntO+1;\nOverViewResults{1,cntO} = 'extra Exchanges Added';cntO = cntO+1;\nOverViewResults{1,cntO} = 'num recovered exchanges';cntO = cntO+1;\n\nfor j = 1:length(samples)\n\n    j\n    %   load([path filesep 'model.mat']); %% uncomment for Recon1\n    ExtraExchAdded = 0;\n\n\n    FILENAME = char(samples(j,1));\n    load([path filesep FILENAME '.mat'])%, 'uptake_value', 'secr_value' , 'uptake' ,'secretion', 'cell_line' );\n\n\n    % Map exo-metabolomic data\n    model2=model;\n    model2.lb(find(ismember(model2.rxns,obj)))=minGrowth;% based on slowlest cell line in data\n\n\n    % Map uptake\n    for k=1:length(uptake)\n        Uptake_rxns=uptake(k);\n        lb = uptake_value(k,2);\n        ub = uptake_value(k,3);\n        model2 = changeRxnBounds(model2,Uptake_rxns,ub,'u'); %enforce uptake of metabolites taken up by cells in the experiment\n        model2 = changeRxnBounds(model2,Uptake_rxns,lb,'l'); %enforce uptake of metabolites taken up by cells in the experiment\n\n    end\n    clear A sol\n    model2ori=model2;\n    SecretionRxnsRecovered =[];\n    cnt2=1;\n\n    % Map secretion\n    for k=1:length(secretion)\n        secretion_rxns= secretion(k);\n        lb = secr_value(k,3);\n        ub = secr_value(k,2);\n        model2 = changeRxnBounds(model2, secretion_rxns,lb,'l');% enforce secretion of metabolites that are secreted by the cells in the experiment\n        model2 = changeRxnBounds(model2, secretion_rxns,ub,'u');% enforce secretion of metabolites that are secreted by the cells in the experiment\n\n        % check if model works after adding constraints\n        SOL = optimizeCbModel(model2);\n        if SOL.f<=abs(tol)\n            sol(k,1)=SOL.f;\n            secretion_rxns\n            model2=model2ori; % model2ori is overwritten after each successful iteration so its not the original model (without any secretions)\n            model2 = changeRxnBounds(model2, secretion_rxns,ub,'u');% set secretion of metabolite to measured upper bound nevertheless\n            SecretionRxnsRecovered{cnt2,1}=secretion_rxns{1,:}; cnt2 = cnt2 +1;\n        else\n            sol(k,1)=SOL.f;\n            model2ori=model2;\n        end\n    end\n\n    % sets bounds to the lowest measured uptake/secretion rate\n    for k=1:length(No_upt_secr)\n        No_upt_secr_rxns= No_upt_secr(k);\n        bound = min(abs([max(uptake_value(:,3));min(secr_value(:,3))]));\n        model2 = changeRxnBounds(model2, No_upt_secr_rxns,-bound,'l');\n        model2 = changeRxnBounds(model2, No_upt_secr_rxns,bound,'u');% sets bounds to the lowest measured uptake/secretion rate\n    end\n\n\n\n    % do not allow secretion or uptake of certain metabolites\n    model2 = changeRxnBounds(model2, no_secretion,0,'u');% enforce secretion of metabolites that are secreted by the cells in the experiment\n    model2 = changeRxnBounds(model2, no_uptake,0,'l');% enforce secretion of metabolites that are secreted by the cells in the experiment\n\n\n\n    %% test if model can grow AT ALL\n    SOL = optimizeCbModel(model2);\n    if abs(SOL.f) < abs(tol)\n\n        model2 = changeRxnBounds(model2, addExtraExch,-addExtraExch_value,'l');% sets bounds to the lowest measured uptake/secretion rate\n        model2 = changeRxnBounds(model2, addExtraExch,addExtraExch_value,'u');% sets bounds to the lowest measured uptake/secretion rate\n        ExtraExchAdded = 1;\n    end\n\n\n    SOL = optimizeCbModel(model2);\n    if abs(SOL.f) > abs(tol)\n        %Generate submodel\n        [modelMin, modelPruned, Ex_Rxns] = generateCompactExchModel(model2,minGrowth);\n\n        %added 23/07/2015\n        modelPruned.c = zeros(length(modelPruned.rxns),1);\n        modelPruned.c(find(ismember(modelPruned.rxns,obj)),1)=1;\n        %added 23/07/2015\n\n        sol= optimizeCbModel(modelPruned);\n        Ex_RxnsAdded = Ex_Rxns;\n\n        % remove reactions that are in uptake and secretion\n        US = unique([secretion;uptake]);\n        Ex_RxnsAdded(ismember(Ex_RxnsAdded,US))=[];\n        [a(:,1),a(:,2)]=fluxVariability(modelPruned,1,[],Ex_RxnsAdded);\n\n\n        % print Results\n\n        ResultsAllCellLines.(samples{j}).modelPruned = modelPruned;\n        ResultsAllCellLines.(samples{j}).modelMin = modelMin;\n        ResultsAllCellLines.(samples{j}).Ex_Rxns = Ex_Rxns;\n        ResultsAllCellLines.(samples{j}).Ex_RxnsAdded = Ex_RxnsAdded;\n        ResultsAllCellLines.(samples{j}).MinMaxAddedRxns = a;\n        ResultsAllCellLines.(samples{j}).maxBiomass = sol;\n\n        ResultsAllCellLines.(samples{j}).SecretionRxnsRecovered = SecretionRxnsRecovered;\n\n        cntO=1;\n        OverViewResults{j+1,cntO} = samples{j};cntO = cntO+1;% cell line\n        OverViewResults{j+1,cntO} = num2str(length(ResultsAllCellLines.(samples{j}).Ex_RxnsAdded));cntO = cntO+1;% num Added Rxns\n        OverViewResults{j+1,cntO} = num2str(length(ResultsAllCellLines.(samples{j}).modelPruned.rxns));cntO = cntO+1;% num rxns\n        OverViewResults{j+1,cntO} = num2str(length(ResultsAllCellLines.(samples{j}).modelPruned.mets));cntO = cntO+1;% num mets\n        OverViewResults{j+1,cntO} = num2str(length(ResultsAllCellLines.(samples{j}).modelPruned.genes));cntO = cntO+1;% num genes\n        OverViewResults{j+1,cntO} = num2str(ResultsAllCellLines.(samples{j}).maxBiomass.f);cntO = cntO+1;% max growth rate\n        OverViewResults{j+1,cntO} = num2str(length(ResultsAllCellLines.(samples{j}).Ex_Rxns));cntO = cntO+1;% num Exchange rxns\n        if ~isempty(strmatch('EX_o2(e)',ResultsAllCellLines.(samples{j}).Ex_RxnsAdded))\n            OverViewResults{j+1,cntO} = num2str(1);cntO = cntO+1;% O2 requirement\n        else\n            OverViewResults{j+1,cntO} = num2str(0);cntO = cntO+1;% O2 requirement\n        end\n\n        OverViewResults{j+1,cntO} = num2str(ExtraExchAdded);cntO = cntO+1;% num Exchange rxns\n        OverViewResults{j+1,cntO} = num2str(length(SecretionRxnsRecovered));cntO = cntO+1;% num Exchange rxns\n\n\n    else\n        ResultsAllCellLines.(samples{j}).model = [];\n        ResultsAllCellLines.(samples{j}).AddedExchange = [];\n        ResultsAllCellLines.(samples{j}).maxBiomass = [];\n        cntO=1;\n        OverViewResults{j+1,cntO} = samples{j};cntO = cntO+1;% cell line\n    end\n    clear sol Extra* addExtraExch* model2 modelMin* modelU* modelP* model2ori No* upt* secr* gr* Rxn* cnt* Blocked* h* FBA* j k m bound ans lb Close* Ex_Rxns1* Ex_Rxns2*  Sol U* Ori* i* ma* rev* t un* us* w a SOL a1 ub ToDe* ReP* Ex_* Secr* AddedExchang*\n    save([path filesep 'setQuantConstraints.mat'], '-v7.3');\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/metabotools/setQuantConstraints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21996500622684403}}
{"text": "%--------------------------------------------------------------------------------------------------------\n% The system is created based on the principles described in the following paper\n% Jimmy SJ. Ren, Li Xu, Qiong Yan, Wenxiu Sun, \"Shepard Convolutional Neural Networks\", \n% Advances in Neural Information Processing Systems (NIPS 2015)\n% email: jimmy.sj.ren@gmail.com\n%--------------------------------------------------------------------------------------------------------\naddpath applications/Shepard_CNN/Shepard_super_res/\naddpath utils/\naddpath cuda/\naddpath mem/\naddpath layers/\naddpath layers_adapters/\naddpath optimization/\naddpath pipeline/\naddpath data/\n\nclearvars -global config;\nclearvars -global mem;\nclear gen_mask_patch_cat_idx_for_super_res;\nclear;\nglobal config mem;\nshepard_sr_x2_configure();\ninit(0);\n\nload('data/Shepard_CNN/Shepard_super_res/x2/val_1ch/val_1');\n\nimages_t = reshape(images_t, size(images_t,1), size(images_t,2), 1, size(images_t,3));\nlabels_t = reshape(labels_t, size(labels_t,1), size(labels_t,2), 1, size(labels_t,3));\n\nperm = randperm(size(images_t, 4));\nimages_t = images_t(:,:,:,perm);\nlabels_t = labels_t(:,:,:,perm);\ntest_samples = config.NEW_MEM(images_t(:,:,:,1:1000));\ntest_labels = config.NEW_MEM(labels_t(:,:,:,1:1000));\n\nmask = config.NEW_MEM([1 0; 0 0]);\nmask = repmat(mask, config.input_size(1)/2, config.input_size(2)/2, config.chs);\nmask = repmat(mask, 1,1,1,config.batch_size);\n\ncount = 0;\ncost_avg = 0;\nepoc = 0;\npoints_seen = 0;\ndisplay_points = 5000;\nsave_points = 50000;\nmax_grad = 1;\nfprintf('%s\\n', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));\nfor pass = 1:10\n    for p = 1:50\n        load(strcat('data/Shepard_CNN/Shepard_super_res/x2/train_1ch/patches_', num2str(p), '.mat'));\n        \n        images = reshape(images, size(images,1), size(images,2), 1, size(images,3));\n        labels = reshape(labels, size(labels,1), size(labels,2), 1, size(labels,3));\n        \n        perm = randperm(20000);\n        images = images(:,:,:,perm);\n        labels = labels(:,:,:,perm);\n        train_imgs = config.NEW_MEM(images);\n        train_labels = config.NEW_MEM(labels);\n        \n        for i = 1:size(train_labels, 4) / config.batch_size            \n            points_seen = points_seen + config.batch_size;\n            in = train_imgs(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            %in = train_labels(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            out = train_labels(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            out = out((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...\n                      (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :, :);\n            \n                  \n            % make the mask list\n            mask_li = {};\n            mask_li{1} = mask;\n            % operate the training pipeline\n            op_train_pipe_with_mask(in.*mask, mask_li, out);\n            % update the weights\n            config.UPDATE_WEIGHTS();\n            \n            if(cost_avg == 0)\n                cost_avg = config.cost;\n            else\n                cost_avg = (cost_avg + config.cost) / 2;\n            end\n\n            % display point\n            if(mod(points_seen, display_points) == 0)\n                count = count + 1;\n                fprintf('%d ', count);\n            end\n            % save point\n            if(mod(points_seen, save_points) == 0)\n                fprintf('\\n%s', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));\n                epoc = epoc + 1;\n                test_cost = 0;\n                for t = 1:size(test_samples, 4) / config.batch_size\n                    t_label = test_labels(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size);\n                    t_label = config.NEW_MEM(t_label((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...\n                                            (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :));\n                    \n                    op_test_pipe_with_mask(test_samples(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size).*mask, mask_li, t_label);\n                    \n                    test_out = gather(mem.output);\n                    test_cost = test_cost + config.cost;\n                end\n                test_cost = test_cost / (size(test_samples, 4) / config.batch_size);\n                fprintf('\\nepoc %d, training avg cost: %f, test avg cost: %f\\n', epoc, cost_avg, test_cost);                \n                \n                save_weights(strcat('applications/Shepard_CNN/Shepard_super_res/results/shepard_layer_x2/epoc', num2str(epoc), '.mat'));\n                \n                cost_avg = 0;\n            end\n        end\n    end\nend\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/applications/Shepard_CNN/Shepard_super_res/shepard_sr_x2_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2199650005369408}}
{"text": "function [yAvg, tHRF, nTrials] = hmrG_SubjAvg_Nirs(yAvgSubjs, tHRFSubjs, nTrialsSubjs)\n% SYNTAX:\n% [yAvg, tHRF, nTrials] = hmrG_SubjAvg_Nirs(yAvgSubjs, tHRFSubjs, nTrialsSubjs)\n%\n% UI NAME:\n% Subj_Average\n%\n% DESCRIPTION:\n% Calculate avearge HRF of all subjects in a group . \n%\n% INPUTS:\n% yAvgSubjs:\n% tHRFSubjs: \n% nTrialsSubjs:\n%\n% OUTPUTS:\n% yavg: the averaged results\n% tHRF: the time vector\n% nTrials: the number of trials averaged for each condition across all\n%          subjects\n%\n% USAGE OPTIONS:\n% Subj_Average_on_Concentration_Data: [dcAvg, tHRF, nTrials] = hmrG_SubjAvg_Nirs(dcAvgSubjs, tHRFSubjs, nTrialsSubjs)\n% Subj_Average_on_Delta_OD_Data:      [dodAvg, tHRF, nTrials] = hmrG_SubjAvg_Nirs(dodAvgSubjs, tHRFSubjs, nTrialsSubjs)\n%\n%\n\nyAvg       = [];\ntHRF       = [];\nnTrials    = [];\n    \nsubjCh = [];\nnStim = 0;\ngrp1=[];\nnSubj = length(yAvgSubjs);\n\nfor iSubj = 1:nSubj\n    \n    if isempty(yAvgSubjs{iSubj}) || isempty(tHRFSubjs{iSubj}) || isempty(nTrialsSubjs{iSubj})\n        continue;\n    end\n    \n    yAvg      = yAvgSubjs{iSubj};\n    tHRF      = tHRFSubjs{iSubj};\n    nTrials   = nTrialsSubjs{iSubj};\n        \n    nCond = size(nTrials,2);\n    \n    if ndims(yAvg) == (4-(nCond<2))\n        \n        if iSubj==1\n            grp1 = zeros(size(yAvg,1), size(yAvg,2), size(yAvg,3), nCond);\n        end\n        \n        nCh  = size(yAvg,3);\n        if isempty(subjCh)\n            subjCh = zeros(nCh, nCond);\n        end\n        \n        for iC = 1:nCond\n            if nTrials(:,iC)==0\n                continue;\n            end\n            \n            if iSubj==1 | iC>nStim\n                for iCh = 1:size(yAvg,3)\n                    for iHb=1:3\n                        grp1(:,iHb,iCh,iC) = interp1(tHRF,yAvg(:,iHb,iCh,iC),tHRF(:));\n                    end\n                end\n                nStim = iC;\n            else\n                for iCh = 1:size(yAvg,3)\n                    for iHb=1:3\n                        grp1(:,iHb,iCh,iC) = grp1(:,iHb,iCh,iC) + interp1(tHRF,yAvg(:,iHb,iCh,iC),tHRF(:));\n                    end\n                end\n            end\n            subjCh(:,iC) = subjCh(:,iC) + 1; %#ok<*AGROW>\n        end\n        \n        yAvg = [];\n        if ~isempty(grp1)\n            for iC = 1:size(grp1,4)\n                for iCh = 1:size(grp1,3)\n                    yAvg(:,1,iCh,iC) = grp1(:,1,iCh,iC) / subjCh(iCh,iC);\n                    yAvg(:,2,iCh,iC) = grp1(:,2,iCh,iC) / subjCh(iCh,iC);\n                    yAvg(:,3,iCh,iC) = grp1(:,3,iCh,iC) / subjCh(iCh,iC);\n                end\n            end\n        end\n        \n    elseif ndims(yAvg) == (3-(nCond<2))\n        \n        if iSubj==1\n            grp1 = zeros(size(yAvg,1),size(yAvg,2),nCond);\n        end\n        \n        nCh  = size(yAvg,2);\n        if isempty(subjCh)\n            subjCh = zeros(nCh, nCond);\n        end\n        \n        for iC = 1:nCond\n            if nTrials(:,iC)==0\n                continue;\n            end\n            \n            for iWl = 1:2\n                if iSubj==1 | iC>nStim\n                    for iCh = 1:size(yAvg,2)\n                        grp1(:,iCh,iC) = interp1(tHRF,yAvg(:,iCh,iC),tHRF(:));\n                    end\n                    nStim = iC;\n                else\n                    for iCh = 1:size(yAvg,3)\n                        grp1(:,iCh,iC) = grp1(:,iCh,iC) + interp1(tHRF,yAvg(:,iCh,iC),tHRF(:));\n                    end\n                end\n                subjCh(:,iC) = subjCh(:,iC) + 1;\n            end\n        end\n        \n        yAvg = [];\n        if ~isempty(grp1)\n            for iC = 1:size(grp1,3)\n                for iCh = 1:size(grp1,2)\n                    yAvg(:,iCh,iC) = grp1(:,iCh,iC) / subjCh(iCh,iC);\n                    yAvg(:,iCh,iC) = grp1(:,iCh,iC) / subjCh(iCh,iC);\n                    yAvg(:,iCh,iC) = grp1(:,iCh,iC) / subjCh(iCh,iC);\n                end\n            end            \n        end\n        \n    end\nend\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/Archive/hmrG_SubjAvg_Nirs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21996500053694076}}
{"text": "% Function to difference each column in a matrix\n%\n% Description\n%  Function to difference each column in a matrix\n%\n%  This version is a slightly later one than that described in the\n%  above published 2013 CSL paper [2]. The algorithm here rather than using binary\n%  decision trees using artificial neural networks and combines the\n%  features used in the CSL paper with those proposed in Ishi et al.\n%  (2008). This updated version has been submitted to CSL for a special\n%  issue on glottal source processing on April 14th 2013. It will have\n%  reference [1].\n%\n% Inputs\n%  mat  : [samples] [NxM] Feature matrix\n%\n% Outputs\n%  delta_mat : [samples] [NxM] Differenced feature matrix\n%\n% Example\n%  Please see the HOWTO_glottalsource.m example file.\n%\n% References\n%  [1] Drugman, T., Kane, J., Gobl, C., `Automatic Analysis of Creaky\n%       Excitation Patterns', Submitted to Computer Speech and\n%       Language.\n%  [2] Kane, J., Drugman, T., Gobl, C., (2013) `Improved automatic \n%       detection of creak', Computer Speech and Language 27(4), pp.\n%       1028-1047.\n%  [3] Drugman, T., Kane, J., Gobl, C., (2012) `Resonator-based creaky \n%       voice detection', Interspeech 2012, Portland, Oregon, USA.\n%\n% Copyright (c) 2013 University of Mons, FNRS & 2013 Trinity College Dublin\n%\n% License\n%  This code is a part of the GLOAT toolbox with the following\n%  licence:\n%  This program is free software: you can redistribute it and/or modify\n%  it under the terms of the GNU General Public License as published by\n%  the Free Software Foundation, either version 3 of the License, or\n%  (at your option) any later version.\n%  This program is distributed in the hope that it will be useful,\n%  but WITHOUT ANY WARRANTY; without even the implied warranty of\n%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%  GNU General Public License for more details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n% \n% Authors\n%  Thomas Drugman <thomas.drugman@umons.ac.be> & John Kane <kanejo@tcd.ie>\n\nfunction delta_mat = get_delta_mat(mat)\n\ndelta_mat=zeros(size(mat));\nN=size(mat,2);\n\nfor n=1:N\n    delta_mat(2:end,n)=diff(mat(:,n));\nend\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/glottalsource/creaky_voice_detection/private/get_delta_mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.21970876019914887}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright 2014 National Renewable Energy Laboratory and National \n% Technology & Engineering Solutions of Sandia, LLC (NTESS). \n% Under the terms of Contract DE-NA0003525 with NTESS, \n% the U.S. Government retains certain rights in this software.\n% \n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n% \n% http://www.apache.org/licenses/LICENSE-2.0\n% \n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef mooringClass<handle\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % The ``mooringClass`` creates a ``mooring`` object saved to the MATLAB\n    % workspace. The ``mooringClass`` includes properties and methods used\n    % to define cable connections relative to other bodies.\n    % It is suggested that the ``mooringClass`` be used for connections between\n    % bodies and the global reference frame.\n    % \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    \n    % This class contains mooring parameters and settings\n    properties (SetAccess = 'public', GetAccess = 'public')%input file \n        initial                 = struct(...                               % (`structure`) Defines the initial displacement of the mooring. \n            'displacement',         [0 0 0], ...                           % \n            'axis',                 [0 1 0], ...                           % \n            'angle',                0)                                     % (`structure`) Defines the initial displacement of the mooring. ``displacement`` (`3x1 float vector`) is defined as the initial displacement of the pto [m] in the following format [x y z], Default = [``0 0 0``].\n        location                = [0 0 0]                                  % (`float 1 x 3`) Mooring Reference location. Default = ``[0 0 0]``        \n        matrix                  = struct(...                               % (`structure`) Defines the mooring parameters.\n            'damping',              zeros(6,6), ...                        % \n            'stiffness',            zeros(6,6), ...                        % \n            'preTension',           [0 0 0 0 0 0])                         % (`structure`) Defines the mooring parameters. ``damping`` (`6x6 float matrix`) Matrix of damping coefficients, Default = ``zeros(6)``. ``stiffness`` (`6x6 float matrix`) Matrix of stiffness coefficients, Default = ``zeros(6)``. ``preTension`` (`6x6 float matrix`) Array of pretension force in each dof, Default = ``[0 0 0 0 0 0]``.\n        moorDyn                 = 0                                        % (`integer`) Flag to indicate a MoorDyn block, 0 or 1. Default = ``0``\n        moorDynLines            = 0                                        % (`integer`) Number of lines in MoorDyn. Default = ``0``\n        moorDynNodes            = []                                       % (`integer`) number of nodes for each line. Default = ``'NOT DEFINED'``\n        name                    = 'NOT DEFINED'                            % (`string`) Name of the mooring. Default = ``'NOT DEFINED'``\n    end\n\n    properties (SetAccess = 'private', GetAccess = 'public') %internal\n        orientation             = []                                       % (`float 1 x 6`) Initial 6DOF location. Default = ``[0 0 0 0 0 0]``        \n        number                  = []                                       % (`integer`) Mooring number. Default = ``'NOT DEFINED'``        \n    end\n\n    methods (Access = 'public')                                        \n        function obj = mooringClass(name)\n            % This method initializes the mooringClass object\n            if exist('name','var')\n                obj.name = name;\n            else\n                error('The mooring class number(s) in the wecSimInputFile must be specified in ascending order starting from 1. The mooringClass() function should be called first to initialize each mooring line with a name.')\n            end\n        end\n\n        function setInitDisp(obj, relCoord, axisAngleList, addLinDisp)\n            % Function to set a mooring's initial displacement\n            % \n            % This function assumes that all rotations are about the same relative coordinate. \n            % If not, the user should input a relative coordinate of 0,0,0 and \n            % use the additional linear displacement parameter to set the cg or orientation\n            % correctly.\n            %\n            % Parameters\n            % ------------\n            %    relCoord : [1 3] float vector\n            %        Distance from x_rot to the body center of gravity or the constraint\n            %        or pto location as defined by: relCoord = cg - x_rot. [m]\n            %\n            %    axisAngleList : [nAngle 4] float vector\n            %        List of axes and angles of the rotations with the \n            %        format: [n_x n_y n_z angle] (angle in rad)\n            %        Rotations applied consecutively in order of dimension 1\n            %\n            %    addLinDisp : [1 3] float vector\n            %        Initial linear displacement (in addition to the \n            %        displacement caused by rotation) [m]\n            % \n            \n            % initialize quantities before for loop\n            axisList = axisAngleList(:,1:3);\n            angleList = axisAngleList(:,4);\n            nAngle = size(axisList,1);\n            rotMat = eye(3);            \n            % Loop through all axes and angles.\n            for i=1:nAngle\n                rotMat = axisAngle2RotMat(axisList(i,:),angleList(i))*rotMat;\n            end\n            % calculate net axis-angle rotation\n            [netAxis, netAngle] = rotMat2AxisAngle(rotMat);\n            % calculate net displacement due to rotation\n            rotatedRelCoord = relCoord*(rotMat');\n            linDisp = rotatedRelCoord - relCoord;\n            % apply rotation and displacement to object\n            obj.initial.displacement = linDisp + addLinDisp;\n            obj.initial.axis = netAxis;\n            obj.initial.angle = netAngle;            \n        end\n        \n        function listInfo(obj)\n            % Method to list mooring info\n            fprintf('\\n\\t***** Mooring Name: %s *****\\n',obj.name)\n        end\n\n        function obj = setLoc(obj)\n            % This method sets mooring location\n            obj.orientation = [obj.location + obj.initial.displacement 0 0 0];\n        end\n\n        function setNumber(obj,number)\n            % Method to set the private number property\n            obj.number = number;\n        end\n    end\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/mooringClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.21956785322839426}}
{"text": "function [h,s,v] = rgb2hsv_fast(r,g,b,opt_typ,opt_sel)\n%RGB2HSV_FAST does the same as RGB2HSV\n%but faster and less memory exhaustive,\n%especially on images which are stored as integers.\n%\n%RGB2HSV_FAST(IMG,'single')\n%You can specify the optional argument 'single'\n%to use single precision.\n%This saves memory and is sufficiently exact, anyhow.\n%\n%RGB2HSV_FAST(IMG,'','H')\n%Optionally, you can specify which channels to calculate:\n%'HSV' is default.\n%'H' calculates hue only.\n%'S' calculates saturation only.\n%'V' calculates value only.\n%'HS', 'HV', or 'SV' are also possible.\n\n% How to make it efficient?\n%  -  Don't cast integer images to floating point too soon.\n%     Operate on integers as far as possible and\n%     take advantage of functions like IMLINCOMB().\n%  -  Avoid FIND(). Directly index via binary arrays instead.\n%  -  Avoid RESHAPE().\n%     http://blogs.mathworks.com/loren/?p=28\n\n%\n% Alexander Ihlow, Germany, Oct 2006\n% Version 1.1\n% 2006-11-02 added support for individual channel selection\n%            version 1.0 saved to rgb2hsv_fast_10.m\n%\n%\n% RGB2HSV_FAST has a high cyclomatic complexity\n% due to lots of case checking.\n%\n% Please report bugs or suggestions to ml-user@web.de.\n\n\n\nthreeD = ndims(r) >= 3;\n\nif (nargin < 4), opt_typ = ''; end\nif (nargin < 5), opt_sel = ''; end\nif (nargin > 1) && ~isnumeric(g), opt_typ = g; end\nif (nargin > 2) && ~isnumeric(b), opt_sel = b; end\n\n%disp(['threeD = ' num2str(threeD)])\n%disp(['opt_typ = ' opt_typ])\n%disp(['opt_sel = ' opt_sel])\n\nvv = version; vv=str2double(vv(1));\n% Check input class\nswitch (class(r))\n  case 'uint8'\n    immax = 255;\n  case 'uint16'\n    immax = 65535;\n  case 'double'\n    immax = 1;\n  case 'single'\n    if vv < 7\n      error('Matlab version < 7 cannot perform calculations with single precision. Please cast to double first!')\n    else\n      immax = 1;\n      % If input is single, output single per default.\n      if isempty(opt_typ), opt_typ = 'single'; end\n    end\n  otherwise\n    if vv < 7\n      error('Only images of type uint8, uint16, and double are supported!')\n    else\n      error('Only images of type uint8, uint16, single, and double are supported!')\n    end\nend\n\n% Default output is double.\nif isempty(opt_typ), opt_typ = 'double'; end\n\n% Use single precision if optionally specified.\n% This saves 1/2 of memory and is exact enough\n% for those simple colorspace transformations.\n% single : out_typ = 1\n% double : out_typ = 2\nswitch lower(opt_typ(1))\n  case 's'\n    out_typ = 1;\n  otherwise\n    out_typ = 2;\nend\n\n% For Matlab < version 7, no single precision is supported.\nif (out_typ == 1) && (vv < 7)\n  disp('Single precision is not available in this Matlab version. Using double.')\n  out_typ = 2;\nend\n\n% Helper functions to map float either to single or double.\nif out_typ == 1\n  im2float = inline('im2single(x)');\n  float = inline('single(x)');\n  floatstr = 'single';\nelse\n  im2float = inline('im2double(x)');\n  float = inline('double(x)');\n  floatstr = 'double';\nend\n\nimmax = float(immax);\n\n\nif threeD\n  % Split RGB image into R G B channels and\n  % thereby support arbitrary dimensional images.\n  % R G B is assumed to be contained in the third dimension.\n  sizc = num2cell(size(r));\n  for k=1:numel(sizc), sizc{k} = ':'; end\n  sizc{3} = 2;\n  g = r(sizc{:});\n  sizc{3} = 3;\n  b = r(sizc{:});\n  sizc{3} = 1;\n  r = r(sizc{:});\nelseif nargin==1\n  % split N x 3 matrix into three vectors\n  g = r(:,2); b = r(:,3); r = r(:,1);\nend\nsiz = size(r);\n\n\nif isempty(opt_sel), opt_sel = 'HSV'; else opt_sel = upper(opt_sel); end\n\nif any( (opt_sel ~= 'H') & (opt_sel ~= 'S') & (opt_sel ~= 'V') )\n  error('Invalid optional argument! Please use ''H'', ''S'', or ''V''')\nend\n\n\nif exist('imsubtract','file')\n  % Image Processing Toolbox available\n  % --> The calculation of HUE and SAT\n  %     is performed without precasting R, G, and B to floats.\n  v = max(max(r,g),b);\n  if any(opt_sel == 'H') || any(opt_sel == 'S')\n    s = imsubtract(v, min(min(r,g),b));\n    z = ~s;\n    s = im2float(s);\n    s(z) = 1;\n    \n    if any(opt_sel == 'H')\n      % Calculating HUE via IMLINCOMB() is highly efficient.\n      sizc = num2cell(siz);\n      h(sizc{:}) = float(0);\n      k = (r == v);\n      h(k) =     imlincomb(1,g(k),-1,b(k),floatstr)./(immax*s(k));\n      k = (g == v);\n      h(k) = 2 + imlincomb(1,b(k),-1,r(k),floatstr)./(immax*s(k));\n      k = (b == v);\n      h(k) = 4 + imlincomb(1,r(k),-1,g(k),floatstr)./(immax*s(k));\n      \n      h = (1/6) * h;\n      k = (h < 0);\n      h(k) = h(k) + 1;\n      \n      h(z) = 0;\n    end\n    \n    if any(opt_sel == 'S') || any(opt_sel == 'V')\n      k = (v ~= 0);\n      v = im2float(v);\n      if any(opt_sel == 'S')\n        s(k) = (~z(k)).*s(k)./v(k);\n        s(~k) = 0;\n      end\n    end\n  else\n    v = im2float(v);\n  end\n  \nelse\n  % Image Processing Toolbox not available\n  % --> Use suboptimal procedure.\n  v = im2float(max(max(r,g),b));\n  if any(opt_sel == 'H') || any(opt_sel == 'S')\n    s = v - im2float(min(min(r,g),b));\n    z = ~s;\n    s(z) = 1;\n    \n    sizc = num2cell(siz);\n    h(sizc{:}) = float(0);\n    \n    if any(opt_sel == 'H')\n      k = (im2float(r) == v);\n      h(k) =     (im2float(g(k))-im2float(b(k)))./s(k);\n      k = (im2float(g) == v);\n      h(k) = 2 + (im2float(b(k))-im2float(r(k)))./s(k);\n      k = (im2float(b) == v);\n      h(k) = 4 + (im2float(r(k))-im2float(g(k)))./s(k);\n      \n      h = (1/6) * h;\n      k = (h < 0);\n      h(k) = h(k) + 1;\n      \n      h(z) = 0;\n    end\n    \n    if any(opt_sel == 'S')\n      k = (v ~= 0);\n      s(k) = (~z(k)).*s(k)./v(k);\n      s(~k) = 0;\n    end\n  end\n\nend\n\nif ~any(opt_sel == 'H'), h = float([]); end\nif ~any(opt_sel == 'S'), s = float([]); end\nif ~any(opt_sel == 'V'), v = float([]); end\n\nif nargout <= 1,\n  if (threeD || nargin>=3),\n    h = cat(3,h,s,v);\n  else\n    h = [h s v];\n  end\nelse\n  switch opt_sel\n    case 'HSV'\n      %\n    case 'H'\n      disp('There is more than one output variable given, but only HUE is assigned to the first one!')\n    case 'S'\n      h = s;\n      disp('There is more than one output variable given, but only SAT is assigned to the first one!')\n    case 'V'\n      h = v;\n      disp('There is more than one output variable given, but only VAL is assigned to the first one!')\n    case 'HS'\n      if nargout > 2\n        disp('There are more than two output variables given, but only HUE and SAT are assigned to the first two!')\n      end\n    case 'HV'\n      s = v;\n      if nargout > 2\n        disp('There are more than two output variables given, but only HUE and VAL are assigned to the first two!')\n      end\n    case 'SV'\n      h = s;\n      s = v;\n      if nargout > 2\n        disp('There are more than two output variables given, but only SAT and VAL are assigned to the first two!')\n      end\n    otherwise\n      disp('Unrecognized output - please check what happened!')\n  end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15985-fast-rgb2hsv/rgb2hsv_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.21956784838315682}}
{"text": "function [im] = prep_im_for_blob(im, im_means, target_size, max_size)\n    im = single(im);\n    \n    if ~isa(im, 'gpuArray')\n        try\n            im = bsxfun(@minus, im, im_means);\n        catch\n            im_means = imresize(im_means, [size(im, 1), size(im, 2)], 'bilinear', 'antialiasing', false);    \n            im = bsxfun(@minus, im, im_means);\n        end\n        %im_scale = prep_im_for_blob_size(size(im), target_size, max_size);\n\n        %target_size = round([size(im, 1), size(im, 2)] * im_scale);\n        im = imresize(im, target_size, 'bilinear', 'antialiasing', false);\n    else\n        % for im as gpuArray\n        try\n            im = bsxfun(@minus, im, im_means);\n        catch\n            im_means_scale = max(double(size(im, 1)) / size(im_means, 1), double(size(im, 2)) / size(im_means, 2));\n            im_means = imresize(im_means, im_means_scale);    \n            y_start = floor((size(im_means, 1) - size(im, 1)) / 2) + 1;\n            x_start = floor((size(im_means, 2) - size(im, 2)) / 2) + 1;\n            im_means = im_means(y_start:(y_start+size(im, 1)-1), x_start:(x_start+size(im, 2)-1));\n            im = bsxfun(@minus, im, im_means);\n        end\n        \n        %im_scale = prep_im_for_blob_size(size(im), target_size, max_size);\n        %im = imresize(im, target_size);\n    end\nend", "meta": {"author": "wenguanwang", "repo": "deepattention", "sha": "d66e2db4a9dc0ec5ebc4eb275e3199f9a59f6752", "save_path": "github-repos/MATLAB/wenguanwang-deepattention", "path": "github-repos/MATLAB/wenguanwang-deepattention/deepattention-d66e2db4a9dc0ec5ebc4eb275e3199f9a59f6752/utils/prep_im_for_blob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954586785042035}}
{"text": "function d =  testing(a,d)\n  \n Kt=get_x(a.Xsv)*get_x(d)'; \n Yt=get_y(d);\n  \n Yest=((a.alpha'* Kt)+a.b0)';\n if a.algorithm.use_signed_output\n   Yest=sign(Yest);\n end\n \n d=set_x(d,Yest); \n d=set_name(d,[get_name(d) ' -> ' get_name(a)]); \n  \n \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/pat/@template/testing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2195001664095534}}
{"text": "function model = update_integer_bounds(model);\n\nif ~isempty(model.integer_variables)\n    % Clean up things like 0.00001 <= x <= 0.999999 to 0 <= x <= 1\n    % however, don't kill equalities 1 <= x <= 1\n    lbfixed = fix(model.lb(model.integer_variables));\n    ubfixed = fix(model.ub(model.integer_variables));\n    fixlb = find(model.lb(model.integer_variables) == lbfixed);\n    fixub = find(model.ub(model.integer_variables) == ubfixed);\n    model.lb(model.integer_variables) = ceil(model.lb(model.integer_variables)-1e-4);\n    model.ub(model.integer_variables) = floor(model.ub(model.integer_variables)+1e-4);\n    if ~isempty(fixlb)\n        model.lb(model.integer_variables(fixlb)) = lbfixed(fixlb);\n    end\n    if ~isempty(fixub)\n        model.ub(model.integer_variables(fixub)) = ubfixed(fixub);\n    end\nend\nif ~isempty(model.binary_variables)\n    lbfixed = fix(model.lb(model.binary_variables));\n    ubfixed = fix(model.ub(model.binary_variables));\n    fixlb = find(model.lb(model.binary_variables) == lbfixed);\n    fixub = find(model.ub(model.binary_variables) == ubfixed);\n    model.lb(model.binary_variables) = ceil(model.lb(model.binary_variables)-1e-4);\n    model.ub(model.binary_variables) = floor(model.ub(model.binary_variables)+1e-4);\n    if ~isempty(fixlb)\n        model.lb(model.binary_variables(fixlb)) = lbfixed(fixlb);\n    end\n    if ~isempty(fixub)\n        model.ub(model.binary_variables(fixub)) = ubfixed(fixub);\n    end\nend\nif any(model.lb(model.binary_variables) > model.ub(model.binary_variables))\n    model.feasible = 0;\nend\nif any(model.lb(model.integer_variables) > model.ub(model.integer_variables))\n    model.feasible = 0;\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/modules/global/update_integer_bounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21934320047198635}}
{"text": "function [DCM] = spm_dcm_ssr_results(DCM,Action)\n% Results for ERP Dynamic Causal Modeling (DCM)\n% FORMAT spm_dcm_erp_results(DCM,'spectral data');\n% FORMAT spm_dcm_erp_results(DCM,'Coupling (A)');\n% FORMAT spm_dcm_erp_results(DCM,'Coupling (B)');\n% FORMAT spm_dcm_erp_results(DCM,'Coupling (C)');\n% FORMAT spm_dcm_erp_results(DCM,'trial-specific effects');\n% FORMAT spm_dcm_erp_results(DCM,'Input');\n% FORMAT spm_dcm_erp_results(DCM,'Cross-spectral density');\n% FORMAT spm_dcm_erp_results(DCM,'Dipoles');\n%                \n%___________________________________________________________________________\n%\n% DCM is a causal modelling procedure for dynamical systems in which\n% causality is inherent in the differential equations that specify the model.\n% The basic idea is to treat the system of interest, in this case the brain,\n% as an input-state-output system.  By perturbing the system with known\n% inputs, measured responses are used to estimate various parameters that\n% govern the evolution of brain states.  Although there are no restrictions\n% on the parameterisation of the model, a bilinear approximation affords a\n% simple re-parameterisation in terms of effective connectivity.  This\n% effective connectivity can be latent or intrinsic or, through bilinear\n% terms, model input-dependent changes in effective connectivity.  Parameter\n% estimation proceeds using fairly standard approaches to system\n% identification that rest upon Bayesian inference.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_dcm_ssr_results.m 4096 2010-10-22 19:40:34Z karl $\n \n \n% get figure handle\n%--------------------------------------------------------------------------\nFgraph = spm_figure('GetWin','Graphics');\ncolormap(gray)\nfigure(Fgraph)\nclf\n\n% placespectral features in xY.y\n%--------------------------------------------------------------------------\nDCM.xY.y  = spm_cond_units(DCM.xY.csd,'csd');\n\n% trial data\n%--------------------------------------------------------------------------\nxY  = DCM.xY;                   % data\nnt  = length(xY.y);             % Nr trial types\nnf  = size(xY.y{1},1);          % Nr frequency bins\nnm  = size(xY.y{1},2);          % Nr spatial modes\nHz  = xY.Hz;                    % PST\n\n% switch\n%--------------------------------------------------------------------------\nswitch(lower(Action))    \n    \ncase{lower('spectral data')}\n    \n    % spm_dcm_ssr_results(DCM,'Data');\n    %----------------------------------------------------------------------\n    co = {'b', 'r', 'g', 'm', 'y', 'k', 'c'};\n    Hz = xY.Hz;\n    q  = max(spm_vec(xY.y));\n    nm = min(nm,4);\n    \n    for k = 1:nt\n        str{k} = sprintf('trial %i',k);\n    end\n    \n    for i = 1:nm\n        for j = i:nm\n \n            % for each trial type\n            %--------------------------------------------------------------\n            subplot(nm,nm,(i - 1)*nm + j),cla\n            for k = 1:nt\n                plot(Hz,xY.y{k}(:,i,j),'color',co{k}), hold on\n                set(gca,'YLim',[0 q])\n            end\n        end\n \n        % spectral density\n        %------------------------------------------------------------------\n        subplot(2,2,3)\n        for k = 1:nt\n            plot(Hz,xY.y{k}(:,i,i),'color',co{i}), hold on\n            set(gca,'YLim',[0 q])\n        end\n    end\n    \n    title('spectral density over modes')\n    xlabel('Frequency (Hz)')\n    ylabel('CSD')\n    axis square\n    return\n    \nend\n \n% post inversion parameters\n%--------------------------------------------------------------------------\nnu  = length(DCM.B);          % Nr experimental inputs\nns  = size(DCM.A{1},2);       % Nr of sources\n\n \n% switch\n%--------------------------------------------------------------------------\nswitch(lower(Action))    \n    \ncase{lower('Coupling (A)')}\n    \n    % spm_dcm_ssr_results(DCM,'coupling (A)');\n    %----------------------------------------------------------------------\n    str = {'Forward','Backward','Lateral'};\n    for  i = 1:3\n        \n        % images\n        %------------------------------------------------------------------\n        subplot(4,3,i)\n        imagesc(exp(DCM.Ep.A{i}))\n        title(str{i},'FontSize',10)\n        set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname,'FontSize',8)\n        set(gca,'XTick',[])\n        xlabel('from','FontSize',8)\n        ylabel('to','FontSize',8)\n        axis square\n    \n        % table\n        %------------------------------------------------------------------\n        subplot(4,3,i + 3)\n        text(0,1/2,num2str(full(exp(DCM.Ep.A{i})),' %.2f'),'FontSize',8)\n        axis off,axis square\n \n    \n        % PPM\n        %------------------------------------------------------------------\n        subplot(4,3,i + 6)\n        image(64*DCM.Pp.A{i})\n        set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname,'FontSize',8)\n        set(gca,'XTick',[])\n        title('PPM')\n        axis square\n    \n        % table\n        %------------------------------------------------------------------\n        subplot(4,3,i + 9)\n        text(0,1/2,num2str(DCM.Pp.A{i},' %.2f'),'FontSize',8)\n        axis off, axis square\n        \n    end\n    \ncase{lower('Coupling (C)')}\n    \n    % spm_dcm_ssr_results(DCM,'coupling (C)');\n    %----------------------------------------------------------------------\n    \n    % images\n    %----------------------------------------------------------------------\n    subplot(2,4,1)\n    imagesc(exp(DCM.Ep.C))\n    title('Factors','FontSize',10)\n    set(gca,'XTick',[1:nu],'XTickLabel','Input','FontSize',8)\n    set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname, 'FontSize',8)\n    axis square\n    \n    % PPM\n    %----------------------------------------------------------------------\n    subplot(2,4,3)\n    image(64*DCM.Pp.C)\n    title('Factors','FontSize',10)\n    set(gca,'XTick',[1:nu],'XTickLabel','Input','FontSize',8)\n    set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname, 'FontSize',8)\n    axis square\n    title('PPM')\n    \n    % table\n    %----------------------------------------------------------------------\n    subplot(2,4,2)\n    text(0,1/2,num2str(full(exp(DCM.Ep.C)),' %.2f'),'FontSize',8)\n    axis off\n \n    % table\n    %----------------------------------------------------------------------\n    subplot(2,4,4)\n    text(0,1/2,num2str(DCM.Pp.C,' %.2f'),'FontSize',8)\n    axis off\n \n \ncase{lower('Coupling (B)')}\n    \n    % spm_dcm_ssr_results(DCM,'coupling (B)');\n    %----------------------------------------------------------------------\n    for i = 1:nu\n        \n        % images\n        %------------------------------------------------------------------\n        subplot(4,nu,i)\n        imagesc(exp(DCM.Ep.B{i}))\n        title(DCM.xU.name{i},'FontSize',10)\n        set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname,'FontSize',8)\n        set(gca,'XTick',[])\n        xlabel('from','FontSize',8)\n        ylabel('to','FontSize',8)\n        axis square\n \n        % tables\n        %------------------------------------------------------------------\n        subplot(4,nu,i + nu)\n        text(0,1/2,num2str(full(exp(DCM.Ep.B{i})),' %.2f'),'FontSize',8)\n        axis off\n        axis square\n        \n        % PPM\n        %------------------------------------------------------------------\n        subplot(4,nu,i + 2*nu)\n        image(64*DCM.Pp.B{i})\n        set(gca,'YTick',[1:ns],'YTickLabel',DCM.Sname,'FontSize',8)\n        set(gca,'XTick',[])\n        title('PPM')\n        axis square\n \n        % tables\n        %------------------------------------------------------------------\n        subplot(4,nu,i + 3*nu)\n        text(0,1/2,num2str(DCM.Pp.B{i},' %.2f'),'FontSize',8)\n        axis off\n        axis square\n        \n    end\n    \ncase{lower('trial-specific effects')}\n    \n    % spm_dcm_ssr_results(DCM,'trial-specific effects');\n    %----------------------------------------------------------------------\n    for i = 1:ns\n        for j = 1:ns\n \n            % ensure connection is enabled\n            %--------------------------------------------------------------\n            q     = 0;\n            for k = 1:nu\n                q = q | DCM.B{k}(i,j);\n            end\n \n            % plot trial-specific effects\n            %--------------------------------------------------------------\n            if q\n                B     = zeros(nt,1);\n                for k = 1:nu\n                    B = B + DCM.xU.X(:,k)*DCM.Ep.B{k}(i,j);\n                end\n                \n                subplot(ns,ns,(i - 1)*ns + j)\n                bar(exp(B)*100,'c')\n                title([DCM.Sname{j}, ' to ' DCM.Sname{i}],'FontSize',10)\n                xlabel('trial',  'FontSize',8)\n                ylabel('strength (%)','FontSize',8)\n                set(gca,'XLim',[0 nt + 1])\n                axis square\n \n            end\n        end\n    end\n    \ncase{lower('Input')}\n    \n    % spectrum of innovations or noise (Gu)\n    %----------------------------------------------------------------------\n    try\n        Gu   = exp(DCM.Ep.a)*xY.Hz.^(-1)*2;    % spectral density of (AR) input\n        Gu   = Gu + exp(DCM.Ep.b);             % spectral density of IID input\n    catch\n        Gu   = exp(DCM.Ep.a(1))*xY.Hz.^(-1);    % spectral density of (AR) input\n        Gu   = Gu + exp(DCM.Ep.a(2));           % spectral density of IID input\n    end\n    \n    % plot spectral density of innovations\n    % ---------------------------------------------------------------------\n    subplot(2,1,1)\n    plot(xY.Hz,Gu)\n    xlabel('frquency (Hz)')\n    title('spectrum of innovations or noise')\n    axis square, grid on\n    \ncase{lower('Cross-spectral density')}\n    \n    % spm_dcm_ssr_results(DCM,'Cross-spectral density');\n    %----------------------------------------------------------------------\n    co = {'b', 'r', 'g', 'm', 'y', 'k', 'c'};\n    Hz = xY.Hz;\n    q  = max(spm_vec(DCM.Hc));\n    nm = min(nm,4);\n    \n    tstr = {};\n    mstr = {};\n    for k = 1:nt\n        tstr{end + 1} = sprintf('predicted: trial %i',k);\n        tstr{end + 1} = sprintf('observed: trial %i',k);\n    end\n    for k = 1:nm\n        mstr{end + 1} = sprintf('predicted: mode %i',k);\n        mstr{end + 1} = sprintf('observed: mode %i',k);\n    end\n    \n    for i = 1:nm\n        for j = i:nm\n \n            % for each trial type\n            %--------------------------------------------------------------\n            subplot(nm,nm,(i - 1)*nm + j),cla\n            for k = 1:nt\n                plot(Hz,DCM.Hc{k}(:,i,j),'color',co{k}), hold on\n                plot(Hz,DCM.Hc{k}(:,i,j) + DCM.Rc{k}(:,i,j),':','color',co{k})\n                set(gca,'YLim',[0 q])\n            end\n        end\n \n        % legend\n        %------------------------------------------------------------------      \n        if i == nm && j == nm\n            legend(tstr)\n        end\n        \n        % spectral density\n        %------------------------------------------------------------------\n        subplot(2,2,3)\n        for k = 1:nt\n            plot(Hz,DCM.Hc{k}(:,i,i),'color',co{i}), hold on\n            plot(Hz,DCM.Hc{k}(:,i,i) + DCM.Rc{k}(:,i,i),':','color',co{i})\n            set(gca,'YLim',[0 q])\n        end\n    end\n   \n    title({'Spectral density over modes';'(in channel-space)'},'FontSize',16)\n    xlabel('Frequency (Hz)')\n    ylabel('root CSD')\n    axis square\n    legend(mstr)\n    \n    \n    \ncase{lower('Dipoles')}\n    \n    % return if LFP\n    % ---------------------------------------------------------------------\n    if strcmp(lower(DCM.xY.modality),'lfp')\n        warndlg('There are no ECDs for these LFP data')\n        return\n    end\n    \n    % plot dipoles\n    % ---------------------------------------------------------------------\n    try\n        P            = DCM.Ep;   \n        np           = size(P.L,2)/size(P.Lpos,2);\n        sdip.n_seeds = 1;\n        sdip.n_dip   = np*ns;\n        sdip.Mtb     = 1;\n        sdip.j{1}    = full(P.L);\n        sdip.j{1}    = sdip.j{1}(:);\n        sdip.loc{1}  = kron(ones(1,np),full(P.Lpos));\n        spm_eeg_inv_ecd_DrawDip('Init', sdip)\n    end\n \nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/dcm_meeg/spm_dcm_ssr_results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.21923128076823017}}
{"text": "% run_simMegaExTEShaped.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% This script is run simply by editing the input parameters and then\n% clicking \"Run\".\n% \n% DESCRIPTION:\n% This script simulates an ExTE-MEGA-PRESS experiment with fully shaped editing \n% and refocusing pulses.  Phase cycling of both the editing and refocusing\n% pulses is performed.  Simulations are run at various\n% locations in space to account for the within-voxel spatial variation of\n% the GABA signal.  Summation across phase cycles and spatial positions is\n% performed.  As a result of the phase cycling and spatially resolved simulations, \n% this code takes a long time to run.  Therefore, the MATLAB parallel computing\n% toolbox (parfor loop) was used to accelerate the siumulations.  Accelration \n% is currently performed in the direction of the slice selective pulse along\n% the x-direction, but this can be changed.  Up to a factor of 12 acceleration\n% can be achieved using this approach.  To enable the use of the MATLAB\n% parallel computing toolbox, initialize the multiple worked nodes using\n% \"matlabpool size X\" where \"X\" is the number of available processing\n% nodes.  If the parallel processing toolbox is not available, then replace\n% the \"parfor\" loop with a \"for\" loop.\n% \n% INPUTS:\n% To run this script, edit the parameters below as desired and then click\n% \"run\":\n% refocWaveform     = name of refocusing pulse waveform.\n% editWaveform      = name of editing pulse waveform.\n% editOnFreq        = freqeucny of edit on pulse[ppm]\n% editOffFreq       = frequency of edit off pulse[ppm]\n% refTp             = duration of refocusing pulses[ms]\n% editTp            = duration of editing pulses[ms]\n% Bfield            = Magnetic field strength in [T]\n% Npts              = number of spectral points\n% sw                = spectral width [Hz]\n% Bfield            = magnetic field strength [Tesla]\n% lw                = linewidth of the output spectrum [Hz]\n% thkX              = slice thickness of x refocusing pulse [cm]\n% thkY              = slice thickness of y refocusing pulse [cm]\n% x                 = vector of X positions to simulate [cm]\n% y                 = vector of y positions to simulate [cm]\n% taus              = vector of pulse sequence timings  [ms]\n% spinSys           = spin system to simulate \n% editPhCyc1        = vector of phase cycling steps for 1st editing pulse [degrees]\n% editPhCyc2        = vector of phase cycling steps for 2nd editing pulse [degrees]\n% refPhCyc1         = vector of phase cycling steps for 1st refocusing pulse [degrees]\n% refPhCyc2         = vector of phase cycling steps for 2nd refocusing pulse [degrees]\n%\n% OUTPUTS:\n% outON_posxy       = Simulated ExTE-MEGA-PRESS edit-ON spectrum, spatially resolved. \n% outOFF_posxy      = Simulated ExTE-MEGA-PRESS edit-OFF spectrum, spatially resolved.\n% outDIFF_posxy     = Simulated ExTE-MEGA-PRESS difference spectrum, spatially resolved.\n% outON             = Simulated ExTE-MEGA-PRESS edit-ON spectrum, summed over\n%                     all positions.\n% outOFF            = Simulated ExTE-MEGA-PRESS edit-OFF spectrum, summed over\n%                     all positions.\n% outDIFF           = Simulated ExTE-MEGA-PRESS difference spectrum, summed over\n%                     all positions.\n\n% ************INPUT PARAMETERS**********************************\nrefocWaveform='sampleRefocPulse.pta'; %name of refocusing pulse waveform.\neditWaveform='sampleEditPulse.pta'; %name of editing pulse waveform.\neditOnFreq=1.88; %freqeucny of edit on pulse[ppm]\nrefTp=5.2; %duration of refocusing pulses[ms]\neditTp=14; %duration of editing pulses[ms]\nNpts=2048; %number of spectral points\nsw=2000; %spectral width [Hz]\nlw=2; %linewidth of the output spectrum [Hz]\nBfield=2.89; %Magnetic field strength in [T]\nthkX=3.5; %slice thickness of x refocusing pulse [cm]\nthkY=3.5; %slice thickness of y refocusing pulse [cm]\nx=linspace(-2.0125,2.0125,12); %X positions to simulate [cm]\ny=linspace(-2.0125,2.0125,12); %y positions to simulate [cm]\ntaus_inv=...  %Timing for J-Inverted scan\n        [4.9,...    %time from excitation to 1st refoc pulse [ms]\n        67.4885,... %time from 1st refoc pulse to 1st editing pulse [ms]\n        33.5115,... %time from 1st editing pulse to 2nd refoc pulse [ms]\n        33.4885,... %time from 2nd refoc pulse to 2nd editing pulse [ms]\n        62.6115];   %time from 2nd editing pulse to ADC onset [ms]\ntaus_ref=... %Timing for J-refocused scan\n        [4.9,...    %time from excitation to 1st refoc pulse [ms]\n        50.4885,... %time from 1st refoc pulse to 1st editing pulse [ms]\n        50.5115,... %time from 1st editing pulse to 2nd refoc pulse [ms]\n        50.4885,... %time from 2nd refoc pulse to 2nd editing pulse [ms]\n        45.6115];   %time from 2nd editing pulse to ADC onset [ms]\nspinSys='GABA'; %spin system to simulate\ncentreFreq=3.0; %Centre frequency of MR spectrum [ppm]\neditPhCyc1=[0 90]; %phase cycling steps for 1st editing pulse [degrees]\neditPhCyc2=[0 90]; %phase cycling steps for 2nd editing pulse [degrees]\nrefPhCyc1=[0,90]; %phase cycling steps for 1st refocusing pulse [degrees]\nrefPhCyc2=[0,90]; %phase cycling steps for 2nd refocusing pulse [degrees]\n% ************END OF INPUT PARAMETERS**********************************\n\n%Load RF waveforms\nrefRF=io_loadRFwaveform(refocWaveform,'ref',0);\neditRF=io_loadRFwaveform(editWaveform,'inv',0);\n\ngamma=42577000; %gyromagnetic ratio\n\n%Load spin systems\nload spinSystems\nif strcmp(spinSys,'MM');\n    sys=sysGABA;\n    sys.shifts(3)=1.7;\n    sys.shifts(4)=1.7;\nelse\n    sys=eval(['sys' spinSys]);\nend\n    \n%Resample refocusing RF pulse from 400 pts to 100 pts to reduce\n%computational workload\nrefRF=rf_resample(refRF,100);\n\n%This is the step where the editing pulse waveform (initially a pulse with \n%zero-frequency) is frequency shifted to produce and edit-on and an\n%edit-off pulse;\neditRFon=rf_freqshift(editRF,editTp,(centreFreq-editOnFreq)*Bfield*gamma/1e6);\n\nGx=(refRF.tbw/(refTp/1000))/(gamma*thkX/10000); %[G/cm]\nGy=(refRF.tbw/(refTp/1000))/(gamma*thkY/10000); %[G/cm]\n\n[DX,DY]=meshgrid(x,y);\n\n%n=1;\n%totalIters=length(x)*length(y)*length(editPhCyc1)*length(editPhCyc2)*length(refPhCyc1)*length(refPhCyc2);\n\n%Initialize structures:\noutON_posxy_epc_rpc=cell(length(x),length(y),length(editPhCyc1),length(editPhCyc2),length(refPhCyc1),length(refPhCyc2));\noutOFF_posxy_epc_rpc=cell(length(x),length(y),length(editPhCyc1),length(editPhCyc2),length(refPhCyc1),length(refPhCyc2));\noutON_posxy_epc=cell(length(x),length(y),length(editPhCyc1),length(editPhCyc2));\noutOFF_posxy_epc=cell(length(x),length(y),length(editPhCyc1),length(editPhCyc2));\noutON_posxy=cell(length(x),length(y));\noutOFF_posxy=cell(length(x),length(y));\noutDIFF_posxy=cell(length(x),length(y));\noutON=struct([]);\noutOFF=struct([]);\n\n\n%loop through space: Don't forget to initialize the parallel processing\n%toolbox workers using 'matlabpool open N' (for N workers, 12 max).\n\nfor X=1:length(x);\n%parfor X=1:length(x);\n    for Y=1:length(y);\n        for EP1=1:length(editPhCyc1)\n            for EP2=1:length(editPhCyc2)\n                for RP1=1:length(refPhCyc1)\n                    for RP2=1:length(refPhCyc2)\n                        disp(['Executing X-position ' num2str(X) ' of ' num2str(length(x)) ', '...\n                            'Y-position ' num2str(Y) ' of ' num2str(length(y)) ', '...\n                            'First Edit phase cycle ' num2str(EP1) ' of ' num2str(length(editPhCyc1)) ', '...\n                            'Second Edit phase cycle ' num2str(EP2) ' of ' num2str(length(editPhCyc2)) ', '...\n                            'First Refoc phase cycle ' num2str(RP1) ' of ' num2str(length(refPhCyc1)) ', '...\n                            'Second Refoc phase cycle ' num2str(RP2) ' of ' num2str(length(refPhCyc2)) '!!!']); \n                        outON_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2}=sim_megapress_shaped(Npts,sw,Bfield,lw,taus_ref,sys,...\n                            editRFon,editTp,editPhCyc1(EP1),editPhCyc2(EP2),...\n                            refRF,refTp,Gx,Gy,x(X),y(Y),refPhCyc1(RP1),refPhCyc2(RP2));\n                        outOFF_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2}=sim_megapress_shaped(Npts,sw,Bfield,lw,taus_inv,sys,...\n                            editRFon,editTp,editPhCyc1(EP1),editPhCyc2(EP2),...\n                            refRF,refTp,Gx,Gy,x(X),y(Y),refPhCyc1(RP1),refPhCyc2(RP2));\n                    \n                        if RP1==1 && RP2==1\n                            outON_posxy_epc{X}{Y}{EP1}{EP2}=outON_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2};\n                            outOFF_posxy_epc{X}{Y}{EP1}{EP2}=outOFF_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2};\n                        else\n                            outON_posxy_epc{X}{Y}{EP1}{EP2}=op_addScans(outON_posxy_epc{X}{Y}{EP1}{EP2},outON_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2},xor(RP1==length(refPhCyc1),RP2==length(refPhCyc2)));\n                            outOFF_posxy_epc{X}{Y}{EP1}{EP2}=op_addScans(outOFF_posxy_epc{X}{Y}{EP1}{EP2},outOFF_posxy_epc_rpc{X}{Y}{EP1}{EP2}{RP1}{RP2},xor(RP1==length(refPhCyc1),RP2==length(refPhCyc2)));\n                        end\n                    end %end of 1st refocusing phase cycle loop\n                end %end of 2nd refocusing phase cycle loop.\n                \n                if EP1==1 && EP2==1\n                    outON_posxy{X}{Y}=outON_posxy_epc{X}{Y}{EP1}{EP2};\n                    outOFF_posxy{X}{Y}=outOFF_posxy_epc{X}{Y}{EP1}{EP2};\n                else\n                    outON_posxy{X}{Y}=op_addScans(outON_posxy{X}{Y},outON_posxy_epc{X}{Y}{EP1}{EP2});\n                    outOFF_posxy{X}{Y}=op_addScans(outOFF_posxy{X}{Y},outOFF_posxy_epc{X}{Y}{EP1}{EP2});\n                end\n                outDIFF_posxy{X}{Y}=op_subtractScans(outON_posxy{X}{Y},outOFF_posxy{X}{Y});\n            end %end of 1st editing phase cycle loop.\n        end %end of 2nd editing phase cycle loop.\n        \n        \n        outON=op_addScans(outON,outON_posxy{X}{Y});\n        outOFF=op_addScans(outOFF,outOFF_posxy{X}{Y});\n        \n        \n    end %end of spatial loop (parfor) in y direction.\nend %end of spatial loop (parfor) in x direction.\n\noutDIFF=op_subtractScans(outON,outOFF);\n        \nfigure \nsim_make2DSimPlot(outON_posxy,2.75,3.25);\nfigure\nsim_make2DSimPlot(outOFF_posxy,2.75,3.25);\nfigure\nsim_make2DSimPlot(outDIFF_posxy,2.75,3.25);\n\n\n\n       ", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/exampleRunScripts/run_simMegaExTEShaped.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.21923127230331962}}
{"text": "function aux_parkfield(vResult, hParentFigure)\n\nhSets = gui_result2('GetDatasetsHandle', hParentFigure, [], guidata(hParentFigure));\nsList = get(hSets, 'String');\nnLen = length(sList);\nvResults = gui_result2('GetResults', hParentFigure, [], guidata(hParentFigure));\n\n\nnCS=[[-154.01 60.88 -150.50 60.37];\n    [-153.45 61.68 -149.81 61.21]];\n\nfor nCnt = 1:size(nCS,1)  % nLen\n\n    vResults(nLen+nCnt)=aux_cs2(vResults(nCnt),nCS(nCnt,:));\n\n    hPlot = gui_result2('GetFigureHandle', hParentFigure, [], guidata(hParentFigure));\n    %   exportfig(hPlot, [num2str(nCnt) '.eps'], 'Color', 'cmyk');\n\nend\n\nsave vResults_CS.mat vResults -mat\n\ndisp('Calc of CS finished: vResults_CS.mat')\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/thomas/slabanalysis/aux_movie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.21908162719838364}}
{"text": "% clc; clear all; close all;\n\n%% hydro data\nhydro = struct();\nhydro = readAQWA(hydro, 'WEC3.AH1', 'WEC3.LIS');\nhydro = radiationIRF(hydro,100,[],[],[],[]);\nhydro = radiationIRFSS(hydro,[],[]);\nhydro = excitationIRF(hydro,100,[],[],[],[]);\nwriteBEMIOH5(hydro)\n\n%% Plot hydro data\n% plotBEMIO(hydro)\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/examples/BEMIO/AQWA/WEC3/bemio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21908162719838362}}
{"text": "%SurfPointFeature  SURF point corner feature object\n%\n% A subclass of OrientedScalePointFeature for SURF features.\n%\n% Methods::\n% plot         Plot feature position\n% plot_scale   Plot feature scale\n% distance     Descriptor distance\n% ncc          Descriptor similarity\n% match        Match features\n% uv           Return feature coordinate\n% display      Display value\n% char         Convert value to string\n%\n% Properties::\n% u             horizontal coordinate\n% v             vertical coordinate\n% strength      feature strength\n% scale         feature scale\n% theta         feature orientation [rad]\n% descriptor    feature descriptor (vector)\n% image_id      index of image containing feature\n%\n% Properties of a vector of SurfCornerFeature objects are returned as a vector.\n% If F is a vector (Nx1) of SurfCornerFeature objects then F.u is a 2xN matrix\n% with each column the corresponding u coordinate.\n%\n% Notes::\n% - SurfCornerFeature is a reference object.\n% - SurfCornerFeature objects can be used in vectors and arrays\n%\n% Reference::\n% \"SURF: Speeded Up Robust Features\", \n% Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool,\n% Computer Vision and Image Understanding (CVIU), \n% Vol. 110, No. 3, pp. 346--359, 2008\n%\n% See also ISURF, PointFeature, ScalePointFeature, OrientedScalePointFeature, SiftPointFeature.\n\nclassdef SurfPointFeature < OrientedScalePointFeature\n\n    properties\n        %image_id_\n    end % properties\n\n    methods\n        function f = SurfPointFeature(varargin)\n        %SurfPointFeature.SurfPointFeature Create a SURF point feature object\n        %   \n        % F = SurfPointFeature() is a point feature object with null parameters.\n        %   \n        % F = SurfPointFeature(U, V) is a point feature object with specified\n        % coordinates.\n        %   \n        % F = SurfPointFeature(U, V, STRENGTH) as above but with specified strength.\n        %\n        % F = SurfScalePointFeature(U, V, STRENGTH, SCALE) as above but with specified \n        % feature scale.\n        %\n        % F = SurfPointFeature(U, V, STRENGTH, SCALE, THETA) as above but with specified \n        % feature orientation.\n        %\n        % See also isurf, OrientedScalePointFeature.\n\n            f = f@OrientedScalePointFeature(varargin{:});  % invoke the superclass constructor\n        end\n\n        function val = image_id(features)\n            val = [features.image_id_];\n        end\n\n        function [m,corresp] = match(f1, f2, varargin)\n        %SurfPointFeature.match Match SURF point features\n        %   \n        % M = F.match(F2, OPTIONS) is a vector of FeatureMatch objects that \n        % describe candidate matches between the two vectors of SURF \n        % features F and F2.  Correspondence is based on descriptor\n        % similarity.\n        %\n        % [M,C] = F.match(F2, OPTIONS) as above but returns a correspodence\n        % matrix where each row contains the indices of corresponding features\n        % in F and F2  respectively.\n        %\n        % Options::\n        % 'thresh',T    Match threshold\n        % 'top',N       Take strongest N matches\n        %\n        % Notes::\n        % - to obtain all matches use 'top', Inf\n        %\n        % See also FeatureMatch.\n        \n            if isempty(f2)\n                m = [];\n                corresp = [];\n                return;\n            end\n\n            % HACK, pg 463 requires median (default)\n            opt.thresh = [];\n            opt.top = [];\n            opt.all = false;\n            opt = tb_optparse(opt, varargin);\n\n            % Put the landmark descriptors in a matrix\n            D1 = f1.descriptor;\n            D2 = f2.descriptor;\n\n            % Find the best matches\n\n            \n%             err=zeros(1,length(f1));\n%             cor1=1:length(f1); \n%             cor2=zeros(1,length(f1));\n%             for i=1:length(f1)\n%                 distance = sum((D2-repmat(D1(:,i),[1 length(f2)])).^2,1);\n%                 [err(i),cor2(i)] = min(distance);\n%             end\n\n            % vectorized code (much faster)\n            cor1 = 1:length(f1);\n            [cor2,err] = closest(D1, D2);\n            err = err.^2;  % closest returns distance, old code used distance squared\n\n            % Sort matches on vector distance\n            [err, ind] = sort(err); \n            cor1=cor1(ind); \n            cor2=cor2(ind);\n\n            % Build a list of FeatureMatch objects\n            m = [];\n            cor = [];\n            for i=1:length(f1)\n                k1 = cor1(i);\n                k2 = cor2(i);\n                mm = FeatureMatch(f1(k1), f2(k2), err(i));\n                m = [m mm];\n                cor(:,i) = [k1 k2]';\n            end            \n\n            % find the strongest matches\n            if ~opt.all\n                if ~isempty(opt.top)\n                    % take the N strongest\n                    \n                    k = min(opt.top, numcols(cor));\n                    cor(:,k+1:end) = [];\n                    m(k+1:end) = [];\n                else\n                    % use a threshold\n                    \n                    if isempty(opt.thresh)\n                        % use median of errors if no threshold given\n                        thresh = median(err);\n                    else\n                        thresh = opt.thresh;\n                    end\n                    \n                    k = err > thresh;\n                    cor(:,k) = [];\n                    m(k) = [];\n                end\n            end\n\n            if nargout > 1\n                corresp = cor;\n            end\n        end\n\n\n    end % methods\n\n    methods(Static)\n\n        % the MEX functions live in a private subdirectory, so these static methods\n        % provide convenient access to them\n\n        function Ipts = surf(im, opt)\n            \n            if exist('detectSURFFeatures') && 0\n                % Use the CVST version\n                fprintf('Using CVST\\n');\n                \n                % do some option translation\n                points = detectSURFFeatures(im);\n                \n                if ~isinf(opt.nfeat)\n                    % choose strongest\n                    points = points.selectStrongest(opt.nfeat);\n                end\n                \n                [features,valid_points] = extractFeatures(im, points);\n                \n                p = valid_points.Location;\n                Ipts = struct(...\n                    'x',           num2cell(p(:,1)), ...\n                    'y',           num2cell(p(:,2)), ...\n                    'scale',       num2cell(valid_points.Scale), ...\n                    'strength',    num2cell(valid_points.Metric), ...\n                    'orientation', num2cell(valid_points.Orientation), ...\n                    'descriptor',  num2cell(features, 2)   )';\n                \n            elseif exist('OpenSurf')\n                % Use OpenSurf (MATLAB)\n                params.octaves = opt.octaves;   % for OpenSurf\n                if ~isempty(opt.thresh)\n                    params.tresh = opt.thresh;      % for OpenSurf, (sic)\n                end\n\n                Ipts = OpenSurf(im, params);\n                \n\n            if false\n                % Use surfmex (mex OpenCV wrapper)\n                \n                %if exist('surfpoints') == 3\n                fprintf('MEX\\n');\n                % do the OpenCV/MEX version\n                % put the results into the same return format as OpenSurf\n                params.extended = 0;\n                params.nOctaves = opt.octaves;\n                if ~isempty(opt.thresh)\n                    params.hessianThreshold = opt.thresh;\n                end\n\n                try\n                    [p,d,l,info] = surfpoints(iint(im), params);\n                catch me\n                    if strcmp(me.identifier, 'MATLAB:UndefinedFunction')\n                        error('MVTB:SurfPointFeature:notinstalled', 'Contributed software for SURF features is not installed')\n                    end\n                end\n\n                % returns\n                % p    point coordinates, one per column\n                % d    SURF descriptor, one per column\n                % l    sign of the Laplacian (light or dark feature)\n                % info other parameters, per row: scale, strength,\n                %      orientation\n                \n                % put the data into a vector of structs format to \n                % match OpenSurf\n                Ipts = struct('x', num2cell(p(1,:)), ...\n                              'y', num2cell(p(2,:)), ...\n                              'scale', num2cell(info(1,:)), ...\n                              'strength', num2cell(info(2,:)), ...\n                              'orientation', num2cell(info(3,:)), ...\n                              'descriptor', num2cell(d,1)   );\n\n            end\n        end\n    end\n    end\nend % classdef\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/@SurfPointFeature/SurfPointFeature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.21908162122896319}}
{"text": "%*********************************************************\n%% svec: compute the vector svec(M),\n%%\n%%   x = svec(blk,M,isspx);\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%**********************************************************\n\n  function x = svec(blk,M,isspx); \n     \n   if iscell(M) \n      if (size(blk,1) ~= size(M,1))\n         error('svec: number of rows in blk and M not equal');\n      end\n      if (nargin == 2)\n         %%if (size(M,2) == 1)\n         %%   isspx = zeros(size(blk,1),1); \n         %%else \n         %%   isspx = ones(size(blk,1),1); \n         %%end\n         isspx = ones(size(blk,1),1); \n      else\n         if (length(isspx) < size(blk,1))\n            isspx = ones(size(blk,1),1); \n         end\n      end\n      x = cell(size(blk,1),1); \n      for p=1:size(blk,1)\n         pblk = blk(p,:);  \n         n = sum(pblk{2});  m = size(M,2); \n         if strcmp(pblk{1},'s')\n            n2 = sum(pblk{2}.*(pblk{2}+1))/2; \n            if (isspx(p)); \n               x{p} = sparse(n2,m); \n            else \n               x{p} = zeros(n2,m); \n            end\n            numblk = length(pblk{2}); \n            if (pblk{2} > 0)\n               for k = 1:m\n                  if (numblk > 1) & ~issparse(M{p,k});\n                     x{p}(:,k) = mexsvec(pblk,sparse(M{p,k}),isspx(p)); \n                  else\n                     x{p}(:,k) = mexsvec(pblk,M{p,k},isspx(p)); \n                  end\n               end               \n            end\n\t else\n            if (isspx(p)) \n               x{p} = sparse(n,m); \n            else \n               x{p} = zeros(n,m); \n            end\n            for k = 1:m \n                x{p}(:,k) = M{p,k};\n            end\n         end\n      end\n   else \n      if strcmp(blk{1},'s')\n         numblk = length(blk{2}); \n         if (numblk > 1) & ~issparse(M);\n            x = mexsvec(blk,sparse(M),1); \n         else\n            x = mexsvec(blk,sparse(M)); \n         end\n      else\n         x = M;\n      end\n   end \n%%**********************************************************   \n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/svec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2190522431542699}}
{"text": "function [] = main(training_file, test_file, layers, units_per_layer, rounds)\n    obj = neural_network(training_file, test_file, layers, units_per_layer, rounds);\n    obj = obj.initialise(obj);\n    for i = 1:obj.rounds\n        obj = obj.feed_forward(obj, i-1);\n    end\n    obj = obj.testing(obj);\nend", "meta": {"author": "jayshah19949596", "repo": "Machine-Learning-Models", "sha": "66d18aa24744b2ed60e768e96b587594cdb4eed5", "save_path": "github-repos/MATLAB/jayshah19949596-Machine-Learning-Models", "path": "github-repos/MATLAB/jayshah19949596-Machine-Learning-Models/Machine-Learning-Models-66d18aa24744b2ed60e768e96b587594cdb4eed5/Neural Network/Source code/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21905224315426988}}
{"text": "function audio = mergeAudio(data, window)\n\npad = [];\nif window(1) <= 1\n    pad=zeros(abs(window(1)), 1);\n    window(1) = 1;\nend\nif isstring(data) |ischar(data)\n    audio = audioread(data, window);\nelse\n   audio = data; \nend\naudio = [mean(audio - mean(audio,1) ,2)]; % Take the mean of the audio channels\naudio = int16(audio * 32767); % Convert to int16", "meta": {"author": "DrCoffey", "repo": "DeepSqueak", "sha": "c62f2c7bb86a9d77ae177248abe7d234857edf53", "save_path": "github-repos/MATLAB/DrCoffey-DeepSqueak", "path": "github-repos/MATLAB/DrCoffey-DeepSqueak/DeepSqueak-c62f2c7bb86a9d77ae177248abe7d234857edf53/Functions/mergeAudio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.21883280789483642}}
{"text": "function [pX,gX,pY,gY,X,Y,U] = get_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb,N,np,lx,ly)\n\n% legacy code\ns = warning ('on');\nwarning ('*** The function `get_MCMC_predictiveDensity_fb` is now deprecated. Please use `VBA_MCMC_predictiveDensity_fb` instead (same syntax).') \nwarning (s);\n\n% fallback\nswitch nargin\n    case 11\n        [pX,gX,pY,gY,X,Y] = VBA_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb,N,np,lx,ly);\n    case 10\n        [pX,gX,pY,gY,X,Y] = VBA_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb,N,np,lx);\n    case 9\n        [pX,gX,pY,gY,X,Y] = VBA_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb,N,np);\n    case 8\n        [pX,gX,pY,gY,X,Y] = VBA_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb,N);\n    case 7\n        [pX,gX,pY,gY,X,Y] = VBA_MCMC_predictiveDensity_fb(f_fname,g_fname,u,n_t,options,dim,fb);\n    otherwise\n        error('VBA_MCMC_predictiveDensity_fb: wrong number of arguments');\nend\n\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/legacy/get_MCMC_predictiveDensity_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2187830169197473}}
{"text": "function main()\n    addpath('../include/vlfeat-0.9.20/toolbox/');\n    vl_setup();\n    addpath(genpath('../include/eccv14text'));\n    %data_infos\n    data_infos.img_path = '../data/msra_torch/im/';\n    data_infos.map_path = '../data/msra_torch/multiscale/';\n    data_infos.res_path = '../data/msra_torch/proposal_res/';\n    \n    %global variable\n    global globalVar\n    \n    %gen_proposals param\n    global param\n    param.workPath = '/Users/zhangzheng/Documents/FCN_FULL/genProposal';\n    param.reuse_mser = false;\n    param.debug = false;\n    param.minRegionProb = 0.2;\n    param.minRegionCompCoveredArea = 0.7;\n    param.maxRegionCompArea = 1;\n    param.secondaryMinRegionCompArea = 0.5;\n    param.orient_param.orientationInterval = 2;\n    param.orient_param.minOrientation = -90;\n    param.orient_param.maxOrientation = 90;\n    param.minCompHeightSimilarity = 0.7;\n    param.maxCompOrientationDiff = 3;\n    param.minIoUDiff = 0.85;\n    param.maxDistRatio = 2;\n    %minmaxRFs = [137, 68, 5];\n    minmaxRFs = [137, 32, 5];\n    \n    %% Only used for normal_mser3\n    param.mser_info.delta = 1;\n    param.mser_info.minArea = 0.002;\n    param.mser_info.maxArea = 1;\n    param.mser_info.minDiversity = 0.8;\n    param.mser_info.maxVariation = 0.15;\n\n    mkdir(data_infos.res_path);\n    \n    extension = '.jpg';\n    imgData = dir([data_infos.img_path,'*.jpg']);% original image.\n    if(length(imgData) == 0)\n       imgData = dir([data_infos.img_path,'*.JPG']);% original image.\n       extension = '.JPG';\n    end\n    nImg = length(imgData);\n    for ii= 1:nImg\n        disp(ii);\n        [~, name, ~] = fileparts(imgData(ii).name);\n%         if(~strcmp(name, 'img_11'))\n%             continue;\n%         end\n\n        globalVar.imgName = name;\n        img_path = [data_infos.img_path, imgData(ii).name];%the original image.\n        \n        proposalsSavePath = [data_infos.res_path, name, '.txt'];\n        nMap = 3;\n        proposals = cell(nMap, 1);\n        for jj = 1 : nMap\n            map_path = [data_infos.map_path, name, '_', num2str(jj), extension];%the res image from last phase.\n            img = imread(img_path);\n            map = imread(map_path);\n            map = double(map) / 255;\n            \n            [map_h,map_w,~]=size(map);\n            resizeRatio = size(img, 1) / map_h;\n            img = imresize(img, [map_h, map_w], 'bilinear');\n            \n            proposals_tmp = gen_proposals(img, map, resizeRatio, minmaxRFs(jj));\n            if(isempty(proposals_tmp) == false)\n                proposals_tmp(:, 1 : 8) = proposals_tmp(:, 1 : 8) * resizeRatio;\n            end\n            proposals{jj} = proposals_tmp;\n            \n            if(false)\n                imshow(img);\n                hold on;\n                for nProposal = 1 : size(proposals_tmp, 1)\n                    x_arr = proposals_tmp(nProposal, 1 : 2 : 8);\n                    y_arr = proposals_tmp(nProposal, 2 : 2 : 8);\n                    plot([x_arr, x_arr(1)], [y_arr, y_arr(1)], 'color', rand(3,1));\n                end\n                hold off;\n                saveas(gcf, [data_infos.res_path, name, '_', num2str(jj), '.jpg'], 'jpg');\n            end\n        end\n        proposals = cell2mat(proposals);\n        \n        if(true)\n            img = imread(img_path);\n            imshow(img);\n            hold on;\n            for nProposal = 1 : size(proposals, 1)\n                x_arr = proposals(nProposal, 1 : 2 : 8);\n                y_arr = proposals(nProposal, 2 : 2 : 8);\n                plot([x_arr, x_arr(1)], [y_arr, y_arr(1)], 'color', rand(3,1));\n            end\n            hold off;\n            saveas(gcf, [data_infos.res_path, name, '_all.jpg'], 'jpg');\n        end\n        \n        %% to adapter old code\n        proposalsToSave = zeros(10, size(proposals, 1));\n        if(size(proposalsToSave, 2) ~= 0)\n            proposalsToSave(1 : 8, :) = round(proposals(:, 1 : 8))';\n            proposalsToSave(10, :) = proposals(:, 9);\n        end\n        fid = fopen(proposalsSavePath, 'w');\n        fprintf(fid, '%d %d %d %d %d %d %d %d %d %f\\n', proposalsToSave);\n        fclose(fid);\n    end\nend", "meta": {"author": "stupidZZ", "repo": "FCN_Text", "sha": "4bfa6736adf59924f766c3825bb145054ddc439d", "save_path": "github-repos/MATLAB/stupidZZ-FCN_Text", "path": "github-repos/MATLAB/stupidZZ-FCN_Text/FCN_Text-4bfa6736adf59924f766c3825bb145054ddc439d/ProposalGeneration/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.21875516185868607}}
{"text": "function headmodel = ft_headmodel_fns(seg, varargin)\n\n% FT_HEADMODEL_FNS creates the volume conduction structure to be used\n% in the FNS forward solver.\n%\n% Use as\n%   headmodel = ft_headmodel_fns(seg, ...)\n%\n% Optional input arguments should be specified in key-value pairs and\n% can include\n%   tissuecond       = matrix C [9XN tissue types]; where N is the number of\n%                      tissues and a 3x3 tensor conductivity matrix is stored\n%                      in each column.\n%   tissue           = see fns_contable_write\n%   tissueval        = match tissues of segmentation input\n%   transform        = 4x4 transformation matrix (default eye(4))\n%   sens             = sensor information (for which ft_datatype(sens,'sens')==1)\n%   deepelec         = used in the case of deep voxel solution\n%   tolerance        = scalar (default 1e-8)\n%\n% Standard default values for conductivity matrix C are derived from\n% Saleheen HI, Ng KT. New finite difference formulations for general\n% inhomogeneous anisotropic bioelectric problems. IEEE Trans Biomed Eng.\n% 1997\n%\n% Additional documentation available at:\n% http://hunghienvn.nmsu.edu/wiki/index.php/FNS\n%\n% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD\n\n% Copyright (C) 2011, Cristiano Micheli and Hung Dang\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nft_hastoolbox('fns', 1);\n\n% get the optional arguments\ntissue       = ft_getopt(varargin, 'tissue', []);\ntissueval    = ft_getopt(varargin, 'tissueval', []);\ntissuecond   = ft_getopt(varargin, 'tissuecond', []);\ntransform    = ft_getopt(varargin, 'transform', eye(4));\nunit         = ft_getopt(varargin, 'unit', 'mm');\nsens         = ft_getopt(varargin, 'sens', []);\ndeepelec     = ft_getopt(varargin, 'deepelec', []); % used in the case of deep voxel solution\ntolerance    = ft_getopt(varargin, 'tolerance', 1e-8);\n\nif isempty(sens)\n  ft_error('A set of sensors is required')\nend\n\nif ispc\n  ft_error('FNS only works on Linux and OS X')\nend\n\n% check the consistency between tissue values and the segmentation\nvecval = ismember(tissueval,unique(seg(:)));\nif any(vecval)==0\n  ft_warning('Some of the tissue values are not in the segmentation')\nend\n\n% create the files to be written\ntry\n  tmpfolder = pwd;\n  \n  cd(tempdir)\n  [tmp,tname] = fileparts(tempname);\n  segfile   = [tname];\n  [tmp,tname] = fileparts(tempname);\n  confile   = [tname '.csv'];\n  [tmp,tname] = fileparts(tempname);\n  elecfile = [tname '.h5'];\n  [tmp,tname] = fileparts(tempname);\n  exefile   = [tname '.sh'];\n  [tmp,tname] = fileparts(tempname);\n  datafile  = [tname '.h5'];\n  \n  % this requires the fieldtrip/fileio toolbox\n  ft_hastoolbox('fileio', 1);\n  \n  % create a fake mri structure and write the segmentation on disk\n  disp('writing the segmentation file...')\n  mri = [];\n  mri.dim = size(seg);\n  mri.transform = eye(4);\n  mri.seg = uint8(seg);\n  \n  cfg = [];\n  cfg.datatype = 'uint8';\n  cfg.coordsys  = 'ctf';\n  cfg.parameter = 'seg';\n  cfg.filename  = segfile;\n  cfg.filetype  = 'analyze';\n  ft_volumewrite(cfg, mri);\n  \n  % write the cond matrix on disk, load the default cond matrix in case not specified\n  disp('writing the conductivity file...')\n  condmatrix = fns_contable_write('tissue',tissue,'tissueval',tissueval,'tissuecond',tissuecond);\n  csvwrite(confile,condmatrix);\n  \n  % write the positions of the electrodes on disk\n  disp('writing the electrodes file...')\n  pos = ft_warp_apply(inv(transform),sens.elecpos); % in voxel coordinates!\n  \n  % convert pos into int32 datatype.\n  hdf5write(elecfile, '/electrodes/gridlocs', int32(pos));\n  \n  % Exe file\n  efid = fopen(exefile, 'w');\n  if ~ispc\n    fprintf(efid,'#!/usr/bin/env bash\\n');\n    fprintf(efid,['elecsfwd1 -img ' segfile ' -electrodes ./' elecfile ' -data ./', ...\n      datafile ' -contable ./' confile ' -TOL ' num2str(tolerance) ' \\n']); %2>&1 > /dev/null\n  end\n  fclose(efid);\n  \n  % run the shell instructions\n  dos(sprintf('chmod +x %s', exefile));\n  dos(['./' exefile]);\n  \n  % FIXME: find a cleverer way to store the huge transfer matrix (vista?)\n  [transfer,status] = fns_read_transfer(datafile);\n  \n  cleaner(segfile,confile,elecfile,exefile,datafile)\n  \ncatch ME\n  disp('The transfer matrix was not written')\n  cleaner(segfile,confile,elecfile,exefile,datafile)\n  cd(tmpfolder)\n  rethrow(ME)\nend\n\n% start with an empty volume conductor\nheadmodel = [];\nheadmodel.tissue     = tissue;\nheadmodel.tissueval  = tissueval;\nheadmodel.transform  = transform;\nheadmodel.unit       = unit;\nheadmodel.segdim     = size(seg);\nheadmodel.type       = 'fns';\nheadmodel.transfer   = transfer;\n\nif ~isempty(deepelec)\n  headmodel.deepelec  = deepelec;\nend\n\nfunction cleaner(segfile,confile,elecfile,exefile,datafile)\ndelete([segfile '.hdr']);\ndelete([segfile '.img']);\ndelete(confile);\ndelete(elecfile);\ndelete(exefile);\ndelete(datafile);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/ft_headmodel_fns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2186974336595646}}
{"text": "function trl = sampleinfo2trl(data)\n\n% SAMPLEINFO2TRL constructs the trial definition from the sampleinfo, the time axes\n% and optionally from the trialinfo\n%\n% Use as\n%   trl = sampleinfo2trl(data)\n%\n% See also ARTIFACT2BOOLVEC, ARTIFACT2EVENT, ARTIFACT2TRL, BOOLVEC2ARTIFACT, BOOLVEC2EVENT, BOOLVEC2TRL, EVENT2ARTIFACT, EVENT2BOOLVEC, EVENT2TRL, TRL2ARTIFACT, TRL2BOOLVEC, TRL2EVENT\n\n% get the begin and end sample of each trial\nbegsample = data.sampleinfo(:,1);\nendsample = data.sampleinfo(:,2);\n\n% recreate the offset\noffset = zeros(numel(data.trial), 1);\nfor i=1:numel(data.trial)\n  offset(i) = time2offset(data.time{i}, data.fsample);\nend\n\nif isfield(data, 'trialinfo') && istable(data.trialinfo)\n  trl = table(begsample, endsample, offset);\n  trl = horzcat(trl, data.trialinfo);\nelseif isfield(data, 'trialinfo') && isnumeric(data.trialinfo)\n  trl = [begsample endsample offset data.trialinfo];\nelse\n  trl = [begsample endsample offset];\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/sampleinfo2trl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.21868593800993352}}
{"text": "function model = presolve_bounds_from_domains(model);\n\n% Sigmonial with non-integer powers must be positive\nsigmonials = find((model.variabletype == 4));\nfor i = 1:length(sigmonials)\n    j = sigmonials(i);\n    involved = find(model.monomtable(j,:));\n    fractional = involved(model.monomtable(j,involved)~=fix(model.monomtable(j,involved)));\n    for k = 1:length(fractional)\n        model.lb(fractional(k)) = max([1e-9  model.lb(fractional(k))]);\n    end\nend\n\n% The evaluation based operators can communicate the domain (although\n% this really should be available via domain constraints anyway)\n% The operator model can however also include range constraints, which we\n% just as well might extract and add to the model\nfor i = 1:length(model.evalVariables)\n    j = model.evalVariables(i);\n    model.lb(j) = max([model.lb(j) model.evalMap{i}.properties.range(1)]);\n    model.ub(j) = min([model.ub(j) model.evalMap{i}.properties.range(2)]);\n    j = model.evalMap{i}.variableIndex;\n    model.lb(j) = max([model.lb(j) repmat(model.evalMap{i}.properties.domain(1),length(j),1)],[],2);\n    model.ub(j) = min([model.ub(j) repmat(model.evalMap{i}.properties.domain(2),length(j),1)],[],2);\nend\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/presolve_bounds_from_domains.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.21868593800993344}}
{"text": "function [HDR]=scpopen(arg1,CHAN,arg4,arg5,arg6)\n% SCPOPEN reads and writes SCP-ECG files \n%\n% SCPOPEN is an auxillary function to SOPEN for \n% opening of SCP-ECG files for reading ECG waveform data\n% \n% Use SOPEN instead of SCPOPEN  \n% \n% See also: fopen, SOPEN, \n\n\n%\t$Id: scpopen.m 2205 2009-10-27 12:18:15Z schloegl $\n%\t(C) 2004,2006,2007,2008 by Alois Schloegl <a.schloegl@ieee.org>\t\n%    \tThis is part of the BioSig-toolbox http://biosig.sf.net/\n%\n%    BioSig is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n\nif nargin<2, CHAN=0; end;\n\nif isstruct(arg1) \n        HDR=arg1; \n        FILENAME=HDR.FileName;\nelseif ischar(arg1); \n        HDR.FileName=arg1;\n        fprintf(2,'Warning SCPOPEN: the use of SCPOPEN is discouraged; please use SOPEN instead.\\n');\nend;\n\nVER = version;\n\nfid = fopen(HDR.FileName,HDR.FILE.PERMISSION,'ieee-le');\nHDR.FILE.FID = fid; \nif ~isempty(findstr(HDR.FILE.PERMISSION,'r')),\t\t%%%%% READ \n\ttmpbytes = fread(fid,inf,'uchar');\n        tmpcrc   = crc16eval(tmpbytes(3:end));\n\tfseek(fid, 0, 'bof'); \n        HDR.FILE.CRC = fread(fid,1,'uint16');\n\tif (HDR.FILE.CRC ~= tmpcrc);\n\t\tfprintf(HDR.FILE.stderr,'Warning: CRC check failed (%x vs %x)\\n',tmpcrc,HDR.FILE.CRC);        \n        end;\n\t\n        HDR.FILE.Length = fread(fid,1,'uint32');\n        if HDR.FILE.Length~=HDR.FILE.size,\n                fprintf(HDR.FILE.stderr,'Warning SCPOPEN: header information contains incorrect file size %i %i \\n',HDR.FILE.Length,HDR.FILE.size);\n        end; \n\tHDR.data = [];\n        \n        DHT = [0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9;0,1,5,3,11,7,23,15,47,31,95,63,191,127,383,255,767,511,1023]';\n        prefix  = [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,10,10];\n\tPrefixLength = prefix; \n\n        %PREFIX = [0,4,5,12,13,28,29,60,61,124,125,252,253,508,509,1020,1021,1022,1023];\n        PREFIX  = [0,4,5,12,13,28,29,60,61,124,125,252,253,508,509,1020,1021,1022,1023]'.*2.^[32-prefix]';\n        codelength = [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,18,26];\n        mask    = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]'.*2.^[32-prefix]';\n        %MASK    = dec2bin(mask);\n        %mask   = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]';\n\n        mask2    = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]';\n        PREFIX2  = DHT(:,2);\n\n\tHT19999 = [prefix',codelength',ones(length(prefix),1),DHT];\n\tHT = [prefix',codelength',ones(length(prefix),1),DHT];\n        \n        dd = [0:255]';\n        ACC = zeros(size(dd));\n        c = 0;\n        for k2 = 1:8,\n                ACC = ACC + (dd>127).*(2^c);\n                dd  = mod(dd*2, 256);\n                c   = c + 1;\n        end;\n        \n        section.CRC     = fread(fid,1,'uint16');\n        section.ID      = fread(fid,1,'uint16');\n        section.Length  = fread(fid,1,'uint32');\n        section.Version = fread(fid,[1,2],'uint8');\n        section.tmp     = fread(fid,[1,6],'uint8');\n        \n        NSections = min(11,(section.Length-16)/10);\n        for k = 1:NSections,\n                HDR.Block(k).id = k; \n                HDR.Block(k).length = 0; \n                HDR.Block(k).startpos = -1;\n        end;\n\tfor K = 1:NSections,\n                k = fread(fid,1,'uint16');\n\t\tlen = fread(fid,1,'uint32');\n\t\tpos = fread(fid,1,'uint32');\n\t\tif ((k > 0) && (k < NSections))\n\t                HDR.Block(k).id = k; \n        \t        HDR.Block(k).length = len; \n                \tHDR.Block(k).startpos = pos-1;\n\n%% [HDR.Block(k).id ,length(tmpbytes), HDR.Block(k).length, HDR.Block(k).length+HDR.Block(k).startpos]                \n\t\t%% FIXME: instead of min(...,FileSize) a warning or error message should be reported \n\t                tmpcrc = crc16eval(tmpbytes(HDR.Block(k).startpos+3:min(HDR.Block(k).startpos+HDR.Block(k).length,HDR.FILE.size)));\n\n\t                if (HDR.Block(k).length>0)\n        \t        if (tmpcrc~=(tmpbytes(HDR.Block(k).startpos+(1:2))'*[1;256]))\n                \t\tfprintf(HDR.FILE.stderr,'Warning SCPOPEN: faulty CRC %04x in section %i\\n',tmpcrc,k-1);\n\t                end;\n        \t        end;\n\t\tend;\n        end;\n        \n%%[[HDR.Block.id];[HDR.Block.length];[HDR.Block.startpos]]'\n\t\n\t% default values - in case Section 6 is missing  \n\tHDR.NS = 0; HDR.SPR = 0; HDR.NRec = 0; HDR.Calib = zeros(1,0); \n        secList = find([HDR.Block.length]);\n        for K = secList(1:end),\n                if fseek(fid,HDR.Block(K).startpos,'bof');\n                        fprintf(HDR.FILE.stderr,'Warning SCPOPEN: section %i not available, although it is listed in Section 0\\n',secList(K+1));\n                end;\n                section.CRC     = fread(fid,1,'uint16');\n                section.ID      = fread(fid,1,'uint16');\n                section.Length  = fread(fid,1,'uint32');\n                section.Version = fread(fid,[1,2],'uint8');\n                section.tmp     = fread(fid,[1,6],'uint8'); \n\t\n                HDR.SCP.Section{find(K==secList)} = section;\n                if (section.Length==0),\n                elseif section.ID==0, \n                        NSections = (section.Length-16)/10;\n                        for k = 1:NSections,\n                                HDR.Block(k).id = fread(fid,1,'uint16');    \n                                HDR.Block(k).length = fread(fid,1,'uint32');    \n                                HDR.Block(k).startpos = fread(fid,1,'uint32')-1;    \n                        end;\n                        \n                elseif section.ID==1,\n                        tag = 0; \n                        k1  = 0;\n                        Sect1Len = section.Length-16;\n                        ListOfRequiredTags = [2,14,25,26];\n                        ListOfRecommendedTags = [0,1,5,8,15,34];\n                        while (tag~=255) & (Sect1Len>2),\n                                tag = fread(fid,1,'uint8');\n                                len = fread(fid,1,'uint16');\n                                Sect1Len = Sect1Len - 3 - len; \n%% [tag,len,Sect1Len],          %% DEBUGGING information\n                                field = fread(fid,[1,len],'uchar');\n                                if tag == 0,\t\n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                        HDR.Patient.Name = char(field);  %% LastName\n                                elseif tag == 1,\n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                        HDR.Patient.FirstName = char(field);\n                                elseif tag == 2,\n                                        ListOfRequiredTags(find(ListOfRequiredTags==2))=[];\n                                        HDR.Patient.Id = char(field);\n                                elseif tag == 3,\n                                        HDR.Patient.LastName2 = char(field);\n                                elseif tag == 4,\n                                        HDR.Patient.Age = field(1:2)*[1;256];\n                                        tmp = field(3);\n                                        if     tmp==1, HDR.Patient.Age = HDR.Patient.Age; % unit='Y';\n                                        elseif tmp==2, HDR.Patient.Age = HDR.Patient.Age/12; % unit='M';\n                                        elseif tmp==3, HDR.Patient.Age = HDR.Patient.Age/52; % unit='W';\n                                        elseif tmp==4, HDR.Patient.Age = HDR.Patient.Age/365.25; % unit='d';\n                                        elseif tmp==5, HDR.Patient.Age = HDR.Patient.Age/(365.25*24); %unit='h';\n                                        else warning('units of age not specified');\n                                        end;\n                                elseif (tag == 5) \n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                \tif any(field(1:4)~=0)\n                                        \tHDR.Patient.Birthday = [field(1:2)*[1;256],field(3:4),12,0,0];\n                                        end;\t\n                                elseif (tag == 6) \n                                \tif any(field(1:3)),\n                                        HDR.Patient.Height = field(1:2)*[1;256];\n                                        tmp = field(3);\n                                        if tmp==1, % unit='cm';\n                                        elseif tmp==2, HDR.Patient.Height = HDR.Patient.Height*2.54; %unit='inches'; \n                                        elseif tmp==3, HDR.Patient.Height = HDR.Patient.Height*0.1; %unit='mm';\n                                        else warning('units of height not specified');\n                                        end;\n                                        end;\n                                elseif (tag == 7) \n                                \tif any(field(1:3)),\n                                        HDR.Patient.Weight = field(1:2)*[1;256];\n                                        tmp = field(3);\n                                        if tmp==1, % unit='kg';\n                                        elseif tmp==2, HDR.Patient.Weight = HDR.Patient.Weight/1000; %unit='g';\n                                        elseif tmp==3, HDR.Patient.Weight = HDR.Patient.Weight/2.2; %unit='pound';\n                                        elseif tmp==4, HDR.Patient.Weight = HDR.Patient.Weight*0.0284; %unit='ounce';\n                                        else warning('units of weight not specified');\n                                        end;\n                                        end;\n                                elseif tag == 8,\n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                        HDR.Patient.Sex = field;\n                                elseif tag == 9,\n                                        HDR.Patient.Race = field;\n                                elseif tag == 10,\n\t\t\t\t\tif (field(1)~=0)\n\t                                        HDR.Patient.Medication = field;\n\t\t\t\t\telse\t\n\t                                        HDR.Patient.Medication.Code = field(2:3);\n\t\t\t\t\t\tHDR.Patient.Medication = field(4:end);\n\t\t\t\t\tend;\t\n                                elseif tag == 11,\n                                        HDR.Patient.BloodPressure.Systolic = field*[1;256];\n                                elseif tag == 12,\n                                        HDR.Patient.BloodPressure.Diastolic = field*[1;256];\n                                elseif tag == 13,\n                                        HDR.Patient.Diagnosis = char(field);\n                                elseif tag == 14,\n                                        ListOfRequiredTags(ListOfRequiredTags==tag)=[];\n                                        HDR.SCP1.AcquiringDeviceID = char(field);\n                                        HDR.VERSION = field(15)/10;\n                                elseif tag == 15,\n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                        HDR.SCP1.AnalyisingDeviceID = char(field);\n                                elseif tag == 16,\n                                        HDR.SCP1.AcquiringInstitution = char(field);\n                                elseif tag == 17,\n                                        HDR.SCP1.AnalyzingInstitution = char(field);\n                                elseif tag == 18,\n                                        HDR.SCP1.AcquiringDepartment = char(field);\n                                elseif tag == 19,\n                                        HDR.SCP1.AnalyisingDepartment = char(field);\n                                elseif tag == 20,\n                                        HDR.SCP1.Physician = char(field);\n                                elseif tag == 21,\n                                        HDR.SCP1.LatestComfirmingPhysician = char(field);\n                                elseif tag == 22,\n                                        HDR.SCP1.Technician = char(field);\n                                elseif tag == 23,\n                                        HDR.SCP1.Room = char(field);\n                                elseif tag == 24,\n                                        HDR.SCP1.Emergency = field;\n                                elseif tag == 25,\n                                        ListOfRequiredTags(ListOfRequiredTags==tag)=[];\n                                        HDR.T0(1,1:3) = [field(1:2)*[1;256],field(3:4)];\n                                elseif tag == 26,\n                                        ListOfRequiredTags(ListOfRequiredTags==tag)=[];\n                                        HDR.T0(1,4:6) = field(1:3);\n                                elseif tag == 27,\n                                        HDR.Filter.HighPass = field(1:2)*[1;256]/100;\n                                elseif tag == 28,\n                                        HDR.Filter.LowPass = field(1:2)*[1;256]/100;\n                                elseif tag == 29,\n                                        if (field==0)\n                                                HDR.FILTER.Notch = NaN; \n                                        elseif bitand(field,1)\n                                                HDR.FILTER.Notch = 60; % 60Hz Notch \n                                        elseif bitand(field,2)\n                                                HDR.FILTER.Notch = 50; % 50Hz Notch \n                                        elseif bitand(field,3)==0\n                                                HDR.FILTER.Notch = -1; % Notch Off\n                                        end;\n                                        HDR.SCP1.Filter.BitMap = field;\n                                elseif tag == 30,\n                                        HDR.SCP1.FreeText = char(field);\n                                elseif tag == 31,\n                                        HDR.SCP1.ECGSequenceNumber = char(field);\n                                elseif tag == 32,\n                                        HDR.SCP1.MedicalHistoryCodes = char(field);\n                                elseif tag == 33,\n                                        HDR.SCP1.ElectrodeConfigurationCodes = field;\n                                elseif tag == 34,\n                                        ListOfRecommendedTags(ListOfRecommendedTags==tag)=[];\n                                        HDR.SCP1.Timezone = field;\n                                elseif tag == 35,\n                                        HDR.SCP1.MedicalHistory = char(field);\n                                elseif tag == 255,\n                                        % section terminator\t\n                                elseif tag >= 200,\n                                \t% manufacturer specific - not standardized \n                                else\n                                        fprintf(HDR.FILE.stderr,'Warning SCOPEN: unknown tag %i (section 1)\\n',tag);\n                                end;\n                        end;\n                        if ~isempty(ListOfRequiredTags)\n                                fprintf(HDR.FILE.stderr,'Warning SCPOPEN: the following tags are required but missing in file %s\\n',HDR.FileName);\n                                disp(ListOfRequiredTags);\n                        end;\n                        if ~isempty(ListOfRecommendedTags)\n                                fprintf(HDR.FILE.stderr,'Warning SCPOPEN: the following tags are recommended but missing in file %s\\n',HDR.FileName);\n                                disp(ListOfRecommendedTags);\n                        end;\n                        \n                elseif section.ID==2, \t% Huffman tables \n                        HDR.SCP2.NHT = fread(fid,1,'uint16');            \n                        HDR.SCP2.NCT = fread(fid,1,'uint16');    \n\t\t\tif HDR.SCP2.NHT~=19999,\n\t\t\t\tNHT = HDR.SCP2.NHT;\n\t\t\telse\n\t\t\t\tNHT = 0; \n\t\t\tend;\n                        k3 = 0;\n                        for k1 = 1:NHT,\n                        \tHT1 = zeros(HDR.SCP2.NCT,5);\n                                for k2 = 1:HDR.SCP2.NCT,\n                                \ttmp = fread(fid,3,'uint8') ;\n                                        HDR.SCP2.prefix = tmp(1);\t% PrefixLength\n                                        HDR.SCP2.codelength = tmp(2);\t% CodeLength\n                                        HDR.SCP2.TableModeSwitch = tmp(3);\t\n                                        tmp(4) = fread(fid,1,'int16');  % BaseValue   \n                                        tmp(5) = fread(fid,1,'uint32'); % BaseCode    \n                                \tk3 = k3   + 1;\n\t\t\t\t        HT (k3,:) = [tmp']; \n\t\t\t\t        HT1(k2,:) = [tmp']; \n                                end;\n                                HDR.SCP2.HTree{k1} = makeTree(HT1);\n                                HDR.SCP2.HTs{k1} = HT1;\n\t\t\tend;\n\t\t\tif HDR.SCP2.NHT~=19999,\n\t\t\t\tHDR.SCP2.HT = HT;\n\t\t\telse\n\t\t\t\ttmp = size(HT19999,1);\n\t\t\t\tHDR.SCP2.HT = [ones(tmp,1),[1:tmp]',HT19999];\n                                HDR.SCP2.HTree{1} = makeTree(HT19999);\n                                HDR.SCP2.HTs{1} = HT19999;\n\t\t\tend;\n\n                elseif section.ID==3, \n                        HDR.NS = fread(fid,1,'uint8');\n                        HDR.FLAG.Byte = fread(fid,1,'uint8');    \n                        if ~bitand(HDR.FLAG.Byte,4)\n                                fprintf(HDR.FILE.stdout,'Warning SCPOPEN: not all leads simultaneously recorded - this mode is not supported.\\n');\n                        end;\n                                        \n                        HDR.FLAG.ReferenceBeat = mod(HDR.FLAG.Byte,2);    \n                        %HDR.NS = floor(mod(HDR.FLAG.Byte,128)/8);    \n                        for k = 1:HDR.NS,\n                                HDR.LeadPos(k,1:2) = fread(fid,[1,2],'uint32');    \n                                HDR.LeadIdCode(k,1) = fread(fid,1,'uint8');    \n                        end;\n                        HDR.N = max(HDR.LeadPos(:))-min(HDR.LeadPos(:))+1;\n                        HDR.AS.SPR = HDR.LeadPos(:,2)-HDR.LeadPos(:,1)+1;\n                        HDR.SPR = HDR.AS.SPR(1);  \n\t\t\tfor k = 2:HDR.NS\n\t\t\t\tHDR.SPR = lcm(HDR.SPR,HDR.AS.SPR(k)); \n\t\t\tend; \t                        \n                        \n                        HDR = leadidcodexyz(HDR);\n                        for k = 1:HDR.NS,\n                                if 0,\n                                elseif (HDR.LeadIdCode(k)==0),\n                                        HDR.Label{k} = 'unspecified lead';\n                                elseif (HDR.VERSION <= 1.3) & (HDR.LeadIdCode(k) < 86),\n                                %        HDR.Label{k} = H.Label(H.LeadIdCode==HDR.LeadIdCode(k));\n                                elseif (HDR.VERSION <= 1.3) & (HDR.LeadIdCode(k) > 99),\n                                        HDR.Label{k} = 'manufacturer specific';\n                                elseif (HDR.VERSION >= 2.0) & (HDR.LeadIdCode(k) < 151),\n                                %        HDR.Label{k} = H.Label(H.LeadIdCode==HDR.LeadIdCode(k));\n                                elseif (HDR.VERSION >= 2.0) & (HDR.LeadIdCode(k) > 199),\n                                        HDR.Label{k} = 'manufacturer specific';\n                                else\n                                        HDR.Label{k} = 'reserved';\n                                end;\n                        end;\n                        HDR.Label = strvcat(HDR.Label);\n\n                elseif section.ID==4, \n                        HDR.SCP4.L = fread(fid,1,'int16');    \n                        HDR.SCP4.fc0 = fread(fid,1,'int16');    \n                        HDR.SCP4.N = fread(fid,1,'int16');    \n                        HDR.SCP4.type = fread(fid,[7,HDR.SCP4.N],'uint16')'*[1,0,0,0; 0,1,0,0;0,2^16,0,0; 0,0,1,0;0,0,2^16,0; 0,0,0,1;0,0,0,2^16];   \n\n                        tmp = fread(fid,[2*HDR.SCP4.N],'uint32');\n                        HDR.SCP4.PA = reshape(tmp,2,HDR.SCP4.N)';   \n                        HDR.SCP4.pa = [0;tmp;HDR.N];   \n                        \n                elseif any(section.ID==[5,6]), \n\n                        SCP = [];\n                        SCP.Cal = fread(fid,1,'int16')/1e6;    % quant in nV, converted into mV\n                        SCP.PhysDim = 'mV';\n                        SCP.Dur = fread(fid,1,'int16');    \n                        SCP.SampleRate = 1e6/SCP.Dur;\n                        SCP.FLAG.DIFF  = fread(fid,1,'uint8');    \n                        SCP.FLAG.bimodal_compression = fread(fid,1,'uint8');    \n\n                        if isnan(HDR.NS),\n\t\t\t\tHDR.ERROR.status = -1; \n\t\t\t\tHDR.ERROR.message = sprintf('Error SCPOPEN: could not read %s\\n',HDR.FileName);\n\t\t\t\tfprintf(HDR.FILE.stderr,'Error SCPOPEN: could not read %s\\n',HDR.FileName);\n\t\t\t\treturn;\n\t\t\tend;\n\t\t\t\n\t\t\tif CHAN==0, CHAN = 1:HDR.NS; end;\n                        SCP.SPR = fread(fid,HDR.NS,'uint16');\n\t\t\tHDR.InChanSelect = CHAN; \n\n                        if section.ID==6,\n                                HDR.HeadLen = ftell(fid);\n                                HDR.FLAG.DIFF = SCP.FLAG.DIFF;\n                                HDR.FLAG.bimodal_compression = SCP.FLAG.bimodal_compression;\n                                HDR.data = [];\n                                outlen = HDR.SPR; \n\t\t\t        HDR.Calib = sparse(2:HDR.NS+1, 1:HDR.NS, SCP.Cal);\n                        elseif isfield(HDR,'SCP4') %% HACK: do no know whether it is correct  \n                        \toutlen = floor(1000*HDR.SCP4.L/SCP.Dur);\n                        else \n                        \toutlen = inf;\n                        end;\n\n                        if ~isfield(HDR,'SCP2'),\n                                if any(SCP.SPR(1)~=SCP.SPR),\n                                        error('SCPOPEN: SPR do not fit');\n                                else\n                                        S2 = fread(fid,[SCP.SPR(1)/2,HDR.NS],'int16');\n                                end;\n\t\t\t\t%S2 = S2(:,CHAN); \n        \n                        elseif (HDR.SCP2.NHT==1) && (HDR.SCP2.NCT==1) && (HDR.SCP2.prefix==0), \n\t\t\t\tcodelength = HDR.SCP2.HT(1,4);\n                                if (codelength==16)\n                                        S2 = fread(fid,[HDR.N,HDR.NS],'int16');  \n                                elseif (codelength==8)\n                                        S2 = fread(fid,[HDR.N,HDR.NS],'int8');  \n                                else\n                                        fprintf(HDR.FILE.stderr,'Warning SCPOPEN: codelength %i is not supported yet.',codelength);\n                                        fprintf(HDR.FILE.stderr,' Contact <a.schloegl@ieee.org>\\n');\n                                        return;\n                                end;\n\t\t\t\t%S2 = S2(:,CHAN); \n                                \n                        elseif 1, HDR.SCP2.NHT~=19999;\n                        \t%% User specific Huffman table \n                        \t%% a more elegant Huffman decoder is used here %%\n                                for k = 1:HDR.NS,\n                                        SCP.data{k} = fread(fid,SCP.SPR(k),'uint8');    \n                                end;\n%                                S2 = repmat(NaN,outlen,length(HDR.InChanSelect));\n                                clear S2;  \n                                sz = inf;\n                                for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS,\n\t\t\t\t\toutdata{k3} = DecodeHuffman(HDR.SCP2.HTree,HDR.SCP2.HTs,SCP.data{k},outlen);\n\t\t\t\t\tsz = min(sz,length(outdata{k3}));\n\t\t\t\tend;\n\t\t\t\t\n                                for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS,\n                                \tS2(:,k) = outdata{k3}(1:sz);\n                                end; \t \n\t\t\t\taccu=0;  \t\n\n                        elseif HDR.SCP2.NHT==19999,\n                                HuffTab = DHT;\n                                for k = 1:HDR.NS,\n                                        SCP.data{k} = fread(fid,SCP.SPR(k),'uint8');    \n                                end;\n                                %for k = 1:HDR.NS,\n                                for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS,\n                                %for k = CHAN(:)',\n                                        s2 = SCP.data{k};\n                                        s2 = [s2; repmat(0,ceil(max(HDR.SCP2.HT(:,4))/8),1)];\n\t\t\t\t\tk1 = 0;\t\n\t\t\t\t\tl2 = 0; \n\t\t\t\t\taccu = 0;\n\t\t\t\t\tc  = 0; \n\t\t\t\t\tx  = [];\n\t\t\t\t\tHT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==1),3:7);\n\t\t\t\t\twhile (l2 < HDR.LeadPos(k,2)),\n\t\t\t\t\t\twhile ((c < max(HT(:,2))) & (k1<length(s2)-1));\n\t\t\t\t\t\t\tk1 = k1 + 1;\n\t\t\t\t\t\t\tdd = s2(k1);\n\t\t\t\t\t\t\taccu = accu + ACC(dd+1)*(2^c);\n\t\t\t\t\t\t\tc = c + 8;\n\n\t\t\t\t\t\t\tif 0, %for k2 = 1:8,\n\t\t\t\t\t\t\t\taccu = accu + (dd>127)*(2^c);\n\t\t\t\t\t\t\t\tdd = mod(dd*2,256);\n\t\t\t\t\t\t\t\tc = c + 1;\n\t\t\t\t\t\t\tend;\n\t\t\t\t\t\tend;\n\n                                                ixx = 1;\n                                                %acc = mod(accu,2^32);   % bitand returns NaN if accu >= 2^32\n\t\t\t\t\t\tacc = accu - 2^32*fix(accu*(2^(-32)));   % bitand returns NaN if accu >= 2^32\n\t\t\t\t\t\twhile (bitand(acc,2^HT(ixx,1)-1) ~= HT(ixx,5)),\n\t\t\t\t\t\t\tixx = ixx + 1;\n\t\t\t\t\t\tend;\n                                                \n                                                dd = HT(ixx,2) - HT(ixx,1);\n\t\t\t\t\t\tif HT(ixx,3)==0,\n\t\t\t\t\t\t\tHT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==HT(ixx,5)),3:7);\n\t\t\t\t\t\t\tfprintf(HDR.FILE.stderr,'Warning SCPOPEN: Switching Huffman Tables is not tested yet.\\n');\n\t\t\t\t\t\telseif (dd==0),\n\t\t\t\t\t\t\tl2 = l2 + 1;\n\t\t\t\t\t\t\tx(l2) = HT(ixx,4);\n\t\t\t\t\t\telse %if (HT(ixx,3)>0),\n\t\t\t\t\t\t\tl2 = l2 + 1;\n\t\t\t\t\t\t\t%acc2  = fix(accu*(2^(-HT(ixx,1))));\n\t\t\t\t\t\t\t%tmp = mod(fix(accu*(2^(-HT(ixx,1)))),2^dd);\n\t\t\t\t\t\t\t\n                                                        tmp = fix(accu*(2^(-HT(ixx,1))));       % bitshift(accu,-HT(ixx,1))\n                                                        tmp = tmp - (2^dd)*fix(tmp*(2^(-dd)));  % bitand(...,2^dd)\n                                                        \n                                                        %tmp = bitand(accu,(2^dd-1)*(2^HT(ixx,1)))*(2^-HT(ixx,1));\n                                                        % reverse bit-pattern\n                                                        if dd==8,\n                                                                tmp = ACC(tmp+1);\n                                                        else\n                                                                tmp = dec2bin(tmp);\n                                                                tmp = [char(repmat('0',1,dd-length(tmp))),tmp];\n                                                                tmp = bin2dec(tmp(length(tmp):-1:1));\n                                                        end\n                                                        x(l2) = tmp-(tmp>=(2^(dd-1)))*(2^dd);\n\t\t\t\t\t\tend;\n\t\t\t\t\t\taccu = fix(accu*2^(-HT(ixx,2)));\n\t\t\t\t\t\tc = c - HT(ixx,2); \n\t\t\t\t\tend;\n\t\t\t\t\tx = x(:);\n                                        if k3==1,\n                                                S2=x(:,ones(1,k));\n                                        elseif size(x,1)==size(S2,1),\n                                                S2(:,k) = x;\n\t\t\t\t\telse\n\t                                        fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \\n',size(x,1));\n\t    \t\t\t\t\tHDR.data = S2;\n\t\t\t\t\t\treturn;\n                                        end;\n\t\t\t\tend;\n                                \n                                \n                        elseif (HDR.SCP2.NHT==19999), % alternative decoding algorithm. \n                                warning('this branch is experimental - it might be broken')\n                                HuffTab = DHT;\n                                for k = 1:HDR.NS,\n                                        SCP.data{k} = fread(fid,SCP.SPR(k),'uint8');\n                                end;\n                                %for k = 1:HDR.NS,\n                                for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS,\n                                %for k = CHAN(:)',\n\t\t\t\t        tmp = SCP.data{k};\n                                        accu = [tmp(4)+256*tmp(3)+65536*tmp(2)+2^24*tmp(1)];\n                                        %accu = bitshift(accu,HDR.SCP2.prefix,32);\n                                        c  = 0; %HDR.SCP2.prefix;\n                                        l  = 4;\n                                        l2 = 0;\n                                        clear x;\n                                        Ntmp = length(tmp);\n                                        tmp = [tmp; zeros(4,1)];\n                                        while c <= 32, %1:HDR.SPR(k),\n                                                ixx = 1;\n                                                while (bitand(accu,mask(ixx)) ~= PREFIX(ixx)), \n                                                        ixx = ixx + 1;\n                                                end;\n\n                                                if ixx < 18,\n                                                        c = c + prefix(ixx);\n                                                        %accu  = bitshift(accu, prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        x(l2) = HuffTab(ixx,1);\n                                                        \n                                                elseif ixx == 18,\n                                                        c = c + prefix(ixx) + 8;\n                                                        %accu = bitshift(accu, prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        \n                                                        acc1  = mod(floor(accu*2^(-24)),256);\n                                                        %accu = bitshift(accu, 8, 32);\n                                                        accu  = mod(accu*256, 2^32);\n                                                        \n                                                        x(l2) = acc1-(acc1>=2^7)*2^8;\n                                                        acc2  = 0;\n                                                        for kk = 1:8,\n                                                                acc2 = acc2*2 + mod(acc1,2);\n                                                                acc1 = floor(acc1/2);\n                                                        end;\n                                                        \n                                                elseif ixx == 19,\n                                                        c = c + prefix(ixx);\n                                                        %accu = bitshift(accu, prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        while (c > 7) & (l < Ntmp),\n                                                                l = l+1;\n                                                                c = c-8;\n                                                                accu = accu + tmp(l)*2^c;\n                                                        end;\n                                                        \n                                                        acc1 = mod(floor(accu*2^(-16)),2^16);\n                                                        %accu = bitshift(accu, 16, 32);\n                                                        accu = mod(accu.*(2^16), 2^32);\n                                                        \n                                                        x(l2) = acc1-(acc1>=2^15)*2^16;\n                                                        acc2 = 0;\n                                                        for kk=1:16,\n                                                                acc2 = acc2*2+mod(acc1,2);\n                                                                acc1 = floor(acc1/2);\n                                                        end;\n                                                        %x(l2) = acc2;\n                                                        c = c + 16;\n                                                end;\n                                                \n                                                while (c > 7) & (l < Ntmp),\n                                                        l = l+1;\n                                                        c = c-8;\n                                                        accu = accu + tmp(l)*(2^c);\n                                                end;\n                                        end;\n\n                                        x = x(1:end-1)';\n                                        if k3==1,\n                                                S2=x(:,ones(1,k));\n                                        elseif size(x,1)==size(S2,1),\n                                                S2(:,k) = x;\n                                        elseif 1,\n\t                                        fprintf(HDR.FILE.stderr,'Error SCPOPEN: length=%i of channel %i different to length=%i of channel 1 \\n',size(x,1),k,size(S2,1));\n                                                return;\n                                        else\n\t                                        fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \\n',size(x,1));\n\t    \t\t\t\t\tHDR.data=S2;\n\t\t\t\t\t\treturn;\n                                        end;\n                                end;\n                                        \n                        elseif HDR.SCP2.NHT~=19999,\n                        \t%% OBSOLETE %%\n                                fprintf(HDR.FILE.stderr,'Error SOPEN SCP-ECG: user specified Huffman Table not supported\\n');\n                                HDR.SCP = SCP;\n                                return;\n                                \n                        else\n                                HDR.SCP2,\n                        end;\n\n                        % Decoding of Difference encoding                  \n                        if SCP.FLAG.DIFF==2,\n                                for k1 = 3:size(S2,1);\n                                        S2(k1,:) = S2(k1,:) + [2,-1] * S2(k1-(1:2),:);\n                                end;\n                        elseif SCP.FLAG.DIFF==1,\n                                S2 = cumsum(S2);    \n                        end;\n                        \n                        if section.ID==5,\n                                HDR.SCP5 = SCP;\n                                HDR.SCP5.data = S2;\n                                HDR.SampleRate = SCP.SampleRate;\n                                \n                        elseif section.ID==6,\n                                HDR.SCP6 = SCP;\n                                HDR.SampleRate = SCP.SampleRate;\n                                HDR.PhysDim = repmat({HDR.SCP6.PhysDim},HDR.NS,1);\n                                HDR.data = S2;\n\n                                if HDR.FLAG.bimodal_compression,\n                                \t%% FIXME: THIS IS A HACK - DO NOT KNOW WHETHER IT IS CORRECT. \n                                %\tHDR.FLAG.bimodal_compression = isfield(HDR,'SCP5') & isfield(HDR,'SCP4');\n                                \tHDR.FLAG.bimodal_compression = isfield(HDR,'SCP4');\n\t\t\t\tend; \n                                if HDR.FLAG.bimodal_compression,\n\t\t\t\t\tif isfield(HDR,'SCP5')\n\t                                        F = HDR.SCP5.SampleRate/HDR.SCP6.SampleRate;\n        \t                                HDR.SampleRate = HDR.SCP5.SampleRate;\n                \t                        HDR.FLAG.F = F;\n\t\t\t\t\telse\n                \t                        HDR.FLAG.F = 1;\n\t\t\t\t\tend;\n                                        \n                                        tmp=[HDR.SCP4.PA(:,1);HDR.LeadPos(1,2)]-[1;HDR.SCP4.PA(:,2)+1];\n                                        if ~all(tmp==floor(tmp))\n                                                tmp,\n                                        end;\n                                        t  = (1:HDR.N) / HDR.SampleRate;\n                                        S1 = zeros(HDR.N, HDR.NS);\n                                        \n                                        p  = 1;\n                                        k2 = 1;\n                                        pa = [HDR.SCP4.PA;NaN,NaN];\n                                        flag = 1;\n                                        %% FIXME: accu undefined ##\n\t\t\t\t\taccu = 0;\n                                        for k1 = 1:HDR.N,\n                                                if k1 == pa(p,2)+1,\n                                                        flag = 1;\n                                                        p    = p+1;\n                                                        accu = S2(k2,:);\n                                                elseif k1 == pa(p,1),\n                                                        flag = 0;\n                                                        k2 = ceil(k2);\n                                                end;\n                                                \n                                                if flag,\n                                                        S1(k1,:) = ((F-1)*accu + S2(fix(k2),:)) / F;\n                                                        k2 = k2 + 1/F;\n                                                else\t\n                                                        S1(k1,:) = S2(k2,:);\n                                                        k2 = k2 + 1;\n                                                end;\n                                        end;\t\n                                        \n                                        HDR.SCP.S2 = S2;\n                                        HDR.SCP.S1 = S1;\n                                        S2 = S1;\n                                end;\n                                \n                                if HDR.FLAG.ReferenceBeat & ~isfield(HDR,'SCP5') \n\t                                fprintf(HDR.FILE.stderr,'Warning SOPEN SCP-ECG: Flag ReferenceBeat set, but no section 5 (containing the reference beat) is available\\n');\n                                elseif HDR.FLAG.ReferenceBeat,\n\n                                \ttmp_data = HDR.SCP5.data*(HDR.SCP5.Cal/HDR.SCP6.Cal); \n                                        for k = find(~HDR.SCP4.type(:,1)'),\n                                                t1 = (HDR.SCP4.type(k,2):HDR.SCP4.type(k,4));\n                                                t0 = t1 - HDR.SCP4.type(k,3) + HDR.SCP4.fc0;\n                                                S2(t1,:) = S2(t1,:) + tmp_data(t0,:); \n                                        end;\n                                end;\n\t                        HDR.data  = S2;\n                        end;\n\n                elseif section.ID==7, \n                        HDR.SCP7.byte1   = fread(fid,1,'uint8');    \n                        HDR.SCP7.Nspikes = fread(fid,1,'uint8');    \n                        HDR.SCP7.meanPPI = fread(fid,1,'uint16');    \n                        HDR.SCP7.avePPI  = fread(fid,1,'uint16');    \n                        \n                        for k=1:HDR.SCP7.byte1,\n                                HDR.SCP7.RefBeat{k} = fread(fid,16,'uint8');    \n                                %HDR.SCP7.RefBeat1 = fread(fid,16,'uint8');    \n                        end;\n                        \n                        for k=1:HDR.SCP7.Nspikes,\n                                tmp = fread(fid,16,'uint16');    \n                                tmp(1,2) = fread(fid,16,'int16');    \n                                tmp(1,3) = fread(fid,16,'uint16');    \n                                tmp(1,4) = fread(fid,16,'int16');    \n                                HDR.SCP7.ST(k,:) = tmp;\n                        end;\n                        for k=1:HDR.SCP7.Nspikes,\n                                tmp = fread(fid,6,'uint8');    \n                                HDR.SCP7.ST2(k,:) = tmp;\n                        end;\n                        HDR.SCP7.Nqrs = fread(fid,1,'uint16');    \n                        HDR.SCP7.beattype = fread(fid,HDR.SCP7.Nqrs,'uint8');    \n                        \n                        HDR.SCP7.VentricularRate = fread(fid,1,'uint16');    \n                        HDR.SCP7.AterialRate = fread(fid,1,'uint16');    \n                        HDR.SCP7.QTcorrected = fread(fid,1,'uint16');    \n                        HDR.SCP7.TypeHRcorr = fread(fid,1,'uint8');    \n                        \n                        len = fread(fid,1,'uint16');\n                        tag = 255*(len==0); \n                        k1 = 0;\n                        while tag~=255,\n                                tag = fread(fid,1,'uchar');    \n                                len = fread(fid,1,'uint16');    \n                                field = fread(fid,[1,len],'uchar');    \n                                \n                                if tag == 0,\t\n                                        HDR.Patient.LastName = char(field);\n                                elseif tag == 1,\n                                        \n                                end;\n                        end;\n                        HDR.SCP7.P_onset = fread(fid,1,'uint16');    \n                        HDR.SCP7.P_offset = fread(fid,1,'uint16');    \n                        HDR.SCP7.QRS_onset = fread(fid,1,'uint16');    \n                        HDR.SCP7.QRS_offset = fread(fid,1,'uint16');    \n                        HDR.SCP7.T_offset = fread(fid,1,'uint16');    \n                        HDR.SCP7.P_axis = fread(fid,1,'uint16');    \n                        HDR.SCP7.QRS_axis = fread(fid,1,'uint16');    \n                        HDR.SCP7.T_axis = fread(fid,1,'uint16');    \n                        \n                elseif section.ID==8, \n                        tmp = fread(fid,9,'uint8');    \n                        HDR.SCP8.Report = tmp(1);    \n                        HDR.SCP8.Time = [[1,256]*tmp(2:3),tmp(4:8)'];    \n                        HDR.SCP8.N = tmp(9);    \n                        for k = 1:HDR.SCP8.N,\n                                ix  = fread(fid,1,'uint8');\n                                len = fread(fid,1,'uint16');\n                                tmp = fread(fid,[1,len],'uchar');    \n                                HDR.SCP8.Statement{k,1} = char(tmp);    \n                        end\n                        \n                %elseif section.ID==9, \n                %        HDR.SCP9.byte1 = fread(fid,1,'uint8');    \n                        \n                elseif section.ID==10, \n                        tmp = fread(fid,2,'uint16');\n                        HDR.SCP10.NumberOfLeads = tmp(1);\n                        HDR.SCP10.ManufacturerCode = tmp(2);\n                        for k = []; 1:HDR.SCP10.NumberOfLeads,\n                                tmp = fread(fid,2,'uint16')\n                                LeadId = tmp(1); \n                                LeadLen = tmp(2); \n                                tmp = fread(fid,LeadLen/2,'uint16');    \n                                HDR.SCP10.LeadId(k)=LeadId; \n                                HDR.SCP10.LeadLen(k)=LeadLen; \n                                HDR.SCP10.Measurements{k}=tmp; \n                        end;\n                        \n                elseif section.ID==11, \n                        bytes = fread(fid,11,'uint8');    \n                        HDR.SCP11.T0 = [bytes(2)*256+bytes(3), bytes(4:8)];\n                        HDR.SCP11.Confirmed = bytes(1);\n                        HDR.SCP11.NumberOfStatements = bytes(9);\n                        for k = 1:HDR.SCP11.NumberOfStatements,\n                                SeqNo = fread(fid,1,'uint8');\n                                len11 = fread(fid,1,'uint16');\n                                typeID = fread(fid,1,'uint8');\n                                Statement = fread(fid,len11-1,'uint8');\n                                HDR.SCP11.Statement.SeqNo(k) = SeqNo;         \n                                HDR.SCP11.Statement.len11(k) = len11;         \n                                HDR.SCP11.Statement.typeID(k) = typeID;         \n                                HDR.SCP11.Statement.Statement{k} = Statement;         \n                        end;\n                end;\n                \n\t\tif ~section.Length,\n\t\t\tHDR.ERROR.status  = -1; \n\t\t\tHDR.ERROR.message = 'Error SCPOPEN: \\n';\n\t\t\treturn;\n\t\tend;\t\t\t\n        end;\n\n        HDR.SPR  = size(HDR.data,1);\n        HDR.NRec = 1;\n        HDR.AS.endpos = HDR.SPR;\n        \n        HDR.FILE.OPEN = 0; \n        HDR.FILE.POS  = 0;\n        HDR.TYPE = 'native'; \n        fclose(HDR.FILE.FID);\n\nelse    % writing SCP file \n\n\tNSections = 12;\n        SectIdHdr = zeros(1,16); \n        VERSION = round(HDR.VERSION*10); \n        if ~any(VERSION==[10,13,20])\n                fprintf(HDR.FILE.stderr,'Warning SCPOPEN(WRITE): unknown Version number %4.2f\\n',HDR.VERSION);\n              \tVERSION = 20; \n        end;\n\tSectIdHdr(9:10) = VERSION; % Section and Protocol version number\n\n        POS = 6; B = zeros(1,POS);\n        for K = 0:NSections-1;\n                b = [];\n                if K==0,\n                        % SECTION 0\n                        b = [SectIdHdr(1:10),'SCPECG', zeros(1,NSections*10)];\n\t                b(16+(7:10)) = s4b(POS+1);\n\n                elseif K==1,\n                        % SECTION 1\n                        b = SectIdHdr;\n                        % tag(1),len(1:2),field(1:len)\n                        if isfield(HDR.Patient,'Name'),\n\t\t\t\tb = [b, 0, s2b(length(HDR.Patient.Name)), HDR.Patient.Name];\n\t\t\tend;\t\n                        if isfield(HDR.Patient,'Id'),\n\t\t\t\tb = [b, 2, s2b(length(HDR.Patient.Id)), HDR.Patient.Id];\n\t\t\tend;\n                        if isfield(HDR.Patient,'Age'),\n\t\t\t\t%b = [b, 4, s2b(3), s2b(HDR.Patient.Age),1];  %% use birthday instead\n\t\t\tend;\n                        if isfield(HDR.Patient,'Birthday'),\n\t                        b = [b, 5, s2b(4), s2b(HDR.Patient.Birthday(1)),HDR.Patient.Birthday(2:3)];\n\t\t\tend;      \n                        if isfield(HDR.Patient,'Height'),\n                        if ~isnan(HDR.Patient.Height),\n                        \tb = [b, 6, s2b(3), s2b(HDR.Patient.Height),1];\n                        end;\n                        end;\t\n                        if isfield(HDR.Patient,'Weight'),\n                        if ~isnan(HDR.Patient.Weight),\n                        \tb = [b, 7, s2b(3), s2b(HDR.Patient.Weight),1];\n                        end;\n                        end;\t\n\t                if isfield(HDR.Patient,'Sex'),\n\t                if ~isempty(HDR.Patient.Sex)\n                        \tsex = HDR.Patient.Sex;\n                        \tif 0,\n                        \telseif isnumeric(sex),           sex = sex(1); \n                        \telseif strncmpi(sex,'male',1);   sex = 1; \n                        \telseif strncmpi(sex,'female',1); sex = 2;\n                        \telse sex = 9; % unspecified\n                        \tend;\n\t                      \tb = [b, 8, s2b(1), sex];\n\t                end;      \t\n                        end;\t\n                        if isfield(HDR.Patient,'Race'),\n \t                       \tb = [b, 9, s2b(1), HDR.Patient.Race(1)];\n                        end;\t\n                        if isfield(HDR.Patient,'BloodPressure'),\n                        \tb = [b, 11, s2b(2), s2b(HDR.Patient.BloodPressure.Systolic)];\n                        \tb = [b, 12, s2b(2), s2b(HDR.Patient.BloodPressure.Diastolic)];\n                        end;\n                        \n                        %% Tag 14\n                        tag14.AnalyzingProgramRevisionNumber = ['',char(0)];\n                        tag14.SerialNumberAcqDevice = ['',char(0)];\n                        tag14.AcqDeviceSystemSoftware = ['',char(0)];\n                        tag14.SCPImplementationSoftware = ['BioSig4OctMat v 1.76+',char(0)];\t\n                        tag14.ManufactureAcqDevice = ['',char(0)];\t\n                        t14 = [zeros(1,35), length(tag14.AnalyzingProgramRevisionNumber),tag14.AnalyzingProgramRevisionNumber,tag14.SerialNumberAcqDevice,tag14.AcqDeviceSystemSoftware,tag14.SCPImplementationSoftware,tag14.ManufactureAcqDevice];\n                        t14(8)  = 255;  % Manufacturer\n                        %%% ### FIXME ###  t14(9:14) = % cardiograph model\n                        t14(15) = VERSION;        % Version\n                        t14(16) = hex2dec('A0');  % Demographics and ECG rhythm data\" (if we had also the reference beats we should change it in 0xC0).\n                        t14(18) = hex2dec('D0');  % Capabilities of the ECG Device: 0xD0 (acquire, print and store). \n                        b   = [b, 14, s2b(length(t14)), t14];\n                         \n                        b = [b, 25, s2b(4), s2b(HDR.T0(1)),HDR.T0(2:3)];\n                        b = [b, 26, s2b(3), HDR.T0(4:6)];\n                        if ~any(isnan(HDR.Filter.HighPass))\n\t                        b = [b, 27, s2b(2), s2b(round(HDR.Filter.HighPass(1)*100))];\n                        end; \n                        if ~any(isnan(HDR.Filter.LowPass))\n\t                \tb = [b, 28, s2b(2), s2b(round(HDR.Filter.LowPass(1)))];\n\t\t\tend;\n                        b = [b, 255, 0, 0];\t% terminator\n\t\t\tb = b + (b<0)*256;\n\n                elseif K==3,\n                        % SECTION 3\n                        b = [SectIdHdr,HDR.NS,4+HDR.NS*8];\n                        if ~isfield(HDR,'LeadIdCode'), HDR.LeadIdCode = zeros(1,HDR.NS); end; \n                        if (numel(HDR.LeadIdCode)~=HDR.NS); warning('HDR.LeadIdCode does not have HDR.NS elements'); end; \n                        if any(HDR.LeadIdCode>255), warning('invalid LeadIdCode'); end;\n                        for k = 1:HDR.NS,\n                                b = [b, s4b(1), s4b(HDR.SPR*HDR.NRec), mod(HDR.LeadIdCode(k),256)];\n                        end;\n\n                elseif K==6,\n                        % SECTION 6\n                        Cal = full(HDR.Calib(2:end,:)); Cal = Cal - diag(diag(Cal)); \n                        if any(Cal(:))\n                                fprintf(HDR.FILE.stderr,'Calibration is not a diagonal matrix.\\n\\tThis can result in incorrect scalings.\\n'); \n                        end;\n                        Cal = full(diag(HDR.Calib(2:end,:)));\n                        if any(Cal~=Cal(1)), \n                                fprintf(HDR.FILE.stderr,'scaling information is not equal for all channels; \\n\\tThis is not supported by SCP and can result in incorrect scalings.\\n'); \n                        end;\n                        [tmp,scale1] = physicalunits(HDR.PhysDim{1});\n                        [tmp,scale2] = physicalunits('nV');\n                        b = [SectIdHdr, s2b(round(Cal(1)*scale1/scale2)), s2b(round(1e6/HDR.SampleRate)), 0, 0];\n                        for k = 1:HDR.NS,\n                                b = [b, s2b(HDR.SPR*HDR.NRec*2)];\n                        end;\n                        data = HDR.data(:);\n                        data = data + (data<0)*2^16;\n                        tmp  = s2b(round(data))';\n                        b = [b,tmp(:)'];\n                else\n                        b = [];\n                end;\n                if (length(b)>0)\n                        if mod(length(b),2), % align to multiple of 2-byte blocks\n                                b = [b,0];\n                        end;\n                        if (length(b)<16), fprintf(HDR.FILE.stderr,'section header %i less then 16 bytes %i', K,length(b)); end;\n                        b(3:4) = s2b(K);\n                        b(5:8) = s4b(length(b));\n                        %b(1:2)= s4b(crc);\n                        b(1:2) = s2b(crc16eval(b(3:end)));\n                        % section 0: startpos in pointer field \n\t                B(22+K*10+(7:10)) = s4b(POS+1);\n                end;\n                B = [B(1:POS),b]; \n                % section 0 pointer field \n                B(22+K*10+(1:2)) = s2b(K);\n                B(22+K*10+(3:6)) = s4b(length(b)); % length\n                POS = POS + length(b);\n        end\n        B(3:6) = s4b(POS);      % length of file\n        B(7:8) = s2b(crc16eval(B(9:22+NSections*10)));  % CRC of Section 0\n\n        B(1:2) = s2b(crc16eval(B(3:end)));\n\n        %        fwrite(fid,crc,'int16');\n        count = fwrite(fid,B,'uchar');\n        fclose(fid); \nend\nend  %% scpopen\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  Auxillary functions \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b2 = s2b(i)\n\t% converts 16bit into 2 bytes\n\tb2 = [bitand(i,255),bitand(bitshift(i,-8),255)];\n\treturn; \nend\t%%%%% s2b %%%%%\n\n\nfunction b4 = s4b(i)\n\t% converts 32 bit into 4 bytes\n\tb4 = [s2b(bitand(i,2^16-1)),s2b(bitand(bitshift(i,-16),2^16-1)) ];\n\treturn; \nend\t%%%%% s4b %%%%%\n\n\nfunction T = makeSubTree(T,bc,len,val)\n\tif (len==0)\n\t\tT.idxTable = val;\n\t\treturn \n\tend; \nif 1,\n\tb = bitand(bc,1)+1;\n\tif ~isfield(T,'branch') T.branch = {[],[]}; end;\n\tT.branch{b} = makeSubTree(T.branch{b},bitshift(bc,-1),len-1,val);\nelse \n\tif bitand(bc,1)\n\t\tif ~isfield(T,'node1'),T.node1 = []; end;  \n\t\tT.node1 = makeSubTree(T.node1,bitshift(bc,-1),len-1,val);\n\telse\n\t\tif ~isfield(T,'node0'),T.node0 = []; end;  \n\t\tT.node0 = makeSubTree(T.node0,bitshift(bc,-1),len-1,val); \n\tend; \nend,\n\treturn; \nend\t%%%%% makeSubTree %%%%%\n\nfunction T = makeTree(HT)\n\tT = []; \n\tfor k1 = 1:size(HT,1)\n\t\tfor k2 = 1:HT(k1,1) % CodeLength\n\t\t\tT = makeSubTree(T,HT(k1,5),HT(k1,1),k1); \n\t\tend;  \n\tend; \n%save matlab T,pause\n\treturn; \nend\t%%%%% makeTree %%%%%\n\nfunction outdata = DecodeHuffman(HTrees,HTs,indata,outlen)\n\tActualTable = 1; \n\tk1 = 1; r=0; \n\tk2 = 0; \n\n\tif ((outlen>0) && isfinite(outlen))\n\t\toutdata = repmat(NaN,outlen,1);\n\telse \t\n\t\toutdata = [0;0];  %% make it a column vector\n\tend; \t \n\tNode    = HTrees{ActualTable}; \n\twhile ((k1*8+r <= 8*length(indata)) && (k2<outlen))\n\t\tif ~isfield(Node,'idxTable')\n\t\t\tr = r+1; if (r>8), k1=k1+1; r=1; end;\nif 1,\n\t\t\tb = bitand(bitshift(indata(k1),r-8),1)+1;\n\t\t\tif ~isempty(Node.branch{b})\n\t\t\t\tNode = Node.branch{b};\n\t\t\telse \n\t\t\t\tfprintf(2,'Warning SCPOPEN: empty node in Huffman table\\n');\n\t\t\tend; \t\t \nelse\n\t\t\tif bitand(bitshift(indata(k1),r-8),1)\n\t\t\t\tif isfield(Node,'node1') \n\t\t\t\t\tNode = Node.node1;\n\t\t\t\telse \n\t\t\t\t\tfprintf(2,'Warning SCPOPEN: empty node in Huffman table\\n');\n\t\t\t\tend; \t\t \n\t\t\telse \t \n\t\t\t\tif isfield(Node,'node0') \n\t\t\t\t\tNode = Node.node0; \n\t\t\t\telse \n\t\t\t\t\tfprintf(2,'Warning SCPOPEN: empty node in Huffman table\\n');\n\t\t\t\tend; \n\t\t\tend; \t\t\nend;\n\t\tend; \n\n\t\tif isfield(Node,'idxTable')\n\t\t\tTableEntry = HTs{ActualTable}(Node.idxTable,:);\n\t\t\tdlen = TableEntry(2)-TableEntry(1); \n\t\t\tif (~TableEntry(3))\n\t\t\t\tActualTable = TableEntry(4); \n\t\t\telseif (dlen~=0) \n\t\t\t\tacc = 0;\n\t\t\t\tfor k3 = 1:dlen,\n\t\t\t\t\tr = r+1; if (r>8), k1=k1+1; r=1; end;\n\t\t\t\t\tacc = 2*acc + bitand(bitshift(indata(k1),r-8), 1);\n\t\t\t\tend;\n\t\t\t\tif (acc>=bitshift(1,dlen-1))\n\t\t\t\t\tacc = acc - bitshift(1,dlen);  \n\t\t\t\tend; \t\n\t\t\t\tk2 = k2+1;\n\t\t\t\toutdata(k2) = acc; \n\t\t\telse\n\t\t\t\tk2 = k2+1;\n\t\t\t\toutdata(k2)=TableEntry(4);\n\t\t\tend;\n\t\t\tNode = HTrees{ActualTable}; \n\t\tend;\n\tend;\n\treturn; \nend %%%%%%%% DecodeHuffman %%%%%%%%%\n\nfunction crc16 = crc16eval(D)\n% CRC16EVAL cyclic redundancy check with the polynomiaL x^16+x^12+x^5+1  \n% i.e. CRC-CCITT http://en.wikipedia.org/wiki/Crc16 \n\n\tD = uint16(D);\n\n\tcrchi = 255;\n\tcrclo = 255;\n\n\tt = '00102030405060708191a1b1c1d1e1f112023222524272629383b3a3d3c3f3e32434041464744454a5b58595e5f5c5d53626160676665646b7a79787f7e7d7c74858687808182838c9d9e9f98999a9b95a4a7a6a1a0a3a2adbcbfbeb9b8bbbab6c7c4c5c2c3c0c1cedfdcdddadbd8d9d7e6e5e4e3e2e1e0effefdfcfbfaf9f8f9181b1a1d1c1f1e110003020504070608393a3b3c3d3e3f30212223242526272b5a59585f5e5d5c53424140474645444a7b78797e7f7c7d72636061666764656d9c9f9e99989b9a95848786818083828cbdbebfb8b9babbb4a5a6a7a0a1a2a3afdedddcdbdad9d8d7c6c5c4c3c2c1c0cefffcfdfafbf8f9f6e7e4e5e2e3e0e1e';\n\tcrc16htab = hex2dec(reshape(t,2,length(t)/2)');\n\n\tt = '0021426384a5c6e708294a6b8cadceef31107352b594f7d639187b5abd9cffde62432001e6c7a4856a4b2809eecfac8d53721130d7f695b45b7a1938dffe9dbcc4e586a740610223cced8eaf48690a2bf5d4b79671503312fddcbf9e79583b1aa687e4c522036041ae8feccd2a0b684997b6d5f4133251709fbeddfc1b3a597888a9caeb0c2d4e6f80a1c2e304254667b998fbda3d1c7f5eb190f3d235147756eacba8896e4f2c0de2c3a08166472405dbfa99b85f7e1d3cd3f291b0577615344c6d0e2fc8e98aab44650627c0e182a37d5c3f1ef9d8bb9a75543716f1d0b3922e0f6c4daa8be8c926076445a283e0c11f3e5d7c9bbad9f81736557493b2d1f0';\n\tcrc16ltab = hex2dec(reshape(t,2,length(t)/2)');\n\n\tfor k = 1:length(D),\n\t\tix = double(bitxor(crchi,D(k)))+1;\n\t\tcrchi = bitxor(crclo,crc16htab(ix));\n\t\tcrclo = crc16ltab(ix);\n\tend;\n\tcrc16 = crchi*256+crclo;\n\t\nend\t%%%%% crc16eval %%%%%\n\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/biosig-partial/t200_FileAccess/scpopen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.21868593800993344}}
{"text": "function [result,croppedImage] = isGoodPhoto(img)\n\nminWidth = 480;\nminHeight = 480;\n\n%minWidth = 128;\n%minHeight = 128;\n\n\ncroppedImage = [];\n\nif isa(img,'char')\n    img = imread(img);\nend\n\nif isa(img,'logical')\n    result = 'binary';\n    return;\nend\n\nif ndims(img)>3\n    result = 'animation';\n    return;    \nend\n\nif size(img,1)<minHeight || size(img,2)<minWidth\n    result = 'too small';\n    return;\nend\n\n\npersistent emptyFlickrGIF;\npersistent emptyFlickrPNG;\nif isempty(emptyFlickrGIF) \n    [emptyFlickrGIF,map]= imread('emptyFlickr.gif');\n    if ~isempty( map )\n        emptyFlickrGIF = ind2rgb( emptyFlickrGIF, map );\n    end\nend\nif isempty(emptyFlickrPNG) \n    emptyFlickrPNG = imread('emptyFlickr.png');\nend\n\n% check if it is flickr empty image\nimgT = imresize(img,[size(emptyFlickrGIF,1), size(emptyFlickrGIF,2)]);\nif size(imgT,3)==1\n    diff= sum(reshape(abs(im2double(imgT)-rgb2gray(emptyFlickrGIF)),1,[]));\nelse\n    diff= sum(reshape(abs(im2double(imgT)-emptyFlickrGIF),1,[]));\nend\nif diff<50\n    result = 'flickr empty';\n    return;\nend\n\n\nimgT = imresize(img,[size(emptyFlickrPNG,1), size(emptyFlickrPNG,2)]);\nif size(imgT,3)==1\n    diff= sum(reshape(abs(imgT-rgb2gray(emptyFlickrPNG)),1,[]));\nelse\n    diff= sum(reshape(abs(imgT-emptyFlickrPNG),1,[]));\nend\nif diff<50\n    result = 'flickr empty';\n    return;\nend\n\n% check if it is line drawing\nif size(img,3)==1\n    h = imhist(img);\n    if sum(h(240:end))/sum(h) > 0.5\n        result = 'too white';\n        return;\n    elseif sum(h(1:10))/sum(h) > 0.5\n        result = 'too black';\n        return;\n    end\nelse\n    h = imhist(img(:,:,1)) + imhist(img(:,:,2)) + imhist(img(:,:,3));\n    if sum(h(240:end))/sum(h) > 0.6\n        result = 'too white';\n        return;\n    elseif sum(h(1:10))/sum(h) > 0.8\n        result = 'too black';\n        return;\n    end\nend\n\nimgG = img;\n\nG = fspecial('gaussian',[5 5],2);\n%# Filter it\nimgG = imfilter(imgG,G,'symmetric','same');\n\nif size(imgG,3)>1\n    imgG = rgb2gray(imgG);\nend\n\ntto = edge(imgG,'canny');\n\nif sum(tto(:))/numel(tto) < 0.01\n    result = 'too pure';\n    return;\nend\n   \n%{\n% check if it is line drawing\nimgG = img;\nif size(imgG,3)>1\n    imgG = rgb2gray(imgG);\nend\nh = imhist(imgG);\nif sum(h(240:end))/sum(h) > 0.5\n    result = 'too white';\n    return;\nelseif sum(h(1:10))/sum(h) > 0.5\n    result = 'too black';\n    return;\nelse\n    [~,ind]=max(h);\n    if sum(h(max(1,ind-7):min(256,ind+7)))/sum(h) > 0.7\n        result = 'too pure';\n        return;\n    end\nend\n%}\n\n% maybe useful http://www.mathworks.com/matlabcentral/fileexchange/25354-cropmat\n\n\nif size(img,3)==1\n    ttWhite = img>252;\nelse\n    ttWhite = img(:,:,1)>252 & img(:,:,2)>252 & img(:,:,3)>252;\nend\n\nif size(img,3)==1\n    ttBlack = img<5;\nelse\n    ttBlack = img(:,:,1)<5 & img(:,:,2)<5 & img(:,:,3)<5;\nend\n\nwWhite=sum(ttWhite,1) > size(tto,1)*0.7;\nhWhite=sum(ttWhite,2) > size(tto,2)*0.7;\nwBlack=sum(ttBlack,1) > size(tto,1)*0.7;\nhBlack=sum(ttBlack,2) > size(tto,2)*0.7;\n\nanyEdgeW = sum(tto,1) > size(tto,1)*0.01;\nanyEdgeH = sum(tto,2) > size(tto,2)*0.01;\n\nminW=find(anyEdgeW, 1 )-1+2;   maxW=size(imgG,2)-find(anyEdgeW, 1, 'last' );\nminH=find(anyEdgeH, 1 )-1+2;   maxH=size(imgG,1)-find(anyEdgeH, 1, 'last' );\n\n\ntry\n    if minW<3 || maxW<3\n        minW = 0;\n        maxW = 0;\n    else\n        wMargin = wWhite | wBlack;\n        if ~(any(wMargin(1:minW)) && any(wMargin(end-maxW:end)))\n            minW = 0;\n            maxW = 0;\n        end        \n    end\n\n    if minH<3 || maxH<3\n        minH = 0;\n        maxH = 0;\n    else\n        hMargin = hWhite | hBlack;\n        if ~(any(hMargin(1:minH)) && any(hMargin(end-maxH:end)))\n            minH = 0;\n            maxH = 0;\n        end\n    end\n\n    if minW>0 || maxW>0 || minH>0 || maxH>0\n        croppedImage = img(minH+1:size(imgG,1)-maxH,minW+1:size(imgG,2)-maxW,:);\n        result = 'crop';\n        \n        if size(croppedImage,1)<minHeight || size(croppedImage,2)<minWidth\n            result = 'too small';\n        end\n        \n        \n        return;\n    end\ncatch\nend\n\n\n%{\n\n% automatic image cropping\n% http://stackoverflow.com/questions/11121657/find-the-edges-of-image-and-crop-it-in-matlab\n%# instead of \"==\" you can check for similarity within a tolerance\n%tt=img(:,:,1)==img(:,:,2) & img(:,:,2) == img(:,:,3);\n\nif size(img,3)==1\n    tt = img>252;\nelse\n    tt = img(:,:,1)>252 & img(:,:,2)>252 & img(:,:,3)>252;\nend\n\n%# invert tt so that it's 1 where there is signal\ntt = ~tt;\n\n%# clean up some of the smaller artifacts\ntto = imopen(tt,strel('square',10));\n\n%# get the areas and bounding box of the areas above threshold\n%# as an additional criterion, you could also use excentricity\n\nstats = regionprops(tto,'BoundingBox','Area');\nif ~isempty(stats)\n    area = cat(1,stats.Area);\n    [~,maxAreaIdx] = max(area);\n    bb = round(stats(maxAreaIdx).BoundingBox);\n    \n    \n    %# note that regionprops switches x and y (it's a long story)\n    croppedImage = img(bb(2):bb(2)+bb(4)-1,bb(1):bb(1)+bb(3)-1,:);\n\n    if size(croppedImage,1)<size(img,1)-5 || size(croppedImage,2)<size(img,2)-5\n        result = 'crop';\n        return;\n    end\nend\n\n%% black \nif size(img,3)==1\n    tt = img<5;\nelse\n    tt = img(:,:,1)<5 & img(:,:,2)<5 & img(:,:,3)<5;\nend\n\n%# invert tt so that it's 1 where there is signal\ntt = ~tt;\n\n%# clean up some of the smaller artifacts\ntto = imopen(tt,strel('square',10));\n\n%# get the areas and bounding box of the areas above threshold\n%# as an additional criterion, you could also use excentricity\n\nstats = regionprops(tto,'BoundingBox','Area');\nif ~isempty(stats)\n    area = cat(1,stats.Area);\n    [~,maxAreaIdx] = max(area);\n    bb = round(stats(maxAreaIdx).BoundingBox);\n    \n    %# note that regionprops switches x and y (it's a long story)\n    croppedImage = img(bb(2):bb(2)+bb(4)-1,bb(1):bb(1)+bb(3)-1,:);\n    \n    if size(croppedImage,1)<size(img,1)-5 || size(croppedImage,2)<size(img,2)-5\n        result = 'crop';\n        return;\n    end\nend\n\n%}\n\n\nresult = 'good';\nreturn;\n\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/InternetImageCleaner/isGoodPhoto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2186859380099334}}
{"text": "function calcAllFusedTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,CTweight_mat,scale_mat,algo_cell,Ng_mat,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% function calcAllFusedTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,CTweight_mat,scale_mat,Ng_mat,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes FUSED texture features for all patients, for all \n% different combinations of the following texture extraction parameters:\n% - CT weight: Weight given to MRI wavelet low-pass sub-bands in the \n%               PET/CT fusion process. \n% - Scale: Resolution at which the ROI is isotropically resampled.\n% - Ng: Number of gray-levels in the quantization process. \n%\n% Different extraction parameters are passed as arrays or cells in the\n% function in order to test all possible combinations. This function is \n% used for FUSED scans specifically. See Ref. [1,2] and 'prepareVolume.m' \n% for more details.\n%\n% Texture features are computed for all head and neck (HN) DICOM  imaging \n% data downloaded from The Cancer Imaging Archive (TCIA) website at: \n% <http://dx.doi.org/10.7937/K9/xxxxxxxxxxxxxxxxxxx, and first organized \n% in a 'DATA' directory using the function readAllDICOM_HN.m.  Results are \n% then saved in a folder 'TEXTURES' in the HN WORKSPACE.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n%     early prediction of different tumour outcomes in head and neck cancer.\n%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n%     doi:\n% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathData: Full path to the HN sData files directory.\n%              --> Ex: '/myProject/WORKSPACE/DATA'\n% 2. pathText: Full path to the HN non texture features directory.\n%              --> Ex: '/myProject/WORKSPACE/FEATURES/TEXTURES'\n% 3. namePT: Cell of strings of all PET sData files to read\n%            --> Ex: {'HGJ_001_PT.PTscan.mat';'HGJ_022_PT.PTscan.mat'}\n% 4. namePT: Cell of strings of all CT sData files to read\n%            --> Ex: {'HGJ_001_CT.CTscan.mat';'HGJ_022_CT.CTscan.mat'}\n% 5. nameROI: Cell of strings specifying the ROI names to analyze for the\n%             patients defined by \"namePT\" and \"nameCT\"\n%             --> Ex: {'GTV';'GTV-P'}\n% 6. outcomes: Structure specifying the status (1 or 0) for different\n%              outcomes in HN cancer. Contains: outcomes.Failure, \n%              outcomes.Locoregional, outcomes.Distant. See ref.[1] for \n%              more details.\n% 7. featType: Either 'GTVp' for primary GTV, or 'GTVtot' for primaty GTV +\n%              nodal GTVs\n%              --> Ex: 'GTVp'\n% 8. CTweight_mat: Array vector specifying the different CT weights to test\n%                  --> Ex: [1/4,1/3,1/2,2/3,3/4]\n% 9. scale_mat: Array vector specifying the different 'Scale' values to test.\n%               --> Ex: [1,2,3,4,5]\n% 10. Ng_mat: Array vector specifying the different 'Ng' values to test.\n%            --> Ex: [8,16,32,64]\n% 11. nBatch: Number of parallel batch.\n%             --> Ex: 8\n% 12.  matlabPATH: Full path to the MATLAB excutable on the system.\n%      --> Ex: 'matlab' (symbolic link)\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\nind = strfind(namePT{1},'_'); cohortID = namePT{1}(1:ind-1);\ncd(pathText), mkdir(['batchLog_',cohortID,'_',featType,'_FusText']), cd(['batchLog_',cohortID,'_',featType,'_FusText']), pathBatch = pwd;\ntime = 60; % Number of seconds to wait before checking if parallel computations are done\nnameOutcomes = fieldnames(outcomes); nOutcomes = numel(nameOutcomes);\nscans = {'PTCT'}; nScans = numel(scans);\n\n% PRODUCE BATCH COMPUTATIONS\nnPatient = numel(namePT); valid = ones(nPatient,1);\nfor i = 1:nPatient\n    if isempty(nameROI{i})\n        valid(i) = 0;\n    end\nend\nindValid = find(valid); nPatient = numel(indValid);\nif nPatient < nBatch\n    nBatch = nPatient;\nend\n[patients] = batchPatients(nPatient,nBatch);\nsave('workspace','pathData','pathText','namePT','nameCT','nameROI','patients','indValid','featType','CTweight_mat','scale_mat','algo_cell','Ng_mat'), pause(5);\nfor i = 1:nBatch\n    nameScript = ['batch',num2str(i),'_script.m'];\n    fid = fopen(nameScript,'w');\n    fprintf(fid,'load(''workspace'')\\n');\n    fprintf(fid,['calcAllFusedTextures_HN(pathData,pathText,namePT(indValid(patients{',num2str(i),'})),nameCT(indValid(patients{',num2str(i),'})),nameROI(indValid(patients{',num2str(i),'})),featType,CTweight_mat,scale_mat,algo_cell,Ng_mat)\\n']);\n    fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n    fprintf(fid,'clear all');\n    fclose(fid);\n    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nBatch)\ndelete('workspace.mat')\n\n% GROUPING RESULTS FROM ALL BATCH\nnPatient = numel(namePT);\nfor scan = 1:nScans\n    cd(pathText)\n    if exist(['HGJ_001_',scans{scan},'_',featType,'_text.mat'],'file')\n        temp = load(['HGJ_001_',scans{scan},'_',featType,'_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields\n    else\n        temp = load(['HGJ_001_',scans{scan},'_','GTVp','_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields\n    end\n    nameType = fieldnames(temp.Experiment1); nameType(end) = []; nType = numel(nameType); % All texture types are the same\n    text = cell(numel(CTweight_mat),numel(scale_mat),numel(algo_cell),numel(Ng_mat));\n    tempText = cell(1,nPatient); % Cell used to load patient textures only once\n    for p = 1:nPatient\n        ind = strfind(namePT{p},'_'); namePatient = namePT{p}(1:ind(2)-1);\n        if exist([namePatient,'_',scans{scan},'_',featType,'_text.mat'],'file')\n            load([namePatient,'_',scans{scan},'_',featType,'_text.mat']) % Variable 'textures' is now in MATLAB workspace\n        else\n            load([namePatient,'_',scans{scan},'_','GTVp','_text.mat']) % Variable 'textures' is now in MATLAB workspace\n        end\n        tempText{p} = textures;\n    end\n    experiment = 0;\n    for c = 1:numel(CTweight_mat)\n        for s = 1:numel(scale_mat)\n            for a = 1:numel(algo_cell)\n                for n = 1:numel(Ng_mat)\n                    text{c,s,a,n} = struct;\n                    experiment = experiment + 1;\n                    strExperiment = ['Experiment',num2str(experiment)];\n                    for t = 1:nType\n                        nameFeature = fieldnames(temp.(strExperiment).(nameType{t})); nFeature = numel(nameFeature);\n                        for f = 1:nFeature\n                            data = zeros(nPatient,1);\n                            for p = 1:nPatient\n                                data(p,1) = tempText{p}.(strExperiment).(nameType{t}).(nameFeature{f});\n                            end\n                            text{c,s,a,n}.(nameType{t}).(nameFeature{f}).Data = data;\n                            for o = 1:nOutcomes\n                                [text{c,s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).rs,text{c,s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).p] = corr(data,outcomes.(nameOutcomes{o}),'type','Spearman');\n                            end\n                        end\n                    end\n                end\n            end\n        end\n    end\n    cd .., save(['text_',cohortID,'_',scans{scan},'_',featType],'text')\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/calcAllFusedTextures_batchHN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.21864626569553847}}
{"text": "function conv_feat_data = extract_image_activation_maps(CNN, image, scales, mean_pix, ...\n    Semantic_Aware_CNN, semantic_scales)\n% extract_image_activation_maps(CNN, image, scales, mean_pix): extract the \n% activation maps of one image (section 3 of technical report) for the \n% specified scales using the convolutional neural network CNN. \n% extract_image_activation_maps(CNN, image, scales, mean_pix, Semantic_Aware_CNN, semantic_scales):\n% In this case the current function it also extracts the semantic\n% segmentation aware activation maps (see section 4 of the technical\n% report). \n% \n% INPUTS:\n% 1) CNN: the caffe net struct with the convolutional neural network that\n% implements the activation mas module (section 3)\n% 2) image: a Height x Width x 3 uint8 array that represents the image\n% pixels\n% 3) scales: NumScales x 1 or 1 x NumScales vector with the images scales\n% that will be used. The i-th value should be the size in pixels of the\n% smallest dimension of the image in the i-th scale.\n% 4) mean_pix: is a 3 x 1 or 1 x 3 vector with the mean pixel value per \n% color channel that is subtracted from the scaled image before is being \n% fed to the CNN\n% 5) Semantic_Aware_CNN (OPTIONAL): the caffe net struct with the \n% convolutional neural that implements the activation mas module for the \n% semantic segmentation aware CNN features (section 4). The Semantic_Aware_CNN\n% network gets as input the convolutional feature maps that the CNN network\n% yields and outputs semantic segmentation aware activation maps.\n% 6) semantic_scales: a NumScales2 x 1 or 1 x NumScales2 vector with the \n% images scales that will be used for the semantic segmentation aware\n% features. The elements of this vector should be a subset of the scales vector.\n%\n% OUTPUTS:\n% 1) conv_feat_data: a struct that includes the activation maps of the\n% image. Its field is:\n%    conv_feat_data.feat: \n%    1.a) In case the function is called with the arguments:\n%    extract_image_activation_maps(CNN, image, scales, mean_pix)\n%    then conv_feat_data.feat is a struct that includes 1) the convolutional \n%    feature maps (field rsp) that the CNN network yields, 2) the image scales \n%    from which they were extracted (field scale), and 3) the original size \n%    of the image (fields im_height and im_width)\n%    1.b) In case the function is called with the arguments:\n%    extract_image_activation_maps(CNN, image, scales, mean_pix, Semantic_Aware_CNN, semantic_scales):\n%    then it is a 1 x 2 cell array where 1st element is a struct with the\n%    convolutional feature maps of the CNN network (like in the 1.a case)\n%    and the 2nd element is a struct with the convolutional feature maps of \n%    the Semantic_Aware_CNN network (like in the 1.a case).\n% \n% This file is part of the code that implements the following ICCV2015 accepted paper:\n% title: \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% authors: Spyros Gidaris, Nikos Komodakis\n% institution: Universite Paris Est, Ecole des Ponts ParisTech\n% Technical report: http://arxiv.org/abs/1505.01749\n% code: https://github.com/gidariss/mrcnn-object-detection\n%\n% \n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2015 Spyros Gidaris\n% \n% \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% Technical report: http://arxiv.org/abs/1505.01749\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n\nconv_feat_data = init_feat_data();\nconv_feat_data.feat.im_height = size(image,1);\nconv_feat_data.feat.im_width  = size(image,2);\n% extract the activation maps of an image for a given set of scales\n[conv_feat_data.feat.rsp, conv_feat_data.feat.scale] = extract_conv_features(...\n    CNN, image, scales, mean_pix);\n\nif exist('Semantic_Aware_CNN','var')>0\n    assert(exist('semantic_scales','var')>0)\n    % extract the semantic segmentation aware activation maps of an image\n    % of a given set of scales and the convolutional feature maps (activation \n    % maps) that were previously extracted from the image using the CNN\n    % network\n    semantic_conv_feat_data      = conv_feat_data;\n    semantic_conv_feat_data.feat = pick_scales_if_there(...\n        semantic_conv_feat_data.feat, semantic_scales);    \n    conf.do_interleave        = true; % if set to true then the\n    % resolution augmentation technique described on the OverFeat paper: http://arxiv.org/abs/1312.6229\n    % (section 3.3 of OverFeat technical report) is being used\n    conf.interleave_num_steps = 2; % a scalar value for the number of steps \n    % that are being using on the above resolution augmentation technique \n    \n    % extract the semantic segmentation aware activation maps\n    semantic_conv_feat_data.feat.rsp = extract_semantic_seg_features_from_conv5(...\n        Semantic_Aware_CNN, semantic_conv_feat_data.feat.rsp, conf);\n    conv_feat_data.feat = {conv_feat_data.feat, semantic_conv_feat_data.feat};\nend\n\nend\n\nfunction d = init_feat_data() \nd.feat     = [];\nend\n\nfunction feat = pick_scales_if_there(feat, scales)\nnum_scales = length(scales);\n\nfound_scales = zeros(size(scales));\nfound_rsp = {};\nc = 0;\nfor s = 1:num_scales\n    scale_index = find(feat.scale == scales(s));\n    if ~isempty(scale_index)\n        assert(numel(scale_index) == 1);\n        c = c + 1;\n        found_scales(c) = scales(s);\n        found_rsp{c}    = feat.rsp{scale_index}; \n    end\nend\nfeat.scale = found_scales(1:c);\nfeat.rsp   = found_rsp;\n\nend\n\n", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/conv_features/extract_image_activation_maps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.21864626456352756}}
{"text": "function sr_img = superresolve_drcn(slidingWindows, magFactor)\n\nlIm       = slidingWindows.referenceFrame;\nupscaling = magFactor;\n\n\n% Important Note: Grayscale or YCbCr input data expected!\n\ncurrentDir = pwd;\ncd('../algorithms/SRAlgorithms/DRCN'); % MAGI-FIX\n\nrun('snu_matconvnet/matlab/vl_setupnn.m');\n\nmodel = ['sf',num2str(upscaling),'/DRCN_sf',num2str(upscaling),'.mat'];\n\nif isempty(model)\n    error('no model');\nelse\n    modelPath = ['DRCN model/',model];\n    %gpu = 1;\n    gpu = 0; % MAGI-ADAPT\nend\n\nload(modelPath);\n\nnet = dagnn.DagNN.loadobj(net);\n\nif gpu\n    net.move('gpu');\nend\n\nmanagableMax = 300000;\n\nif isa(lIm,'uint8'),\n    lIm = single(lIm)/255;\nelse\n    lIm = single(lIm);\nend\n\nlIm = imresize(lIm, upscaling, 'bicubic');\n\nif size(lIm,3)>1\n    imlowy = lIm(:,:,1);\n    imlowy = max(16.0/255, min(235.0/255, imlowy));\n    imlowcb = lIm(:,:,2);\n    imlowcr = lIm(:,:,3);\nelse\n    imlowy = lIm;\nend\n\n% Perform actual SR\nif size(imlowy,1)*size(imlowy,2) > managableMax\n    impred = runPatchDRCN(net, imlowy, gpu, 20);\nelse\n    if gpu,\n        imlowy = gpuArray(imlowy);\n    end\n    impred = runDRCN(net, imlowy, gpu);\nend\n\nif size(lIm,3) > 1\n    impredColor = cat(3,impred,imlowcb,imlowcr);\nelse\n    impredColor = impred;\nend\n\nsr_img = im2double(impredColor); % Going back to double images\n\ncd(currentDir);\n\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/superresolve_drcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.21859322920677413}}
{"text": "function [E, Es, O] = detectEdge(Iin, Din, id, C, model, sc, outFile, cacheFile)\n  if(isstr(Iin)), Iin = imread(Iin); end\n  if(isstr(Din)), Din = imread(Din); end\n  if(isstr(model)), load(model); end\n\n\n  opts = model.opts;\n  rgbd = opts.rgbd;\n\n  model.opts.multiscale=1;          % for top accuracy set multiscale=1\n  model.opts.nTreesEval=4;          % for top speed set nTreesEval=1\n  model.opts.nThreads=1;            % max number threads for evaluation\n  model.opts.sharpen=0;             % for top speed set sharpen=0\n\n  if(rgbd == 3), \n    colorModel = model.colorModel.model;\n    cues = getAllCues(Iin, Din, C, colorModel, opts.rgbd3opts.vars, cacheFile); \n  end\n  \n  for i = 1:length(sc),\n    I = imresize(Iin, sc(i), 'lanczos3');\n    ng = zeros(size(I,1), size(I,2), 0);\n\n    if(rgbd), \n      D = imresize(Din, sc(i), 'nearest');\n      D=single(D)/1e4;\n    end\n    if(rgbd==1), \n      I=D; \n    elseif(rgbd==2), \n      I=cat(3,single(I)/255,D);\n    elseif(rgbd==3), \n      I=cat(3,single(I)/255,D,1e-3./D); \n      ng = cat(3, cues{:});\n      ng = imresize(ng, sc(i), 'lanczos3');\n    end\n    model.opts.nms = 0;\n    [Es{i}, O{i}] = edgesDetect(I,model,ng); \n    E{i} = edgesNmsMex(Es{i}, O{i}, 1, 5, 1.01, model.opts.nThreads);\n    \n    % model.opts.nms = 1;\n    % [E{i} O{i}] = edgesDetect(I,model,ng); \n  end\n  if(~isempty(outFile)), save(outFile, 'E', 'Es', 'O'); end\nend\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/structured-edges/detectEdge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2185922776000119}}
{"text": "function [RFcov, figHandle, all_models, weight, data] = rmPlotCoverage(vw, varargin)\n% [RFcov, figHandle, all_models, weight, data] = rmPlotCoverage(vw, varargin)\n% rmPlotCoverage - calulate the visual field coverage within an ROI\n% \n%\n% Before you run this script, you have to load 'variance explained', 'eccentricity',\n% 'polar-angle' and 'prf size' into 'co', 'map', 'ph' and 'amp' fields, respectively\n% \n% OUTPUT\n%  RFcov\n% INPUT\n%  prf_size:        0 = plot pRF center; 1 = use pRF size\n%  fieldRange:      maximum eccentricity to plot (deg)\n%  method:          'sum','max', 'clipped average', 'signed profile'\n%  newfig:          make a new figure (1) or not (0). (-1 indicates don't plot\n%                       anything, just return the coverage map.)\n%  nboot:           the number of bootstrapping (0 means no bootstrapping)\n%  normalizeRange:  if true, scale z axis to [0 1]\n%  smoothSigma:     median smoothing default: 2 nearest values\n%  cothresh:        threshold by variance explained in model\n%  eccthresh:       2-vector ecc limits (default = [0 1.5*fieldRange])\n%  nsamples:        num samples in square grid (default = 128)\n%  weight:          any of {'fixed', 'parameter map', 'variance explained'} (default = fixed) \n%  weightBeta:      use beta values from rmModel to weight pRFs (default = false)\n%  threshByCoh:     if true, threshold by values in coherence map, not variance explained in model \n%                       (note: these are often the same, but don't have to be)  %   addcenters\n%  addcenters:      1 = superimpose dots for pRF centers; 0 = do not show centers\n%  dualVEthresh:    use both pRF model VE and GLM fit VE as threshold\n%\n\n% 08/02 KA wrote\n% 08/04 KA added bootstrapping\n% 08/04 SD various mods\n% 09/02 SD large rearrangments\n% 09/08 JW allow superposition of pRF centers; various minor debugs\n% 02/10 MB added method 'betasum'\n% 09/16 RL edited code to allow for the edge case of ROIs that are 1 or 2 voxels large\nif notDefined('vw'),       error('View must be defined.'); end\nif notDefined('varargin'), varargin{1} = 'dialog'; end\n\n%% default parameters\nvfc.prf_size = true; \nvfc.fieldRange = min(30, vw.rm.retinotopyParams.analysis.maxRF);\nvfc.method = 'max';         \nvfc.newfig = true;                      \nvfc.nboot = 50;                          \nvfc.normalizeRange = true;              \nvfc.smoothSigma = true;                \nvfc.cothresh = viewGet(vw, 'co thresh');         \nvfc.eccthresh = [0 1.5*vfc.fieldRange]; \nvfc.nSamples = 128;            \nvfc.meanThresh = 0;\nvfc.weight = 'fixed';  \nvfc.weightBeta = 0;\nvfc.cmap = 'jet';\t\t\t\t\t\t\nvfc.clipn = 'fixed';                    \nvfc.threshByCoh = false;                \nvfc.addCenters = true;                 \nvfc.verbose = prefsVerboseCheck;\nvfc.dualVEthresh = 0;\n\ncompVolume = false;\n\n%% parse options\nif strcmpi(varargin{1},'dialog')\n    % get parameters from a dialog\n    vfc = rmPlotCoverageDialog(vfc);\nelse\n    for ii = 1:2:length(varargin)\n        switch lower(varargin{ii})\n            case 'prf_size',        vfc.prf_size        = varargin{ii+1}; % deg\n            case 'fieldrange',      vfc.fieldRange      = varargin{ii+1}; % deg\n            case 'method',          vfc.method          = varargin{ii+1}; % string\n            case 'newfig',          vfc.newfig          = varargin{ii+1}; % boolean\n            case 'nboot',           vfc.nboot           = varargin{ii+1}; % integer\n            case 'normalizerange',  vfc.normalizeRange  = varargin{ii+1}; % boolean\n            case 'smoothsigma',     vfc.smoothSigma     = varargin{ii+1}; % boolean   \n            case 'cothresh',        vfc.cothresh        = varargin{ii+1};\n            case 'eccthresh',       vfc.eccthresh       = varargin{ii+1};\n            case 'nsamples',        vfc.nSamples        = varargin{ii+1};\n\t\t\tcase 'minmeanmap',      vfc.meanThresh\t\t= varargin{ii+1};\n            case 'weight',          vfc.weight          = varargin{ii+1};\n            case 'weightbeta',      vfc.weightBeta      = varargin{ii+1};\n\t\t\tcase 'cmap',\t\t\tvfc.cmap\t\t\t= varargin{ii+1};\n            case 'threshbycoh',     vfc.threshByCoh     = varargin{ii+1}; \n            case 'addcenters',      vfc.addCenters      = varargin{ii+1}; % boolean   \n            case 'vfc.verbose',     vfc.verbose         = varargin{ii+1}; % boolean   \n            case 'dualvethresh',    vfc.dualVEthresh    = varargin{ii+1}; % boolean\n        end\n    end\nend\n\n\n%% load different pRF parameters\ntry\n    rmModel   = viewGet(vw,'rmSelectedModel');\ncatch %#ok<CTCH>\n    error('Need retModel information. Try using rmSelect. ');\nend\n\n% Get coordinates for current ROI\nroi.coords   = viewGet(vw, 'roiCoords');\nroi.indices  = viewGet(vw, 'roiIndices');\nroi.name     = viewGet(vw, 'roiName');\ncurScan      = viewGet(vw, 'curScan');\n\n% Get co and ph (vectors) for the current scan, within the\n% current ROI.\nvt      = vw.viewType;\nco      = rmCoordsGet(vt, rmModel,'varexp',     roi.indices);\nsigma1  = rmCoordsGet(vt, rmModel,'sigmamajor', roi.indices);\nsigma2  = rmCoordsGet(vt, rmModel,'sigmaminor', roi.indices);\ntheta   = rmCoordsGet(vt, rmModel,'sigmatheta', roi.indices);\nbeta    = rmCoordsGet(vt, rmModel,'beta',       roi.indices);\nx0      = rmCoordsGet(vt, rmModel,'x0',         roi.indices);\ny0      = rmCoordsGet(vt, rmModel,'y0',         roi.indices);\nclear rmModel\n\n%%%%%%%%%%%%%%\n% y flip note (r.a.s., 10/2009): \n% ------------------------------\n% I believe the stimulus generation code has had problems (from around\n% 2006-2009) where all stimuli were up/down flipped with respect to the pRF\n% sampling grid [X, Y]. As a consequence, all models solved in this time\n% seem to have a Y flip. The values saved on disk are off; you can \n% manually test this with an ROI like V2d which covers a quarterfield. \n%\n% I'm now trying to fix this issue. All accessor functions seem to have \n% implicitly corrected the flip, but in hard to trace ways. (This involves \n% a lot of post-hoc calls to functions like 'flipud' which made things \n% confusing.) I'm trying to (1) fix the core problems in the stim code; and\n% (2) remove the post-hoc corrections to the accessor code.\n%\n% But for now, there are a lot of models saved on disk, and it will take a\n% long time to fix them. So, I'm keeping the y-flip correction, but making\n% it explicit here. When the code is fixed and most models saved on disk\n% are correct, we can remove this. \n% y0 = -y0;\n\n% ok. I think it is time to remove. I suggest putting in a flag to flip the\n% y-dimension if requested, but otherwise not to.\nif getpref('VISTA', 'verbose')\n    warning('Negative y values plotted as lower visual field. This may be incorrect for old pRF models, as old code used to treat neagitve y as upper field.'); %#ok<*WNTAG>\nend\n%%%%%%%%%%%%%%\n\n% grabbing both (x0, y0) and (pol, ecc) are redundant, and allow for the\n% two specifications to get separated (because of the y-flip issue). So,\n% re-express ecc and pol using x0 and y0.\n[ph ecc] = cart2pol(x0, y0);\n\n% If 'threshByCoh' is set (i.e., true), thresholding will be set based on the\n% view struct's coherence field, instead of from the variance explained in\n% the model. \nif vfc.threshByCoh, co = vw.co{curScan}(roi.indices); end\nif ~any(co), co = []; end\n\n% If 'dualVEthresh' is set, thresholding will be based on both the VE of\n% the model AND the VE of the GLM fit\nif vfc.dualVEthresh == 1\n    fprintf('[%s] Using dual VE thresholding \\n',mfilename);\n    if isempty(vw.dualVE)\n        error('Need VE from GLM fit');\n    else\n        co = (co + vw.dualVE(roi.indices)) ./ 2;\n    end\nend\n\n% Remove NaNs from subCo and subAmp that may be there if ROI\n% includes volume voxels where there is no data.\nNaNs = sum(isnan(co));\nif NaNs\n    fprintf('[%s]:WARNING:ROI includes voxels that have no data. These voxels are being ignored.',mfilename);\n    notNaNs = ~isnan(co);\n    co      = co(notNaNs);\n    ph      = ph(notNaNs);\n    ecc     = ecc(notNaNs);\nend\n\n% Find voxels which satisfy cothresh and eccthresh.\ncoIndices = co>vfc.cothresh & ...\n    ecc>=vfc.eccthresh(1) & ecc<=vfc.eccthresh(2);\nif ~any(coIndices)\n   fprintf(1,'[%s]:No values above threshold.\\n',mfilename); \n   RFcov = zeros(vfc.nSamples);\n   figHandle    = [];\n   all_models   = [];\n   weight       = [];\n   data         = [];\n   return\nend\n\n% also select by the mean map, if that's selected\nif vfc.meanThresh > 0\n\tmeanMapFile = fullfile(dataDir(vw), 'meanMap.mat');\n\tif ~exist(meanMapFile, 'file')\n\t\twarning(['A mean map threshold is specified, but no mean map ' ...\n\t\t\t\t 'exists. This threshold will be ignored for now.'])\n\telseif isempty(map{vw.curScan})\n\t\twarning(['A mean map threshold is specified, but no mean map ' ...\n\t\t\t\t 'is computed for the current scan. ' ...\n\t\t\t\t 'This threshold will be ignored for now.'])\n\telse\n\t\tload(meanMapFile, 'map');\n\t\tmeanVals = map{vw.curScan};\n\t\tif NaNs\n\t\t\tmeanVals = meanVals(notNaNs);\n\t\tend\n\t\tcoIndices = coIndices & (meanVals > vfc.meanThresh);\n\tend\nend\n\n% check\nif vfc.verbose\n    fprintf(1,'[%s]:co-thresh:%.2f.\\n',mfilename,vfc.cothresh); \n    fprintf(1,'[%s]:ecc-thresh:[%.2f %.2f].\\n',mfilename,vfc.eccthresh(1),vfc.eccthresh(2)); \n    fprintf(1,'[%s]:Number of voxels above thresh in ROI: %d (total=%d).\\n',...\n        mfilename,sum(coIndices),numel(coIndices));\nend\n\n% Pull out co and ph for desired pixels\nsubCo    = co(coIndices);\nsubPh    = ph(coIndices);\nsubEcc   = ecc(coIndices);\nsubSize1 = single(sigma1(coIndices));\nsubSize2 = single(sigma2(coIndices));\nsubTheta = single(theta(coIndices));\nsubx0    = x0(coIndices);\nsuby0    = y0(coIndices);\n\n% smooth sigma\nif vfc.smoothSigma\n    \n    % Cannot do sigma smoothing if the ROI has less than 3 voxels. \n    if size(subx0,2) < 3\n        error('Cannot perform sigma smoothing when the ROI has less than 3 voxels. ')\n    end\n    \n    \n    if vfc.smoothSigma == 1\n        vfc.smoothSigma = 3; %default\n    end\n    n = vfc.smoothSigma;\n\t\n    %check sigma1==sigma2\n    if subSize1 == subSize2\n        for ii = 1:length(subSize1)\n            %compute nearest coords\n            dev = sqrt(abs(subx0(ii) - subx0).^2 + abs(suby0(ii) - suby0).^2);\n            [dev, ix] = sort(dev); %#ok<*ASGLU>\n            subSize1(ii) = median(subSize1(ix(1:n)));           \n        end\n        subSize2 = subSize1;\n    else\n        for ii = 1:length(subSize1)\n            %compute nearest coords\n            dev = sqrt(abs(subx0(ii) - subx0).^2 + abs(suby0(ii) - suby0).^2);\n            [dev, ix] = sort(dev);\n            subSize1(ii) = median(subSize1(ix(1:n)));\n            subSize2(ii) = median(subSize2(ix(1:n)));\n        end\n    end\nend\n             \n% polar plot\nsubX = single(subEcc .* cos(subPh));\nsubY = single(subEcc .* sin(subPh));\n\n\n% visual field\nx = single( linspace(-vfc.fieldRange, vfc.fieldRange, vfc.nSamples) );\n[X,Y] = meshgrid(x,x);\n\n% gather this data to make accessible in the plot\nif vfc.newfig  > -1   % -1 is a flag that we shouldn't plot the results\n\tdata.figHandle = gcf;\n\tdata.co        = co;\n\tdata.ph        = ph;\n\tdata.subCo     = subCo;\n\tdata.subPh     = subPh;\n\tdata.subEcc    = subEcc;\n\tdata.subx0     = subx0;\n\tdata.suby0     = suby0;\n    data.subSize1  = subSize1;\n    data.subSize2  = subSize2;\n    data.X         = X;\n\tdata.Y         = Y;\n\nend\n\n% For the pRF center plot, use a small constant pRF size\nif vfc.prf_size==0\n   subSize1 = ones(size(subSize1)) * 0.1;\n   subSize2 = ones(size(subSize2)) * 0.1;   \n   subTheta = zeros(size(subTheta));   \nend\n\nswitch lower(vfc.weight)\n    case 'fixed'\n        weight = ones(size(subCo));\n        \n    case 'parameter map'\n        weight = getCurDataROI(vw,'map',curScan,roi.coords);\n        weight = weight(coIndices);\n        \n    case {'variance explained', 'varexp', 've'}\n        weight = subCo;\n        \n    otherwise \n        error('Unknown weight parameter: %s',vfc.weight);\nend\n\nif vfc.weightBeta==1\n    weight = weight .* beta(coIndices);\nend\nweight = single(weight);\n\n%% special case: for the 'density' coverage option, we don't need to\n%% do a lot of memory-hungry steps like making all pRFs. So, I've set those\n%% computations aside in their own subroutine. (ras)\nif isequal( lower(vfc.method), 'density' )\n\tRFcov = prfCoverageDensityMap(vw, subx0, suby0, subSize1, X, Y);\n\t\n\tall_models = []; % not created for this option\t\n\tif vfc.newfig==-1\n\t\tfigHandle = [];\n\telse\n\t\t[figHandle, data]  = createCoveragePlot(vw, RFcov, vfc, roi, data);\n\tend\n\n\treturn\nend\n\n\n%% make all pRFs:\n% make in small steps so we don't go into swap space for large ROIs\nn = numel(subX);\ns = [(1:ceil(n./1000):n-2) n+1]; \n\n% For the line above (which assumes that we have at least 3 voxels,\n% probably for median smoothing),  s is an empty vector when n < 3 \n% -- and an empty rfcov is  returned when we try to plot the \n% coverage. So modify s accordingly for these edge cases: \n% The definition of s is not very intuitive\nif n < 3\n    s = [1:n+1]; \nend\n\nall_models = zeros( numel(X), n, 'single' );\nfprintf(1,'[%s]:Making %d pRFs:...', mfilename, n);\ndrawnow;\nfor n=1:numel(s)-1,\n    % make rfs\n    rf   = rfGaussian2d(X(:), Y(:),...\n\t\t\t\t\t\tsubSize1(s(n):s(n+1)-1), ...\n\t\t\t\t\t\tsubSize2(s(n):s(n+1)-1), ...\n\t\t\t\t\t\tsubTheta(s(n):s(n+1)-1), ...\n\t\t\t\t\t\tsubX(s(n):s(n+1)-1), ...\n\t\t\t\t\t\tsubY(s(n):s(n+1)-1));\n    all_models(:,s(n):s(n+1)-1) = rf;\nend;\nclear n s rf pred;\nfprintf(1, 'Done.\\n');\ndrawnow;\n\n% Correct volume\nif compVolume\n    tmp = ones(size(all_models, 1), 1, 'single');\n    \n    vol = sigma1(coIndices).^2;\n    vol = vol * (2 * pi);\n    \n    all_models = all_models ./ (tmp * vol);\nend\n\n% For the pRF center plot, put a constant value (1) within each Gaussian\nif vfc.prf_size==0\n    all_models(all_models>0.1)=1;\nend\n\n% weight all models\nif isequal( lower(vfc.weight), 'fixed' )\n\t% if the weights are even, we avoid the redundant, memory-hungry\n\t% multiplication step that would otherwise be done. \n\tall_models_weighted = all_models;\nelse\n\ttmp = ones(size(all_models, 1), 1, 'single');\n\tall_models_weighted = all_models .* (tmp * weight);\n\tclear tmp\nend\n\n%% Different ways of combining them: \n% 1) bootstrap (yes, no) 2) which statistic (sum, max, etc), \n% bootstrap\n\n% If we are only working with 1 voxel, bootstrapping does not do anything. \n% We turn it off because the bootstp function does not handle this case well. \nif size(subX,2) == 1\n    vfc.nboot = 0; \nend\n\nif vfc.nboot>0\n    if isempty(which('bootstrp'))\n        warndlg('Bootstrap requires statistics toolbox');\n        RFcov = [];\n        return;\n    end\n    all_models(isnan(all_models))=0;\n\n    switch lower(vfc.method)\n        case {'sum','add','avg','average everything', 'average'}\n            m = bootstrp(vfc.nboot, @mean, all_models');\n        \n        case {'max','profile','maximum profile' 'maximum'}\n            m = bootstrp(vfc.nboot, @max, all_models');\n        \n        otherwise\n            error('Unknown method %s',vfc.method)\n    end\n    RFcov=median(m,1)';\n    \n% no bootstrap\nelse\n    switch lower(vfc.method)\n                    \n        % coverage = sum(pRF(i)*w(i)) / (sum(pRF(i))\n        case {'beta-sum','betasum','weight average'}\n            RFcov = sum(all_models_weighted, 2) ./ sum(all_models,2);\n            \n        % coverage = sum(pRF(i)*w(i)) / (sum(pRF(i)) + clipping\n        case {'clipped beta-sum','clippedbeta','clipped weight average'}\n            % set all pRF beyond 2 sigmas to zero\n            clipval = exp( -.5 *((2./1).^2));\n            all_models(all_models<clipval) = 0;\n            n = all_models > 0;\n            \n            % recompute all_models_weighted\n\t\t\ttmp = ones( size(all_models,1), 1, 'single' );\n            all_models_weighted = all_models .* (tmp*weight);\n            \n            % compute weighted clipped sum/average\n            sumn = sum(n,2);\n            mask = sumn==0;\n            sumn(mask) = 1; % prevent dividing by 0\n            RFcov = sum(all_models_weighted,2) ./ sum(all_models,2);\n            RFcov(mask) = 0;\n            \n            %clip to zero if n<clipn\n            if isnumeric(vfc.clipn)\n                RFcov(sumn<=vfc.clipn) = 0;\n            end            \n           \n        % coverage = sum(pRF(i)*w(i)) / (sum(w(i))\n        case {'sum','add','avg','average','prf average'}\n            RFcov = sum(all_models_weighted, 2) ./ sum(weight);\n        \n        % coverage = sum(pRF(i)*w(i)) / (sum(w(i)) + clipping\n        case {'clipped average','clipped','clipped prf average'}\n            % set all pRF beyond 2 sigmas to zero\n            clipval = exp( -.5 *((2./1).^2));\n            all_models(all_models<clipval) = 0;\n            n = all_models > 0;\n            \n            % recompute all_models_weighted\n\t\t\ttmp = ones( size(all_models,1), 1, 'single' );\n            all_models_weighted = all_models .* (tmp*weight);\n            \n            % compute weighted clipped mean\n            sumn = sum(weight.*n);\n            mask = sumn==0;\n            sumn(mask) = 1; % prevent dividing by 0\n            RFcov = sum(all_models_weighted,2) ./ sumn;\n            RFcov(mask) = 0;\n            \n            %clip to zero if n<clipn\n            if isnumeric(vfc.clipn)\n                RFcov(sumn<=vfc.clipn) = 0;\n            end\n            \n        % coverage = max(pRF(i))\n        case {'maximum profile', 'max', 'maximum'}\n            RFcov = max(all_models_weighted,[],2);\n            \n        case {'signed profile'}\n            RFcov  = max(all_models_weighted,[],2);\n            covmin = min(all_models_weighted,[],2);\n            ii = RFcov<abs(covmin);\n            RFcov(ii)=covmin(ii);\n            \n        case {'p','probability','weighted statistic corrected for upsampling'}\n            RFcov = zeros(vfc.nSamples);\n\t\t\t\n\t\t\t% I guess this upsample factor assumes your functional data are\n\t\t\t% 2.5 x 2.5 x 3 mm?\n            upsamplefactor = 2.5*2.5*3; % sigh.....\n            for ii = 1:size(all_models,1)\n                s = wstat(all_models(ii,:),weight,upsamplefactor);\n                if isfinite(s.tval)\n                    RFcov(ii) = 1 - t2p(s.tval,1,s.df);\n                end\n            end\n\n        otherwise\n            error('Unknown method %s',vfc.method)\n    end\nend\n\n% convert 1D to 2D\nRFcov = reshape( RFcov, [1 1] .* sqrt(numel(RFcov)) );\n\n% When no voxels exceed threshold, return nan matrix rather than empty\n% matrix\nif sum(size(RFcov))==0\n    RFcov=nan(nSamples,nSamples);\nend\n\n% if the newfig flag is set to -1, just return the image\nif vfc.newfig==-1, \n    figHandle = [];\nelse\n\t[figHandle, data] = createCoveragePlot(vw, RFcov, vfc, roi, data);\nend\n\n\nreturn\n% /--------------------------------------------------------------------/ %\n\n\n\n\n% /--------------------------------------------------------------------/ %\nfunction [figHandle, data] = createCoveragePlot(vw, RFcov, vfc, roi, data)\n% plotting subroutine for rmPlotCoverage. Broken off by ras 10/2009.\nif vfc.newfig\n    figHandle = figure('Color', 'w');\nelse\n\tfigHandle = selectGraphWin;\nend\n\nheaderStr = sprintf('Visual field coverage, ROI %s, scan %i', ...\n\t\t\t\t\troi.name, vw.curScan);\nset(gcf, 'Name', headerStr);\n\n\n% normalize the color plots to 1\nif vfc.normalizeRange, \n\trfMax = max(RFcov(:)); \nelse\n\trfMax = 1; \nend\n\nimg = RFcov ./ rfMax;\nmask = makecircle(length(img));\nimg = img .* mask;\nimagesc(data.X(1,:), data.Y(:,1), img);\nset(gca, 'YDir', 'normal');\ngrid on\n\ndata.img = img;\n\ncolormap(vfc.cmap);\ncolorbar;\n\n% start plotting\nhold on;\n\n% t = 0:.01:2*pi;\n%\n% % rings every 5 deg\n% for n=(1:3)/3*vfc.fieldRange\n%     polar(t,ones(size(t))*n,'w');\n% end\n% plot([0 0],[-vfc.fieldRange vfc.fieldRange],'w')\n% plot([-sqrt(vfc.fieldRange^2/2) sqrt(vfc.fieldRange^2/2)],[-sqrt(vfc.fieldRange^2/2) sqrt(vfc.fieldRange^2/2)],'w')\n% plot([-vfc.fieldRange vfc.fieldRange],[0 0],'w')\n% plot([-sqrt(vfc.fieldRange^2/2) sqrt(vfc.fieldRange^2/2)],[sqrt(vfc.fieldRange^2/2) -sqrt(vfc.fieldRange^2/2)],'w')\n\n\n% add polar grid on top\np.ringTicks = (1:3)/3*vfc.fieldRange;\np.color = 'w';\npolarPlot([], p);\n\n% add pRF centers if requested\nif vfc.addCenters, \n    inds = data.subEcc < vfc.fieldRange;\n    plot(data.subx0(inds), data.suby0(inds), '.', ...\n\t\t'Color', [.5 .5 .5], 'MarkerSize', 4); \nend\n\n\n% scale z-axis\nif vfc.normalizeRange\n\tif isequal( lower(vfc.method), 'maximum profile' )\n\t\tcaxis([.5 1]);\n\telse\n\t    caxis([0 1]);\n\tend\nelse\n    if min(RFcov(:))>=0\n        caxis([0 ceil(max(RFcov(:)))]);\n    else\n        caxis([-1 1] * ceil(max(abs(RFcov(:)))));\n    end\nend\naxis image;   % axis square;\nxlim([-vfc.fieldRange vfc.fieldRange])\nylim([-vfc.fieldRange vfc.fieldRange])\n\ntitle(roi.name, 'FontSize', 24, 'Interpreter', 'none');\n\n% Save the data in gca('UserData')\nset(gca, 'UserData', data);\n\nreturn;\n% /------------------------------------------------------------------/ %\n\n\n\n\n% /------------------------------------------------------------------/ %\nfunction RFcov = prfCoverageDensityMap(vw, x0, y0, sigma, X, Y) %#ok<INUSL>\n% for each point (x, y) in visual space, this returns\n% the proportion of voxels in the ROI for which (x, y) is\n% within one standard deviation of the pRF center.\nmask = NaN( size(X, 1), size(X, 2), length(x0) );\n\nfor v = 1:length(x0)\n\t% make a binary mask within one sigma of the center\n\tR = sqrt( (X - x0(v)) .^ 2 + (Y - y0(v)) .^ 2 );\n\tmask(:,:,v) = ( R < 2*sigma(v) );\nend\n\n% average (sum?) across all masks\nRFcov = nansum(mask, 3);\n\nreturn\n% /------------------------------------------------------------------/ %\n\n\n\n\n% /------------------------------------------------------------------/ %\nfunction vfc = rmPlotCoverageDialog(vfc)\n%% dialog to get parameters for rmPlotCoverage.\ndlg(1).fieldName = 'method';\ndlg(end).style = 'popup';\ndlg(end).list = {'maximum profile' 'average' 'clipped average' ...\n\t\t\t\t 'density' 'signed profile' 'probability'};\ndlg(end).string = 'Method for combining pRFs?';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'weight';\ndlg(end).style = 'popup';\ndlg(end).list = {'fixed' 'variance explained' 'parameter map'};\ndlg(end).string = 'Method for weighting pRFs?';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'fieldRange';\ndlg(end).style = 'number';\ndlg(end).string = 'Visual Field Range (deg)?';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'nboot';\ndlg(end).style = 'number';\ndlg(end).string = 'Number of bootstrapping steps?';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'cmap';\ndlg(end).style = 'popup';\ndlg(end).list = mrvColorMaps;\ndlg(end).string = 'If plotting, color map for coverage?';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'normalizeRange';\ndlg(end).style = 'checkbox';\ndlg(end).list = {};\ndlg(end).string = 'Normalize data range to [0 1]';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'smoothSigma';\ndlg(end).style = 'checkbox';\ndlg(end).list = {};\ndlg(end).string = 'Smooth sigma (medianfilter)';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'prf_size';\ndlg(end).style = 'checkbox';\ndlg(end).list = {};\ndlg(end).string = 'Use pRF sizes from model';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'newfig';\ndlg(end).style = 'checkbox';\ndlg(end).string = 'Show results in new figure';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\ndlg(end+1).fieldName = 'addCenters';\ndlg(end).style = 'checkbox';\ndlg(end).string = 'Add dots to show pRF centers';\ndlg(end).value = vfc.(dlg(end).fieldName);\n\n\n[resp ok] = generalDialog(dlg, mfilename);\nif ~ok\n\terror('User Aborted.')\nend\ndrawnow;\n\nvfc = mergeStructures(vfc, resp);\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/rmPlotCoverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2184339270001337}}
{"text": "function MapFig = createMapFig(Rob,Sen,Lmk, Trj, Frm, Fac,SimRob,SimSen,SimLmk,FigOpt)\n\n% CREATEMAPFIG  Create 3D map figure and handles.\n%   MAPFIG = CREATEMAPFIG(Rob,Sen,Lmk,SimRob,SimSen,SimLmk,MapFigure)\n%   creates the map figure in figure 1, containing the following graphics\n%   objects:\n%       - a grid representing the ground\n%       - simulated robots and sensors - in green\n%       - estimated robots and sensors - in blue\n%       - simulated landmarks (virtual world) - in red\n%       - estimated landmarks, containing mean and uncertainty ellipsoid - in\n%       colors depending on the landmark type.\n%\n%   The output MAPFIG is a structure of handles to all these graphics\n%   objects. See the Matlab documentation for information about graphics\n%   handles and the way to efficiently manipulate graphics. MAPFIG has the\n%   following fields:\n%       .fig    handle to the figure\n%       .axes   handle to the axes\n%       .simRob array of handles to the simulated robots 'patch' objects\n%       .simSen array of handles to the simulated sensors 'patch' objects\n%       .simLmk handle to the simulated landmarks 'line' object\n%       .Rob array of handles to the estimated robots 'patch' objects\n%       .Sen array of handles to the estimated sensors 'patch' objects\n%       .Lmk array of structures with handles to the estimated landmarks, with\n%           .mean       handle to the ellipsoid's center 'line' object\n%           .ellipse    handle to the ellipsoid's contour 'line' object\n%\n%   The figure is updated using drawMapFig.\n%\n%   See also DRAWMAPFIG, CREATESENFIG, MAPOBSERVER, LINE, PATCH, SURFACE,\n%   SET, GET.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nglobal Map\n\n% Figure\nif FigOpt.createVideo\n    MapFig.fig = figure(99);\n    set(MapFig.fig, 'WindowStyle', 'normal');\n    figPos     = get(MapFig.fig,'position');\n    figSize    = FigOpt.map.size;\n    newFigPos  = [0 figPos(2)  figSize];\n    set(MapFig.fig,'position',newFigPos);\nelse\n    if ishandle(99)\n        MapFig.fig = figure(99);\n    else\n        MapFig.fig = figure(99);\n        if ~strcmp( get(MapFig.fig, 'WindowStyle'), 'docked')\n            figPos     = get(MapFig.fig,'position');\n            figSize    = FigOpt.map.size;\n            newFigPos  = [0 figPos(2)  figSize];\n            set(MapFig.fig,'position',newFigPos);\n        end\n    end\nend\nclf\nmoreindatatip\n\nset(MapFig.fig,...\n    'numbertitle',   'off',...\n    'name',          '3D Map',...\n    'doublebuffer',  'off',...\n    'renderer',      FigOpt.renderer,...\n    'toolbar',       'none',...\n    'color',         FigOpt.map.colors.bckgnd);\ncameratoolbar('show');\ncameratoolbar('setmode','orbit');\n\n% World dimensions\nworld.lims         = FigOpt.map.lims;\nworld.dims.l       = FigOpt.map.lims.xMax - FigOpt.map.lims.xMin;\nworld.dims.w       = FigOpt.map.lims.yMax - FigOpt.map.lims.yMin;\nworld.dims.h       = FigOpt.map.lims.zMax - FigOpt.map.lims.zMin;\nworld.center.xMean = (FigOpt.map.lims.xMax + FigOpt.map.lims.xMin)/2;\nworld.center.yMean = (FigOpt.map.lims.yMax + FigOpt.map.lims.yMin)/2;\nworld.center.zMean = (FigOpt.map.lims.zMax + FigOpt.map.lims.zMin)/2;\n\n% Map viewpoint\nviewPnt = mapObserver(world,FigOpt.map.view);\n\n% Axes\naxis equal\nMapFig.axes = gca;\nset(MapFig.axes,...\n    'parent',              MapFig.fig,...\n    'nextplot',            'replacechildren',...\n    'position',            [ 0 0 1 1],...\n    'SortMethod',          'childorder',... % {'depth'  'childorder'}\n    'projection',          FigOpt.map.proj,...\n    'CameraPosition',      viewPnt.X,...\n    'CameraPositionMode',  'manual',...\n    'CameraUpVector',      viewPnt.upvec,...\n    'CameraUpVectorMode',  'manual',...\n    'CameraViewAngle',     viewPnt.fov,...\n    'CameraViewAngleMode', 'manual',...\n    'CameraTarget',        viewPnt.tgt,...\n    'CameraTargetMode',    'manual',...\n    'xlim',                [FigOpt.map.lims.xMin FigOpt.map.lims.xMax],...\n    'ylim',                [FigOpt.map.lims.yMin FigOpt.map.lims.yMax],...\n    'zlim',                [FigOpt.map.lims.zMin FigOpt.map.lims.zMax],...\n    'alimmode',            'manual',...\n    'climmode',            'manual',...\n    'vis',                 'off');%,...\n\n\n\n\n% OBJECTS COMMON TO SIMULATION AND ESTIMATION\n% Ground\nMapFig.ground = createGround(FigOpt.map,MapFig.axes,FigOpt.map.colors.ground);\n    \n\n% ESTIMATED OBJECTS\n% robots\nfor rob = 1:numel(Rob)\n    \n    % create and draw robot - with ellipse\n    MapFig.Rob(rob).patch = createObjPatch(Rob(rob),FigOpt.map.colors.est,MapFig.axes);\n    MapFig.Rob(rob).ellipse = line(...\n        'parent', MapFig.axes,...\n        'xdata',  [],    ...\n        'ydata',  [],    ...\n        'zdata',  [],    ...\n        'color',  'r',   ...\n        'marker', 'none');\n    \n    % sensors\n    for sen = Rob(rob).sensors\n        \n        % create and draw sensor\n        MapFig.Sen(sen) = createObjPatch(Sen(sen),FigOpt.map.colors.est,MapFig.axes);\n        \n        % redraw sensor in robot frame\n        F = composeFrames(Rob(rob).frame,Sen(sen).frame);\n        drawObject(MapFig.Sen(sen),Sen(sen),F);\n        \n    end\n    \n    % trajectory\n    n = size(Frm,2);\n    Z = zeros(2,n);\n    MapFig.Rob(rob).trj = line(...\n        Z,    ...\n        Z,    ...\n        Z,    ...\n        'parent', MapFig.axes,...\n        'visible','off', ...\n        'color',  FigOpt.map.colors.graph.motion,   ...\n        'marker', 'o');\n\n    % measurement factors\n    n = numel(Fac);\n    Z = zeros(2,n);\n    MapFig.Rob(rob).factors = line(...\n        Z,    ...\n        Z,    ...\n        Z,    ...\n        'parent', MapFig.axes,...\n        'visible','off', ...\n        'color',  FigOpt.map.colors.graph.meas,   ...\n        'marker', 'none');\n\nend\n\n\n% landmarks\nfor lmk = 1:numel(Lmk)\n    \n    MapFig.Lmk(lmk) = createLmkGraphics(Lmk(lmk),FigOpt.map.colors.label,MapFig.axes);\n    \nend\n\n\n% SIMULATED OBJECTS\nif ~isempty(SimRob) && ~isempty(SimSen) && ~isempty(SimLmk)\n\n    % Landmarks - do not loop, draw all at once\n    MapFig.simLmk = createSimLmkGraphics(SimLmk,FigOpt.map.colors.simLmk,MapFig.axes,FigOpt.map.showSimLmk);\n    \n    % Robots\n    for rob = 1:numel(SimRob)\n        \n        % create and draw robot\n        MapFig.simRob(rob) = createObjPatch(SimRob(rob),FigOpt.map.colors.simu,MapFig.axes);\n        \n        % Sensors\n        for sen = SimRob(rob).sensors\n            \n            % create and draw sensor\n            MapFig.simSen(sen) = createObjPatch(SimSen(sen),FigOpt.map.colors.simu,MapFig.axes);\n            \n            % redraw sensor in robot frame\n            F = composeFrames(SimRob(rob).frame,SimSen(sen).frame);\n            drawObject(MapFig.simSen(sen),SimSen(sen),F);\n        end\n    end\nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n%   # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n%   This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n%   SLAMTB is free software: you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation, either version 3 of the License, or\n%   (at your option) any later version.\n%\n%   SLAMTB is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You should have received a copy of the GNU General Public License\n%   along with SLAMTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n%---------------------------------------------------------------------\n\n%   SLAMTB is Copyright:\n%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n%   Copyright (c) 2010-2013, Joan Sola,\n%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n%   SLAMTB is Copyright 2009 \n%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n%   @ LAAS-CNRS.\n%   See on top of this file for its particular copyright.\n\n%   # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/createMapFig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2183859533341219}}
{"text": "function [s1 s2 distances] = findTwoNearest(Input,nodes) %#codegen\n\nNumOfNodes = size(nodes,2);\n\ndistances = zeros(1,NumOfNodes);\nfor i=1:NumOfNodes\n    distances(i) = norm(Input - nodes(:,i));\nend\n\n[sdistances indices] = sort(distances);\n\ns1 = indices(1);\ns2 = indices(2);\n\n% MEX Code Generation:\n\n% mexcfg = coder.config('mex');\n% mexcfg.DynamicMemoryAllocation = 'AllVariableSizeArrays'; \n% codegen -config mexcfg findTwoNearest -args {coder.typeof(In(:,n),[Inf 1]),coder.typeof(nodes,[Inf Inf])}", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43665-unsupervised-learning-with-growing-neural-gas-gng-neural-network/Final/findTwoNearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "function [t,amps,data,aux] = read_intan_data(filename)\n\n% [t,amps,data,aux] = read_intan_data\n%\n% Opens file selection GUI to select and then read data from an Intan \n% amplifier data file (*.int).\n%\n% t = time vector (in seconds)\n% amps = vector listing active amplifier channels\n% data = matrix of electrode-referred amplifier signals (in microvolts)\n% aux = matrix of six auxiliary TTL input signals\n%\n% Example usage:\n%  >> [t,amps,data,aux] = read_intan_data;\n%  >> plot(t,data(:,1));\n%\n% Version 1.1, June 26, 2010\n% (c) 2010, Intan Technologies, LLC\n% For more information, see http://www.intantech.com\n% For updates and latest version, see http://www.intantech.com/software.html\n%\n% 06-22-10 Added GUI file selection and optimized: Craig Patten, Plexon, Inc.\n\n% use MATLAB predefined gui uigetfile to select the file(s) to analyze\nif ~exist('filename','var')\n    [file, path, filterindex] = uigetfile('*.int','Select a .int file','MultiSelect', 'off');\n    filename = [path,file];\nend\n\nfid = fopen(filename, 'r');\n\n% Read first three header bytes encoding file version\nfor i=1:3\n    header(i) = fread(fid, 1, 'uint8');\nend\n\nif (header(1) ~= 128)\n    error('Improper data file format.');\nend\n\nif (header(2) ~= 1 || header(3) ~= 1)\n    warning('Data file version may not be compatible with this m-file.');\nend\n\n% Now see which amplifier channels are saved in this file.\nfor i=1:64\n    amp_on(i) = fread(fid, 1, 'uint8');\nend\n\nnum_amps = sum(amp_on);\n\n% Create a list of amplifier channels in this file.\namps = zeros(1,num_amps);\nindex = 1;\nfor i=1:64\n    if (amp_on(i) == 1)\n        amps(index) = i;\n        index = index + 1;\n    end\nend\n\n% Now search for the end of the file to find out the length of the data.\n% t_count = 0;\n% while (~feof(fid))\n%    fread(fid, 1+4*num_amps, 'uint8'); \n%    t_count = t_count + 1;\n% end\n% t_count = t_count - 1;\n% t_max = t_count/25000;\n\n%-----------------------------------\n% replace above code with a more efficient method CDP 06-24-10\ns = dir(filename);\nfilesize = s.bytes;\nt_count = (filesize - 67)/(num_amps*4 + 1);\nt_max = t_count/25000;\n%-----------------------------------\n\n% print channel (singular) when there is only one channel! CDP 06-24-10\nif num_amps == 1;\n    fprintf(1, '\\nData file contains %0.2f seconds of data from %d amplifier channel.\\n', t_max, num_amps);\n    fprintf(1, 'Channel: ');\nelse\n    fprintf(1, '\\nData file contains %0.2f seconds of data from %d amplifier channels.\\n', t_max, num_amps);\n    fprintf(1, 'Channels: ');\nend\n\nfor i=1:num_amps\n    fprintf(1, '%d ', amps(i));\nend\nfprintf(1, '\\n\\n');\n\n% Pre-allocate large data matrices.\naux = zeros(t_count,6,'uint8');\nt = (0:1:(t_count-1))/25000;\nt = t';\n\n%--------------------------------------\n% Replace code code below with much faster code CDP 06-24-10\n% Go back to the beginning of the file...\nfrewind(fid);\n\n% ...skip the header this time...\nfread(fid, 3+64, 'uint8');\n\n% allocate space to read the entire file\ndata2 = zeros((filesize-67),1,'uint8');\n% read the entire file\ndata2 = fread(fid,(filesize-67),'uint8=>uint8');\n\n% extract the digital data\naux_data = data2((num_amps*4)+1:num_amps*4+1:filesize-67);\n\n% extract individual bits\naux = [bitget(aux_data,6),bitget(aux_data,5),bitget(aux_data,4),bitget(aux_data,3),bitget(aux_data,2),bitget(aux_data,1)];\nclear aux_data;\n\n% delete the digital data\ndata2((num_amps*4)+1:num_amps*4+1:filesize-67) = [];\n\n% convert the remaining data from bytes to single\ndata2 = typecast(data2,'single');\n\ndata = zeros(t_count,num_amps);\n% de-mux the channels\nfor ind = 1:num_amps\n    data(:,ind) = data2(ind:num_amps:length(data2));\nend\n%---------------------------------------\n\n% % Go back to the beginning of the file...\n% frewind(fid);\n% \n% % ...skip the header this time...\n% fread(fid, 3+64, 'uint8');\n% \n% % ...and read all the data.\n% fprintf(1, 'Reading data...  (This may take a while.)\\n\\n');\n% for i=1:t_count\n%     for j=1:num_amps\n%         data(i,j) = double(fread(fid, 1, 'float32'));\n%     end\n%     \n%     aux_byte = fread(fid, 1, 'uint8');\n%     \n%     % Decode auxiliary TTL inputs\n%     if aux_byte >= 32\n%         aux(i,6) = 1;\n%         aux_byte = aux_byte - 32;\n%     end\n%     if aux_byte >= 16\n%         aux(i,5) = 1;\n%         aux_byte = aux_byte - 16;\n%     end\n%     if aux_byte >= 8\n%         aux(i,4) = 1;\n%         aux_byte = aux_byte - 8;\n%     end\n%     if aux_byte >= 4\n%         aux(i,3) = 1;\n%         aux_byte = aux_byte - 4;\n%     end\n%     if aux_byte >= 2\n%         aux(i,2) = 1;\n%         aux_byte = aux_byte - 2;\n%     end\n%     if aux_byte >= 1\n%         aux(i,1) = 1;\n%         aux_byte = aux_byte - 1;\n%     end        \n% end\n\n% Close file, and we're done.\nfclose(fid);\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/utilities/fileConversions/ConvertToPlexon/read_intan_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.21802172316021223}}
{"text": "% This script is a demonstration of how to train a toy acoustic model for\n% English using filterbank features for the TIMIT task. Note that the demo\n% does not contain the TIMIT corpus. You need to provide the TIMIT corpus\n% root directory. \n%\n% Warning: this demo assumes that your system has at least 8GB of free\n% memory for Matlab.\n%\n% Author: Xiong Xiao, NTU, Singapore\n% Date Created: 10 Oct 2013\n% Last Modified: 16 Jun 2015\n%\n\nclear\npara.IO.nStream = 2;        % Two input streams, one is the MFCC features, and the other is the frame-level phone label.\npara.NET.sequential = 0;    % Use frame-based training, not sentence based training\npara.NET.batchSize = 256;   % minibatch size\npara.NET.learning_rate = 3e-2;      % global learning rate\npara.NET.momentum = [0.5];          % momentun\npara.NET.L2weight = 3e-4;           % L2 regularization weight\npara.useGPU = 0;                    % whether to use GPU\npara.displayInterval = 100;         % display training progress after N minibathces\npara.checkGradient = 0;             % whether to perform gradient checking before training\npara.stopImprovement = 0.1;         % when to stop the training, Most of time I use Ctr+C :)\npara.reduceLearnRate = 0.5;         % when to start reducing learning rate\npara.reduceLearnRateSpeed = 0.7;    % how fast do we decay the learning rate in each iteration\npara.maxItr = 50;                   % maximum number of iterations allowed\npara.minItr = 20;                   % maximum number of iterations allowed\n\npara.local.V = 39;                  % put task specific configurations into para.local. Here we specify that we use only 39 phones. \npara.local.fs = 16000;              % sampling rate, we can use 16000Hz or 8000Hz. \npara.local.doCMN = 1;               % whether to perform cepstral mean normalization for each utterance\n\n[Data_tr, Data_cv, para] = LoadData_TIMIT(para, 'train');\n\n% generate the preprocessing of streams. We need to generate dynamic\n% featuers for stream 1, i.e. the fbank stream. \npara.preprocessing{1}{1}.name = 'delta';\npara.preprocessing{1}{end}.delta_order = 2;   % use upto second derivative of MFCCs\npara.preprocessing{1}{end}.inputDim = 40;\npara.preprocessing{1}{end}.outputDim = 120;\n\nfeat_tmp = cell2mat(Data_tr(1).data(1:10:end));\nfeat_tmp_delta = FeaturePipe(feat_tmp, para.preprocessing{1});  % generate the MFCCs with dynamic features\ntmpProcessing = genDNNPreprocessing_splice_norm(feat_tmp_delta, para.IO.context(1));    % generate the splicing setting, and global mean and variance normalization processing\npara.preprocessing{1} = [para.preprocessing{1} tmpProcessing];\nfeat_tmp2 = FeaturePipe(feat_tmp, para.preprocessing{1});\nplot(mean(feat_tmp2')); hold on         % verify that we now have normal distributed input features\nplot(std(feat_tmp2')); hold off;\n\npara.preprocessing{2} = {};     % we don't need any preprocessing for the second stream, i.e. the label\n\ninputDim = para.preprocessing{1}{end}.outputDim;\nhiddenLayerSize = [1024 1024 1024];        % you can generate deeper network by using something like: hiddenLayerSize = [512 512 200 512]. Then it will generate 4 hidden layers. \noutputDim = length(unique(cell2mat(Data_tr(2).data)));\ncost_function = 'cross_entropy';\nlayer = genNetworkFeedForward_v2(inputDim, hiddenLayerSize, outputDim, cost_function);\npara.cost_func.layer_idx = length(layer);\npara.cost_func.layer_weight = [1];\n\npara.output = sprintf('nnet/DNN_phone_TIMIT');\npara.output = sprintf('%s.U%d.%d', para.output, length(Data_tr(1).data), inputDim);\nfor i=1:length(hiddenLayerSize)\n    para.output = sprintf('%s-%d', para.output, hiddenLayerSize(i));\nend\npara.output = sprintf('%s-%d.L2_%s.LR_%s/nnet', para.output, outputDim, FormatFloat4Name(para.NET.L2weight),FormatFloat4Name(para.NET.learning_rate));\nLOG = [];\n\ntrainGraph_SGD(layer, Data_tr, Data_cv, para, LOG);\n\n\n\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/classification_framewise/TrainPhoneRecognizerDNN_TIMIT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.218015018222487}}
{"text": "function [out] = VBA_spm_eeg_displayECD(Pos,Orient,Var,Names,options)\n% Plot dipole positions onto the SPM canonical mesh\n% FORMAT [out] = spm_eeg_displayECD(Pos,Orient,Var,Names,options)\n%\n% IN (admissible choices):\n%   - Pos: a 3xndip matrix containing the positions of the dipoles in\n%   the canonical frame of reference\n%   - Orient: the same with dipole orientations\n%   - Var: the same with position variance\n%   - Names: the same with dipole names\n%   - options: an optional structure containing\n%       .hfig: the handle of the display figure\n%       .tag: the tag to be associated with the created UI objects\n%       .add: binary variable ({0}, 1: just add dipole in the figure .hfig)\n%\n% OUT:\n%   - out: a structure containing the handles of the object in the figure\n%   (including the mesh, the dipoles, the transparency slider, etc...)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Jean Daunizeau\n% $Id: spm_eeg_displayECD.m 5737 2013-11-10 20:23:49Z karl $\n\n\n% checks and defaults\n%--------------------------------------------------------------------------\nhfig       = [];\nParentAxes = [];\nquery      = [];\nhandles    = [];\ntag        = '';\ntry, options; catch, options = [];      end\ntry, hfig        = options.hfig;        end\ntry, tag         = options.tag;         end\ntry, ParentAxes  = options.ParentAxes;  end\ntry, query       = options.query;       end\ntry, handles     = options.handles;     end\ntry\n    figure(hfig);\ncatch\n    hfig  = VBA_spm_figure('GetWin','Graphics');\n    VBA_spm_figure('Clear',hfig);\n    ParentAxes = axes('parent',hfig);\nend\ntry\n    markersize = options.markersize;\ncatch\n    markersize = 20;\nend\ntry\n    meshsurf = options.meshsurf;\ncatch\n    meshsurf = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');\nend\n\nif isscalar(Var), Var = Pos*0 + Var^2;   end\ntry, Pos{1};    catch, Pos = {Pos};      end\ntry, Orient{1}; catch, Orient = {Orient};end\ntry, Var{1};    catch, Var = {Var};      end\n\nndip = size(Pos{1},2);\nif ~exist('Names','var') || isempty(Names)\n    for i=1:ndip\n        Names{i} = num2str(i);\n    end\nend\n\n\ncol = ['b','g','r','c','m','y','k','w'];\ntmp = ceil(ndip./numel(col));\ncol = repmat(col,1,tmp);\npa  = get(ParentAxes,'position');\n\nif ndip > 0\n    \n    if isempty(query)\n        opt.hfig = hfig;\n        opt.ParentAxes = ParentAxes;\n        opt.visible = 'off';\n        pos2 = [pa(1),pa(2)+0.25*pa(4),0.03,0.5*pa(4)];\n        out  = VBA_spm_eeg_render(meshsurf,opt);\n        handles.mesh = out.handles.p;\n        handles.BUTTONS.transp = out.handles.transp;\n        handles.hfig = out.handles.fi;\n        handles.ParentAxes  = out.handles.ParentAxes;\n        set(handles.mesh,...\n            'facealpha',0.1,...\n            'visible','on')\n        set(handles.BUTTONS.transp,...\n            'value',0.1,...\n            'position',pos2,...\n            'visible','on')\n    end\n    \n    set(ParentAxes,'nextplot','add')\n    for j=1:length(Pos)\n        for i =1:ndip\n            try\n                set(handles.hp(j,i),...\n                    'xdata',Pos{j}(1,i),...\n                    'ydata',Pos{j}(2,i),...\n                    'zdata',Pos{j}(3,i));\n            catch\n                handles.hp(j,i) = plot3(handles.ParentAxes,...\n                    Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n                    [col(i),'.'],...\n                    'markerSize',markersize,...\n                    'visible','off');\n            end\n            try\n                no = sqrt(sum(Orient{j}(:,i).^2));\n                if no > 0\n                    Oi = 1e1.*Orient{j}(:,i)./no;\n                else\n                    Oi = 1e-5*ones(3,1);\n                end\n                try\n                    set(handles.hq(j,i),...\n                        'xdata',Pos{j}(1,i),...\n                        'ydata',Pos{j}(2,i),...\n                        'zdata',Pos{j}(3,i),...\n                        'udata',Oi(1),...\n                        'vdata',Oi(2),...\n                        'wdata',Oi(3))\n                catch\n                    handles.hq(j,i) = quiver3(handles.ParentAxes,...\n                        Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n                        Oi(1),Oi(2),Oi(3),col(i),...\n                        'lineWidth',2,'visible','off');\n                end\n                if isequal(query,'add')\n                    set(handles.hq(j,i),...\n                        'LineStyle','--',...\n                        'lineWidth',1)\n                end\n            end\n            [x,y,z]= ellipsoid(Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n                1.*sqrt(Var{j}(1,i)),1.*sqrt(Var{j}(2,i)),1.*sqrt(Var{j}(1,i)),20);\n            try\n                set(handles.hs(j,i),...\n                    'xdata',x,...\n                    'ydata',y,...\n                    'zdata',z);\n            catch\n                handles.hs(j,i) = surf(handles.ParentAxes,...\n                    x,y,z,...\n                    'edgecolor','none',...\n                    'facecolor',col(i),...\n                    'facealpha',0.2,...\n                    'visible','off');\n            end\n            try\n                set(handles.ht(j,i),...\n                    'position',Pos{j}(:,i));\n            catch\n                handles.ht(j,i) = text(...\n                    Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n                    Names{i},...\n                    'Parent',handles.ParentAxes,...\n                    'visible','off');\n            end\n        end\n    end\n    \n    if length(Pos) > 1\n        \n        try, set(handles.hp(end,:),'visible','on'); end\n        try, set(handles.hq(end,:),'visible','on'); end\n        try, set(handles.hs(end,:),'visible','on'); end\n        try, set(handles.ht(end,:),'visible','on'); end\n        \n        handles.uic(1) = uicontrol(handles.fi,...\n            'units','normalized',...\n            'position',[0.45,0.5,0.2,0.03],...\n            'style','radio','string','Show priors',...\n            'callback',@doChange1,...\n            'BackgroundColor',[1 1 1],...\n            'tooltipstring','Display prior locations',...\n            'userdata',handles,'value',0,...\n            'BusyAction','cancel',...\n            'Interruptible','off',...\n            'tag','plotEEG');\n\n        handles.uic(2) = uicontrol(handles.fi,...\n            'units','normalized',...\n            'position',[0.45,0.53,0.2,0.03],...\n            'style','radio','string','Show posteriors',...\n            'callback',@doChange2,...\n            'BackgroundColor',[1 1 1],...\n            'tooltipstring','Display posterior locations',...\n            'userdata',handles,'value',1,...\n            'BusyAction','cancel',...\n            'Interruptible','off',...\n            'tag','plotEEG');\n        \n    else\n        \n        try, set(handles.hp(1,:),'visible','on'); end\n        try, set(handles.hq(1,:),'visible','on'); end\n        try, set(handles.hs(1,:),'visible','on'); end\n        try, set(handles.ht(1,:),'visible','on'); end\n        \n    end\n    \nend\n\ntry\n    clear out\n    out.handles = handles;\ncatch\n    out = [];    \nend\n\n%==========================================================================\nfunction doChange1(i1,i2)\nval = get(i1,'value');\nhandles = get(i1,'userdata');\nif ~val\n    try, set(handles.hp(1,:),'visible','off'); end\n    try, set(handles.hq(1,:),'visible','off'); end\n    try, set(handles.hs(1,:),'visible','off'); end\n    try, set(handles.ht(1,:),'visible','off'); end\nelse\n    try, set(handles.hp(1,:),'visible','on');  end\n    try, set(handles.hq(1,:),'visible','on');  end\n    try, set(handles.hs(1,:),'visible','on');  end\n    try, set(handles.ht(1,:),'visible','on');  end\nend\n\n\n%==========================================================================\nfunction doChange2(i1,i2)\nval = get(i1,'value');\nhandles = get(i1,'userdata');\nif ~val\n    try, set(handles.hp(2,:),'visible','off'); end\n    try, set(handles.hq(2,:),'visible','off'); end\n    try, set(handles.hs(2,:),'visible','off'); end\n    try, set(handles.ht(2,:),'visible','off'); end\nelse\n    try, set(handles.hp(2,:),'visible','on');  end\n    try, set(handles.hq(2,:),'visible','on');  end\n    try, set(handles.hs(2,:),'visible','on');  end\n    try, set(handles.ht(2,:),'visible','on');  end\nend\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/thrid-party/spm/VBA_spm_eeg_displayECD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.2179937365982224}}
{"text": "function [batches, batch_padding] = rcnn_extract_regions(im, boxes, rcnn_model)\n% [batches, batch_padding] = rcnn_extract_regions(im, boxes, rcnn_model)\n%   Extract image regions and preprocess them for use in Caffe.\n%   Output is a cell array of batches.\n%   Each batch is a 4-D tensor formatted for input into Caffe:\n%     - BGR channel order\n%     - single precision\n%     - mean subtracted\n%     - dimensions from fastest to slowest: width, height, channel, batch_index\n%\n%   im is an image in RGB order as returned by imread\n%   boxes are in [x1 y1 x2 y2] format with one box per row\n\n% AUTORIGHTS\n% ---------------------------------------------------------\n% Copyright (c) 2014, Ross Girshick\n% \n% This file is part of the R-CNN code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% ---------------------------------------------------------\n\n% convert image to BGR and single\nim = single(im(:,:,[3 2 1]));\nnum_boxes = size(boxes, 1);\nbatch_size = rcnn_model.cnn.batch_size;\nnum_batches = ceil(num_boxes / batch_size);\nbatch_padding = batch_size - mod(num_boxes, batch_size);\nif batch_padding == batch_size\n  batch_padding = 0;\nend\n\ncrop_mode = rcnn_model.detectors.crop_mode;\nimage_mean = rcnn_model.cnn.image_mean;\ncrop_size = size(image_mean,1);\ncrop_padding = rcnn_model.detectors.crop_padding;\n\nbatches = cell(num_batches, 1);\n%for batch = 1:num_batches\nparfor batch = 1:num_batches\n  batch_start = (batch-1)*batch_size+1;\n  batch_end = min(num_boxes, batch_start+batch_size-1);\n\n  ims = zeros(crop_size, crop_size, 3, batch_size, 'single');\n  for j = batch_start:batch_end\n    bbox = boxes(j,:);\n    crop = rcnn_im_crop(im, bbox, crop_mode, crop_size, ...\n        crop_padding, image_mean);\n    % swap dims 1 and 2 to make width the fastest dimension (for caffe)\n    ims(:,:,:,j-batch_start+1) = permute(crop, [2 1 3]);\n  end\n\n  batches{batch} = ims;\nend\n", "meta": {"author": "rbgirshick", "repo": "rcnn", "sha": "43b0334e96e9e910bc45c94902a093b5a6f35d0a", "save_path": "github-repos/MATLAB/rbgirshick-rcnn", "path": "github-repos/MATLAB/rbgirshick-rcnn/rcnn-43b0334e96e9e910bc45c94902a093b5a6f35d0a/rcnn_extract_regions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.21793556304606926}}
{"text": "function vf_out = get_vector_field(deformS,toPlanC,toScanNum,fromPlanC,fromScanNum)\n% function vf = get_vector_field(deformS,toPlanC,toScanNum,fromPlanC,fromScanNum)\n% \n% APA, 09/24/2012\n\n% Obtain base and moving scan UIDs\nbaseScanUID = deformS.baseScanUID;\nmovScanUID  = deformS.movScanUID;\n\n% Figure out whether an inverse Vector field is required\nindexToS = toPlanC{end};\nindexFromS = fromPlanC{end};\n\ntoScanUID = toPlanC{indexToS.scan}(toScanNum).scanUID;\nfromScanUID = fromPlanC{indexFromS.scan}(fromScanNum).scanUID;\nif isequal(baseScanUID, fromScanUID)\n    calc_inv_vf_flag = 0;\nelse\n    calc_inv_vf_flag = 1;\nend\n\n% Create b-spline coefficients file\nbspFileName = fullfile(getCERRPath,'ImageRegistration','tmpFiles',['bsp_coeffs_',baseScanUID,'_',movScanUID,'.txt']);\n% bspFileName = fullfile(tempdir,'tmpFiles',['bsp_coeffs_',baseScanUID,'_',movScanUID,'.txt']);\nsuccess     = write_bspline_coeff_file(bspFileName,deformS.algorithmParamsS);\n\n% Obtain Vf from b-splice coefficients\nvfFileName = fullfile(getCERRPath,'ImageRegistration','tmpFiles',['vf_',baseScanUID,'_',movScanUID,'.mha']);\n%vfFileName = fullfile(tempdir,'tmpFiles',['vf_',baseScanUID,'_',movScanUID,'.mha']);\nsystem(['plastimatch xf-convert --input ',escapeSlashes(bspFileName), ' --output ', escapeSlashes(vfFileName), ' --output-type vf'])\n%system(['plastimatch convert --xf ',escapeSlashes(bspFileName), ' --output-vf=', escapeSlashes(vfFileName)])\ndelete(bspFileName)\n\nif calc_inv_vf_flag\n    % Get dims, origin, spacing for toScan\n    [uniformCT, uniformScanInfoS] = getUniformizedCTScan(0,toScanNum,toPlanC);\n    uniformCT = permute(uniformCT, [2 1 3]);\n    uniformCT = flipdim(uniformCT,3);\n    % Change data type to int16 to allow (-)ve values\n    uniformCT = int16(uniformCT) - int16(toPlanC{indexToS.scan}(toScanNum).scanInfo(1).CTOffset);    \n    % [dx, dy, dz]\n    resolution = [uniformScanInfoS.grid2Units, uniformScanInfoS.grid1Units, uniformScanInfoS.sliceThickness] * 10;    \n    [xVals, yVals, zVals] = getUniformScanXYZVals(toPlanC{indexToS.scan}(toScanNum));    \n    offset = [xVals(1) -yVals(1) -zVals(end)] * 10;\n    img_size = size(uniformCT);   \n    system(['vf_invert --input ', escapeSlashes(vfFileName), ' --output ', escapeSlashes(vfFileName), ' --dims=\"',num2str(img_size),'\" --origin=\"',num2str(offset),'\" --spacing=\"',num2str(resolution),'\"'])\nend\n\n% infoS  = mha_read_header(vfFileName);\n% vf = mha_read_volume(infoS);\n[vf,infoS] = readmha(vfFileName);\n%vf = flipdim(permute(vf,[2,1,3]),3);\ndelete(vfFileName)\n\nvf_out(:,:,:,1) = flipdim(permute(vf(:,:,:,1),[2,1,3]),3)/10;\nvf_out(:,:,:,2) = flipdim(permute(-vf(:,:,:,2),[2,1,3]),3)/10;\nvf_out(:,:,:,3) = flipdim(permute(-vf(:,:,:,3),[2,1,3]),3)/10;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/get_vector_field.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2178674138356302}}
{"text": "function [flatView, allDist] = measureCorticalDistanceLineROI(flatView, coords,plotFlag)\n% \n% USAGE: measureCorticalDistanceLineROI(flatView, coords)\n%   \n% AUTHOR:  Dougherty\n% DATE:    2002.04.10\n% PURPOSE:\n%   Compute the shortest cortical manifold distance between \n%   points. The coords is passed in are assume to be a line ROI\n%   where the first coord is at one end of the line and the last\n%   coord is at the other end.\n% \n% HISTORY\n%\n% 7/16/02 djh, replaced mrSESSION.vAnatomyPath with global vANATOMYPATH\n\nsampleDist = 5;\n\nglobal vANATOMYPATH;\nmmPerPix = readVolAnatHeader(vANATOMYPATH);\n\nif (~exist('plotFlag','var'))\n    plotFlag=1;\nend\n\n% Get a gray structure because we need the gray nodes.\ngrayView = getSelectedGray;\nif isempty(grayView)\n    grayView = initHiddenGray;\nend\n\n% the third coordinate is the 'slice', which, for flat views, means left or right hemisphere.\nslice = coords(3,1);\nif (slice==1)\n    nodes = grayView.allLeftNodes;\n    edges = grayView.allLeftEdges;\nelse\n    nodes = grayView.allRightNodes;\n    edges = grayView.allRightEdges;\nend\n\nnCoords = size(coords,2);\ndisp(['Finding nodes for ',num2str(nCoords),' coords...']);\nallNodeIndices = zeros(1,nCoords);\n% Find the nearest gray node for each coordinate.\n%\nfor(ii=1:nCoords)\n    % get nearest flat coordinate (not all points on the flat correspond to flat coordinates)\n    flatDistances = (flatView.coords{slice}(1,:) - coords(1,ii)).^2 + ...\n        (flatView.coords{slice}(2,:) - coords(2,ii)).^2;\n    % There is a one-to-many mapping of flatCoords to grayCoords, but we ignore that\n    % here by using 'min', which will always reuturn one value, even if there are several\n    % identical minima. \n    % FIX THIS- we should always grab layer 1, or something more consistent\n    % than relying on min's arbitrary sort.\n    [val,coordIndex] = min(flatDistances);\n        \n    grayNode = find(nodes(2,:) == flatView.grayCoords{slice}(1,coordIndex) & ...\n            nodes(1,:) == flatView.grayCoords{slice}(2,coordIndex) & ...\n            nodes(3,:) == flatView.grayCoords{slice}(3,coordIndex));\n    % This should produce exactly one index.\n    \n    % Catch errors. \n    if(isempty(grayNode))\n        myErrorDlg('No gray nodes were found!');\n    end\n    if(length(grayNode)>1)\n        disp([mfilename,': WARNING- coord ',num2str(ii),'- more than one grayNode found!']);\n        grayNode = grayNode(1);\n    end\n    allNodeIndices(ii) = grayNode;\nend\n\nsampleNodes = allNodeIndices(1);\nnodeIndices = allNodeIndices(2:end);\ndone = 0;\nwhile(~done)\n    % Now, compute the manifold distance to all other points from the given 'start' point.\n    allDist = mrManDist(nodes, edges, sampleNodes(end), mmPerPix, -1, 0);\n    drop = intersect(find(allDist<=sampleDist), nodeIndices);\n    if(~isempty(drop))\n        for(ii=1:length(drop))\n            nodeIndices = nodeIndices(nodeIndices~=drop(ii)); \n        end\n    end\n    if(~isempty(nodeIndices))\n        % *** WE SHOULD GET THE NEXT NEAREST\n        nearest = find(allDist(nodeIndices)==min(allDist(nodeIndices)));\n        nearest = nearest(1);\n        sampleNodes = [sampleNodes, nodeIndices(nearest)];\n        nodeIndices = nodeIndices(nodeIndices~=nodeIndices(nearest));\n    end\n    if(isempty(nodeIndices))\n        done = 1;\n    end\nend\n\n% This would be much simpler if we kept track of which coords we were sampling in the loop above.\nfor(ii=1:length(sampleNodes))\n    thisOne = find(allNodeIndices==sampleNodes(ii));\n    sampleCoords(:,ii) = coords(:, thisOne(1)); \nend\n\n% We loop for the number of line segements, which is the number of coords - 1.\nfor(ii=1:size(sampleCoords,2)-1)\n    % Draw a line for each measured segment\n    h(ii) = line(sampleCoords(2,ii:ii+1), sampleCoords(1,ii:ii+1), 'Color', 'r', 'LineWidth', 2);\n    \n    % Now, compute the manifold distance between these points.\n    % mrManDist returns the distance to all other points from the given 'start' point.\n    allDist = mrManDist(nodes, edges, sampleNodes(ii), mmPerPix, -1, 0);\n    % We just want the distance from the start point to the end point, so we\n    % pull that out by providing the index of the end point.\n    dist(ii) = allDist(sampleNodes(ii+1));\n    disp(['Cortical distance of segment ',num2str(ii),': ',num2str(dist(ii)),' mm.']);  \nend\ndisp(['Total cortical distance: ',num2str(sum(dist)),' mm.']);\nif (plotFlag)\nuiwait(msgbox(['Total cortical distance: ',num2str(sum(dist)),' mm.'], ...\n        'Cortical Distance', 'modal'));\nend\n\n    for ii=1:length(h)\n    delete(h(ii))\nend\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/SurfaceMeasurements/measureCorticalDistanceLineROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2178674138356302}}
{"text": "function res = spm_eeg_reduce_cva(S)\n% Plugin for data reduction using PCA\n% FORMAT res = spm_eeg_reduce_pca(S)\n%\n% S                     - input structure\n% fields of S:\n%    S.ncomp            - number of PCA components\n%\n% Output:\n%  res -\n%   If no input is provided the plugin returns a cfg branch for itself\n%\n%   If input is provided:\n%      montage struct implementing projection to PCA subspace\n%______________________________________________________________________________________\n% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: spm_eeg_reduce_cva.m 5675 2013-10-09 14:27:17Z vladimir $\n\n\nif nargin == 0\n    \n    cvachan = cfg_branch;\n    cvachan.tag = 'cvachan';\n    cvachan.name = 'Channels to reduce';\n    cvachan.val = {spm_cfg_eeg_channel_selector};\n    \n    refchan = cfg_branch;\n    refchan.tag = 'refchan';\n    refchan.name = 'Reference channels';\n    refchan.val = {spm_cfg_eeg_channel_selector};\n    \n    ncomp = cfg_entry;\n    ncomp.tag = 'ncomp';\n    ncomp.name = 'Number of components';\n    ncomp.strtype = 'n';\n    ncomp.num = [1 1];\n    ncomp.val = {1};\n    ncomp.help = {'Number of components to retain'};\n    \n    \n    outlabel = cfg_entry;\n    outlabel.tag = 'outlabel';\n    outlabel.name = 'Output channel label';\n    outlabel.strtype = 's';\n    outlabel.num = [1 Inf];\n    outlabel.help = {'Label for the output channel(s).',...\n        'Numbers are added for multiple channels.'};\n    \n    foi = cfg_entry;\n    foi.tag = 'foi';\n    foi.name = 'Frequency band of interest';\n    foi.strtype = 'r';\n    foi.num = [1 2];\n    foi.val = {[0 Inf]};\n    foi.help = {'Frequency window to optimize for'};\n    \n    tshiftwin = cfg_entry;\n    tshiftwin.tag = 'tshiftwin';\n    tshiftwin.name = 'Time shift window';\n    tshiftwin.strtype = 'r';\n    tshiftwin.num = [1 2];\n    tshiftwin.val = {[0 0]};\n    tshiftwin.help = {'Time shift window (ms). [0 0] - instantaneous'};\n    \n    tshiftres = cfg_entry;\n    tshiftres.tag = 'tshiftres';\n    tshiftres.name = 'Time shift resolution';\n    tshiftres.strtype = 'r';\n    tshiftres.num = [1 1];\n    tshiftres.val = {5};\n    tshiftres.help = {'Time shift resolution (ms)'};\n    \n    chanset = cfg_branch;\n    chanset.tag = 'chanset';\n    chanset.name = 'Set';\n    chanset.val = {cvachan, refchan, ncomp, outlabel, foi, tshiftwin, tshiftres};\n    \n    chansets = cfg_repeat;\n    chansets.tag = 'chansets';\n    chansets.name = 'Channel sets';\n    chansets.values = {chanset};\n    chansets.num = [1 Inf];\n    chansets.val = {chanset};\n    \n    \n    cva = cfg_branch;\n    cva.tag = 'cva';\n    cva.name = 'CVA';\n    cva.val = {chansets};\n    \n    res = cva;\n    \n    return\nend\n\nD = S.D;\n\nnsets = numel(S.chanset);\nbadind = D.badchannels;\n\n% Assuming projecting to columns\nmontage = [];\nmontage.labelorg    = D.chanlabels;\nmontage.labelnew    = {};\nmontage.chantypenew = {};\nmontage.tra         = zeros(0, D.nchannels);\n\nspm('Pointer', 'Watch');drawnow;\nspm_progress_bar('Init', nsets, 'Channel sets processed'); drawnow;\nif nsets > 100, Ibar = floor(linspace(1, nsets,100));\nelse Ibar = 1:nsets; end\n\nfor i = 1:nsets\n    \n    spm_progress_bar('Set','ylabel','preparing data...');\n    \n    cvaind = setdiff(D.selectchannels(spm_cfg_eeg_channel_selector(S.chanset(i).cvachan.channels)), badind);\n    refind = setdiff(D.selectchannels(spm_cfg_eeg_channel_selector(S.chanset(i).refchan.channels)), badind);\n    \n    if any(S.chanset(i).tshiftwin)\n        tshiftind = S.chanset(i).tshiftwin(1):S.chanset(i).tshiftres:S.chanset(i).tshiftwin(2);\n        tshiftind = [0 round(1e-3*D.fsample*tshiftind)];\n        tshiftind = repmat(1:D.nsamples, length(tshiftind), 1)+repmat(tshiftind(:), 1, D.nsamples);\n        tshiftind = tshiftind(:, all(tshiftind>0 & tshiftind<=D.nsamples));\n    else\n        tshiftind = repmat(1:D.nsamples, 2, 1);\n    end\n    \n    nshift = size(tshiftind, 1)-1;\n    nt     = size(tshiftind, 2);\n    \n    Y  = zeros(length(cvaind), nt, D.ntrials);\n    Yr = zeros(length(refind)*nshift, nt, D.ntrials);\n    \n    for j = 1:D.ntrials\n        cY  = D(cvaind, :, j);\n        cYr = D(refind, :, j);\n        \n        if S.chanset(i).foi(1) > 0\n            cY  = ft_preproc_highpassfilter(cY, D.fsample, S.chanset(i).foi(1),...\n                5, 'but', 'twopass', 'reduce');\n            cYr = ft_preproc_highpassfilter(cYr, D.fsample, S.chanset(i).foi(1),...\n                5, 'but', 'twopass', 'reduce');\n        end\n        \n        if isfinite(S.chanset(i).foi(2))\n            cY  = ft_preproc_lowpassfilter(cY, D.fsample, S.chanset(i).foi(2),...\n                5, 'but', 'twopass', 'reduce');\n            cYr = ft_preproc_lowpassfilter(cYr, D.fsample, S.chanset(i).foi(2),...\n                5, 'but', 'twopass', 'reduce');\n        end\n        \n        Y(:, :, j) = cY(:, tshiftind(1, :));\n        \n        for k = 1:size(cYr, 1)\n            Yr(((k-1)*nshift+1):k*nshift, :, j) = reshape(cYr(k, tshiftind(2:end, :)'),[], nshift)';\n        end\n    end\n    \n    Y  = reshape(Y,  size(Y, 1), []);\n    Yr = reshape(Yr, size(Yr, 1), []);\n    \n    if D.fsample>2.5*S.chanset(i).foi(2)\n        dec = floor(D.fsample/(2.5*S.chanset(i).foi(2)));\n        Y   =  Y(:, 1:dec:end);\n        Yr  = Yr(:, 1:dec:end);\n    end\n    \n    spm_progress_bar('Set','ylabel','running CVA...');\n    \n    CVA = spm_cva(Y', Yr');\n    \n    ncomp = min(S.chanset(i).ncomp, size(CVA.V, 2));\n    for j = 1:ncomp\n        if ncomp == 1\n            montage.labelnew{end+1, 1} = S.chanset(i).outlabel;\n        else\n            montage.labelnew{end+1, 1} = [S.chanset(i).outlabel num2str(j)];\n        end\n        \n        montage.tra(end+1, end)  = 0;\n        montage.tra(end, cvaind) = CVA.V(:, j)';\n        \n        montage.chantypenew{end+1}='LFP';\n    end\n    \n    if ismember(i, Ibar)\n        spm_progress_bar('Set', i); drawnow;\n    end\nend\n\nspm_progress_bar('Clear');\n\nif ~isempty(S.chanind)\n    montage.labelnew = [montage.labelnew; D.chanlabels(S.chanind)'];\n    I = eye(D.nchannels);\n    montage.tra = [montage.tra; I(S.chanind, :)];\n    montage.chantypenew = [montage.chantypenew, D.chantype(S.chanind)];\nend\n\nres = montage;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_reduce_cva.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2178674081999862}}
{"text": "function X = plus(X,Y)\n%PLUS Merges two LMI objects to one LMI\n\nif isa(X,'constraint')\n    X = lmi(X);\nelseif isa(X,'sdpvar')\n    X = lmi(X);\nend\n\nif isa(Y,'constraint')\n    Y = lmi(Y);\nelseif isa(Y,'sdpvar')\n    Y = lmi(Y);\nend\n\n% Support set+[]\nif isempty(X)\n    X = Y;\n    return\nelseif isempty(Y)   \n    return\nend\n\nif ~((isa(X,'lmi')) & (isa(Y,'lmi')))\n    error('Both arguments must be constraints')\nend\n\nnX = length(X.LMIid);\nnY = length(Y.LMIid);\nif nX==0\n    X = Y;\n    return\nend\nif nY == 0\n    return;\nend\n\nxBlock = isa(X.clauses{1},'cell');\nyBlock = isa(Y.clauses{1},'cell');\nif yBlock && xBlock && length(X.clauses{1})>1  && length(Y.clauses{1})>1\n    % Both objects are long blocks of constraints. Join these on high level\n    for i = 1:length(Y.clauses)\n        X.clauses{end+1} = Y.clauses{i};\n    end\nelseif ~xBlock && ~yBlock\n    % Both have been flattened\n    \n    % Maybe we should build cells of cells\n    if length(X.clauses)> 99\n        temp = X.clauses;\n        X.clauses = [];\n        X.clauses{1} = temp;\n        X.clauses{2} = {};\n        jx = length(X.clauses);\n        for i = 1:length(Y.clauses)\n            X.clauses{jx}{end+1} = Y.clauses{i};\n        end\n    else\n        for i = 1:length(Y.clauses)\n            X.clauses{end+1} = Y.clauses{i};\n        end\n    end\nelse\n    % This is the standard case. X has been populated with a bunch of\n    % constraints (growing list) while Y is yet another constraint to be\n    % added to that list.\n    if ~xBlock\n        % Lift to a single block\n        temp = X.clauses;\n        X.clauses = [];\n        X.clauses{1} = temp;\n    end\n    % New block in X? This is where performance comes from. Handling cells\n    % of cells is way faster in MATLAB, than a long cell (quadratic running\n    % time, appears to be nasty copying going on when adding new elements)\n    if length(X.clauses{end}) >= 100\n        X.clauses{end+1} = {};\n    end\n    % Special case for performance\n    if isa(Y.clauses{1},'cell') && length(Y.clauses)==1\n        j = length(X.clauses);\n        for i = 1:length(Y.clauses{1})\n            X.clauses{j}{end+1} = Y.clauses{1}{i};\n        end        \n    else\n        Y = flatten(Y);\n        j = length(X.clauses);\n        for i = 1:length(Y.clauses)\n            X.clauses{j}{end+1} = Y.clauses{i};\n        end\n    end\nend\naux = X.LMIid;\nX.LMIid = [X.LMIid Y.LMIid];\n\n% VERY FAST UNIQUE BECAUSE THIS IS CALLED A LOT OF TIMES....\nif ~(max(aux) < min(Y.LMIid))\n    i = sort(X.LMIid);\n    i = i(diff([i NaN])~=0);\n    if length(i)<nX+nY\n        % Flatten first. This typically doesn't happen, so we accept this.\n        X.clauses = [X.clauses{:}];\n        [i,j] = unique(X.LMIid);\n        X = subsref(X,struct('type','()','subs',{{j}}));\n    end\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@lmi/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21785180419547528}}
{"text": "% DEMYALESVARGPLVM4 Run the Shared Var. GP-LVM on a subset of the Yale\n% faces.\n% DESC Run the Shared Var. GP-LVM on a subset of the Yale faces. The code\n% for creating this subset out of raw images exists in comments. Unlike\n% demYaleSvargplvm1, this demo is not a wrapper, it can be used as a\n% standalone demo.\n%\n% VARGPLVM\n\n\n%---\n% ca;clear; trainModel=true; indPoints = 30;  experimentNo=2; % demSitranArtificialLight1 % BAD\n% ca;clear; trainModel=true; indPoints = 60;  experimentNo=3; demSitranArtificialLight1\n% ca;clear; trainModel=true; indPoints = 40;  experimentNo=4; demSitranArtificialLight1 % GOOD % Liv. Machines\n% ca;clear; trainModel=true; indPoints = 100; experimentNo=5; demSitranArtificialLight1 % so and so\n% ca;clear; trainModel=true; indPoints = 35;  experimentNo=6;\n        % initVardistIters = 1200; itNo=[500 8000 5000];demSitranArtificialLight1 % GOOD!!\n\n%--\n\n\n% Fix seeds\nrandn('seed', 1e4);\nrand('seed', 1e4);\n\n\n% Create the dataset out of the images.\nbaseDir=[localDatasetsDirectorySmall 'sharedVargplvm' filesep 'sitranFaces2'];\nselDirs = {'arif','ricardo','zhenwen','andreas','fariba','max'};\n\nfor d=1:length(selDirs)\n    dirFrom=[baseDir filesep selDirs{d}];\n    a=dir(dirFrom);\n    counter = 0;\n    for i=1:length(a)\n        if length(a(i).name)>4 & strcmp(a(i).name(1:7),'cropped')\n            im = imread([dirFrom filesep a(i).name]);\n            im = im(:,:,1);\n            %imagesc(im), colormap('gray'); title(a(i).name), pause\n            counter = counter+1;\n            Yall{d}(counter,:)=im(:)';\n        end\n    end\n    Yall{d} = double(Yall{d});\nend\nheight = size(im,1);\nwidth = size(im,2);\nfor d=1:length(Yall)\n    Yall{d} = util_artificialShadow(reshape(Yall{d},height,width),9,30,[],3000);\nend\n\n\n%{\nfor i=1:size(Yall{1},1)\n    for d=1:length(Yall)\n        subplot(2,3,d)\n        imagesc(reshape(Yall{d}(i,:), height, width)); colormap('gray');\n    end\n    if i==1\n        pause\n    else\n        pause(0.1)\n    end\nend\n%}\n\nfpm = length(Yall)/2;\nY = Yall(1:fpm);\nidentities{1} = [];\nfor i=1:fpm\n    Y{end+1}=[];\n    identities{1} = [identities{1}; i*ones(size(Y{1},1),1)];\n    idTmp{i+fpm}=[];\nend\nfor i=1:size(Yall{1},1)\n    perm = randperm(fpm)+fpm;%perm=[1 2 3 4]+4;\n    for j=1:fpm\n        Y{j+fpm} = [Y{j+fpm}; Yall{perm(j)}(i,:)]; idTmp{j+fpm}=[idTmp{j+fpm}; perm(j)];\n    end\nend\nclear 'Yall'\nYall{1}=[]; Yall{2}=[]; identities{2}=[];\nfor i=1:fpm\n    Yall{1} = [Yall{1}; Y{i}];\n    Yall{2} = [Yall{2}; Y{i+fpm}];\n    identities{2} = [identities{2}; idTmp{i+fpm}];\nend\n\n%{\nY{1} = Yall{1};\nY{2} = Yall{2};\nY{3} = Yall{3};\nY{4} = Yall{4};\nY{5} = [];\nY{6} = [];\nY{7} = [];\nY{8} = [];\nidentities{1}=[ones(size(Y{1},1),1); 2*ones(size(Y{2},1),1); 3*ones(size(Y{3},1),1); 4*ones(size(Y{4},1),1)];\nidTmp{5}=[];idTmp{6}=[];idTmp{7}=[];idTmp{8}=[];\nfor i=1:size(Yall{4},1)\n    perm = randperm(4)+4;%perm=[1 2 3 4]+4;\n    Y{5} = [Y{5}; Yall{perm(1)}(i,:)]; idTmp{5}=[idTmp{5}; perm(1)];\n    Y{6} = [Y{6}; Yall{perm(2)}(i,:)]; idTmp{6}=[idTmp{6}; perm(2)];\n    Y{7} = [Y{7}; Yall{perm(3)}(i,:)]; idTmp{7}=[idTmp{7}; perm(3)];\n    Y{8} = [Y{8}; Yall{perm(4)}(i,:)]; idTmp{8}=[idTmp{8}; perm(4)];\nend\nclear 'Yall'\nYall{1} = [Y{1}; Y{2}; Y{3}; Y{4}];\nYall{2} = [Y{5}; Y{6}; Y{7}; Y{8}];\nidentities{2} = [idTmp{5};idTmp{6};idTmp{7};idTmp{8};];\n%}\n\nclear 'Y' 'idTmp' 'd'\n\nnumberOfDatasets = length(Yall);\n\n %{\nfor i=1:size(Yall{1},1)\n    for d=1:length(Yall)\n        subplot(1,2,d)\n        imagesc(reshape(Yall{d}(i,:), height, width)); colormap('gray'); title(num2str(identities{d}(i)))\n    end\n    if i==1\n        pause\n    else\n        pause(0.05)\n    end\nend\nclear 'd'\n %}\n%%\n\nif ~exist('trainModel','var'), trainModel = false; end\nif ~exist('itNo')         ,  itNo = [500 1500 1500];              end     % Default: 2000\nif ~exist('indPoints')    ,  indPoints = 55;          end     % Default: 49\nif ~exist('initVardistIters'), initVardistIters = 900;      end\nif ~exist('mappingKern')   ,  mappingKern = 'rbfardjit'; end\n\n% Set to empty value {} to work with toy data\nif ~exist('dataSetNames')    ,    dataSetNames = {};    end\nif ~exist('invWidthMult'),       invWidthMult = 5;                     end\nif ~exist('dataType'), dataType = 'artificialLight'; end\nif ~exist('latentDimPerModel'), latentDimPerModel = 7; end\nif ~exist('experimentNo'), experimentNo = 1; end\nif ~exist('doPredictions'), doPredictions = false; end\n% If this is true, then the model is in \"D > N\" mode.\nif ~exist('DgtN'), DgtN = true; end\n% Create initial X by doing e.g. ppca in the concatenated model.m's or by\n% doing ppca in the model.m's separately and concatenate afterwards?\nif ~exist('initial_X'), initial_X = 'separately'; end % Other options: 'concatenated'\n% Which indices to use for training, rest for test\nif ~exist('indTr'), indTr = -1; end\n\nenableParallelism = 0;\n\nif exist('pyramid','var') % extract pyramid representation of the images\n    if pyramid\n        for e=1:size(Y,2)\n            Y{e} = im2pyramid(Y{e}, lbls(1), lbls(2), 4);\n        end\n    end\nend\n\n\n\n\n\n%-- Load datasets\nfor i=1:numberOfDatasets\n    Y = Yall{i};\n    dims{i} = size(Y,2);\n    N{i} = size(Y,1);\n    if indTr == -1\n        indTr = 1:N{i};\n    end\n    indTs = setdiff(1:size(Y,1), indTr);\n    Ytr{i} = Y(indTr,:);\n    Yts{i} = Y(indTs,:);\n    t{i} = linspace(0, 2*pi, size(Y, 1)+1)'; t{i} = t{i}(1:end-1, 1);\n    timeStampsTraining{i} = t{i}(indTr,1); %timeStampsTest = t(indTs,1);\n    d{i} = size(Ytr{i}, 2);\nend\n\nfor i=2:numberOfDatasets\n    if N{i} ~= N{i-1}\n        error('The number of observations in each dataset must be the same!');\n    end\nend\n\n%%\nif trainModel\n    \n    %-- Options for the models\n    for i=1:numberOfDatasets\n        % Set up models\n        options{i} = vargplvmOptions('dtcvar');\n        options{i}.kern = mappingKern; %{'rbfard2', 'bias', 'white'};\n        %indPoints = 80; %%%%%\n        options{i}.numActive = indPoints;\n        options{i}.optimiser = 'scg2';\n        if ~DgtN\n            options{i}.enableDgtN = false;\n        end\n        % !!!!! Be careful to use the same type of scaling and bias for all\n        % models!!!\n        \n        % scale = std(Ytr);\n        % scale(find(scale==0)) = 1;\n        %options.scaleVal = mean(std(Ytr));\n        options{i}.scaleVal = sqrt(var(Ytr{i}(:)));\n    end\n    \n    %-------------- INIT LATENT SPACE ---%\n    for i=1:length(Ytr)\n        % Compute m, the normalised version of Ytr (to be used for\n        % initialisation of X)\n        bias = mean(Ytr{i});\n        scale = ones(1, d{i});\n        \n        if(isfield(options{i},'scale2var1'))\n            if(options{i}.scale2var1)\n                scale = std(Ytr{i});\n                scale(find(scale==0)) = 1;\n                if(isfield(options{i}, 'scaleVal'))\n                    warning('Both scale2var1 and scaleVal set for GP');\n                end\n            end\n        end\n        if(isfield(options{i}, 'scaleVal'))\n            scale = repmat(options{i}.scaleVal, 1, d{i});\n        end\n        \n        % Remove bias and apply scale.\n        m{i} = Ytr{i};\n        for j = 1:d{i}\n            m{i}(:, j) = m{i}(:, j) - bias(j);\n            if scale(j)\n                m{i}(:, j) = m{i}(:, j)/scale(j);\n            end\n        end\n        \n        %    mAll = [mAll m{i}]; % Concatenation (doesn't work if different sizes)\n    end\n    if strcmp(initial_X, 'separately')\n        fprintf('# Initialising X by performing ppca in each observed (scaled) dataset separately and then concatenating...\\n');\n        X_init{1} = ppcaEmbed(m{1},latentDimPerModel);\n        X_init{2} = ppcaEmbed(m{2},latentDimPerModel);\n        X_init = [X_init{1} X_init{2}];\n    else\n        fprintf('# Initialising X by performing ppca in concatenated observed (scaled) data...\\n');\n        X_init = ppcaEmbed([m{1} m{2}], latentDimPerModel*2);\n    end\n    %-----------------\n    \n    latentDim = size(X_init,2);\n    \n    % Free up some memory\n    clear('Y')\n    \n    \n    \n    %-- Create the sub-models: Assume that for each dataset we have one model.\n    % This can be changed later, as long as we find a reasonable way to\n    % initialise the latent spaces.\n    for i=1:numberOfDatasets\n        %---- Here put some code to assign X to the global common X which must\n        % be created by doing pca in the concatenation of Y's...After this\n        % point, model{i}.X will be the same for all i's. TODO...\n        fprintf(1,'# Creating the model...\\n');\n        options{i}.initX = X_init;\n        model{i} = vargplvmCreate(latentDim, d{i}, Ytr{i}, options{i});\n        \n        model{i}.X = X_init; %%%%%%%\n        model{i} = vargplvmParamInit(model{i}, m{i}, model{i}.X);\n        model{i}.X = X_init; %%%%%%%\n        \n        inpScales = invWidthMult./(((max(model{i}.X)-min(model{i}.X))).^2); % Default 5\n        %inpScales(:) = max(inpScales); % Optional!!!!!\n        model{i}.kern.comp{1}.inputScales = inpScales;\n        \n        if strcmp(model{i}.kern.type, 'rbfardjit')\n            model{i}.kern.inputScales = model{i}.kern.comp{1}.inputScales;\n        end\n        params = vargplvmExtractParam(model{i});\n        model{i} = vargplvmExpandParam(model{i}, params);\n        model{i}.vardist.covars = 0.5*ones(size(model{i}.vardist.covars)) + 0.001*randn(size(model{i}.vardist.covars));\n        \n        \n        \n        model{i}.beta=1/(0.01*var(m{i}(:)));\n        prunedModelInit{i} = vargplvmPruneModel(model{i});\n        %disp(model{i}.vardist.covars)\n    end\n    \n    \n    \n    %modelInit = model;%%%TEMP\n    \n    %--  Unify models into a structure\n    svargplvm_init\n    model = svargplvmModelCreate(model);\n    model.dataSetNames = dataSetNames;\n    model.experimentNo = experimentNo;\n    model.dataType = dataType;\n    %%---\n    capName = dataType;\n    capName(1) = upper(capName(1));\n    modelType = model.type;\n    modelType(1) = upper(modelType(1));\n    fileToSave = ['dem' capName modelType num2str(experimentNo) '.mat'];\n    %%---\n    \n    \n    %-- Define what level of parallelism to use (w.r.t submodels or/and w.r.t\n    % datapoints).\n    %{\nfprintf('# Parallel computations w.r.t the submodels!\\n');\nmodel.parallel = 1;\nmodel = svargplvmPropagateField(model,'parallel', 1);\n%\nfprintf('# Parallel computations w.r.t the datapoints!\\n');\nmodel.vardist.parallel = 1;\nfor i=1:model.numModels\n    model.comp{i}.vardist.parallel = 1;\nend\n    %}\n    \n    % Force kernel computations\n    params = svargplvmExtractParam(model);\n    model = svargplvmExpandParam(model, params);\n    \n    %%\n    \n    \n    display = 1;\n    %%%% Optimisation\n    % do not learn beta and sigma_f for few iterations for intitialization\n    if initVardistIters ~=0\n        model.initVardist = 1; model.learnSigmaf = 0;\n        model = svargplvmPropagateField(model,'initVardist', model.initVardist);\n        model = svargplvmPropagateField(model,'learnSigmaf', model.learnSigmaf);\n        fprintf(1,'# Intitiliazing the variational distribution for %s iters...\\n',num2str(initVardistIters));\n        model = svargplvmOptimise(model, display, initVardistIters); % Default: 20\n        %fprintf(1,'1/b = %.4d\\n',1/model.beta);\n        \n        modelInitVardist = model;\n        model.initVardistIters=initVardistIters;\n    end\n    \n    model.initVardist = 0; model.learnSigmaf=1;\n    model = svargplvmPropagateField(model,'initVardist', model.initVardist);\n    model = svargplvmPropagateField(model,'learnSigmaf', model.learnSigmaf);\n    \n    \n    % Optimise the model.\n    model.iters = 0;\n    for i=1:length(itNo)\n        iters = itNo(i); % default: 2000\n        fprintf(1,'\\n# Optimising the model for %d iterations (session %d)...\\n',iters,i);\n        model = svargplvmOptimise(model, display, iters);\n        model.iters = model.iters + iters;\n        % Save model\n        prunedModel = svargplvmPruneModel(model);\n        fprintf(1,'# Saving %s\\n',fileToSave);\n        save(fileToSave, 'prunedModel', 'prunedModelInit');\n    end\nelse\n    capName = dataType;\n    capName(1) = upper(capName(1));\n    modelType = 'svargplvm';\n    modelType(1) = upper(modelType(1));\n    fileToSave = ['dem' capName modelType num2str(experimentNo) '.mat'];\n    load(fileToSave);\n    model = svargplvmRestorePrunedModel(prunedModel, Ytr);clear('prunedModel');clear('prunedModelInit');\nend\n\n%%\n\nif ~exist('resultsDynamic')  resultsDynamic = 0; end\n\n\nfor i=1:length(model.comp)\n    if model.comp{i}.DgtN\n        model.comp{i}.m = model.comp{i}.mOrig;\n    end\nend\nfor i=1:length(model.comp)\n    model.comp{i}.vis.startDim = {1,2};\n    model.comp{i}.vis.startPos = model.vardist.means(1,:);\nend\n\n%%\n% v = 1;\n% modelVis = model.comp{v};\n% if resultsDynamic\n%     %bar(model.comp{v}.kern.comp{1}.inputScales);\n%     %figure\n%     % The following causes OUTOFMEMORY exception except from when we prune the\n%     % video dimensions: (No2te: also, lvmVisualise was changed a bit so that no\n%     % dynamic slides is presented, because otherwise a strange error occurs)..\n%     modelVis.y = Ytr{v};\n%     reduction = 1; % 4\n%     opt.showVariance = 1;    opt.showInducing =1 ;\n%     %opt.showVariance=0; opt.showInducing=0;\n%     [modelP, newHeight, newWidth] = vargplvmReduceVidModel(modelVis, height, width, reduction, reduction);\n%     lvmVisualiseGeneral(modelP, [], 'imageMRDVisualise', 'imageMRDModify', opt, [newHeight newWidth],0,0,1);\n%     clear modelP\n%     figure;svargplvmShowScales(model);\n% end\n\n%%\nif resultsDynamic\n    if exist('modelOrig','var'), model = modelOrig; end\n    modelOrig = model;\n    clear global visualiseInfo\n    for v=1:model.numModels\n        model.comp{v}.y = Ytr{v};\n        reduction = 2; % 4\n        opt.showVariance = 1;    opt.showInducing =1 ;\n        %opt.showVariance=0; opt.showInducing=0;\n        [model.comp{v}, newHeight, newWidth] = vargplvmReduceVidModel(model.comp{v}, height, width, reduction, reduction);\n    end\n    lvmVisualiseMRD(model,[],{'imageMRDVisualise','imageMRDVisualise'},{'imageMRDModify','imageMRDModify'},opt,{{[newHeight newWidth],0,0,1},{[newHeight newWidth],0,0,1}});\n    clear modelP\n    figure;svargplvmShowScales(model);\n    set(gca, 'FontSize', 18);\nend\n\n\n\n%% ---\n%%{\naxFs = 18;\ntitleFs = 0;\nlegFs = 20;\n\nfigure\nsc = svargplvmShowScales(model,0);\nmaxScales1 = max(sc{1});\nmaxScales2 = max(sc{2});\nsc{1} = sc{1}./maxScales1;\nsc{2} = sc{2}./maxScales2;\nsc{1}=sigmoid(sc{1}*5)-0.5;\nsc{2}=sigmoid(sc{2}*5)-0.5;\n\nx=1:size(sc{1},2);\nK=0.75;\nbar1=bar(x, sc{1}, 'FaceColor', 'b', 'EdgeColor', 'b'); \nset(gca, 'YtickLabel',[])\nset(bar1,'BarWidth',K);\nhold on;\nbar2=bar(x, sc{2}, 'FaceColor', 'r', 'EdgeColor', 'r'); \nset(gca, 'YtickLabel',[])\nset(bar2,'BarWidth',K/2.5);\nhold off;\n%lg=legend(['scales1'],['scales2']);\n%set(lg, 'FontSize',legFs)\nset(gca, 'FontSize', axFs);\n%%}\n\n%% Eigenfaces\n%{\nm=1;\nKuu=model.comp{m}.K_uu;\nbeta = model.comp{m}.beta;\nPsi2 = model.comp{m}.Psi2;\nPsi1 = model.comp{m}.Psi1;\nh=newHeight;\nw=newWidth;\nmu = zeros(size(Kuu,1),h*w);\nfor i=1:size(Y,2)\n    mu(:,i) = Kuu*pdinv(1/beta*Kuu+Psi2)*Psi1'*model.comp{m}.m(:,i);\nend\nx = mu';\nx=bsxfun(@minus, x', mean(x'))'; \n\n% calculate covariance \ns = cov(x'); \n% obtain eigenvalue & eigenvector \n[V,D] = eig(s);\neigval = diag(D); \n% sort eigenvalues in descending order \neigval = eigval(end:-1:1); \nV = fliplr(V); \n% show 0th through 15th principal eigenvectors \neig0 = reshape(mean(x,2), [h,w]); \nfigure,subplot(4,4,1) \nimagesc(eig0) \ncolormap gray \nfor i = 1:15 \n    subplot(4,4,i+1) \n    imagesc(reshape(V(:,i),h,w)) \nend\n\n%\nfigure;imagesc(reshape(V(:,3), h,w)); axis off; colormap('gray'); axis('image')\nfigure;imagesc(reshape(V(:,5), h,w)); axis off; colormap('gray'); axis('image')\nfigure;imagesc(reshape(V(:,6), h,w)); axis off; colormap('gray'); axis('image')\nfigure;imagesc(reshape(V(:,3), h,w)); axis off; colormap('gray'); axis('image');colormap(flipud(colormap));\nfigure;imagesc(reshape(V(:,5), h,w)); axis off; colormap('gray'); axis('image');colormap(flipud(colormap));\nfigure;imagesc(reshape(V(:,6), h,w)); axis off; colormap('gray'); axis('image');colormap(flipud(colormap));\n%}\n\n%%\n\n%---------------------------- PREDICTIONS ---------------\nif ~doPredictions\n    return\nend\n\n\nobsMod = 1; % one of the involved sub-models (the one for which we have the data)\ninfMod = setdiff(1:2, obsMod);\n\n% Find the dimensions that are shared for obsMod and infMod\nif ~exist('sharedDims')\n    s1 = model.comp{obsMod}.kern.comp{1}.inputScales;\n    s2 = model.comp{infMod}.kern.comp{1}.inputScales;\n    % Normalise values between 0 and 1\n    s1 = s1 / max(s1);\n    s2 = s2 / max(s2);\n    \n    %  thresh = max(model.comp{obsMod}.kern.comp{1}.inputScales) * 0.001;\n    thresh = 0.005;\n    \n    retainedScales{obsMod} = find(s1 > thresh);\n    %thresh = max(model.comp{infMod}.kern.comp{1}.inputScales) * 0.001;\n    retainedScales{infMod} = find(s2  > thresh);\n    sharedDims = intersect(retainedScales{obsMod}, retainedScales{infMod});\nend\n\n% Find X_* only for the shared dimensions (Xs*):\nif ~exist('privateDims')\n    privateDims = setdiff(1:model.comp{obsMod}.q, sharedDims);\nend\n\nif ~exist('testOnTraining')\n    testOnTraining=1;\nend\n\nnumberTestPoints = 10;\nif testOnTraining\n    perm = randperm(model.N);\n    testInd = perm(1:numberTestPoints);\nelse\n    perm = randperm(size(Yts{obsMod},1));\n    testInd = perm(1:numberTestPoints);\nend\n\nscrsz = get(0,'ScreenSize');\n\nfor i=1:length(testInd)\n    curInd = testInd(i);\n    fprintf('# Testing indice number %d ', curInd);\n    if testOnTraining\n        fprintf('taken from the training set\\n');\n        y_star = model.comp{obsMod}.y(curInd,:);\n        x_star = model.comp{obsMod}.vardist.means(curInd,:);\n        varx_star = model.comp{obsMod}.vardist.covars(curInd,:);\n    else\n        fprintf('taken from the test set\\n');\n        y_star = Yts{obsMod}(curInd,:);\n        z_star = Yts{infMod}(curInd,:);\n        dst = dist2(y_star, model.comp{obsMod}.y);\n        [mind, mini] = min(dst);\n        \n        Init(i,:) = model.vardist.means(mini,:);\n        vardistx = vardistCreate(model.comp{obsMod}.vardist.means(mini,:), model.q, 'gaussian');\n        vardistx.covars = model.comp{obsMod}.vardist.covars(mini,:);\n        model.comp{obsMod}.vardistx = vardistx;\n        display=1;\n        iters = 250;\n        % Find p(X_* | Y_*) which is approximated by q(X_*)\n        [x_star, varx_star, modelUpdated] = vargplvmOptimisePoint(model.comp{obsMod}, vardistx, y_star, display, iters);%%%\n    end\n    numberOfNN = 9;\n    % Now we selected a datapoint X_* by taking into account only the\n    % private dimensions for Y. Now, based on the shared dimensions of\n    % that, we select the closest (in a NN manner) X from the training data.\n    fprintf('# Finding the %d NN of X_* with the training X based only on the shared dims.\\n', numberOfNN);\n    [ind, distInd] = nn_class(model.X(:,sharedDims), x_star(:,sharedDims), numberOfNN, 'euclidean');\n    \n    ZpredMu = zeros(length(ind), size(model.comp{infMod}.y,2));\n    ZpredSigma = zeros(length(ind), size(model.comp{infMod}.y,2));\n    \n    \n    % Find p(y_*|x_*) for every x_* found from the NN\n    fprintf('# Predicting images from the NN of X_* ');\n    for k=1:numberOfNN\n        fprintf('.');\n        x_cur = model.X(ind(k),:);\n        %x_cur(sharedDims) = x_star(sharedDims); %%% OPTIONAL!!!\n        %[ZpredMu(k,:), ZpredSigma(k,:)] = vargplvmPosteriorMeanVar(model.comp{infMod}, model.X(ind(k),:));\n        ZpredMu(k,:) = vargplvmPosteriorMeanVar(model.comp{infMod}, x_cur);\n    end\n    fprintf('\\n\\n');\n    \n    \n    %-- Plots\n    % Open a big figure (first 2 args control the position, last 2 control\n    % the size)\n    figure('Position',[scrsz(3)/100.86 scrsz(4)/6.666 scrsz(3)/1.0457 scrsz(4)/1.0682],...\n        'Name',['Fig: ' num2str(i) ' (Exp: ' num2str(experimentNo) ')'],'NumberTitle','off')\n    numRows = 2;\n    \n    if testOnTraining\n        numCols = ceil((numberOfNN+1)/numRows);\n        plotCounter = 1;\n    else\n        % For the real test image!\n        numCols = ceil((numberOfNN+2)/numRows);\n        plotCounter = 2;\n    end\n    subplot(numRows, numCols, 1)\n    imagesc(reshape(y_star,height,width)), title(['Original y (image #' num2str(curInd) ')']), colormap('gray')\n    \n    if ~testOnTraining\n        subplot(numRows, numCols, 2)\n        imagesc(reshape(z_star,height,width)), title(['Corresponding z (image #' num2str(curInd) ')']), colormap('gray')\n    end\n    \n    for k=1:numberOfNN\n        subplot(numRows, numCols, k+plotCounter)\n        imagesc(reshape(ZpredMu(k,:), height, width)), title(['NN #' num2str(k)]), colormap('gray');\n    end\n    \n    \n    %{\n    indYnn = [];\n    % Do a NN on the DATA space, for every predicted output.\n    for j=1:size(ZpredMu,1)\n        [indYnn(j), distInd] = nn_class(model.comp{infMod}.y, ZpredMu(j,:),1,'euclidean');\n    end\n    for j=1:length(indYnn)\n        figure, imagesc(reshape(model.comp{infMod}.y(indYnn(j),:),height, width)), title([num2str(j)]), colormap('gray')\n    end\n    %}\nend\n\nif ~testOnTraining\n    errsumFull = sum((ZpredMu - Yts).^2);\n    errorFull = mean(errsumFull);\nend\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/demos/demSitranArtificialLight1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21785180419547523}}
{"text": "function [v_res, solution] = MTA_MIQP(OptimizationModel, KOrxn, varargin)\n% Returns the OptimizationModel solution of a particular MTA problem and\n% an specific model\n%\n% USAGE:\n%\n%    [v_res, success, unsuccess] = MTA_MIQP (OptimizationModel, KOrxn, numWorkers, timeLimit, printLevel)\n%\n% INPUT:\n%    OptimizationModel:    Cplex Model struct\n%    KOrxn:                perturbation in the model (reactions)\n%    numWorkers:           number of threads used by Cplex.\n%    FORCE_CPLEX:          1 to force CPLEX solver, 0 (default) for COBRA\n%                          solver.\n%    printLevel:           1 if the process is wanted to be shown on the\n%                          screen, 0 otherwise. Default: 1.\n%\n% OUTPUTS:\n%    Vout:                 Solution flux of MIQP formulation for each case\n%    solution:             Cplex solution struct\n%\n% .. Authors:\n%       - Luis V. Valcarcel, 03/06/2015, University of Navarra, CIMA & TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 26/10/2018, University of Navarra, CIMA & TECNUN School of Engineering.\n%       - Luis V. Valcarcel, 09/03/2021, University of Navarra, CIMA & TECNUN School of Engineering.\n\np = inputParser; % check the input information\n% check requiered arguments\naddRequired(p, 'OptimizationModel');\naddRequired(p, 'KOrxn');\n% Check optional arguments\naddParameter(p, 'numWorkers', 0,@(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'timeLimit', inf,@(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'printLevel', 1,@(x)isnumeric(x)&&isscalar(x));\naddParameter(p, 'FORCE_CPLEX', 0,@(x)isnumeric(x)&&isscalar(x));\n% extract variables from parser\nparse(p, OptimizationModel, KOrxn, varargin{:});\nnumWorkers = p.Results.numWorkers;\ntimeLimit = p.Results.timeLimit;\nprintLevel = max(p.Results.printLevel, 0);\nFORCE_CPLEX = p.Results.FORCE_CPLEX;\n\n%Indexation of variables\nv = OptimizationModel.idx_variables.v;\ny_plus_F = OptimizationModel.idx_variables.y_plus_F;\ny_minus_F = OptimizationModel.idx_variables.y_minus_F;\ny_plus_B = OptimizationModel.idx_variables.y_plus_B;\ny_minus_B = OptimizationModel.idx_variables.y_minus_B;\nOptimizationModel = rmfield(OptimizationModel,'idx_variables');\n\n% Temporal way: use ibm_cplex if installed until MIQP API for COBRA is\n% implemented\nglobal SOLVERS;\nglobal CBT_MIQP_SOLVER\nif FORCE_CPLEX || (SOLVERS.ibm_cplex.installed && strcmp(CBT_MIQP_SOLVER,'ibm_cplex'))\n    % Generate CPLEX model\n    cplex = Cplex('MIQP');\n    CplexModel = OptimizationModel;\n    \n    b_L(CplexModel.csense == 'E') = CplexModel.b(CplexModel.csense == 'E');\n    b_U(CplexModel.csense == 'E') = CplexModel.b(CplexModel.csense == 'E');\n    b_L(CplexModel.csense == 'G') = CplexModel.b(CplexModel.csense == 'G');\n    b_U(CplexModel.csense == 'G') = inf;\n    b_L(CplexModel.csense == 'L') = -inf;\n    b_U(CplexModel.csense == 'L') = CplexModel.b(CplexModel.csense == 'L');\n    CplexModel.rhs = b_U;\n    CplexModel.lhs = b_L;\n    CplexModel.Q = CplexModel.F;\n    CplexModel.obj = CplexModel.c;\n    CplexModel.ctype = CplexModel.vartype;\n    CplexModel.sense = 'minimize';\n    \n    cplex.Model = CplexModel;\n    % include the knock-out reactions\n    cplex.Model.lb(KOrxn) = 0;\n    cplex.Model.ub(KOrxn) = 0;\n    \n    % Cplex Parameter\n    if numWorkers>0\n        cplex.Param.threads.Cur = numWorkers;\n    end\n    if printLevel <=1\n        cplex.Param.output.clonelog.Cur = 0;\n        cplex.DisplayFunc = [];\n    elseif printLevel <=2\n        cplex.Param.output.clonelog.Cur = 0;\n    end\n    if timeLimit < 1e75\n        cplex.Param.timelimit.Cur = timeLimit;\n    end\n    %reduce the tolerance\n    cplex.Param.mip.tolerances.mipgap.Cur = 1e-5;\n    % cplex.Param.mip.tolerances.absmipgap.Cur = 1e-8;\n    % cplex.Param.threads.Cur = 16;\n    \n    % SOLVE the CPLEX problem if not singular\n    try\n        cplex.solve();\n    catch\n        v_res = zeros(length(v),1);\n        return\n    end\n    \n    if cplex.Solution.status ~= 103\n        v_res = cplex.Solution.x(v);\n        solution = cplex.Solution;\n    else\n        v_res = zeros(length(v),1);\n        solution = nan;\n    end\n    \n    % clear the cplex object\n    delete(cplex)\n    clear cplex\nelse\n    % Generate OptimizationModel for this iteration\n    MIQPproblem = OptimizationModel;\n    % include the knock-out reactions\n    MIQPproblem.lb(KOrxn) = 0;\n    MIQPproblem.ub(KOrxn) = 0;\n    \n    % Solver Parameter\n    if timeLimit > 1e75\n        timeLimit = 1e75;\n    end\n    \n    % SOLVE the MIQP problem\n    solution = solveCobraMIQP(MIQPproblem, ...\n        'timeLimit',timeLimit, 'relMipGapTol',  1e-5, ...\n        'printLevel', max(printLevel-1,0), 'logFile', 0,...\n        'threads',numWorkers);\n    \n    if isnumeric(solution.stat) && solution.stat == 1\n        v_res = solution.full(v);\n    elseif ischar(solution.stat) && strcmp(solution.stat, 'OPTIMAL')\n        v_res = solution.full(v);\n    else\n        % Use of try for different outputs of COBRA MIQP solver\n        try\n            v_res = solution.full(v);\n        catch\n            v_res = zeros(length(v),1);\n        end\n    end\n    \nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/rMTA/MTA_MIQP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.21784987845953968}}
{"text": "function [lf] = ft_compute_leadfield(dippos, sens, headmodel, varargin)\n\n% FT_COMPUTE_LEADFIELD computes a forward solution for a dipole in a a volume\n% conductor model. The forward solution is expressed as the leadfield\n% matrix (Nchan*3), where each column corresponds with the potential or field\n% distributions on all sensors for one of the x,y,z-orientations of the\n% dipole.\n%\n% Use as\n%   [lf] = ft_compute_leadfield(dippos, sens, headmodel, ...)\n% with input arguments\n%   dippos    = position dipole (1*3 or Ndip*3)\n%   sens      = structure with gradiometer or electrode definition\n%   headmodel = structure with volume conductor definition\n%\n% The headmodel represents a volume conductor model, its contents\n% depend on the type of model. The sens structure represents a sensor\n% array, i.e. EEG electrodes or MEG gradiometers.\n%\n% It is possible to compute a simultaneous forward solution for EEG and MEG\n% by specifying sens and grad as two cell-arrays, e.g.\n%   sens       = {senseeg, sensmeg}\n%   headmodel  = {voleeg,  volmeg}\n% This results in the computation of the leadfield of the first element of\n% sens and headmodel, followed by the second, etc. The leadfields of the\n% different imaging modalities are subsequently concatenated.\n%\n% Additional input arguments can be specified as key-value pairs, supported\n% optional arguments are\n%   'reducerank'      = 'no' or number\n%   'normalize'       = 'no', 'yes' or 'column'\n%   'normalizeparam'  = parameter for depth normalization (default = 0.5)\n%   'weight'          = number or 1xN vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1)\n%   'backproject'     = 'yes' (default) or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace\n%\n% The leadfield weight may be used to specify a (normalized)\n% corresponding surface area for each dipole, e.g. when the dipoles\n% represent a folded cortical surface with varying triangle size.\n%\n% Depending on the specific input arguments for the sensor and volume, this\n% function will select the appropriate low-level EEG or MEG forward model.\n% The leadfield matrix for EEG will have an average reference over all the\n% electrodes.\n%\n% The supported forward solutions for MEG are\n%   infinite homogenous medium\n%   single sphere (Cuffin and Cohen, 1977)\n%   multiple spheres with one sphere per channel (Huang et al, 1999)\n%   realistic single shell using superposition of basis functions (Nolte, 2003)\n%   leadfield interpolation using a precomputed sourcemodel\n%   boundary element method (BEM)\n%\n% The supported forward solutions for EEG are\n%   infinite homogenous medium\n%   infinite halfspace homogenous medium\n%   single sphere\n%   multiple concentric spheres (up to 4 spheres)\n%   leadfield interpolation using a precomputed sourcemodel\n%   boundary element method (BEM)\n%\n% See also FT_PREPARE_VOL_SENS, FT_HEADMODEL_ASA, FT_HEADMODEL_BEMCP,\n% FT_HEADMODEL_CONCENTRICSPHERES, FT_HEADMODEL_DIPOLI, FT_HEADMODEL_HALFSPACE,\n% FT_HEADMODEL_INFINITE, FT_HEADMODEL_LOCALSPHERES, FT_HEADMODEL_OPENMEEG,\n% FT_HEADMODEL_SINGLESHELL, FT_HEADMODEL_SINGLESPHERE,\n% FT_HEADMODEL_HALFSPACE\n\n% Copyright (C) 2004-2016, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif iscell(sens) && iscell(headmodel) && numel(sens)==numel(headmodel)\n  % this represents combined EEG, ECoG and/or MEG\n  % use recursion to compute all leadfields\n  lf = cell(1, numel(sens));\n  for i=1:length(sens)\n    lf{i} = ft_compute_leadfield(dippos, sens{i}, headmodel{i}, varargin{:});\n  end\n  lf = cat(1, lf{:});\n  return;\nend\n\n% get the optional input arguments\nreducerank      = ft_getopt(varargin, 'reducerank'); % default is handled below\nbackproject     = ft_getopt(varargin, 'backproject', 'yes');\nnormalize       = ft_getopt(varargin, 'normalize' , 'no');\nnormalizeparam  = ft_getopt(varargin, 'normalizeparam', 0.5);\nweight          = ft_getopt(varargin, 'weight');\nchanunit        = ft_getopt(varargin, 'chanunit');   % this is something like V, T, or T/m\ndipoleunit      = ft_getopt(varargin, 'dipoleunit'); % this is something like nA*m\n\nif any(strcmp(varargin(1:2:end), 'unit'))\n  ft_error('the ''unit'' option is not supported any more, please use ''chanunit''');\nend\nif any(strcmp(varargin(1:2:end), 'units'))\n  ft_error('the ''units'' option is not supported any more, please use ''chanunit''');\nend\n\nif ~isstruct(sens) && size(sens, 2)==3\n  % definition of electrode positions only, restructure it\n  sens = struct('elecpos', sens);\nend\n\n% ft_prepare_vol_sens should be called prior to ft_compute_leadfield\n% to ensure that the sens and headmodel are up to date, since the backward\n% compatibility check should not be performed for each dipole location\n% sens       = ft_datatype_sens(sens);\n% headmodel  = ft_datatype_headmodel(headmodel);\n\n% determine whether it is EEG or MEG\niseeg = ft_senstype(sens, 'eeg');\nismeg = ft_senstype(sens, 'meg');\n\n% determine the default for this option\nif isempty(reducerank)\n  if iseeg\n    reducerank = 'no';    % for EEG\n  elseif ismeg && ft_headmodeltype(headmodel, 'infinite')\n    reducerank = 'no';    % for MEG with a magnetic dipole, e.g. a HPI coil\n  else\n    reducerank = 'yes';   % for MEG with a current dipole in a volume conductor\n  end\nend\n\n% multiple dipoles can be represented either as a 1x(N*3) vector or as a\n% as a Nx3 matrix, i.e. [x1 y1 z1 x2 y2 z2] or [x1 y1 z1; x2 y2 z2]\nNdipoles = numel(dippos)/3;\nif all(size(dippos)==[1 3*Ndipoles])\n  dippos = reshape(dippos, 3, Ndipoles)';\nend\n\nif isfield(headmodel, 'unit') && isfield(sens, 'unit') && ~strcmp(headmodel.unit, sens.unit)\n  ft_error('inconsistency in the units of the volume conductor and the sensor array');\nend\n\nif ismeg && iseeg\n  % this is something that could be implemented relatively easily\n  ft_error('simultaneous EEG and MEG not supported');\n\nelseif ~ismeg && ~iseeg\n  ft_error('the input does not look like EEG, nor like MEG');\n\nelseif ismeg\n  switch ft_headmodeltype(headmodel)\n\n    case 'singlesphere'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % MEG single-sphere volume conductor model\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      coilpos = sens.coilpos; % position of each coil\n      coilori = sens.coilori; % orientation of each coil\n\n      if isfield(headmodel, 'o')\n        % shift dipole and magnetometers to origin of sphere\n        dippos  = dippos  - repmat(headmodel.o, Ndipoles, 1);\n        coilpos = coilpos - repmat(headmodel.o, size(coilpos, 1), 1);\n      end\n\n      if Ndipoles>1\n        % loop over multiple dipoles\n        lf = zeros(size(coilpos, 1), 3*Ndipoles);\n        for i=1:Ndipoles\n          lf(:, (3*i-2):(3*i)) = meg_leadfield1(dippos(i, :), coilpos, coilori);\n        end\n      else\n        % only single dipole\n        lf = meg_leadfield1(dippos, coilpos, coilori);\n      end\n\n      if isfield(sens, 'tra')\n        % this appears to be the modern complex gradiometer definition\n        % construct the channels from a linear combination of all magnetometers\n        lf = sens.tra * lf;\n      end\n\n    case 'localspheres'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % MEG multiple overlapping sphere volume conductor model\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      ncoils = length(sens.coilpos);\n\n      if size(headmodel.r, 1)~=ncoils\n        ft_error('number of spheres is not equal to the number of coils')\n      end\n\n      if size(headmodel.o, 1)~=ncoils\n        ft_error('number of spheres is not equal to the number of coils');\n      end\n\n      lf = zeros(ncoils, 3*Ndipoles);\n      for coil=1:ncoils\n        for dip=1:Ndipoles\n          % shift dipole and magnetometer coil to origin of sphere\n          tmppos  = dippos(dip, :) - headmodel.o(coil, :);\n          coilpos = sens.coilpos(coil, :) - headmodel.o(coil, :);\n          tmp = meg_leadfield1(tmppos, coilpos, sens.coilori(coil, :));\n          lf(coil, (3*dip-2):(3*dip)) = tmp;\n        end\n      end\n\n      if isfield(sens, 'tra')\n        % this appears to be the modern complex gradiometer definition\n        % construct the channels from a linear combination of all magnetometers\n        lf = sens.tra * lf;\n      end\n\n    case 'neuromag'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % use external Neuromag toolbox for forward computation\n      % this requires that \"megmodel\" is initialized, which is done in PREPARE_VOL_SENS\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % compute the forward model for all channels\n      % tmp1 = ones(1, Ndipoles);\n      % tmp2 = 0.01*dippos'; %convert to cm\n      % lf = megfield([tmp2 tmp2 tmp2], [[1 0 0]'*tmp1 [0 1 0]'*tmp1 [0 0 1]'*tmp1]);\n      for dip=1:Ndipoles\n        R = 0.01*dippos(dip, :)'; % convert from cm to m\n        Qx = [1 0 0];\n        Qy = [0 1 0];\n        Qz = [0 0 1];\n        lf(:, (3*(dip-1)+1)) = megfield(R, Qx);\n        lf(:, (3*(dip-1)+2)) = megfield(R, Qy);\n        lf(:, (3*(dip-1)+3)) = megfield(R, Qz);\n      end\n      % select only those channels from the forward model that are part of the gradiometer definition\n      lf = lf(headmodel.chansel, :);\n\n    case 'singleshell'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % use code from Guido Nolte for the forward computation\n      % this requires that \"meg_ini\" is initialized, which is done in PREPARE_VOL_SENS\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % the dipole position and orientation should be combined in a single matrix\n      % furthermore, here I want to compute the leadfield for each of the\n      % orthogonal x/y/z directions\n      dippar = zeros(Ndipoles*3, 6);\n      for i=1:Ndipoles\n        dippar((i-1)*3+1, :) = [headmodel.forwpar.scale*dippos(i, :) 1 0 0]; % single dipole with unit strength, x-orientation\n        dippar((i-1)*3+2, :) = [headmodel.forwpar.scale*dippos(i, :) 0 1 0]; % single dipole with unit strength, y-orientation\n        dippar((i-1)*3+3, :) = [headmodel.forwpar.scale*dippos(i, :) 0 0 1]; % single dipole with unit strength, z-orientation\n      end\n      % compute the leadfield for each individual coil\n      lf = meg_forward(dippar, headmodel.forwpar);\n      % the leadfield is computed for cm units, convert it to the desired units\n      lf = lf*headmodel.forwpar.scale^2;\n      if isfield(sens, 'tra')\n        % compute the leadfield for each gradiometer (linear combination of coils)\n        lf = sens.tra * lf;\n      end\n\n    case 'openmeeg'\n        % OpenMEEG lead field already computed in ft_prepare_leadfield;\n        % load here so any post-processing options (e.g. normalization) may\n        % be applied\n        lf = ft_getopt(varargin, 'lf');\n\n    case {'infinite_magneticdipole', 'infinite'}\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % magnetic dipole instead of electric (current) dipole in an infinite vacuum\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      coilpos = sens.coilpos; % position of each coil\n      coilori = sens.coilori; % orientation of each coil\n\n      if Ndipoles>1\n        % loop over multiple dipoles\n        lf = zeros(size(coilpos, 1), 3*Ndipoles);\n        for i=1:Ndipoles\n          lf(:, (3*i-2):(3*i)) = magnetic_dipole(dippos(i, :), coilpos, coilori);\n        end\n      else\n        % only single dipole\n        lf = magnetic_dipole(dippos, coilpos, coilori);\n      end\n\n      if isfield(sens, 'tra')\n        % construct the channels from a linear combination of all magnetometer coils\n        lf = sens.tra * lf;\n      end\n\n    case {'infinite_currentdipole'}\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % current dipole in an infinite homogenous conducting medium\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      coilpos = sens.coilpos; % position of each coil\n      coilori = sens.coilori; % orientation of each coil\n\n      if Ndipoles>1\n        % loop over multiple dipoles\n        lf = zeros(size(coilpos, 1), 3*Ndipoles);\n        for i=1:Ndipoles\n          lf(:, (3*i-2):(3*i)) = current_dipole(dippos(i, :), coilpos, coilori);\n        end\n      else\n        % only single dipole\n        lf = current_dipole(dippos, coilpos, coilori);\n      end\n\n      if isfield(sens, 'tra')\n        % construct the channels from a linear combination of all magnetometer coils\n        lf = sens.tra * lf;\n      end\n\n    otherwise\n      ft_error('unsupported volume conductor model for MEG');\n  end % switch type for MEG\n\nelseif iseeg\n  switch ft_headmodeltype(headmodel)\n\n    case 'multisphere'\n      % Based on the approximation of the potential due to a single dipole in\n      % a multishell sphere by three dipoles in a homogeneous sphere, code\n      % contributed by Punita Christopher. Note that this one should not get\n      % confused with the MEG localspheres model.\n\n      Nelec    = size(sens.elecpos, 1);\n      Nspheres = length(headmodel.r);\n\n      % the center of the spherical volume conduction model does not have\n      % to be in the origin, therefore shift the spheres, the electrodes\n      % and the dipole\n      if isfield(headmodel, 'o')\n        center = headmodel.o;\n      else\n        center = [0 0 0];\n      end\n\n      % sort the spheres from the smallest to the largest\n      % furthermore, the radius should be one (?)\n      [radii, indx] = sort(headmodel.r/max(headmodel.r));\n      sigma = headmodel.cond(indx);\n      r = (sens.elecpos-repmat(center, Nelec, 1))./max(headmodel.r);\n      dippos = dippos./max(headmodel.r);\n\n      if Ndipoles>1\n        % loop over multiple dipoles\n        lf = zeros(Nelec, 3*Ndipoles);\n        for i=1:Ndipoles\n          rq = dippos(i, :) - center;\n          % compute the potential for each dipole ortientation\n          % it would be much more efficient to change the punita function\n          q1 = [1 0 0]; lf(:, (3*i-2)) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n          q1 = [0 1 0]; lf(:, (3*i-1)) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n          q1 = [0 0 1]; lf(:, (3*i )) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n        end\n      else\n        % only single dipole\n        lf = zeros(Nelec, 3);\n        rq = dippos - center;\n        % compute the potential for each dipole ortientation\n        % it would be much more efficient to change the punita function\n        q1 = [1 0 0] ; lf(:, 1) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n        q1 = [0 1 0] ; lf(:, 2) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n        q1 = [0 0 1] ; lf(:, 3) = multisphere(Nspheres, radii, sigma, r, rq, q1);\n      end\n\n    case {'singlesphere', 'concentricspheres'}\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % EEG spherical volume conductor model\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      % FIXME, this is not consistent between spherical and BEM\n      % sort the spheres from the smallest to the largest\n      [headmodel.r, indx] = sort(headmodel.r);\n      headmodel.cond = headmodel.cond(indx);\n\n      Nspheres = length(headmodel.cond);\n      if length(headmodel.r)~=Nspheres\n        ft_error('the number of spheres in the volume conductor model is ambiguous');\n      end\n\n      if isfield(headmodel, 'o')\n        % shift the origin of the spheres, electrodes and dipole\n        sens.elecpos = sens.elecpos - repmat(headmodel.o, size(sens.elecpos, 1), 1);\n        dippos = dippos - repmat(headmodel.o, Ndipoles, 1);\n      end\n\n      switch Nspheres\n        case 1\n          funnam = 'eeg_leadfield1';\n        case 2\n          headmodel.r = [headmodel.r(1) headmodel.r(2) headmodel.r(2) headmodel.r(2)];\n          headmodel.cond = [headmodel.cond(1) headmodel.cond(2) headmodel.cond(2) headmodel.cond(2)];\n          funnam = 'eeg_leadfield4';\n        case 3\n          headmodel.r = [headmodel.r(1) headmodel.r(2) headmodel.r(3) headmodel.r(3)];\n          headmodel.cond = [headmodel.cond(1) headmodel.cond(2) headmodel.cond(3) headmodel.cond(3)];\n          funnam = 'eeg_leadfield4';\n        case 4\n          headmodel.r = [headmodel.r(1) headmodel.r(2) headmodel.r(3) headmodel.r(4)];\n          headmodel.cond = [headmodel.cond(1) headmodel.cond(2) headmodel.cond(3) headmodel.cond(4)];\n          funnam = 'eeg_leadfield4';\n        otherwise\n          ft_error('more than 4 concentric spheres are not supported')\n      end\n\n      lf = zeros(size(sens.elecpos, 1), 3*Ndipoles);\n      for i=1:Ndipoles\n        lf(:, (3*i-2):(3*i)) = feval(funnam, dippos(i, :), sens.elecpos, headmodel);\n      end\n\n    case {'bem', 'dipoli', 'asa', 'bemcp'}\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % EEG boundary element method volume conductor model\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      lf = eeg_leadfieldb(dippos, sens.elecpos, headmodel);\n\n    case 'openmeeg'\n        % OpenMEEG lead field already computed in ft_prepare_leadfield;\n        % load here so any post-processing options (e.g. normalization) may\n        % be applied\n        lf = ft_getopt(varargin, 'lf');\n\n    case {'infinite_currentdipole' 'infinite'}\n      lf = eeg_infinite_dipole(dippos, sens.elecpos, headmodel);\n\n    case 'halfspace'\n      lf = eeg_halfspace_dipole(dippos, sens.elecpos, headmodel);\n\n    case 'infinite_monopole'\n      lf = eeg_infinite_monopole(dippos, sens.elecpos, headmodel);\n\n    case 'halfspace_monopole'\n      lf = eeg_halfspace_monopole(dippos, sens.elecpos, headmodel);\n\n    case 'slab_monopole'\n      lf = eeg_slab_monopole(dippos, sens.elecpos, headmodel);\n\n    case 'simbio'\n      ft_hastoolbox('simbio', 1);\n      % note that the electrode information is contained in the headmodel (thanks to ft_prepare_vol_sens)\n      lf = leadfield_simbio(dippos, headmodel);\n\n    case 'metufem'\n      p3 = zeros(Ndipoles * 3, 6);\n      for i = 1:Ndipoles\n        p3((3*i - 2) : (3 * i), 1:3) = [dippos(i, :); dippos(i, :); dippos(i, :)];\n        p3((3*i - 2) : (3 * i), 4:6) = [1 0 0; 0 1 0; 0 0 1];\n      end\n      lf = metufem('pot', p3', 'interp');\n\n    case 'metubem'\n      session = headmodel.session;\n      p3 = zeros(Ndipoles * 3, 6);\n      for i = 1:Ndipoles\n        p3((3*i - 2) : (3 * i), 1:3) = [dippos(i, :); dippos(i, :); dippos(i, :)];\n        p3((3*i - 2) : (3 * i), 4:6) = [1 0 0; 0 1 0; 0 0 1];\n      end\n      [lf, session] = bem_solve_lfm_eeg(session, p3);\n\n    case 'fns'\n      % note that the electrode information is contained in the headmodel\n      % tolerance = 1e-8;\n      lf = leadfield_fns(dippos, headmodel);\n\n    case 'interpolate'\n      % note that the electrode information is contained in the headmodel\n      lf = leadfield_interpolate(dippos, headmodel);\n      % the leadfield is already correctly referenced, i.e. it represents the\n      % channel values rather than the electrode values. Prevent that the\n      % referencing is done once more.\n      sens.tra = speye(length(headmodel.filename));\n\n    otherwise\n      ft_error('unsupported volume conductor model for EEG');\n\n  end % switch type for EEG\n\n  % the forward model potential is computed on the electrodes relative to\n  % an unknown reference, not on the channels. Therefore the data has to be\n  % explicitly referenced here.\n  if isfield(sens, 'tra')\n    % apply the correct montage to the leadfield\n    lf = sens.tra*lf;\n  else\n    % compute average reference for EEG leadfield\n    for i=1:size(lf,2)\n      lf(:,i) = lf(:,i) - mean(lf(:,i));\n    end\n  end\n\nend % iseeg or ismeg\n\n% optionally apply leadfield rank reduction\nswitch reducerank\n  case 'yes'\n    reducerank = 2;\n  case 'no'\n    reducerank = 3;\n  otherwise\n    % assume that it is specified as a number, keep it like this\nend\n\nif reducerank<size(lf,2)\n  % decompose the leadfield\n  for ii=1:Ndipoles\n    tmplfd=lf(:, (3*ii-2):(3*ii));\n    [u, s, v] = svd(tmplfd);\n    r = diag(s);\n    s(:) = 0;\n    for j=1:reducerank\n      s(j, j) = r(j);\n    end\n\n    if istrue(backproject)\n      % recompose the leadfield with reduced rank\n      lf(:, (3*ii-2):(3*ii)) = u * s * v';\n    else\n      % if not backprojected, the new leadfield has a different dimension\n      if ii==1\n        newlf    = zeros(size(lf,1), Ndipoles*reducerank);\n        origrank = size(lf,2)./Ndipoles;\n      end\n      newlf(:, reducerank*(ii-1) + (1:reducerank)) = lf(:, origrank*(ii-1) + (1:origrank))*v(:,1:reducerank);\n    end\n  end\n\n  if ~istrue(backproject)\n    lf = newlf;\n  end\n  clear newlf;\nend\n\n% optionally apply leadfield normalization\nswitch normalize\n  case 'yes'\n    for ii=1:Ndipoles\n      tmplf = lf(:, (3*ii-2):(3*ii));\n      if normalizeparam==0.5\n        % normalize the leadfield by the Frobenius norm of the matrix\n        % this is the same as below in case normalizeparam is 0.5\n        nrm = norm(tmplf, 'fro');\n      else\n        % normalize the leadfield by sum of squares of the elements of the leadfield matrix to the power \"normalizeparam\"\n        % this is the same as the Frobenius norm if normalizeparam is 0.5\n        nrm = sum(tmplf(:).^2)^normalizeparam;\n      end\n      if nrm>0\n        tmplf = tmplf ./ nrm;\n      end\n      lf(:, (3*ii-2):(3*ii)) = tmplf;\n    end\n  case 'column'\n    % normalize each column of the leadfield by its norm\n    for ii=1:Ndipoles\n      tmplf = lf(:, (3*ii-2):(3*ii));\n      for j=1:size(tmplf, 2)\n        nrm = sum(tmplf(:, j).^2)^normalizeparam;\n        tmplf(:, j) = tmplf(:, j)./nrm;\n      end\n      lf(:, (3*ii-2):(3*ii)) = tmplf;\n    end\nend\n\n% optionally apply a weight to the leadfield for each dipole location\nif ~isempty(weight)\n  for i=1:Ndipoles\n    lf(:, 3*(i-1)+1) = lf(:, 3*(i-1)+1) * weight(i); % the leadfield for the x-direction\n    lf(:, 3*(i-1)+2) = lf(:, 3*(i-2)+1) * weight(i); % the leadfield for the y-direction\n    lf(:, 3*(i-1)+3) = lf(:, 3*(i-3)+1) * weight(i); % the leadfield for the z-direction\n  end\nend\n\nif ~isempty(chanunit) || ~isempty(dipoleunit)\n  assert(strcmp(headmodel.unit,  'm'), 'unit conversion only possible for SI input units');\n  assert(strcmp(sens.unit, 'm'), 'unit conversion only possible for SI input units');\nend\n\nif ~isempty(chanunit)\n  assert(all(strcmp(sens.chanunit, 'V') | strcmp(sens.chanunit, 'V/m') | strcmp(sens.chanunit, 'T') | strcmp(sens.chanunit, 'T/m')), 'unit conversion only possible for SI input units');\n  % compute conversion factor and multiply each row of the matrix\n  scale = cellfun(@ft_scalingfactor, sens.chanunit(:), chanunit(:));\n  lf = bsxfun(@times, lf, scale(:));\n  % prior to this conversion, the units might be  (T/m)/(A*m) for planar gradients or   (V/m)/(A*m) for bipolar EEG\n  % after this conversion, the units will be     (T/cm)/(A*m)                      or (uV/mm)/(A*m)\nend\n\nif ~isempty(dipoleunit)\n  scale = ft_scalingfactor('A*m', dipoleunit); % compue the scaling factor from A*m to the desired dipoleunit\n  lf    = lf/scale;                         % the leadfield is expressed in chanunit per dipoleunit, i.e. chanunit/dipoleunit\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/forward/ft_compute_leadfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.21759857953738584}}
{"text": "classdef DesignVarMonitor_LevelSet < DesignVarMonitor_Abstract\n    \n    properties (Access = protected, Abstract)\n        unfittedType\n        meshIncludeBoxContour\n    end\n    \n    properties (Access = protected)\n        designVarName = 'Level Set - \\phi';\n        meshUnfitted\n    end\n    \n    methods (Access = public)\n        \n        function obj = DesignVarMonitor_LevelSet(cParams)\n            obj@DesignVarMonitor_Abstract(cParams);\n        end\n        \n        function plot(obj)\n            obj.refreshFigure();\n        end\n        \n    end\n    \n    methods (Access = protected)\n        \n        function initPlotting(obj)\n             set(obj.axes,'CLim',[0, 1],'XTick',[],'YTick',[]);\n        end\n        \n    end\n    \n    methods (Access = protected, Static)\n        \n        function color = getColor()\n            color = [1 0 0];\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function refreshFigure(obj)\n            figure(obj.figHandle.Number)\n            cla reset;\n            hold on\n            uMesh = obj.designVar.getUnfittedMesh;\n            uMesh.plot();\n        end\n        \n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Monitoring/DesignVarMonitor/DesignVarMonitor_LevelSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21753919042074682}}
{"text": "function [nCoords, nDim, nVTMode, c] = plx_vt_interpret(ts, sv);\n% plx_vt_interpret - interpret CinePlex video tracking data\n%\n% [nCoords, nDim, nVTMode, c] = plx_vt_interpret(ts, sv);\n%\n% INPUT:\n%   ts - array of timestamps (in seconds) (see plx_event_ts.m)\n%   sv - array of strobed event values (see plx_event_ts.m)\n%\n% OUTPUT:\n%   nCoords - number of produced coordinates\n%   nDim    - number of elemnts in produced coordinates\n%             nDim = 3 for CENTROID, LED_1, LED_2, LED3\n%             nDim = 4 for CENTROID_WITH_MOTION\n%             nDim = 5 for LED_12, LED_23, LED_13\n%             nDim = 7 for LED_123\n%   nVTMode - VT mode:\n%              0 = UNKNOWN\n%              1 = CENTROID                // 1 set of coordinates, no motion\n%              2 = CENTROID_WITH_MOTION    // 1 set of coordinates, with motion\n%              3 = LED_1                   // 1 set of coordinates\n%              4 = LED_2                  \n%              5 = LED_3\n%              6 = LED_12                  // 2 sets of coordinates\n%              7 = LED_13\n%              8 = LED_23\n%              9 = LED_123                 // 3 sets of coordinates\n%   c       - nCoords by nDim matrix of produced coordinates\n%             c(:, 1) - timestamp\n%             c(:, 2) - x1\n%             c(:, 3) - y1\n%             c(:, 4) - x2 or motion (if present)\n%             c(:, 5) - y2 (if present)\n%             c(:, 6) - x3 (if present)\n%             c(:, 7) - y3 (if present)\n%\n\nif nargin < 2\n    error 'Expected 2 input arguments';\nend\n\n[nCoords, nDim, nVTMode, c] = mexPlex(21, '', ts, sv);", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/plexonSDK/plx_vt_interpret.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2175391846438568}}
{"text": "% function cl = enlarge(cl)\n%\n% enlarge cluster\n\nfunction cl = enlarge_cluster(cl)\n\n    XYZ = cl.XYZ;\n    XYZnew = XYZ;\n\n    for i = 1:3\n        Xtmp = XYZ;\n        Xtmp(i, :) = Xtmp(i, :) + 1;\n        XYZnew = [XYZnew Xtmp];         % add to dim\n        Xtmp(i, :) = Xtmp(i, :) - 2;\n        XYZnew = [XYZnew Xtmp];      % subtract 1 from dim\n    end\n\n    XYZnew = unique(round(XYZnew)', 'rows')';\n    cl.XYZ = XYZnew;\n    cl.XYZmm = voxel2mm(XYZnew, cl.M);\n    cl.Z = ones(1, size(cl.XYZ, 2));\n\n    cl.numVox = size(cl.XYZmm, 2);\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Cluster_contig_region_tools/enlarge_cluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.217521971845722}}
{"text": "% io_loadspec_niimrs.m\n% Georg Oeltzschner, Johns Hopkins University 2021\n%\n% USAGE:\n% out = io_loadspec_niimrs(filename);\n% \n% DESCRIPTION:\n% Reads in MRS data stored according to the NIfTI MRS format.\n% See the specification under\n% https://docs.google.com/document/d/1tC4ugzGUPLoqHRGrWvOcGCuCh_Dogx_uu0cxKub0EsM/edit\n% \n% io_loadspec_niimrs outputs the data in structure format, with fields \n% corresponding to time scale, fids, frequency scale, spectra, and header \n% fields containing information about the acquisition. The resulting matlab\n% structure can be operated on by the other functions in this MRS toolbox.\n%\n% This function is currently work-in-progress and is being tested on more\n% and more datasets. Please contact the FID-A developers for help with a\n% particular NIfTI-MRS file that you might encounter problems with when\n% using this function.\n%\n% Currently, this function is limited to single-voxel MRS data. It is\n% planned to develop it for full compatibility with 2D and 3D multi-voxel\n% and spectroscopic imaging data.\n%\n% DEPENDENCIES:\n% This function requires the dcm2nii toolbox (Xiangrui Li) to be on the\n% MATLAB path\n% https://github.com/xiangruili/dicm2nii\n% \n% INPUTS:\n% filename   = filename of NIfTI MRS file (*.nii) to load.\n%\n% OUTPUTS:\n% out        = Input dataset in FID-A structure format.\n\nfunction out = io_loadspec_niimrs(filename)\n\n% Read in the data using the dicm2nii toolbox\n% (https://github.com/xiangruili/dicm2nii)\ntry\n    nii = nii_tool('load', filename);\ncatch ME\n    switch ME.identifier\n        case 'MATLAB:UndefinedFunction'\n            error(['Cannot find the function ''nii_tool.m''.' ...\n                ' Please ensure that you have downloaded the required', ...\n                ' dcm2nii toolbox (https://github.com/xiangruili/dicm2nii)', ...\n                ' and added it to your MATLAB path.']);\n        otherwise\n            rethrow(ME);\n    end\nend\n\n% Extract the header and header extensions\nhdr = nii.hdr;\nhdr_ext = jsondecode(nii.ext.edata_decoded);\n\n% Extract the time-domain data\nfids = nii.img;\n\n% Extract spectrometer frequency and dwell time\nf0 = hdr_ext.SpectrometerFrequency;\ndt = hdr.pixdim(5);\nsw = 1/dt;\n\n% Specify dimensions\n% In NIfTI MRS, the three spatial dimensions and the time dimension occupy\n% fixed indices in the (maximum) 7-D array\ndims.x = 1;\ndims.y = 2;\ndims.z = 3;\ndims.t = 4;\n\n% There are some pre-defined dimension names according to the FID-A\n% convention. These dimensions may or may not be stored in the NIfTI MRS\n% header, so we'll initialize them as 0.\ndims.coils = 0;\ndims.averages = 0;\ndims.subSpecs = 0;\ndims.extras = 0;\n\n% The NIfTI MRS standard reserves the remaining 3 dimensions, which are\n% then explicitly specified in the JSON header extension fields dim_5,\n% dim_6 and dim_7.\nif isfield(hdr_ext, 'dim_5')\n    dim_number = 5;\n    switch hdr_ext.dim_5\n        case 'DIM_COIL'\n            dims.coils      = dim_number;\n        case 'DIM_DYN'\n            dims.averages   = dim_number;\n        case 'DIM_INDIRECT_0'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_1'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_2'\n            dims.extras     = dim_number;\n        case 'DIM_PHASE_CYCLE'\n            dims.extras     = dim_number;\n        case 'DIM_EDIT'\n            dims.subSpecs   = dim_number;\n        case 'DIM_MEAS'\n            dims.extras     = dim_number;\n        case 'DIM_USER_0'\n            dims.extras     = dim_number;\n        case 'DIM_USER_1'\n            dims.extras     = dim_number;\n        case 'DIM_USER_2'\n            dims.extras     = dim_number;\n        case 'DIM_ISIS'\n            dims.subSpecs   = dim_number;\n        otherwise\n            error('Unknown dimension value specified in dim_5: %s', hdr_ext.dim_5);\n    end\n       \nend\nif isfield(hdr_ext, 'dim_6')\n        dim_number = 6;\n    switch hdr_ext.dim_6\n        case 'DIM_COIL'\n            dims.coils      = dim_number;\n        case 'DIM_DYN'\n            dims.averages   = dim_number;\n        case 'DIM_INDIRECT_0'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_1'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_2'\n            dims.extras     = dim_number;\n        case 'DIM_PHASE_CYCLE'\n            dims.extras     = dim_number;\n        case 'DIM_EDIT'\n            dims.subSpecs   = dim_number;\n        case 'DIM_MEAS'\n            dims.extras     = dim_number;\n        case 'DIM_USER_0'\n            dims.extras     = dim_number;\n        case 'DIM_USER_1'\n            dims.extras     = dim_number;\n        case 'DIM_USER_2'\n            dims.extras     = dim_number;\n        case 'DIM_ISIS'\n            dims.subSpecs   = dim_number;\n        otherwise\n            error('Unknown dimension value specified in dim_6: %s', hdr_ext.dim_6);\n    end\nend\nif isfield(hdr_ext, 'dim_7')\n        dim_number = 7;\n    switch hdr_ext.dim_7\n        case 'DIM_COIL'\n            dims.coils      = dim_number;\n        case 'DIM_DYN'\n            dims.averages   = dim_number;\n        case 'DIM_INDIRECT_0'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_1'\n            dims.extras     = dim_number;\n        case 'DIM_INDIRECT_2'\n            dims.extras     = dim_number;\n        case 'DIM_PHASE_CYCLE'\n            dims.extras     = dim_number;\n        case 'DIM_EDIT'\n            dims.subSpecs   = dim_number;\n        case 'DIM_MEAS'\n            dims.extras     = dim_number;\n        case 'DIM_USER_0'\n            dims.extras     = dim_number;\n        case 'DIM_USER_1'\n            dims.extras     = dim_number;\n        case 'DIM_USER_2'\n            dims.extras     = dim_number;\n        case 'DIM_ISIS'\n            dims.subSpecs   = dim_number;\n        otherwise\n            error('Unknown dimension value specified in dim_7: %s', hdr_ext.dim_7);\n    end\nend\n\n% Parse the NIfTI hdr.dim field:\nallDims = hdr.dim(2:end); % all dimensions (including singletons)\n\n% Find the number of points\nnPts = allDims(dims.t);\n\n% Find the number of averages.  'averages' will specify the current number\n% of averages in the dataset as it is processed, which may be subject to\n% change.  'rawAverages' will specify the original number of acquired \n% averages in the dataset, which is unchangeable.\nif dims.subSpecs ~= 0\n    if dims.averages ~= 0\n        averages = allDims(dims.averages)*allDims(dims.subSpecs);\n        rawAverages = averages;\n    else\n        averages = allDims(dims.subSpecs);\n        rawAverages = 1;\n    end\nelse\n    if dims.averages ~= 0\n        averages = allDims(dims.averages);\n        rawAverages = averages;\n    else\n        averages = 1;\n        rawAverages = 1;\n    end\nend\n\n% FIND THE NUMBER OF SUBSPECS\n% 'subspecs' will specify the current number of subspectra in the dataset \n% as it is processed, which may be subject to change. 'rawSubspecs' will \n% specify the original number of acquired  subspectra in the dataset, which\n% is unchangeable.\nif dims.subSpecs ~=0\n    subspecs = allDims(dims.subSpecs);\n    rawSubspecs = subspecs;\nelse\n    subspecs = 1;\n    rawSubspecs = subspecs;\nend\n\n% ORDERING THE DATA AND DIMENSIONS\n% The FID-A array ordering conventions differ from the NIfTI MRS\n% convention. Most importantly, FID-A is primarily tailored towards\n% single-voxel data. We will start designing this function towards this\n% purpose, and later adapt the formalism proposed in the csi_mod branch of\n% the FID-A GitHub repository.\n\nif allDims(1)*allDims(2)*allDims(3) == 1 % x=y=z=1\n    dims.x = 0;\n    dims.y = 0;\n    dims.z = 0;\n    fids = squeeze(fids);\n    \n    %Now that we've indexed the dimensions of the data array, we now need to\n    %permute it so that the order of the dimensions is standardized:  we want\n    %the order to be as follows:\n    %   1) time domain data.\n    %   2) coils.\n    %   3) averages.\n    %   4) subSpecs.\n    %   5) extras.\n\n    % Adjust dimension indices for the fact that we have collapsed the\n    % three spatial dimensions (which we don't need for SVS data)\n    sqzDims = {};\n    dimsFieldNames = fieldnames(dims);\n    for rr = 1:length(dimsFieldNames)\n        if dims.(dimsFieldNames{rr}) ~= 0\n            % Subtract 3 (x, y, z) from the dimension indices\n            dims.(dimsFieldNames{rr}) = dims.(dimsFieldNames{rr}) - 3;\n            sqzDims{end+1} = dimsFieldNames{rr};\n        end\n    end\n\n    if length(sqzDims)==5\n        fids=permute(fids,[dims.t dims.coils dims.averages dims.subSpecs dims.extras]);\n        dims.t=1;dims.coils=2;dims.averages=3;dims.subSpecs=4;dims.extras=5;\n    elseif length(sqzDims)==4\n        if dims.extras==0\n            fids=permute(fids,[dims.t dims.coils dims.averages dims.subSpecs]);\n            dims.t=1;dims.coils=2;dims.averages=3;dims.subSpecs=4;dims.extras=0;\n        elseif dims.subSpecs==0\n            fids=permute(fids,[dims.t dims.coils dims.averages dims.extras]);\n            dims.t=1;dims.coils=2;dims.averages=3;dims.subSpecs=0;dims.extras=4;\n        elseif dims.averages==0\n            fids=permute(fids,[dims.t dims.coils dims.subSpecs dims.extras]);\n            dims.t=1;dims.coils=2;dims;averages=0;dims.subSpecs=3;dims.extras=4;\n        elseif dims.coils==0\n            fids=permute(fids,[dims.t dims.averages dims.subSpecs dims.extras]);\n            dims.t=1;dims.coils=0;dims.averages=2;dims.subSpecs=3;dims.extras=4;\n        end\n    elseif length(sqzDims)==3\n        if dims.extras==0 && dims.subSpecs==0\n            fids=permute(fids,[dims.t dims.coils dims.averages]);\n            dims.t=1;dims.coils=2;dims.averages=3;dims.subSpecs=0;dims.extras=0;\n        elseif dims.extras==0 && dims.averages==0\n            fids=permute(fids,[dims.t dims.coils dims.subSpecs]);\n            dims.t=1;dims.coils=2;dims.averages=0;dims.subSpecs=3;dims.extras=0;\n        elseif dims.extras==0 && dims.coils==0\n            fids=permute(fids,[dims.t dims.averages dims.subSpecs]);\n            dims.t=1;dims.coils=0;dims.averages=2;dims.subSpecs=3;dims.extras=0;\n        end\n    elseif length(sqzDims)==2\n        if dims.extras==0 && dims.subSpecs==0 && dims.averages==0\n            fids=permute(fids,[dims.t dims.coils]);\n            dims.t=1;dims.coils=2;dims.averages=0;dims.subSpecs=0;dims.extras=0;\n        elseif dims.extras==0 && dims.subSpecs==0 && dims.coils==0\n            fids=permute(fids,[dims.t dims.averages]);\n            dims.t=1;dims.coils=0;dims.averages=2;dims.subSpecs=0;dims.extras=0;\n        elseif dims.extras==0 && dims.averages==0 && dims.coils==0\n            fids=permute(fids,[dims.t dims.subSpecs]);\n            dims.t=1;dims.coils=0;dims.averages=0;dims.subSpecs=2;dims.extras=0;\n        end\n    elseif length(sqzDims)==1\n        dims.t=1;dims.coils=0;dims.averages=0;dims.subSpecs=0;dims.extras=0;\n    end\n    \n    %Now get the size of the data array:\n    sz=size(fids);\n    \n    %Compared to NIfTI MRS, FID-A needs the conjugate\n    fids = conj(fids);\n    \n    %Now take fft of time domain to get fid:\n    specs=fftshift(ifft(fids,[],dims.t),dims.t);\n\nend\n\n\n\n% Fill in additional FID-A format variables\n% Nucleus (new field)\nout.nucleus = hdr_ext.ResonantNucleus;\n% Calculate B0 from spectrometer frequency depending on nucleus\n% Gamma from Wikipedia article \"Gyromagnetic ratio\" (3 signif. digits)\nfor rr = 1:length(out.nucleus)\n    switch out.nucleus{rr}\n        case '1H'\n            gamma = 42.577;\n        case '2H'\n            gamma = 6.536;\n        case '3HE'\n            gamma = -32.434;\n        case '7LI'\n            gamma = 16.546;\n        case '13C'\n            gamma = 10.708;\n        case '19F'\n            gamma = 40.052;\n        case '23NA'\n            gamma = 11.262;\n        case '31P'\n            gamma = 17.235;\n        case '129XE'\n            gamma = -11.777;\n    end\n    Bo(rr) = f0(rr) ./ gamma;\nend\n\n% Calculate t and ppm arrays using the calculated parameters:\nf   =[(-sw/2) + (sw/(2*nPts)) : sw/(nPts) : (sw/2) - (sw/(2*nPts))];\nppm = -f / (Bo(1)*42.577);\nppm = ppm + 4.65;\nt   = [0 : dt : (nPts-1)*dt];\n\n\n% MANDATORY FIELDS\n% Data & dimensions\nout.fids = fids;\nout.specs = specs;\nout.sz = sz;\nout.dims = dims;\nout.Bo = Bo;\nout.averages = averages;\nout.rawAverages = rawAverages;\nout.subspecs = subspecs;\nout.rawSubspecs = rawSubspecs;\n\n% Echo/repetition time\nout.te = hdr_ext.EchoTime;\nout.tr = hdr_ext.RepetitionTime;\n\n% time and frequency axis\nout.t   = t;\nout.ppm = ppm;\n\n% Dwell time & spectral width & field strength\nout.spectralwidth = sw;\nout.dwelltime = dt;\nout.txfrq  = f0 * 10^6;\nout.date = '';\n\n% NIfTI-MRS-SPECIFIC FIELDS\n% Save the NIfTI header\nout.nii_mrs.hdr = hdr;\n% Save the header extension\nout.nii_mrs.hdr_ext = hdr_ext;\nif isfield(hdr_ext, 'SequenceName')\n    out.seq = hdr_ext.SequenceName;\nend\n\n\n%FILLING IN THE FLAGS\nout.flags.writtentostruct=1;\nout.flags.gotparams=1;\nout.flags.leftshifted=0;\nout.flags.filtered=0;\nout.flags.zeropadded=0;\nout.flags.freqcorrected=0;\nout.flags.phasecorrected=0;\nif out.dims.averages==0\n    out.flags.averaged=1;\nelse\n    out.flags.averaged=0;\nend\nif out.dims.coils==0\n    out.flags.addedrcvrs=1;\nelse\n    out.flags.addedrcvrs=0;\nend\nout.flags.subtracted=0;\nout.flags.writtentotext=0;\nout.flags.downsampled=0;\nif out.dims.subSpecs==0\n    out.flags.isFourSteps=0;\nelse\n    out.flags.isFourSteps=(out.sz(out.dims.subSpecs)==4);\nend\n\nend\n\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/inputOutput/io_loadspec_niimrs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.217521971845722}}
{"text": "function writePOLY_tetgen(filename,V,F,H,varargin)\n  % WRITEPOLY_TETGEN prints vertices and planar facets to a .poly file for\n  % tetgen\n  %\n  % writePOLY_tetgen(filename,V,F,H)\n  %\n  % Input\n  %   filename:  name of output file as string (caution! will clobber\n  %                    existing)\n  %   V  #V by dim list of vertex positions\n  %   F  #F struct containing polygon information arrays\n  %     .facets  a #facets list of facets, each facet is a again a list of\n  %       polygons\n  %      ** Note: contrary to writePOLY_pyramid, here facets index V directly\n  %     .boundary_markers a #facets list of boundary_markers\n  %     .holes  a #facets list of holes, each holes entry is again a list for\n  %       each facet\n  %    or \n  %   F  #F by uniform_facet_size list of facets into V\n  %   H  #H by dim list of volume hole positions\n  %   Optional:\n  %     'BoundaryMarkers' followed by #facets list of boundary markers\n  %     'BoundaryMarkersNodes' followed by #facets list of boundary markers\n  %     'RegionList' followed by #regions list of region vertex positions and (optional) region numbers and attributes\n  %\n  % Example:\n  %   % constrained Delaunay tetrahedralization of a triangle mesh\n  %   [V,F] = load_mesh('gargoyle.obj');\n  %   % constrained Delaunay tetrahedralization of just points\n  %   D = DelaunayTri(V);\n  %   % Faces on boundary of convex hull\n  %   BF = boundary_faces(D.Triangulation);\n  %   % avoid dupicate faces\n  %   FmBF = setdiff(sort(F,2),sort(BF,2),'rows');\n  %   Facets = [];\n  %   Facets.facets = mat2cell([BF;FmBF],ones(size(BF,1)+size(FmBF,1),1),[3]);\n  %   Facets.boundary_marker = [ones(size(BF,1),1);-ones(size(FmBF,1),1)];\n  %   Facets.holes = cell(numel(Facets.facets),1);\n  %   writePOLY_tetgen('temp.poly',V,Facets,[]);\n  %   % -p: we're giving PLC, -g: output .mesh, -Y: no steiners\n  %   !/usr/local/bin/tetgen -pgY ~/Documents/volume/temp.poly\n  %   [VV,TT,FF] = readMESH('temp.1.mesh');\n  %\n  % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)\n  %\n  % See also: cdt, tetgen, writePOLY_triangle, writePOLY_pyramid\n  %\n\n  v = 1;\n  BM = [];\n  BMN = [];\n  RL = [];\n  while v <= numel(varargin)\n    switch varargin{v}\n    case 'BoundaryMarkers'\n      assert((v+1)<=numel(varargin));\n      v = v+1;\n      BM = varargin{v};\n    case 'BoundaryMarkersNodes'\n      assert((v+1)<=numel(varargin));\n      v = v+1;\n      BMN = varargin{v};\n    case 'RegionList'\n      assert((v+1)<=numel(varargin));\n      v = v+1;\n      RL = varargin{v};\n    otherwise\n      error(['Unsupported parameter: ' varargin{v}]);\n    end\n    v=v+1;\n  end\n\n  % open file for writing\n  poly_file_handle = fopen(filename,'w');\n\n  % dimensions in V, should be 3\n  dim = size(V,2);\n  if isempty(V)\n    dim = 3;\n  end\n\n  if dim ~= 3\n    error('writePOLY_tetgen is for 3d meshes. Try writePOLY_triangle etc.');\n  end\n\n  % vertices section\n  fprintf(poly_file_handle,'# vertices\\n');\n  fprintf(poly_file_handle,'# Part 1 - node list\\n');\n  fprintf(poly_file_handle,'%d %d 0 %d\\n', size(V,1),size(V,2),~isempty(BMN));\n  format = '%d %.17g %.17g %.17g\\n';\n  if ~isempty(V)\n      if ~isempty(BMN)\n          assert(numel(BMN)==size(V,1));\n          formatV = '%d %.17g %.17g %.17g %d\\n';\n          fprintf(poly_file_handle,formatV,[1:size(V,1);V';BMN']);\n      else\n          formatV=format;\n          fprintf(poly_file_handle,formatV,[1:size(V,1);V']);\n          \n      end\n  end\n\n  fprintf(poly_file_handle,'# Part 2 - facet list\\n');\n  % Try to print all at once if facets are all the same size\n  if ~isstruct(F)\n    fprintf(poly_file_handle,'%d %d\\n',size(F,1),~isempty(BM));\n    assert(numel(BM)==size(F,1) || isempty(BM));\n    % build format\n    fformat = '1 0';\n    if ~isempty(BM)\n      fformat = [fformat ' %d'];\n    end\n    fformat = [fformat '\\n' num2str(size(F,2))];\n    for p=1:size(F,2)\n      fformat = [fformat ' %d']; %#ok<AGROW>\n    end\n    fformat = [fformat '\\n'];\n    % print all at once\n    fprintf(poly_file_handle,fformat,[BM F]');\n  else\n    fprintf(poly_file_handle,'%d %d\\n',numel(F.facets),1);\n    % irregular face valences\n    for f=1:numel(F.facets)\n      % [num polygons] [num holes] [boundary marker]\n      fprintf(poly_file_handle,'%d %d %d\\n', ...\n        numel(F.facets{f}),size(F.holes{f},1),F.boundary_marker(f));\n      % loop over polygons\n      for p=1:numel(F.facets{f})\n        % [num corners] [corner 1] [corner 2] ...\n        fprintf(poly_file_handle,' %d',numel(F.facets{f}{p}));\n        fprintf(poly_file_handle,' %d',F.facets{f}{p});\n        fprintf(poly_file_handle,'\\n');\n      end\n      % [hole #] [hole x] [hole y] [hole z]\n      if ~isempty(F.holes{f})\n        assert(size(F.holes{f},2) == size(V,2));\n        fprintf(poly_file_handle,format,[1:size(F.holes{f},1);F.holes{f}']);\n      end\n    end\n  end\n\n  % [num holes]\n  fprintf(poly_file_handle,'# Part 3 - hole list\\n');\n  fprintf(poly_file_handle,'%d\\n',size(H,1));\n  if ~isempty(H)\n    assert(isempty(V) || size(H,2) == size(V,2));\n    fprintf(poly_file_handle,format,[1:size(H,1);H']);\n  end\n  % [num regions]\n  fprintf(poly_file_handle,'# Part 4 - region list\\n');\n  fprintf(poly_file_handle,'%d\\n',size(RL,1));\n  if ~isempty(RL)\n    % [region #] [region x] [region y] [region z] [region attribute] and/or [region number]\n    formatRL = ['%d' repmat(' %.17g',1,size(RL,2)) '\\n'];\n    fprintf(poly_file_handle,formatRL,[1:size(RL,1);RL']);\n  end\n  fprintf(poly_file_handle,'\\n');\n  fclose(poly_file_handle);\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/writePOLY_tetgen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2175157685661471}}
{"text": "function g = kernDiagGradient(kern, x, covDiag)\n\n% KERNDIAGGRADIENT Compute the gradient of the kernel's parameters for the diagonal.\n% FORMAT\n% DESC computes the gradient of functions of the diagonal of the\n% kernel matrix with respect to the parameters of the kernel. The \n% parameters' gradients are returned in the order given by the \n% kernExtractParam command.\n% ARG kern : the kernel structure for which the gradients are computed.\n% ARG x : the input data for which the gradient is being computed.\n% ARG factors : partial derivatives of the function of interest\n% with respect to the diagonal elements of the kernel matrix.\n% RETURN g : gradients of the relevant function with respect to each of the parameters. Ordering should match the ordering given in kernExtractParam.\n%\n% SEEALSO : kernDiagGradient, kernExtractParam, kernGradient\n\n% KERN\n\n\nfileName = [kern.type 'KernDiagGradient'];\nif exist(fileName) == 2\n  fhandle = str2func(fileName);\n  g = fhandle(kern, x, covDiag);\nelse\n  fhandle = str2func([kern.type 'KernGradient']);\n  g = zeros(1, kern.nParams);\n  for i = 1:size(x, 1)\n    g = g ...\n        + fhandle(kern, x(i, :), covDiag(i));\n  end\nend\n% Check if parameters are being optimised in a transformed space.\nfactors = kernFactors(kern, 'gradfact');\ng(factors.index) = g(factors.index).*factors.val;\n\n  \n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/kernDiagGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21751576258908772}}
{"text": "Eat = [E.Longitude.*111, E.Latitude.*111, E.Depth];\nEatlon = newt2.Longitude.*111;\nEatran = ran(:,1).*111;\nEattim = newt2.Date;\nincr = a.Date;\neat = [((Eat(:,1).^2 + Eat(:,2).^2 + Eat(:,3)).^0.5)];\n%\n%\n%\np = min(a.Date);\n\n\ntim2 = [];\ntim3 = [];\n\ntim1 = [];\ntic;\nfor p = min(a.Date):0.0000011:max(a.Date)\n\n    match1 = find(a.Date< (p + 0.0000005) & a.Date> (p - 0.0000005));\n    tim1 = [tim1; match1];\n\nend\ntoc;\n\ntime = a(tim1,3);\nEatlon = [a(tim1,:)]; %[a(tim,1), a(tim,2), a(tim,7)];\n\n\n\nfor p = min(a.Date):0.001+0.01:max(a.Date)\n    match2 = find(a.Date< (p + 0.0001) & a.Date> (p - 0.0001));\n    tim2 = [tim2; match2];\nend\nEat2 = [eat(tim2)];\n\n\nfor p = min(a.Date):0.001+0.02:max(a.Date)\n    match3 = find(a.Date< (p + 0.0001) & a.Date> (p - 0.0001));\n    tim3 = [tim3; match3];\nend\nEat3 = [eat(tim3)];\n\nEat = [Eat1 Eat2 Eat3];\n\n\nfor m = 0:6\n\n    time1(1:3202,(m+1)) = (decyear(E.Date)+ 0.005*m);\n    %Eat(1:3202,(m)) = [Eat(:,1) eat(:,2)+0.005*m;\nend\n\nea = find(decyear(E.Date)>min(decyear(E.Date))+0.05*4);\nE = E(ea,:);\n\n%\n%\n%\n\nm = 1:5:2435; %size(pairdist,1);\nfigure;\n%plot3(eat (m-2), eat(m-1,:), eat(m,:), 'k.', 'Markersize', 0.5);\n%plot3(a((m+40),3), a(m+20,3), a(m,3), 'k.', 'Markersize', 0.5);\nu = plot3(eat(m),eat(m+10),eat(m+20));%,'k.');\nclear m;\n%\n%\n%\n\nk = 1:798;\nu = [eat(k),eat(k+0.75),eat(k+1.5)];%,eat(k+2.25),eat(k+3),eat(k+3.75)];\nfigure;\n%plot3(u(:,1),u(:,2), u(:,3), 'k.', 'Markersize', 0.5);%u(m-2,:)\nxlabel('kt');\nylabel('kt+T');\nzlabel('kt+2T');\n\nk = 1:10:3012245;\nfigure;\nplot3(pairdist(k),pairdist(k+20), pairdist(k+40));%,'k.', 'Markersize', 0.5);\n\n%plot(E(n-1,1), E(n,1),'k.', 'Markersize', 0.5);\n%plot(E(n-1,2), E(n,2),'k.', 'Markersize', 0.5);\n%plot(E(n-1,7), E(n,7),'k.', 'Markersize', 0.5);\n\nk = 1:1:3193;\nE = [Eatlon(k),Eatlon(k+2),Eatlon(k+3), Eatlon(4), Eatlon(k+5), Eatlon(6), Eatlon(k+7), Eatlon(k+8)];\n\nmEatlon = sum(Eatlon,1)/3202;\nEatlon = Eatlon-mEatlon;\nHSig = figure;\nplot(Eattim, Eatlon);\naxis([2500 3000 -10 -15]);\n\n[ps,freq] = spectrum(Eatlon,256,0,[],0.0634);\nHpws = figure;\nplot(freq,ps(:,1));\naxis([0 0.01 0 30]);\nspectrum(Eatlon);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/fractal/attractor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.2173385450144472}}
{"text": "% std_plotcurve() - plot ERP or spectral traces for a STUDY component \n%                   or channel cluster \n% Usage:\n%          >> std_plotcurve( axvals, data, 'key', 'val', ...)\n% Inputs:\n%  axvals - [vector or cell array] axis values for the data. \n%  data  -  [cell array] mean data for each subject group and/or data\n%           condition. For example, to plot mean ERPs from a STUDY \n%           for epochs of 800 frames in two conditions from three groups \n%           of 12 subjects:\n%\n%           >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n%                       [800x12] [800x12] [800x12] };  % 3 groups, cond 2\n%           >> std_plotcurve(erp_ms,data);\n%\n%           By default, parametric statistics are computed across subjects \n%           in the three groups. (group,condition) ERP averages are plotted. \n%           See below and >> help statcond \n%           for more information about the statistical computations.\n%\n% Optional display parameters:\n%  'datatype'    - ['erp'|'spec'] data type {default: 'erp'}\n%  'titles'      - [cell array of string] titles for each of the subplots. \n%                  { default: none}\n%\n% Statistics options:\n%  'groupstats'  - [cell] One p-value array per group {default: {}}\n%  'condstats'   - [cell] One p-value array per condition {default: {}}\n%  'interstats'  - [cell] Interaction p-value arrays {default: {}}\n%  'threshold'   - [NaN|real<<1] Significance threshold. NaN -> plot the \n%                  p-values themselves on a different figure. When possible, \n%                  significance regions are indicated below the data.\n%                  {default: NaN}\n%\n% Curve plotting options (ERP and spectrum):\n%  'plotgroups'  - ['together'|'apart'] 'together' -> plot mean results \n%                  for subject groups in the same figure panel in different \n%                  colors. 'apart' -> plot group results on different figure\n%                  panels {default: 'apart'}\n%  'plotconditions' - ['together'|'apart'] 'together' -> plot mean results \n%                  for data conditions on the same figure panel in\n%                  different \n%                  colors. 'apart' -> plot conditions on different figure\n%                  panel. Note: 'plotgroups' and 'plotconditions' arguments \n%                  cannot both be 'together' {default: 'apart'}\n%  'legend'      - ['on'|'off'] turn plot legend on/off {default: 'off'}\n%  'plotdiff'    - ['on'|'off'] plot difference between two groups\n%                  or conditions plotted together. \n%  'plotstderr'  - ['on'|'off'|'diff'|'nocurve'|'diffnocurve'] plots in \n%                  a surface indicating the standard error. 'diff' only \n%                  does it for the difference (requires 'plotdiff' 'on' \n%                  above). 'nocurve' does not plot the mean. This functionality\n%                  does not work for all data configuration {default: 'off'}\n%  'figure'      - ['on'|'off'] creates a new figure ('on'). The 'off' mode\n%                  plots all of the groups and conditions on the same pannel.\n% 'plotsubjects' - ['on'|'off'] overplot traces for individual components\n%                  or channels {default: 'off'}\n% 'singlesubject' - ['on'|'off'] set to 'on' to plot single subject.\n%                  {default: 'off'}\n% 'ylim'         - [min max] ordinate limits for ERP and spectrum plots\n%                  {default: all available data}\n%\n% Scalp map plotting options:\n%  'chanlocs'    - [struct] channel locations structure\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n%\n% See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond()\n\nfunction std_plotcurve(allx, data, varargin) \n\npgroup = [];\npcond  = [];\npinter = [];\nif nargin < 2\n    help std_plotcurve;\n    return;\nend;\n\nopt = finputcheck( varargin, { 'ylim'          'real'   []              [];\n                               'filter'        'real'   []              [];\n                               'threshold'     'real'   []              NaN;\n                               'unitx'         'string' []              'ms';\n                               'chanlocs'      'struct' []              struct('labels', {});\n                               'plotsubjects'  'string' { 'on' 'off' }  'off';\n                               'condnames'     'cell'   []              {}; % just for legends\n                               'groupnames'    'cell'   []              {}; % just for legends\n                               'groupstats'    'cell'   []              {};\n                               'condstats'     'cell'   []              {};\n                               'interstats'    'cell'   []              {};\n                               'titles'        'cell'   []              {};\n                               'figure'        'string' { 'on' 'off' }   'on';\n                               'plottopo'      'string' { 'on' 'off' }   'off';\n                               'plotstderr'    'string' { 'on' 'off' 'diff' 'nocurve' }   'off';\n                               'plotdiff'      'string' { 'on' 'off' }   'off';\n                               'legend'        { 'string' 'cell' } { { 'on' 'off' } {} }  'off';\n                               'datatype'      'string' { 'ersp' 'itc' 'erp' 'spec' }    'erp';\n                               'plotgroups'    'string' { 'together' 'apart' }  'apart';\n                               'plotmode'      'string' { 'test' 'condensed' }  'test'; % deprecated\n                               'plotconditions'    'string' { 'together' 'apart' }  'apart' }, 'std_plotcurve');\n\n% opt.figure =  'off'; % test by nima\nif isstr(opt), error(opt); end;\nopt.singlesubject = 'off';\nif strcmpi(opt.plottopo, 'on') && size(data{1},3) == 1, opt.singlesubject = 'on'; end;\n%if size(data{1},2) == 1,                              opt.singlesubject = 'on'; end;\nif all(all(cellfun('size', data, 2)==1))               opt.singlesubject = 'on'; end;\nif any(any(cellfun('size', data, 2)==1)), opt.groupstats = {}; opt.condstats = {}; end;\nif strcmpi(opt.datatype, 'spec'), opt.unit = 'Hz'; end;\nif strcmpi(opt.plotsubjects, 'on')\n    opt.plotgroups      = 'apart';\n    opt.plotconditions  = 'apart';\nend;\nif strcmpi(opt.plotconditions, 'together') &&  ~isempty(opt.groupstats), opt.plotconditions = 'apart'; end;\nif strcmpi(opt.plotgroups,     'together') &&  ~isempty(opt.condstats) , opt.plotgroups     = 'apart'; end;\nif isstr(opt.legend), opt.legend = {}; end;\nif isempty(opt.titles), opt.titles = cell(10,10); opt.titles(:) = { '' }; end;\nif length(data(:)) == length(opt.legend(:)), \n    opt.legend = reshape(opt.legend, size(data))'; \n    opt.legend(cellfun(@isempty, data)) = []; \n    opt.legend = (opt.legend)';\nend;\n\n% plot\n% ----\n% if strcmpi(opt.figure, 'on'), \n% else\n%     % all groups and conditions in the same figureopt.chanlocs\n%     ncol = size(tmpdata,3);\n%     if ncol == 1, ncol = size(tmpdata,1); end;\n%     tmpcol = col(colcount:colcount+ncol-1);\n%     colcount = mod(colcount+ncol-1, length(col))+1;\n%     %if strcmpi(opt.plotgroups, 'together') && isempty(tmpdata{1})\n% \n% end;\n%  \n\n% color matrix\n% -----------------------\nonecol  = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' };\nmanycol = { 'b' 'g' 'm' 'c' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ...\n                   'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' };\nif strcmpi(opt.plotgroups, 'together') || strcmpi(opt.plotconditions, 'together') || strcmpi(opt.figure, 'off')\n     col = manycol;\nelse col = onecol;\nend;\nnonemptycell = find(~cellfun(@isempty, data));\nmaxdim = max(length(data(:)), size(data{nonemptycell(1)}, ndims(data{nonemptycell(1)})));\ntmpcol = col;\nif strcmpi(opt.plotsubjects, 'off')\n    coldata = col(mod([0:maxdim-1], length(col))+1);\n    coldata = reshape(coldata(1:length(data(:))), size(data));\nelse\n    coldata = cell(size(data));\nend;\n\n% remove empty entries\n% --------------------\ndatapresent = ~cellfun(@isempty, data);\nif size(data,1) > 1, for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; coldata(c,:) = []; if ~strcmpi(opt.plotconditions, 'together') opt.titles(c,:) = []; end; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end; end;\nif size(data,2) > 1, for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; coldata(:,g) = []; if ~strcmpi(opt.plotgroups    , 'together') opt.titles(:,g) = []; end; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end; end;\nif strcmpi(opt.plotsubjects, 'off'), tmpcol = coldata'; tmpcol = tmpcol(:)'; end;\n\n% number of columns and rows to plot\n% ----------------------------------\nnc = size(data,1);\nng = size(data,2);\nif strcmpi(opt.plotgroups, 'together'),      ngplot = 1; else ngplot = ng; end;\nif strcmpi(opt.plotconditions,  'together'), ncplot = 1; else ncplot = nc; end;     \nif nc >= ng, opt.subplot = 'transpose';\nelse         opt.subplot = 'normal';\nend;\nif isempty(opt.condnames)\n    for c=1:nc, opt.condnames{c} = sprintf('Cond. %d', c); end;\n    if nc == 1, opt.condnames = { '' }; end;\nend;\nif isempty(opt.groupnames)\n    for g=1:ng, opt.groupnames{g} = sprintf('Group. %d', g); end;\n    if ng == 1, opt.groupnames = { '' }; end;\nend;\n\n% plotting paramters\n% ------------------\nif ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end;\nif nc > 1 && ~isempty(opt.condstats ), addr = 1; else addr = 0; end;\nif strcmpi(opt.singlesubject, 'off') ...\n        && ( ~isempty(opt.condstats) || ~isempty(opt.groupstats) ) % only for curves\n    plottag = 0;\n    if strcmpi(opt.plotgroups, 'together') && isempty(opt.condstats) && ~isempty(opt.groupstats) && ~isnan(opt.threshold), addc = 0; plottag = 1; end;\n    if strcmpi(opt.plotconditions , 'together') && ~isempty(opt.condstats) && isempty(opt.groupstats) && ~isnan(opt.threshold), addr = 0; plottag = 1; end;\n    if ~isnan(opt.threshold) && plottag == 0 && strcmpi(opt.figure, 'on')\n        disp('Warning: cannot plot condition/group on the same panel while using a fixed');\n        disp('         threshold, unless you only compute statistics for ether groups or conditions');\n        opt.plotgroups = 'apart';\n        opt.plotconditions  = 'apart';\n    end;\nend;\n\n% compute significance mask\n% --------------------------\nif ~isempty(opt.interstats), pinter = opt.interstats{3}; end;\n\nif ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) )    \n    pcondplot  = opt.condstats;\n    pgroupplot = opt.groupstats;\n    pinterplot = pinter;\n    maxplot = 1;\nelse\n    warning off;\n    for ind = 1:length(opt.condstats),  pcondplot{ind}  = -log10(opt.condstats{ind}); end;\n    for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end;\n    if ~isempty(pinter), pinterplot = -log10(pinter); end;\n    maxplot = 3;\n    warning on;\nend;\n\n% labels\n% ------\nif strcmpi(opt.unitx, 'ms'), xlab = 'Time (ms)';      ylab = 'Potential (\\muV)';\nelse                         xlab = 'Frequency (Hz)'; ylab = 'Power (10*log_{10}(\\muV^{2}/Hz))'; \nend;\nif ~isnan(opt.threshold), statopt = {  'xlabel' xlab };\nelse                      statopt = { 'logpval' 'on' 'xlabel' xlab 'ylabel' '-log10(p)' 'ylim' [0 maxplot] };\nend;\n\n% adjust figure size\n% ------------------\nif strcmpi(opt.figure, 'on')\n    figure('color', 'w');\n    pos = get(gcf, 'position');\n    basewinsize = 200/max(nc,ng)*3;\n    if strcmpi(opt.plotgroups, 'together') pos(3) = 200*(1+addc);\n    else                                   pos(3) = 200*(ng+addc);\n    end;\n    if strcmpi(opt.plotconditions , 'together') pos(4) = 200*(1+addr);\n    else                                        pos(4) = 200*(nc+addr);\n    end;\n    if strcmpi(opt.subplot, 'transpose'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);\n    else                                  set(gcf, 'position', pos);\n    end;\nelse\n    opt.subplot = 'noplot';\nend;\n\ntmplim = [Inf -Inf];\ncolcount = 1; % only when plotting all conditions on the same figure\nfor c = 1:ncplot\n    for g = 1:ngplot\n        if strcmpi(opt.plotgroups, 'together'),         hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, 1 + (c-1)*(ngplot+addc), opt.subplot); ci = g;\n        elseif strcmpi(opt.plotconditions, 'together'), hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g, opt.subplot); ci = c;\n        else                                            hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g + (c-1)*(ngplot+addc), opt.subplot); ci = 1;\n        end;\n        \n        if ~isempty(data{c,g})\n\n            % read all data from one condition or group\n            % -----------------------------------------\n            dimreduced_sizediffers = 0;\n            if ncplot ~= nc && ngplot ~= ng\n                maxdim = max(max(cellfun(@(x)(size(x, ndims(x))), data)));\n                for cc = 1:size(data,1)\n                    for gg = 1:size(data,2)\n                        tmptmpdata = real(data{cc,gg});\n                        if ndims(tmptmpdata) == 3, \n                            if cc == 1 && gg == 1, tmpdata = NaN*zeros([size(tmptmpdata,1) size(tmptmpdata,2) maxdim length(data(:))]); end;\n                            tmpdata(:,:,1:size(tmptmpdata,3),gg+((cc-1)*ng)) = tmptmpdata;\n                        else\n                            if cc == 1 && gg == 1, tmpdata = NaN*zeros([size(tmptmpdata,1) maxdim length(data(:))]); end;\n                            tmpdata(:,1:size(tmptmpdata,2),gg+((cc-1)*ng))   = tmptmpdata;\n                        end;\n                    end;\n                end;\n            elseif ncplot ~= nc % plot conditions together\n                for ind = 2:size(data,1), if any(size(data{ind,1}) ~= size(data{1})), dimreduced_sizediffers = 1; end; end;\n                for cc = 1:nc\n                    tmptmpdata = real(data{cc,g});\n                    if dimreduced_sizediffers\n                        tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata));\n                    end;\n                    if cc == 1, tmpdata = zeros([size(tmptmpdata) nc]); end;\n                    if ndims(tmptmpdata) == 3, tmpdata(:,:,:,cc) = tmptmpdata; \n                    else                       tmpdata(:,:,cc)   = tmptmpdata; \n                    end;\n                end;\n            elseif ngplot ~= ng % plot groups together\n                for ind = 2:size(data,2), if any(size(data{1,ind}) ~= size(data{1})), dimreduced_sizediffers = 1; end; end;\n                for gg = 1:ng\n                    tmptmpdata = real(data{c,gg});\n                    if dimreduced_sizediffers\n                        tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata));\n                    end;\n                    if gg == 1, tmpdata = zeros([size(tmptmpdata) nc]); end;\n                    if ndims(tmptmpdata) == 3, tmpdata(:,:,:,gg) = tmptmpdata; \n                    else                       tmpdata(:,:,gg)   = tmptmpdata; \n                    end;\n                end;\n            else tmpdata = real(data{c,g}); \n                % nothing\n            end;\n            \n            % plot difference\n            % ---------------\n            if ~strcmpi(opt.plotdiff, 'off')\n                if ngplot ~= ng || ncplot ~= nc\n                    if size(tmpdata,3) == 2\n                        tmpdata(:,:,end+1) = tmpdata(:,:,2)-tmpdata(:,:,1);\n                        opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ];\n                    elseif size(tmpdata,4) == 2\n                        tmpdata(:,:,:,end+1) = tmpdata(:,:,:,2)-tmpdata(:,:,:,1);\n                        opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ];\n                    else\n                        disp('Cannot plot difference, more than 2 indep. variable values');\n                    end;\n                else\n                    disp('Cannot plot difference, indep. variable value must be plotted together');\n                end;\n            end;\n            \n            if ~isempty(opt.filter), tmpdata = myfilt(tmpdata, 1000/(allx(2)-allx(1)), 0, opt.filter); end;\n            \n            % plotting options\n            % ----------------\n            plotopt = { allx };\n            if ~dimreduced_sizediffers\n                if strcmpi(opt.plottopo, 'on'),\n                    if strcmpi(opt.plotsubjects, 'off') tmpstd = squeeze(real(std(tmpdata,[],3)))/sqrt(size(tmpdata,3)); tmpstd = squeeze(permute(tmpstd, [2 1 3])); tmpdata = squeeze(real(nan_mean(tmpdata,3))); end;\n                elseif strcmpi(opt.plotsubjects, 'off') tmpstd = squeeze(real(std(tmpdata,[],2)))/sqrt(size(tmpdata,2)); tmpstd = squeeze(permute(tmpstd, [2 1 3])); tmpdata = squeeze(real(nan_mean(tmpdata,2))); \n                end;\n            end;\n            tmpdata = squeeze(permute(tmpdata, [2 1 3]));\n            if strcmpi(opt.plottopo, 'on'), highlight = 'background'; else highlight = 'bottom'; end;\n            if strcmpi(opt.plotgroups, 'together') &&  isempty(opt.condstats) && ...\n                             ~isnan(opt.threshold) && ~isempty(opt.groupstats)\n                plotopt = { plotopt{:} 'maskarray' };\n                tmpdata = { tmpdata pgroupplot{c}' };\n            elseif strcmpi(opt.plotconditions, 'together') &&  isempty(opt.groupstats) && ...\n                                     ~isnan(opt.threshold) && ~isempty(opt.condstats)\n                plotopt = { plotopt{:} 'maskarray' };\n                tmpdata = { tmpdata pcondplot{g}' };\n            end;\n            plotopt = { plotopt{:} 'highlightmode', highlight };\n            if strcmpi(opt.plotsubjects, 'on')\n                plotopt = { plotopt{:} 'plotmean' 'on' 'plotindiv' 'on' };\n            else\n                plotopt = { plotopt{:} 'plotmean' 'off' };\n            end;\n            plotopt = { plotopt{:} 'ylim' opt.ylim 'xlabel' xlab 'ylabel' ylab };\n            if ncplot ~= nc || ngplot ~= ng\n                plotopt = { plotopt{:} 'legend' opt.legend };\n            end;\n            \n%             % plot\n%             % ----\n%             if strcmpi(opt.figure, 'on'), \n%                 tmpcol = col; \n%             else\n%                 % all groups and conditions in the same figureopt.chanlocs\n%                 ncol = size(tmpdata,3);\n%                 if ncol == 1, ncol = size(tmpdata,1); end;\n%                 tmpcol = col(colcount:colcount+ncol-1);\n%                 colcount = mod(colcount+ncol-1, length(col))+1;\n%                 %if strcmpi(opt.plotgroups, 'together') && isempty(tmpdata{1})\n%                     \n%             end;\n%             \n            if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1\n                metaplottopo(tmpdata, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                    'plotargs', { plotopt{:} }, 'datapos', [2 3], 'title', opt.titles{c,g});\n            elseif iscell(tmpdata)\n                plotcurve( allx, tmpdata{1}, 'colors', tmpcol, 'maskarray', tmpdata{2}, plotopt{3:end}, 'title', opt.titles{c,g});\n            else\n                if isempty(findstr(opt.plotstderr, 'nocurve'))\n                    plotcurve( allx, tmpdata, 'colors', tmpcol, plotopt{2:end}, 'title', opt.titles{c,g});\n                end;\n                if ~strcmpi(opt.plotstderr, 'off') \n                    if ~dimreduced_sizediffers\n                        if ~isempty(findstr(opt.plotstderr, 'diff')), begind = 3; else begind = 1; end;\n                        set(gcf, 'renderer', 'OpenGL')\n                        for tmpi = begind:size(tmpdata,1)\n                            hold on; chandle = fillcurves( allx, tmpdata(tmpi,:)-tmpstd(tmpi,:), tmpdata(tmpi,:)+tmpstd(tmpi,:), tmpcol{tmpi}); hold on;\n                            numfaces = size(get(chandle(1), 'Vertices'),1);\n                            set(chandle(1), 'FaceVertexCData', repmat([1 1 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', 0.3, 'edgecolor', 'none');\n                        end;\n                    else\n                        disp('Some conditions have more subjects than others, cannot plot standard error');\n                    end;\n                end;\n            end;\n        end;\n        \n        if strcmpi(opt.plottopo, 'off'), % only non-topographic\n            xlim([allx(1) allx(end)]); hold on;\n            if isempty(opt.ylim)\n                tmp = ylim;\n                tmplim = [ min(tmplim(1), tmp(1)) max(tmplim(2), tmp(2)) ];\n            else \n                ylim(opt.ylim);\n            end;\n        end;\n\n        % statistics accross groups\n        % -------------------------\n        if g == ngplot && ng > 1 && ~isempty(opt.groupstats)            \n            if ~strcmpi(opt.plotgroups, 'together') || ~isempty(opt.condstats) || isnan(opt.threshold)\n                if strcmpi(opt.plotgroups, 'together'),         mysubplot(ncplot+addr, ngplot+addc, 2 + (c-1)*(ngplot+addc), opt.subplot); ci = g;\n                elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, ngplot + 1, opt.subplot); ci = c;\n                else                                            mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + (c-1)*(ngplot+addc), opt.subplot); ci = 1;\n                end;\n                if strcmpi(opt.plotconditions, 'together'), condnames = 'Conditions'; else condnames = opt.condnames{c}; end;\n                if ~isnan(opt.threshold)\n                     if strcmpi(opt.plottopo, 'on'), \n                          metaplottopo({zeros(size(pgroupplot{c}')) pgroupplot{c}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                              'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1});\n                     else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pgroupplot{c},2), 'ylim', [0.1 1], 'title', opt.titles{c, g+1}, statopt{:});\n                     end;\n                else\n                     if strcmpi(opt.plottopo, 'on'), \n                          metaplottopo(pgroupplot{c}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                              'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1});\n                     else plotcurve(allx, mean(pgroupplot{c},2), 'title', opt.titles{c, g+1}, statopt{:});\n                     end;\n                end;\n            end;\n        end;\n    end;\nend;\n\nfor g = 1:ng\n    % statistics accross conditions\n    % -----------------------------\n    if ~isempty(opt.condstats) && nc > 1\n        if ~strcmpi(opt.plotconditions, 'together') || ~isempty(opt.groupstats) || isnan(opt.threshold)\n            if strcmpi(opt.plotgroups, 'together'),         mysubplot(ncplot+addr, ngplot+addc, 1 + c*(ngplot+addc), opt.subplot); ci = g;\n            elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, g + ngplot+addc, opt.subplot); ci = c;\n            else                                            mysubplot(ncplot+addr, ngplot+addc, g + c*(ngplot+addc), opt.subplot); ci = 1;\n            end;\n            if strcmpi(opt.plotgroups, 'together'), groupnames = 'Groups'; else groupnames = opt.groupnames{g}; end;\n            if ~isnan(opt.threshold)\n                 if strcmpi(opt.plottopo, 'on'), \n                      metaplottopo({zeros(size(pcondplot{g}')) pcondplot{g}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                          'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g});\n                 else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pcondplot{g},2), 'ylim', [0.1 1], 'title', opt.titles{end, g}, statopt{:});\n                 end;\n            else\n                 if strcmpi(opt.plottopo, 'on'), \n                      metaplottopo(pcondplot{g}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                          'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g});\n                 else plotcurve(allx, mean(pcondplot{g},2), 'title',  opt.titles{end, g}, statopt{:});\n                 end;\n            end;\n        end;\n    end;\nend;\n\n% statistics accross group and conditions\n% ---------------------------------------\nif ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1\n    mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + ncplot*(ngplot+addr), opt.subplot);\n    if ~isnan(opt.threshold)\n         if strcmpi(opt.plottopo, 'on'), \n              metaplottopo({zeros(size(pinterplot')) pinterplot'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                  'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end});\n         else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pinterplot,2), 'ylim', [0.1 1], 'title', opt.titles{end, end}, statopt{:});\n              xlabel(xlab); ylabel('-log10(p)');\n        end;\n    else\n         if strcmpi(opt.plottopo, 'on'), \n              metaplottopo(pinterplot', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...\n                  'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end});\n         else plotcurve(allx, mean(pinterplot,2), 'title', opt.titles{end, end}, statopt{:});\n         end;\n    end;\nend;  \n\n% axis limit\n% ----------\nfor c = 1:ncplot\n    for g = 1:ngplot\n        if isempty(opt.ylim) && strcmpi(opt.plottopo, 'off')\n            set(hdl(c,g), 'ylim', tmplim);\n        end;\n    end;\nend;\n\nif strcmpi(opt.plottopo, 'off') && length(hdl(:)) > 1\n    axcopy;\n    % remove axis labels (for most but not all)\n    % ------------------\n    if strcmpi(opt.subplot, 'transpose')\n        for c = 1:size(hdl,2)\n            for g = 1:size(hdl,1)\n                axes(hdl(g,c));\n                if c ~= 1 && size(hdl,2) ~=1, xlabel(''); legend off; end;\n                if g ~= 1 && size(hdl,1) ~= 1, ylabel(''); legend off; end;\n            end;\n        end;\n    else\n        for c = 1:size(hdl,1)\n            for g = 1:size(hdl,2)\n                axes(hdl(c,g));\n                if g ~= 1 && size(hdl,2) ~=1, ylabel(''); legend off; end;\n                if c ~= size(hdl,1) && size(hdl,1) ~= 1, xlabel(''); legend off; end;\n            end;\n        end;\n    end;\nend;\n\n\n% mysubplot (allow to transpose if necessary)\n% -------------------------------------------\nfunction hdl = mysubplot(nr,nc,ind,subplottype);\n\n    r = ceil(ind/nc);\n    c = ind -(r-1)*nc;\n    if strcmpi(subplottype, 'transpose'),  hdl = subplot(nc,nr,(c-1)*nr+r);\n    elseif strcmpi(subplottype, 'normal'), hdl = subplot(nr,nc,(r-1)*nc+c);\n    elseif strcmpi(subplottype, 'noplot'), hdl = gca;\n    else error('Unknown subplot type');\n    end;\n\n% rapid filtering for ERP\n% -----------------------\nfunction tmpdata2 = myfilt(tmpdata, srate, lowpass, highpass)\n\n    tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));\n    tmpdata2 = eegfiltfft(tmpdata2',srate, lowpass, highpass)';\n    tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_plotcurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.21733853228880817}}
{"text": "function chEOG=identify_eog_channels(fn,x); \n% IDENTIFY_EOG_CHANNELS returns bipolar EOG channels for \n%  correcting of EOG artifacts using regression analysis\n% \n%  EOGchan = IDENTIFY_EOG_CHANNELS(...) \n%\n% EOGchan is a sparse matrix of size number_of_channels x 2. \n% The sparsity ensures that missing samples of unrelated channels \n% do not affect the data.  \n%\n%  [...] = IDENTIFY_EOG_CHANNELS(filename) \n%  [...] = IDENTIFY_EOG_CHANNELS(HDR) \n%\tfilename or HDR struct can be used\n%  [...] = IDENTIFY_EOG_CHANNELS(...,'x') \n%     looks for EOG channels whos Label start with x\n%\n% see also: GET_REGRESS_EOG, SLOAD\n%\n% Reference(s):\n% [1] Schlogl A, Keinrath C, Zimmermann D, Scherer R, Leeb R, Pfurtscheller G. \n%\tA fully automated correction method of EOG artifacts in EEG recordings.\n%\tClin Neurophysiol. 2007 Jan;118(1):98-104. Epub 2006 Nov 7.\n% \thttp://dx.doi.org/10.1016/j.clinph.2006.09.003\n%       http://pub.ist.ac.at/~schloegl/publications/schloegl2007eog.pdf\n\n%\t$Id: identify_eog_channels.m 2649 2011-03-09 09:52:44Z schloegl $\n%\tCopyright (C) 2006,2007,2009,2010 by Alois Schloegl \n%    \tThis is part of the BIOSIG-toolbox http://biosig.sf.net/\n\n% Biosig is free software; you can redistribute it and/or\n% modify it under the terms of the GNU Library General Public\n% License as published by the Free Software Foundation; either\n% Version 3 of the License, or (at your option) any later version.\n%\n% This library is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n% Library General Public License for more details.\n%\n% You should have received a copy of the GNU Library General Public\n% License along with this library; if not, write to the\n% Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n% Boston, MA  02111-1307, USA.\n\n\nif ischar(fn), \n\tHDR=sopen(fn); \n\tHDR=sclose(HDR); \nelseif isstruct(fn)\n\tHDR=fn; \nend;\n\n% graz \ng1 = strmatch('EOG-left',HDR.Label);\ng2 = strmatch('EOG-central',HDR.Label);\ng3 = strmatch('EOG-right',HDR.Label);\nif isempty([g1,g2,g3])\n\tg1 = strmatch('EOG:ch01',HDR.Label);\n\tg2 = strmatch('EOG:ch02',HDR.Label);\n\tg3 = strmatch('EOG:ch03',HDR.Label);\nend; \n\n% berlin\nif nargin<2,\n\tv1 = strmatch('eogv1',lower(HDR.Label));\n\tv2 = strmatch('eogv2',lower(HDR.Label));\n\tv0 = strmatch('eogv',lower(HDR.Label));\n\tv3 = strmatch('eogvp',lower(HDR.Label));\n\tv4 = strmatch('eogvn',lower(HDR.Label));\n\n\th1 = strmatch('eogh1',lower(HDR.Label));\n\th2 = strmatch('eogh2',lower(HDR.Label));\n\th0 = strmatch('eogh' ,lower(HDR.Label));\n\th3 = strmatch('eoghp',lower(HDR.Label));\n\th4 = strmatch('eoghn',lower(HDR.Label));\nelse\n\tv1 = [];\n\tv2 = [];\n\tv0 = [];\n\tv3 = strmatch('xeogvp',lower(HDR.Label));\n\tv4 = strmatch('xeogvn',lower(HDR.Label));\n\n\th1 = [];\n\th2 = [];\n\th0 = [];\n\th3 = strmatch('xeoghp',lower(HDR.Label));\n\th4 = strmatch('xeoghn',lower(HDR.Label));\nend;\n\ng = [g1;g2;g3];\nv = [v1,v2,v3,v4];\nif isempty(v), v=v0; end; \nh = [h1,h2,h3,h4];\nif isempty(h), h=h0; end; \nif length(g)==3,\n\tchEOG = sparse([g1,g2,g2,g3],[1,1,2,2],[1,-1,1,-1],HDR.NS,2);\nelseif length(g)==2,\n\tchEOG = sparse([g1,g2,g3],[1,1],[1,-1],HDR.NS,1);\nelse \n\tc = (length(v)>0);  \n\tsz2 = (length(v)>0) + (length(h)>0);  \n\tif length(v)==1, \n\t\tchEOG = sparse(v,c,1,HDR.NS,sz2); \n\telseif length(v)==2, \n\t\tchEOG = sparse(v,[c,c],[1,-1],HDR.NS,sz2); \n\telse \n\t\tchEOG = 0; \n\tend;\n\tif length(h)==1, \n\t\tchEOG = chEOG+sparse(h,1+c,1,HDR.NS,1+c); \n\telseif length(h)==2, \n\t\tchEOG = chEOG+sparse(h,[1,1]+c,[1,-1],HDR.NS,1+c); \n\tend;\nend; \n\nif size(chEOG,2)<2, \n\twarning('EOG channels are missing, or were not recognized'); \nend; \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/biosig-partial/t250_ArtifactPreProcessingQualityControl/identify_eog_channels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21733517129437277}}
{"text": "function u = pend_control(x)\n\nload('pend_data', 'K', 'U', 'domain');\n\np = [x(2) x(4)];\nu = tpcontroller(p, x, K, U, domain);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25514-tp-tool/tptool/example/pend/pend_control.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.21733516318344398}}
{"text": "%% subfunction: split nii components into multiple nii\nfunction nii = split_components(nii, s)\nfld = 'ComplexImageComponent';\nif ~strcmp(tryGetField(s, fld, ''), 'MIXED'), return; end\n\nif ~isfield(s, 'Volumes') % PAR file and single-frame file have this\n    nSL = nii.hdr.dim(4); nVol = nii.hdr.dim(5);\n    iFrames = 1:nSL:nSL*nVol;\n    if isfield(s, 'SortFrames'), iFrames = s.SortFrames(iFrames); end\n    s1 = struct(fld, {cell(1, nVol)}, 'MRScaleSlope', nan(1,nVol), ...\n            'RescaleSlope', nan(1,nVol), 'RescaleIntercept', nan(1,nVol));\n    s.Volumes = dicm_hdr(s, s1, iFrames);\nend\nif ~isfield(s, 'Volumes'), return; end\n\n% suppose scl not applied in set_nii_hdr, since MRScaleSlope is not integer\nflds = {'EchoTimes' 'CardiacTriggerDelayTimes'}; % to split\ns1 = s.Volumes;\nnii0 = nii;\n% [c, ia] = unique(s.Volumes.(fld), 'stable'); % since 2013a?\n[~, ia] = unique(s1.(fld));\nia = sort(ia);\nc = s1.(fld)(ia);\nfor i = 1:numel(c)\n    nii(i) = nii0;\n    ind = strcmp(c{i}, s1.(fld));\n    nii(i).img = nii0.img(:,:,:,ind);\n    slope = s1.RescaleSlope(ia(i)); if isnan(slope), slope = 1; end \n    inter = s1.RescaleIntercept(ia(i)); if isnan(inter), inter = 0; end\n    if ~isnan(s1.MRScaleSlope(ia(i)))\n        inter = inter / (slope * s1.MRScaleSlope(ia(i)));\n        slope = 1 / s1.MRScaleSlope(ia(i));\n    end\n    nii(i).hdr.scl_inter = inter;\n    nii(i).hdr.scl_slope = slope;\n    nii(i).hdr.file_name = [s.NiftiName '_' lower(c{i})];\n    nii(i) = nii_tool('update', nii(i));\n    \n    for j = 1:numel(flds)\n        if ~isfield(nii(i).json, flds{j}), continue; end\n        nii(i).json.(flds{j}) = nii(i).json.(flds{j})(ind);\n    end\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Nifti_utils/split_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21716649864022286}}
{"text": "%*******************************************************************\n%Summary: This file runs the specified model and logs the data from the listed signals \n%and plots the results.  \n%\n%In this file you specify the name of the signal\n%that you want to log.  You can also specify a decimation for the logged\n%signals.  This models uses a variation of the Simulink Demo model named\n%'sldemo_househeat'\n% JAD - 1/6/06\n%*********************************************************************\n\n%**********Prepare workspace************\n    clear\n    clc\n    close all\n    name_mod='sldemo_househeat1'; %Name of model to simulate\n%***************end***************************\n\n    % Simulation Time Calculationss *******    \n    \n    Sub_Sample_Time=3; % Log every third value\n\n\n%Structure file that will contain the name of the signals to log\n%Comment all names to disable signal logging\n\n    log_struct{1}='Set_Temp';\n    log_struct{2}='blower_cmd';\n    log_struct{3}='Tout';\n    log_struct{4}='Temp_in';\n    log_struct{5}='Heat_Cost';\n    log_struct{6}='Tout2';\n    log_struct{7}='time';  %The time value can also be obtained from the logged Structure\n\n    log_struct{8}='House/Sub_Temp';\n%     log_struct{9}='';\n%     log_struct{10}='';\n%     log_struct{11}='';\n%     log_struct{12}='';\n%     log_struct{13}='';\n%         \n%     log_struct{14}='';\n%     log_struct{15}='';\n%     log_struct{16}='';\n%     log_struct{17}='';    \n%     log_struct{18}='';\n%     log_struct{19}='';\n\n\n    %Turn on logging for specified signals in the model\n    if exist('log_struct') \n                   %log_signals(name of model,name_of_log_var, enable_decimation, decimation_time) \n        signal_name=log_signals(name_mod,log_struct,'off',Sub_Sample_Time);\n    end\n    \n\n    % ********* Run Sim  ***********************************************\n    tic\n     sim(name_mod)\n    toc\n%***************end***************************\n\n%*************Save logged values in the workspace************************\nif exist('log_struct')    \n\n    for i=1:length(log_struct)\n        index=findstr(log_struct{i},'/');\n\n        if isempty(index)\n           temp=[signal_name{i},'=logsout.',signal_name{i},'.Data;'];\n           eval(temp);\n\n        elseif (length(index)>1) % If this signal is in a subsystem\n            sys_name=log_struct{i}(1:index(1)-1); %Grab the name of the system\n            sub_sys_name=log_struct{i}(index(1)+1:index(2)-1); %Grab the name of the subsystem\n            temp=[signal_name{i},'=logsout.(''',sys_name,''').',sub_sys_name,'.',signal_name{i},'.Data;'];\n            eval(temp);\n        else  %This signal is not in a subsystem\n           temp1=log_struct{i}(1:index(1)-1); %Grab the name of the system\n           temp=[signal_name{i},'=logsout.(''',temp1,''').',signal_name{i},'.Data;'];\n           eval(temp);\n        end\n    end\nend\n%***************end***************************\n\n\n%Close model and do not save model changes\n%       close_system(name_mod,0);\n %Plot results\n \n    figure(1)\n    subplot(2,1,1)\n    plot(time,Tout,time,Tout2)\n    subplot(2,1,2)\n    plot(Heat_Cost,time)\n    \n    \n    ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9563-logaccess-simulink-signals-from-the-ml-command-line-useful-for-batch-testing/example_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21704305994259127}}
{"text": "function [study,xmesh,ymesh,zmesh,tags]=dicomrt_d2c_coordsystem(study,xmesh,ymesh,zmesh,tags)\n% dicomrt_d2c_coordsystem(study,xmesh,ymesh,zmesh,tags)\n%\n% Convert DICOM data from native coordinate system to RTOG coordinate system\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n% LM 04/28/2006 DK \n%         Fix for dose x-coordinates when patient position is FFS.\n\n% Check input data\n% PatientPosition is N/A in VOI hence it must be defined previously\n% and stored in tags.dicomPatientPosition if we are dealing with VOI\nif ~isfield(tags,'dicomPatientPosition') || isempty(tags(1).dicomPatientPosition)\n    [study,type,dummylabel,PatientPosition]=dicomrt_checkinput(study);\n    %tags.dicomPatientPosition=PatientPosition;\n    for i=1:length(tags)\n        tags(i).('dicomPatientPosition') = PatientPosition;\n    end\nelse\n    [study,type,dummylabel]=dicomrt_checkinput(study);\n    PatientPosition=tags.dicomPatientPosition;\nend\n\n% Get DICOM-RT toolbox dataset info\nstudy_pointer=study{1,1};\nstudy_array=study{2,1};\n\n% Accounting for different coordinate system between DICOM and RTOG\n%\n% NOTE: The origin of the RTOG coordinate system is defined as the coordinates of\n% the geometrical center of the image. Offsets along the x- and y-direction\n% are calculated from the DICOM original data.\n%\nif strcmpi('VOI',type)~=1                       % Separate case if study is a VOI\n    if PatientPosition==1                       % HFS\n        study_array                 = flipdim(study_array,3);\n        tags.hio                    = 'IN';\n        tags.pos                    = 'NOSE UP';\n        if strcmpi('CT',type)~=1\n            xmesh                       = xmesh;\n            ymesh                       = -ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted \n            tags.coord1OFFirstPoint     = xmesh(1);\n            tags.coord2OFFirstPoint     = ymesh(1);\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.horizontalGridInterval = temp_diff_x(1);\n            tags.verticalGridInterval   = temp_diff_y(1);\n        else\n            tags.originalCTxmesh        = xmesh;\n            tags.originalCTymesh        = ymesh;\n            tags.originalCTzmesh        = zmesh;\n            xmesh                       = xmesh;\n            ymesh                       = -ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted \n            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;\n            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.grid1Units             = abs(temp_diff_x(1));\n            tags.grid2Units             = abs(temp_diff_y(1));\n        end\n        tags.xcoordOfNormaliznPoint = '';\n        tags.ycoordOfNormaliznPoint = '';\n        tags.zcoordOfNormaliznPoint = '';\n    elseif PatientPosition==2                   % FFS\n        study_array                 = flipdim(study_array,3);\n        tags.hio                    = 'OUT';\n        tags.pos                    = 'NOSE UP';\n        if strcmpi('CT',type)~=1\n%             xmesh                       = xmesh;\n            xmesh                       = -xmesh;%DK \n            ymesh                       = -ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted\n%             tags.coord1OFFirstPoint     = xmesh(1);\n            tags.coord1OFFirstPoint     = -xmesh(1);%DK\n            tags.coord2OFFirstPoint     = ymesh(1);\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.horizontalGridInterval = temp_diff_x(1);\n            tags.verticalGridInterval   = temp_diff_y(1);\n        else\n            tags.originalCTxmesh        = xmesh;\n            tags.originalCTymesh        = ymesh;\n            tags.originalCTzmesh        = zmesh;\n            xmesh                       = xmesh;\n            ymesh                       = -ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted\n            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;\n            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.grid1Units             = abs(temp_diff_x(1));\n            tags.grid2Units             = abs(temp_diff_y(1));\n        end\n        tags.xcoordOfNormaliznPoint = '';\n        tags.ycoordOfNormaliznPoint = '';\n        tags.zcoordOfNormaliznPoint = '';\n    elseif PatientPosition==3                   % HFP\n        study_array                 = flipdim(study_array,3);\n        tags.hio                    = 'IN';\n        tags.pos                    = 'NOSE DOWN';\n        if strcmpi('CT',type)~=1\n            xmesh                       = -xmesh;\n            ymesh                       = ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted \n            tags.coord1OFFirstPoint     = xmesh(1);\n            tags.coord2OFFirstPoint     = ymesh(1);\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.horizontalGridInterval = temp_diff_x(1);\n            tags.verticalGridInterval   = temp_diff_y(1);\n        else\n            tags.originalCTxmesh        = xmesh;\n            tags.originalCTymesh        = ymesh;\n            tags.originalCTzmesh        = zmesh;\n            xmesh                       = -xmesh;\n            ymesh                       = ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted \n            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;\n            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.grid1Units             = abs(temp_diff_x(1));\n            tags.grid2Units             = abs(temp_diff_y(1));\n        end\n        tags.xcoordOfNormaliznPoint = '';\n        tags.ycoordOfNormaliznPoint = '';\n        tags.zcoordOfNormaliznPoint = '';\n    else                                        % FFP\n        study_array                 = flipdim(study_array,3);\n        tags.hio                    = 'OUT';\n        tags.pos                    = 'NOSE DOWN';\n        if strcmpi('CT',type)~=1\n            xmesh                       = -xmesh;\n            ymesh                       = ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted\n            tags.coord1OFFirstPoint     = xmesh(1);\n            tags.coord2OFFirstPoint     = ymesh(1);\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.horizontalGridInterval = temp_diff_x(1);\n            tags.verticalGridInterval   = temp_diff_y(1);\n        else\n            tags.originalCTxmesh        = xmesh;\n            tags.originalCTymesh        = ymesh;\n            tags.originalCTzmesh        = zmesh;\n            xmesh                       = -xmesh;\n            ymesh                       = ymesh;\n            zmesh                       = -zmesh;\n            zmesh                       = flipdim(zmesh,1);\n            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted\n            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;\n            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;\n            temp_diff_x                 = diff(xmesh);\n            temp_diff_y                 = diff(ymesh);\n            tags.grid1Units             = abs(temp_diff_x(1));\n            tags.grid2Units             = abs(temp_diff_y(1));\n        end\n        tags.xcoordOfNormaliznPoint = '';\n        tags.ycoordOfNormaliznPoint = '';\n        tags.zcoordOfNormaliznPoint = '';\n    end\nelse\n    if PatientPosition==1                       % HFS flip dimensions\n        xmesh                       = xmesh;\n        ymesh                       = -ymesh;\n        zmesh                       = -zmesh;\n        for jj=1:size(study_array,1)            % loop though the number of VOIs\n            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections\n                % reverse Z\n                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);\n                % reverse Y\n                study_array{jj,2}{kk}(:,2)=-study_array{jj,2}{kk}(:,2);\n            end\n        end\n    elseif PatientPosition==2                   % FFS flip dimensions\n        xmesh                       = xmesh;\n        ymesh                       = -ymesh;\n        zmesh                       = -zmesh;\n        for jj=1:size(study_array,1)            % loop though the number of VOIs\n            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections\n                % reverse Z\n                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);\n                % reverse Y\n                study_array{jj,2}{kk}(:,2)=-study_array{jj,2}{kk}(:,2);\n            end\n        end\n    elseif PatientPosition==3                   % HFP nothing to do\n        xmesh                       = -xmesh;            \n        ymesh                       = ymesh;\n        zmesh                       = -zmesh;\n        for jj=1:size(study_array,1)            % loop though the number of VOIs\n            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections\n                % reverse Z\n                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);\n                % reverse X\n                study_array{jj,2}{kk}(:,1)=-study_array{jj,2}{kk}(:,1);\n            end\n        end\n    else\n        xmesh                       = -xmesh;            \n        ymesh                       = ymesh;\n        zmesh                       = -zmesh;\n        for jj=1:size(study_array,1)            % loop though the number of VOIs\n            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections\n                % reverse Z\n                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);\n                % reverse X\n                study_array{jj,2}{kk}(:,1)=-study_array{jj,2}{kk}(:,1);\n            end\n        end\n    end\nend\n    \n% Return data\nstudy{2,1}=study_array;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/dicomrt2cerr/dicomrt_d2c_coordsystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.2170314554492201}}
{"text": "function proposals = genProposalsByOrientation(img, region, regionPerim, estimated_orientation, region_comp_infos)\n    global param;\n    \n    if(isnan(estimated_orientation))\n        proposals = zeros(0, 9);\n        return\n    end\n    \n    [comp_cluster_ind, ~] = compCluster(img, region_comp_infos, ...\n                                                    estimated_orientation, ...\n                                                    param.minCompHeightSimilarity, ...\n                                                    param.maxCompOrientationDiff, ...\n                                                    param.minIoUDiff);   \n\n    clusterIdx = unique(comp_cluster_ind);\n    clusterCount = length(clusterIdx);\n    proposals = zeros(clusterCount, 9);\n    confident_idx = false(clusterCount, 1);\n    \n    for c = 1 : clusterCount\n        clusterCompInfos = region_comp_infos(comp_cluster_ind == clusterIdx(c));\n        if(length(clusterCompInfos) > 0)\n            confident_idx(c) = true;\n            proposals(c, 1 : 8) = getProposal(img, region, regionPerim, clusterCompInfos, estimated_orientation);\n            proposals(c, 9) = estimated_orientation;\n        end\n    end\n    \n    proposals = proposals(confident_idx, :);\n    \n    %% show proposals\n    if true && param.debug\n        imshow(img);\n        hold on;\n        for i = 1 : clusterCount\n            x_arr = [proposals(i, 1 : 2 : 8), proposals(i, 1)];\n            y_arr = [proposals(i, 2 : 2 : 8), proposals(i, 2)];\n\n            plot(x_arr, y_arr, 'color', rand(3,1));\n        end\n        hold off;\n    end\n    \n    %% show clusters\n    if false && param.debug\n        debug_bbox_gathered = zeros(0, 4);\n        color_gathered = zeros(0, 3);\n        for c = 1: clusterCount\n            clusterCompInfos = region_comp_infos(comp_cluster_ind == clusterIdx(c));\n            debug_bbox = zeros(length(clusterCompInfos), 4);\n            color = repmat(rand(1,3), length(clusterCompInfos), 1);\n\n            for d_i = 1 : length(clusterCompInfos)\n                debug_bbox(d_i,:) = clusterCompInfos{d_i}.box;\n            end\n            \n            debug_bbox_gathered = cat(1, debug_bbox_gathered, debug_bbox);\n            color_gathered = cat(1, color_gathered, color);\n        end\n        show_bbox(img, debug_bbox_gathered, color_gathered);\n    end\nend\n\nfunction [comp_cluster_ind, clusterCount] = compCluster(img, region_comp_infos, estimated_orientation, minCompHeightSimilarity, maxCompOrientationDiff, minIoUDiff)\n    global param;\n    \n    compCount = length(region_comp_infos);\n    \n    if(compCount == 0)\n        comp_cluster_ind = zeros(0, 1);\n        clusterCount = 0;\n        return;\n    end\n    \n    if(compCount == 1)\n        comp_cluster_ind = ones(1,1);\n        clusterCount = 1;\n        return;\n    end\n    \n    comp_cluster_ind = zeros(compCount, 1, 'uint16');\n    clusterCount = 0;\n    \n    box4d = zeros(compCount, 4);\n    heights = zeros(compCount, 1);\n    \n    boxCenter = zeros(compCount, 2);\n    boxCenter_U = zeros(compCount, 2);\n    boxCenter_D = zeros(compCount, 2);\n    boxCenter_L = zeros(compCount, 2);\n    boxCenter_R = zeros(compCount, 2);\n\n    for i = 1 : compCount\n        box4d(i, :) = region_comp_infos{i}.box;\n        [rectX, rectY, ~, ~, sideLenght] = computeMergedBox(box4d(i, :));\n        [~, heights(i)] = findWidthAndHeight(rectX, rectY, sideLenght, estimated_orientation);\n        \n        boxCenter(i, 2) = round(box4d(i, 1) + 0.5*box4d(i, 3));\n        boxCenter(i, 1) = round(box4d(i, 2) + 0.5*box4d(i, 4));\n        \n        boxCenter_U(i, 2) = round(box4d(i, 1) + 0.5*box4d(i, 3));\n        boxCenter_U(i, 1) = box4d(i, 2);\n        \n        boxCenter_D(i, 2) = round(box4d(i, 1) + 0.5*box4d(i, 3));\n        boxCenter_D(i, 1) = box4d(i,2) + box4d(i,4) - 1;\n        \n        boxCenter_L(i, 2) = box4d(i,1);\n        boxCenter_L(i, 1) = round(box4d(i, 2) + 0.5*box4d(i, 4));\n        \n        boxCenter_R(i, 2) = box4d(i,1) + box4d(i,3) - 1;\n        boxCenter_R(i, 1) = round(box4d(i, 2) + 0.5*box4d(i, 4));\n    end\n    \n    heightSimilarity = zeros(compCount);\n    IoUDiff = zeros(compCount);\n    orientationDiffOfBox = zeros(compCount);\n    dists = zeros(compCount);\n\n    for i = 1 : compCount\n        \n        %% Compute height similarity\n        heightSimilarity(i,:) = min( ...\n                                    min(box4d(i, 4), box4d(:, 4)) ./ max(box4d(i, 4), box4d(:, 4)), ...\n                                    min(box4d(i, 3), box4d(:, 3)) ./ max(box4d(i, 3), box4d(:, 3)));\n       %% Compute IoU diff\n        intArea = rectint(box4d(i,:), box4d);\n        unionArea = box4d(i,3) * box4d(i,4) + box4d(:, 3).* box4d(:, 4);\n        IoUDiff(i, :) = intArea ./ unionArea';\n        \n        %% Compute orientation diff of box\n        orientationDiff_U = computeOrientationDiff(boxCenter_U, boxCenter_U(i,:), estimated_orientation);\n        orientationDiff_D = computeOrientationDiff(boxCenter_D, boxCenter_D(i,:), estimated_orientation);\n        orientationDiff_L = computeOrientationDiff(boxCenter_L, boxCenter_L(i,:), estimated_orientation);\n        orientationDiff_R = computeOrientationDiff(boxCenter_R, boxCenter_R(i,:), estimated_orientation);\n        orientationDiffOfBox(i, :) = min(min(orientationDiff_U, orientationDiff_D), ...\n                                    min(orientationDiff_L, orientationDiff_R)); \n                                \n        %% Compute dist\n        dists(i, :) = ((boxCenter(:, 1) - boxCenter(i, 1)).^2 + (boxCenter(:, 2) - boxCenter(i,2)).^2).^0.5;\n    end\n    \n    if true && param.debug\n        imshow(img);\n        for i = 1 : compCount\n            rectangle('position', box4d(i, :), 'edgecolor','y');\n        end\n    end\n    \n    for i = 1 : compCount\n        if comp_cluster_ind(i) == 0 \n            clusterCount = clusterCount + 1;\n            current_cluster_comp_ind = false(compCount, 1);\n            current_cluster_comp_ind(i) = 1;\n            \n            isUpdate = true;\n            while isUpdate\n                isUpdate = false;\n                \n                %% Compute boxCenter of merged bbox\n                mergedBoxCenter_U = [mean(box4d(current_cluster_comp_ind, 2)), ...\n                                        mean(box4d(current_cluster_comp_ind, 1) + 0.5*box4d(current_cluster_comp_ind, 3))];\n\n                mergedBoxCenter_D = [mean(box4d(current_cluster_comp_ind, 2) + box4d(current_cluster_comp_ind, 4) - 1), ...\n                                        mean(box4d(current_cluster_comp_ind, 1) + 0.5*box4d(current_cluster_comp_ind, 3))];\n                                        \n                mergedBoxCenter_L = [mean(box4d(current_cluster_comp_ind, 2) + 0.5*box4d(current_cluster_comp_ind, 4)), ...\n                                        mean(box4d(current_cluster_comp_ind, 1))];\n                                    \n                mergedBoxCenter_R = [mean(box4d(current_cluster_comp_ind, 2) + 0.5*box4d(current_cluster_comp_ind, 4)), ...\n                                        mean(box4d(current_cluster_comp_ind, 1) + box4d(current_cluster_comp_ind, 3) - 1)];\n                \n                %% Compute orientation diff\n                orientationDiff_U = computeOrientationDiff(boxCenter_U, mergedBoxCenter_U, estimated_orientation);\n                orientationDiff_D = computeOrientationDiff(boxCenter_D, mergedBoxCenter_D, estimated_orientation);\n                orientationDiff_L = computeOrientationDiff(boxCenter_L, mergedBoxCenter_L, estimated_orientation);\n                orientationDiff_R = computeOrientationDiff(boxCenter_R, mergedBoxCenter_R, estimated_orientation);\n\n                orientationDiff = min(min(orientationDiff_U, orientationDiff_D), min(orientationDiff_L, orientationDiff_R))';\n                \n                heightSimilarity_rule = heightSimilarity(current_cluster_comp_ind,:) > minCompHeightSimilarity;\n                orientationDiff_rule = orientationDiff < maxCompOrientationDiff;\n                IoUDiff_rule = IoUDiff(current_cluster_comp_ind, :) > minIoUDiff;\n                orientationDiffOfBox_rule = heightSimilarity_rule ...\n                                            & (orientationDiffOfBox(current_cluster_comp_ind, :) < maxCompOrientationDiff) ...\n                                            & (dists(current_cluster_comp_ind, :) < param.maxDistRatio * mean(box4d(current_cluster_comp_ind, 4)));\n                \n                spatial_rule = ((sum(heightSimilarity_rule, 1) > 0) & sum(orientationDiffOfBox_rule, 1) > 0) ...\n                                | (sum(IoUDiff_rule, 1) > 0) ...\n                                | (orientationDiff_rule & (sum(heightSimilarity_rule, 1) > 0));\n                %spatial_rule = sum((heightSimilarity_rule & orientationDiff_rule) | IoUDiff_rule, 1) > 0;\n                \n                satisfiedComp = spatial_rule' ...\n                            & (~current_cluster_comp_ind);\n                \n                satisfiedIdx = find(satisfiedComp);\n                if(~isempty(satisfiedIdx))\n                    isUpdate = true;\n                    current_cluster_comp_ind(satisfiedIdx) = 1;\n%                     x1_tmp = min(min(box4d(satisfiedIdx, 1)), ...\n%                                  mergedBox(1));\n%                     x2_tmp = max(max(box4d(satisfiedIdx, 1) + box4d(satisfiedIdx, 3) - 1), ...\n%                                  mergedBox(1) + mergedBox(3) - 1);\n%                     y1_tmp = min(min(box4d(satisfiedIdx, 2)), ...\n%                                  mergedBox(2));\n%                     y2_tmp = max(max(box4d(satisfiedIdx, 2) + box4d(satisfiedIdx, 4) - 1), ...\n%                                  mergedBox(2) + mergedBox(4) - 1);\n%                     mergedBox(1) = x1_tmp;\n%                     mergedBox(2) = y1_tmp;\n%                     mergedBox(3) = x2_tmp - x1_tmp + 1;\n%                     mergedBox(4) = y2_tmp - y1_tmp + 1;\n\n\n                    if true &&  param.debug\n                        clusterCompInfos = region_comp_infos(current_cluster_comp_ind);\n                        color = zeros(length(clusterCompInfos), 3);\n                        color(:, 2) = 1;\n                        color(1, :) = [1, 0, 0];\n                        imshow(img);\n                        for d_i = 1 : length(clusterCompInfos)\n                           rectangle('position', clusterCompInfos{d_i}.box, 'edgecolor', color(d_i,:));\n                        end\n                    end\n                end\n            end\n            comp_cluster_ind(current_cluster_comp_ind) = clusterCount;\n        end\n    end\nend\n", "meta": {"author": "stupidZZ", "repo": "FCN_Text", "sha": "4bfa6736adf59924f766c3825bb145054ddc439d", "save_path": "github-repos/MATLAB/stupidZZ-FCN_Text", "path": "github-repos/MATLAB/stupidZZ-FCN_Text/FCN_Text-4bfa6736adf59924f766c3825bb145054ddc439d/ProposalGeneration/genProposalsByOrientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.2170314471619018}}
{"text": "% *************************************************************************\n% Video Super-Resolution with Convolutional Neural Networks\n% \n% main VSRnet script, includes the interface to the caffe framework \n% do not run this script directly. call it from VSRnet_demo instead\n% \n% Version 1.0\n%\n% Created by:   Armin Kappeler\n% Date:         02/19/2016\n%\n% *************************************************************************\n\n%% more parameters (do not change, unless you know what you are doing)\n\nBORDERSIZE = 8; %4+2+2; %border size = sum of all zeropaddings in model def file\n\n% parameters for LOW_MEMORY_MODE=2\nParam.patchSize = 36;\nParam.stride = 20; \nParam.outputPatchSize = 20;\nParam.zeropadding = 1;\n\n%% Init VSRnet configuration files\n\nif (MOTIONCOMPENSATION==false && UPSCALE_FACTOR ~= 3 && ADAPTIVEMOTIONCOMPENSATION==false)\n    error('Error: MOTIONCOMPENSATION=false is only available for upscale factor 3. Please either set UPSCALEFACTOR=3 or MOTIONCOMPENSATION=true')\nend\nif (MOTIONCOMPENSATION==false && ADAPTIVEMOTIONCOMPENSATION==true)\n    display('The MOTIONCOMPENSATION flag is ignored because ADAPTIVEMOTIONCOMPENSATION=true')\nend\n\nif MOTIONCOMPENSATION \n    model_def_file_template = ['models/u' num2str(UPSCALE_FACTOR) '/superres_deploy.prototxt'];\n    model_file =    ['models/u' num2str(UPSCALE_FACTOR) '/SRnet_train_iter_200000.caffemodel'];  \nelse\n    model_def_file_template = ['models/u' num2str(UPSCALE_FACTOR) '_noMotionCompensation/superres_deploy.prototxt'];\n    model_file =    ['models/u' num2str(UPSCALE_FACTOR) '_noMotionCompensation/SRnet_train_iter_200000.caffemodel'];      \nend\nmodel_def_file = 'models/tmp/tmp_superres_deploy.prototxt';\n\n%% preprocess input data\n\nTESTVIDEO_PATH\nif PREPROCESSED_INPUT\n    load(TESTVIDEO_PATH);\n\n    if TESTONLY1FRAME       \n        input_data{1} = input_data{1}(:,:,:,TESTONLY1FRAME);\n        im_gt = im_gt(:,:,:,TESTONLY1FRAME);\n    end\nelse\n    data = load(TESTVIDEO_PATH);\n    if TESTONLY1FRAME \n        data.frames = data.frames(:,:,TESTONLY1FRAME:TESTONLY1FRAME+4);\n    end\n    [input_data,idx_gt] = preprocess_frames(data.frames,UPSCALE_FACTOR,MOTIONCOMPENSATION,ADAPTIVEMOTIONCOMPENSATION);\n\nend\nim_bic = permute(input_data{1}(:,:,3,:),[2,1,3,4])*255;\n\n%% caffe setup\n        \nbatchsize = size(input_data{1},4);\nimageSize = [ size(input_data{1},2), size(input_data{1},1)];\nParam.inputImgSize = imageSize;\n\ncaffe.reset_all();\n\nif USE_GPU\n  caffe.set_mode_gpu();\n  caffe.set_device(GPU_ID);\nelse\n  caffe.set_mode_cpu();\nend\n\nif LOW_MEMORY_MODE==1\n    imagecut = imageSize(1)/2;\n    imageSize(1) = imageSize(1)/2 + BORDERSIZE;\nelseif LOW_MEMORY_MODE==2\n    imageSize = [Param.patchSize Param.patchSize];                             \nend\n\nchange_caffe_image_input_size(model_def_file_template,model_def_file,imageSize,1)\nnet = caffe.Net(model_def_file, model_file, 'test');\n\n%% do forward pass\n\ntic;  \noutput = zeros(size(im_bic,2),size(im_bic,1),size(im_bic,3),size(im_bic,4));\nfor imgIdx = 1:size(im_bic,4)\n    display(['Superresolve frame ' num2str(imgIdx)]);\n    if LOW_MEMORY_MODE==1 % divide image in two parts to reduce memory usage\n        tmp1 = net.forward({input_data{1}(:,1:imagecut + BORDERSIZE,:,imgIdx)});\n        tmp2 = net.forward({input_data{1}(:,imagecut+1-BORDERSIZE:end,:,imgIdx)}); \n        output(:,:,:,imgIdx) = cat(2,tmp1{1}(:,1:imagecut,:,:),tmp2{1}(:,BORDERSIZE+1:end,:,:));\n    elseif LOW_MEMORY_MODE==2 % process the image patchwise\n        input_data_new = patchify(input_data{1}(:,:,:,imgIdx), Param);\n        if Param.zeropadding==1\n            output_raw = zeros(size(input_data_new,1),size(input_data_new,2),1,size(input_data_new,4));\n        else\n            output_raw = zeros(Param.outputPatchSize,Param.outputPatchSize,1,size(input_data_new,4));\n        end\n        for pIdx = 1:size(input_data_new,4)\n            output_raw_tmp = net.forward({input_data_new(:,:,:,pIdx)});  \n            output_raw(:,:,:,pIdx) = output_raw_tmp{1};\n            if mod(pIdx,1000)==0\n                fprintf('.');\n            end\n        end   \n        fprintf('\\n');\n        output(:,:,:,imgIdx) = depatchify(output_raw,Param);\n    else\n        tmp = net.forward({input_data{1}(:,:,:,imgIdx)});\n        output(:,:,:,imgIdx) = tmp{1};\n    end\nend\ntoc;\n\nim_SR = output;\nim_SR = permute(im_SR,[2 1 3 4]);\nim_SR = im_SR*255;  \n\nsave(RESULTFILE_PATH,'im_SR','model_file','TESTVIDEO_PATH');\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/VSRnet/functions/main_VSRnet_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21703143887458373}}
{"text": "% DEMHSVARGPLVMREGRESSION A script to run deep GP regression.\n%\n% This is a generic demo. You can replace the data used here with your own\n% data and run it (ie Ytr{1} has to be the observed data and inpX has to be\n% your observed labels).\n%\n% To configure the deepGP used here, do the following:\n%   1. If any of the fields you want to change appear in this demo in the\n%   \"configuring the deep gp\" section, they change it directly there.\n%   2. If the field you're looking for is not there, then check the available\n%    configuration options in hsvargplvm_init.m. The way this works, is that\n%    you just need to overwrite the corresponding workspace variables.\n%    e.g. if in hsvargplvm_init.m you see a field \"fixInducing\", you can\n%    overwrite this field by just calling this demo as:\n%    >> fixInducing = true; demHsvargplvmClassification\n%   3. If the field you're looking for is not in hsvargplvm_init.m, then\n%   check (in this order) svargplvm_init.m and vargplvm_init.m, again\n%   overwritting the configuration by specifying the variable to exist, as\n%   above.\n%    \n% SEEALSO: demHsvargplvmClassification.m\n%\n% COPYRIGHT: Andreas Damianou, 2014\n% DEEPGP\n\n%% ------ CONFIGURING THE DEEP GP\n%--- Mandatory configurations\nif ~exist('Ytr', 'var'), error('You need to specify your outputs in Ytr{1}=...'); end\nif ~exist('inpX', 'var'), error('You need to specify your inputs in inpX=...'); end\n\n%--- Optional configurations: Whatever configuration variable is not already set (ie does not exist\n% as a variable in the workspace) is set to a default value.\nif ~exist('experimentNo'), experimentNo = 404; end\nif ~exist('K'), K = 30; end\nif ~exist('Q'), Q = 6; end\nif ~exist('baseKern'), baseKern = 'rbfardjit'; end % {'rbfard2','white','bias'}; end\n% This is called \"dynamics\" and \"time\" for historical reasons.. It actually refers to a coupling GP in the uppermost level\nif ~exist('dynamicsConstrainType'), dynamicsConstrainType = {'time'}; end\nstackedOpt = [];\nif exist('stackedInitVardistIters', 'var'), stackedOpt.stackedInitVardistIters=stackedInitVardistIters; end\nif exist('stackedInitIters', 'var'), stackedOpt.stackedInitIters=stackedInitIters; end\nif exist('stackedInitSNR', 'var'), stackedOpt.stackedInitSNR=stackedInitSNR; end\nif exist('stackedInitK', 'var'), stackedOpt.stackedInitK=stackedInitK; end\nif ~exist('initXOptions', 'var'), initXOptions = []; end\n\n% Initialise script based on the above variables. This returns a struct\n% \"globalOpt\" which contains all configuration options\nhsvargplvm_init;\n\n% Automatically calibrate initial variational covariances - better to not change that\nglobalOpt.vardistCovarsMult = [];\n\n[options, optionsDyn] = hsvargplvmOptions(globalOpt, inpX);\n\n%% ------------- Initialisation and model creation\n% Initialise latent spaces, unless the user already did that\nif ~(iscell(options.initX) && prod(size(options.initX{1})) > 1)\n    [globalOpt, options, optionsDyn, initXOptions] = hsvargplvmRegressionInitX(globalOpt, options, optionsDyn, inpX, Ytr, stackedOpt);\nend\n\n\n% Create the deep GP based on the model options, global options\n% (configuration) and options for initialising the latent spaces X\nmodel = hsvargplvmModelCreate(Ytr, options, globalOpt, initXOptions);\n\n% Since we do regression, we need to add a GP on the parent node. This GP\n% couples the inputs and is parametrised by options in a struct \"optionsDyn\".\nmodel = hsvargplvmAddParentPrior(model, globalOpt, optionsDyn);\n\n\n%-- We have the option to not learn the inducing points and/or fix them to\n% the given inputs.\n% Learn inducing points? (that's different to fixInducing, ie tie them\n% to X's, if learnInducing is false they will stay in their original\n% values, ie they won't constitute parameters of the model).\nif exist('learnInducing') && ~learnInducing\n    model = hsvargplvmPropagateField(model, 'learnInducing', false);\nend\n%--\n\nif globalOpt.fixInducing && globalOpt.fixInducing\n    model = hsvargplvmPropagateField(model, 'fixInducing', true);\n    for m=1:model.layer{end}.M % Not implemented yet for parent node\n        model.layer{end}.comp{m}.fixInducing = false;\n    end\nend\n\n\n%!!!!!!!!!!!!!!!!!!!!!!!!-----------------------\nif exist('DEBUG_entropy','var') && DEBUG_entropy\n    model.DEBUG_entropy = true;for itmp=1:model.H, model.layer{itmp}.DEBUG_entropy = true; end\nend\n        \nparams = hsvargplvmExtractParam(model);\nmodel = hsvargplvmExpandParam(model, params);\nmodel.globalOpt = globalOpt;\n% Computations can be made in parallel, if option is activated\nmodel.parallel = globalOpt.enableParallelism;\n\nfprintf('# Scales after init. latent space:\\n')\nhsvargplvmShowScales(model,false);\n%% OPTIMISATION\n[model,modelPruned, modelInitVardist] = hsvargplvmOptimiseModel(model, true, true);\n\n% If you decide to train for further iterations...\n% modelOld = model; [model,modelPruned, ~] = hsvargplvmOptimiseModel(model, true, true, [], {0, [100]});\n\n\n", "meta": {"author": "SheffieldML", "repo": "deepGP", "sha": "f72410a0fb354451f2bf58cfe247d2b5d3b08e58", "save_path": "github-repos/MATLAB/SheffieldML-deepGP", "path": "github-repos/MATLAB/SheffieldML-deepGP/deepGP-f72410a0fb354451f2bf58cfe247d2b5d3b08e58/deepGP/matlab/demHsvargplvmRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2169759405072778}}
{"text": "function aedat = RescaleTime(aedat, factor, packetTimeStamps, dataTimeStamps)\n\n%{\nStretches or squeezes time by multiplying all timestamps by a factor.\nThis affects both data.<dataType>.timeStamp and info.packetTimeStamps,\nby default, overridden by the optional flags. \n%}\n\ndbstop if error\n\nif ~exist('packetTimeStamps', 'var') || packetTimeStamps\n\n    if ~isfield(aedat, 'info') || ~isfield(aedat.info, 'packetTimeStamps')\n        disp('No packet timestamps found')\n    else\n        aedat.info.packetTimeStamps = uint64(double(aedat.info.packetTimeStamps * factor));        \n    end\nend\n\nif ~exist('dataTimeStamps', 'var') || dataTimeStamps\n\n    if ~isfield(aedat, 'data')\n        disp('No data found')\n    else\n\n        % Special\n        if isfield(aedat.data, 'special')\n            aedat.data.special.timeStamp = uint64(double(aedat.data.special.timeStamp * factor));\n        end\n\n        % Polarity\n        if isfield(aedat.data, 'polarity')\n            aedat.data.polarity.timeStamp = uint64(double(aedat.data.polarity.timeStamp * factor));\n        end\n\n        % Frames\n        % This assumes that timestamps have been simplified to aedat2 standard, if\n        % they came from aedat3 file\n        if isfield(aedat.data, 'frame')\n            aedat.data.frame.timeStampStart = uint64(double(aedat.data.frame.timeStampStart * factor));\n            aedat.data.frame.timeStampEnd = uint64(double(aedat.data.frame.timeStampEnd * factor));\n        end\n\n        % Imu6\n        if isfield(aedat.data, 'imu6')\n            aedat.data.imu6.timeStamp = uint64(double(aedat.data.imu6.timeStamp * factor));\n        end\n\n        if isfield(aedat.data, 'sample')\n            aedat.data.sample.timeStamp = uint64(double(aedat.data.sample.timeStamp * factor));\n        end\n\n        if isfield(aedat.data, 'ear')\n            aedat.data.ear.timeStamp = uint64(double(aedat.data.ear.timeStamp * factor));\n        end\n\n        if isfield(aedat.data, 'point1D')\n            aedat.data.point1D.timeStamp = uint64(double(aedat.data.point1D.timeStamp * factor));\n        end\n\n        if isfield(aedat.data, 'point2D')\n            aedat.data.point2D.timeStamp = uint64(double(aedat.data.point2D.timeStamp * factor));\n        end\n\n        if isfield(aedat.data, 'point3D')\n            aedat.data.point3D.timeStamp = uint64(double(aedat.data.point3D.timeStamp * factor));\n        end\n\n        aedat = FindFirstAndLastTimeStamps(aedat);\n\n        if isfield(aedat.info, 'packetTimeStamps')\n            aedat.info.packetTimeStamps = uint64(double(aedat.info.packetTimeStamps * factor));\n        end\n    end\nend", "meta": {"author": "panpanfei", "repo": "Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "sha": "aabdd6ae323726132b0e0592ce151461e3ad7c5a", "save_path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera/Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera-aabdd6ae323726132b0e0592ce151461e3ad7c5a/event_cvpr_github/read_data/code/AedatTools-master/Matlab/RescaleTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21697592908316388}}
{"text": "\n\nfunction output_info=cnn_layer_dagnn_wrapper_forward(input_info, layer, work_info_batch)\n\n   \nrun_trn=work_info_batch.ref.run_trn;\ngroup_info=get_current_work_group_idx(work_info_batch);\n\nnet=group_info.dag_net;\n\nif input_info.is_group_data\n    input_var_names=layer.input_var_names;\n    input_num=length(input_var_names);\n    input_data=cell(0);\n    for v_idx=1:input_num\n        one_x=input_info.data_child_groups{v_idx}.x;\n        assert(~isempty(one_x));\n        input_data=cat(2, input_data, {input_var_names{v_idx}, one_x});\n        assert(~isempty(one_x));\n    end\nelse\n    assert(length(layer.input_var_names)==1);\n    input_var_name=layer.input_var_names{1};\n    input_data={input_var_name, input_info.x};\n    assert(~isempty(input_info.x));\nend\n\n\ndo_bp_run=group_info.net_info.ref.do_bp && run_trn;\n\nif do_bp_run\n    \n    net.mode = 'normal' ;\n    net.do_forward_trn(input_data);\n    \nelse\n    \n    net.mode = 'test' ;\n    net.eval(input_data) ;\nend\n\n\noutput_var_names=layer.output_var_names;\noutput_num=length(output_var_names);\noutput_var_idxes=zeros(output_num,1);\nfor o_idx=1:output_num\n    output_var_idxes(o_idx)=net.getVarIndex(output_var_names{o_idx});\nend\nassert(all(output_var_idxes>0));\n\n\nif layer.use_single_output\n    output_x = net.vars(output_var_idxes(end)).value ;\n\n    output_info=[];\n    output_info.is_group_data=false;\n    output_info.x=output_x;\n    \n    assert(~isempty(output_info.x));\nelse\n\n    output_num=length(output_var_idxes);\n    data_child_groups=cell(output_num, 1);\n    for o_idx=1:output_num\n        data_child_groups{o_idx}.is_group_data=false;\n        data_child_groups{o_idx}.x = net.vars(output_var_idxes(o_idx)).value;\n        \n        assert(~isempty(data_child_groups{o_idx}.x));\n    end\n\n    output_info=[];\n    output_info.is_group_data=true;\n    output_info.data_child_groups=data_child_groups;\nend\n\n\noutput_info=my_init_input_info(output_info);\n\n\n% do the print here, generate the network graph :\n\n% for resnet:\n% input_vars=net.getInputs;\n% net.print({input_vars{1}, [400 400 3]}, 'Format', 'dot');\n\n% for cascaded refinenets\n% input_vars=net.getInputs;\n% net.print({input_vars{1}, [13 13 2048], input_vars{2}, [25 25 1024], input_vars{3}, [50 50 512], input_vars{4}, [100 100 256]}, 'Format', 'dot');\n\n\nend\n\n\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/cnn_layer_dagnn_wrapper_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21678555428705867}}
{"text": "function [curYawTheta, curHeight] = get_hdc_initial_value()\n%     NeuroSLAM System Copyright (C) 2018-2019 \n%     NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n%     Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n%     The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n%     The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n%     Reference:\n%     Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n%     \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n    \n    % set the initial position in the hdcell network\n%     global YAW_HEIGHT_HDC_Y_DIM;\n%     global YAW_HEIGHT_HDC_H_DIM;\n%     curYawTheta = floor(YAW_HEIGHT_HDC_Y_DIM / 2);  % in 1:36\n    curYawTheta = 1;  % in 1:36\n    \n%     curHeight = floor(YAW_HEIGHT_HDC_H_DIM / 2);  % in 1:36\n    curHeight = 1;  % in 1:36\nend", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/01_conjunctive_pose_cells_network/yaw_height_hdc_network/get_hdc_initial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21678555428705865}}
{"text": "function model = yalmip2sdpt3(interfacedata)\n[blk,A,C,b,oldKs]=sedumi2sdpt3(interfacedata.F_struc(:,1),-interfacedata.F_struc(:,2:end),-interfacedata.c,interfacedata.K,interfacedata.options.sdpt3.smallblkdim);\ninterfacedata.options.sdpt3.printyes=double(interfacedata.options.verbose);\ninterfacedata.options.sdpt3.expon=interfacedata.options.sdpt3.expon(1);\n\nmodel.blk = blk;\nmodel.A = A;\nmodel.C = C;\nmodel.b = b;\nmodel.ops = interfacedata.options.sdpt3;", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/yalmip2sdpt3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.21663503961660144}}
{"text": "function [D info] = ojw_stereo(images, P, disps, sz, options)\n%OJW_STEREO  Global stereo with 2nd-order smoothness prior & occlusion model\n%\n%   [D info] = ojw_stereo(images, P, disps, sz, options)\n%\n% Generates a disparity (1/depth) map for the first input image. This\n% algorithm implements a \"global\" stereo algorithm, with asymmetrical\n% occlusion modelling, using an alpha-expansion graph cuts style approach,\n% but with arbitrary disparity proposals.\n%\n%IN:\n%   images - 1xN cell array of input images, the reference image being\n%            images{1}.\n%   P - 3x4xN array of projection matrices for the input images, relative\n%       to the output image.\n%   disps - 1xM list of disparities to sample at.\n%   sz - 1x2 vector of output image dimensions: [H W].\n%   options - a structure containing the following input parameters:\n%       col_thresh - scalar noise parameter for data likelihood.\n%       occl_const - scalar occlusion cost.\n%       disp_thresh - scalar disparity threshold for smoothness prior.\n%       smoothness_kernel - index denoting which smoothness kernel to use.\n%                           1: truncated linear; 2: truncated quadratic.\n%       lambda_l - scalar smoothness prior weight for cliques crossing\n%                  segmentation boundaries.\n%       lambda_h - scalar smoothness prior weight for cliques not crossing\n%                  segmentation boundaries.\n%       seg_params - 1x3 vector of parameters for the mean-shift\n%                    over-segmentation of the reference image.\n%       visibility - boolean indicating whether to employ the geometrical\n%                    visbility contstraint.\n%       connect - scalar neighbourhood system of the graph, 4 or 8\n%                 connected.\n%       max_iters - scalar number of iterations to halt after, if\n%                   convergence is not achieved first.\n%       converge - scalar percentage decrease in energy per iteration at\n%                  which optimization stops.\n%       average_over - scalar number of iterations to average over when\n%                      checking convergence.\n%       contract - scalar number of QPBOP iterations to do.\n%       improve - scalar indicating which method to use to label unlabelled\n%                 nodes. 0: QPBO-F, 1: QPBOI-F, 2: QPBO-R, 3: QPBO-L,\n%                 4: QPBOI-R.\n%       independent - boolean indicating whether to use independent, or\n%                     merely strongly-connected, regions for improve\n%                     methods 2 & 4.\n%\n%OUT:\n%   D - HxW disparity map.\n%   info - structure containing other outputs from the algorithm.\n\n% $Id: ojw_stereo.m,v 1.5 2008/11/17 11:27:35 ojw Exp $\n\n% Crude check for a reference image\nif max(abs(P([1:6 9])-[1 0 0 0 1 0 1])) > 1e-12\n    error('First image must be reference image');\nend\n\n% Initialize data arrays\nR = images{1}(round(P(8))+(1:sz(1)),round(P(7))+(1:sz(2)),:);\nvals.I = images(2:end);\nvals.P = permute(P(:,:,2:end), [2 1 3]);\nvals.sz = sz;\ncolors = size(R, 3);\nnum_in = numel(images);\nRorig = uint8(R);\nif colors == 1\n    Rorig = repmat(Rorig, [1 1 3]);\nend\nvals.R = repmat(reshape(single(R), [], colors), [2 1]);\nvals.d_min = disps(end);\nvals.d_step = disps(1) - vals.d_min;\nvals.ndisps = numel(disps);\n\nT = reshape(uint32(1:prod(sz)), sz);\nif options.planar\n    % Use 2nd order smoothness prior\n    SEI = [reshape(T(1:end-2,:), 1, []) reshape(T(:,1:end-2), 1, []); ...\n           reshape(T(2:end-1,:), 1, []) reshape(T(:,2:end-1), 1, []); ...\n           reshape(T(3:end,:), 1, []) reshape(T(:,3:end), 1, [])];\n    if options.connect == 8\n        SEI = [SEI [reshape(T(1:end-2,1:end-2), 1, []) reshape(T(3:end,1:end-2), 1, []); ...\n                    reshape(T(2:end-1,2:end-1), 1, []) reshape(T(2:end-1,2:end-1), 1, []); ...\n                    reshape(T(3:end,3:end), 1, []) reshape(T(1:end-2,3:end), 1, [])]];\n    end\nelse\n    % Use 1st order smoothness prior\n    SEI = [reshape(T(1:end-1,:), 1, []) reshape(T(:,1:end-1), 1, []); ...\n           reshape(T(2:end,:), 1, []) reshape(T(:,2:end), 1, [])];\n    if options.connect == 8\n        SEI = [SEI [reshape(T(1:end-1,1:end-1), 1, []) reshape(T(2:end,1:end-1), 1, []); ...\n                    reshape(T(2:end,2:end), 1, []) reshape(T(1:end-1,2:end), 1, [])]];\n    end\nend\nclear T\n\n% Initialise display\nvals.show_output = options.show_output;\nif vals.show_output\n    vals.show_output = gcf;\n    set(0, 'CurrentFigure', vals.show_output);\n    subplot('Position', [0 0.5 1/3 0.5]);\n    sc(R, [0 255]);\nend\n\n% Segment the image using mean shift\ninfo.segment = vgg_segment_ms(Rorig, options.seg_params(1), options.seg_params(2), options.seg_params(3));\n% Find smoothness edges which don't cross segmentation boundaries\nEW = reshape(~any(diff(int32(info.segment(SEI))), 1), 1, []);\nEW = EW * options.lambda_h + ~EW * options.lambda_l;\nEW = EW * (num_in / ((options.connect==8) + 1));\nEW = reshape(repmat(EW, [4*(1+(options.planar~=0)) 1]), [], 1);\n\n% Set up values for ibr_fuse_depths\nvals.visibility = (options.visibility ~= 0) * 1e4;\nvals.improve = options.improve;\nvals.contract = options.contract;\nvals.independent = options.independent;\nvals.compress_graph = options.compress_graph;\n\n% Set up our robust kernels\nvals.ephoto = @(F) log(2) - log(exp(sum(F .^ 2, 2)*(-1/(options.col_thresh*colors)))+1);\nswitch options.smoothness_kernel\n    case 1\n        vals.esmooth = @(F) EW .* min(abs(F), options.disp_thresh);\n    case 2\n        EW = EW / options.disp_thresh;\n        vals.esmooth = @(F) EW .* min(F.^2, options.disp_thresh^2);\n    otherwise\n        error('Unknown smoothness kernel specified');\nend\nvals.occl_val = options.occl_const + log(2);\nvals.SEI = SEI;\nclear T SEI EW Rorig\n\nif nargout > 1\n    % Save parameters\n    info.params.disp_thresh = options.disp_thresh;\n    info.params.col_thresh = options.col_thresh;\n    info.params.occl_const = options.occl_const;\n    info.params.lambda_l = options.lambda_l;\n    info.params.lambda_h = options.lambda_h;\nend\n\nif isnumeric(options.proposal_method) && size(options.proposal_method, 1) == 1\n    % Use the proposal methods:\n    for a = options.proposal_method\n        switch a\n            case 0\n                % Ordered fronto-parallel\n                [D info.samedisc_optim] = ojw_stereo_optim(vals, @(n) 3, options);\n                info.samedisc_optim.D = D;\n            case 1\n                % SameUni (random fronto-parallel)\n                [D info.sameuni_optim] = ojw_stereo_optim(vals, @(n) 1, options);\n                info.sameuni_optim.D = D;\n            case 2\n                % SegPln (prototypical segment-based stereo proposals)\n                [Dproposals info.segpln_gen] = ojw_segpln(images, P, disps, R, options);\n                clear R\n                Dproposals = @(n) Dproposals(:,:,mod(n-1, size(Dproposals, 3))+1);\n                [D info.segpln_optim] = ojw_stereo_optim(vals, Dproposals, options);\n                clear Dproposals\n                info.segpln_optim.D = D;\n            case 3\n                % Smooth*\n                Dproposals = {info.segpln_optim.D, info.sameuni_optim.D, 2, 2, 2, 2};\n                Dproposals = @(n) Dproposals{mod(n-1, 6)+1};\n                [D info.smooth_optim] = ojw_stereo_optim(vals, Dproposals, options);\n                clear Dproposals\n                info.smooth_optim.D = D;\n            case 4\n                % Smooth\n                Dproposals = {D, 2};\n                Dproposals = @(n) Dproposals{(n>1)+1};\n                [D info.smooth2_optim] = ojw_stereo_optim(vals, Dproposals, options);\n                clear Dproposals\n                info.smooth2_optim.D = D;\n        end\n    end\nelse\n    % Input fixed set of proposals\n    if isnumeric(options.proposal_method)\n        Dproposals = @(n) options.proposal_method(:,:,mod(n-1, size(options.proposal_method, 3))+1);\n    else\n        Dproposals = options.proposal_method;\n    end\n    [D info.udprop_optim] = ojw_stereo_optim(vals, Dproposals, options);\n    clear Dproposals\n    info.udprop_optim.D = D;\nend\nreturn", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/external/imrender/ojw/ojw_stereo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3522017752483204, "lm_q1q2_score": 0.21663503464644102}}
{"text": "function [cnmfeAnalysisOutput] = computeCnmfeSignalExtraction(inputMovie,varargin)\n    % Wrapper function for CNMF-E, update for most recent versions.\n    % Biafra Ahanonu\n    % started: 2018.10.20 [16:38:24]\n    % Building off of demo_large_data_1p.m in CNMF-E github repo\n    % Most recent commit tested on: https://github.com/epnev/ca_source_extraction/commit/187bbdbe66bca466b83b81861b5601891a95b8d1\n    % https://github.com/epnev/ca_source_extraction/blob/master/demo_script_class.m\n    % inputs\n        % inputMovie - a string or a cell array of strings pointing to the movies to be analyzed (recommended).\n        % numExpectedComponents - number of expected components\n    % outputs\n        % cnmfAnalysisOutput - structure containing extractedImages and extractedSignals along with input parameters to the algorithm\n    % READ BEFORE RUNNING\n        % Get CVX from http://cvxr.com/cvx/doc/install.html\n        % Run the below commands in Matlab after unzipping\n        % cvx_setup\n        % cvx_save_prefs (permanently stores settings)\n\n    % changelog\n        % 2016.06.20 - updated to keep in line with recent changes to CNMF functions\n        % 2019.04.04 [11:07:21] - Updated to add many of the options to the varargin options structure for function for easier access in parent functions\n        % 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.\n    % TODO\n        %\n\n    import ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\n    % ========================\n    % OVERALL\n    % turn on parallel\n    options.nonCNMF.parallel = 1;\n    % Binary: 1 = run merging algorithms\n    options.runMerge = 1;\n    % Binary: 1 = remove false positives using CNMF-E algorithm\n    options.runRemoveFalsePositives = 1;\n    % ===COMPUTATION\n    % Float: GB, memory space you allow to use in MATLAB\n    options.memory_size_to_use = 32; %\n    % Float: GB, memory space you allow to use in MATLAB\n    options.memory_size_per_patch = 1.2; % 0.6\n    % Int vector: patch size in pixels\n    options.patch_dims = [128, 128]; % [64, 64]\n    % ===SPATIAL\n    % Int: pixel, gaussian width of a gaussian kernel for filtering the data. 0 means no filtering\n    options.gSig = 3;\n    % Int: pixel, neuron diameter\n    options.gSiz = 11;\n    % Int: spatial downsampling factor\n    options.ssub = 1;\n    % Binary: movie has dendrites?\n    options.with_dendrites = true;\n    % Int: expand kernel for HALS growing (default: 3) and expansion factor of ellipse (default: 3)\n    options.updateA_bSiz = 5;\n    % Char: hals, hals_thresh, lars, nnls\n    options.spatial_algorithm = 'hals_thresh';\n    % ===TEMPORAL\n    % Int: temporal downsampling factor\n    options.tsub = 1;\n    % Int: frame rate\n    options.Fs = 10;\n    % Float: minimum spike size. When the value is negative, the actual threshold is abs(smin)*noise level\n    options.deconv_smin = -5;\n    % Int: maximum decay time (unit: frame);\n    options.max_tau = 100;\n    % Int: detrending the slow fluctuation. usually 1 is fine (no detrending)\n    options.nk = 3;\n    % ===BACKGROUND\n    % Char: model of the background {'ring', 'svd'(default), 'nmf'}\n    options.bg_model = 'ring';\n    % Int: number of background sources for each patch (only be used in SVD and NMF model)\n    options.nb = 1;\n    % Int: when the ring model used, it is the radius of the ring used in the background model. otherwise, it's just the width of the overlapping area\n    options.ring_radius = 18;\n    % Int: downsample background for a faster speed\n    options.bg_ssub = 1;\n    % ===MERGING\n    % Float: 0 to 1, thresholds for merging neurons; [spatial overlap ratio, temporal correlation of calcium traces, spike correlation]\n    options.merge_thr = 0.65;\n    % Char: method for computing neuron distances {'mean', 'max'}\n    options.method_dist = 'max';\n    % Int: minimum distances between two neurons. it is used together with merge_thr\n    options.dmin = 5;\n    % Int: merge neurons if their distances are smaller than dmin_only.\n    options.dmin_only = 2;\n    % Float vector: merge components with highly correlated spatial shapes (corr=0.8) and small temporal correlations (corr=0.1)\n    options.merge_thr_spatial = [0.8, 0.4, -inf];\n    % ===INITIALIZATION\n    % Int: maximum number of neurons per patch. when K=[], take as many as possible.\n    options.K = [];\n    % Float: minimum local correlation for a seeding pixel\n    options.min_corr = 0.8;\n    % minimum peak-to-noise ratio for a seeding pixel\n    options.min_pnr = 8;\n    options.bd = 0;             % number of rows/columns to be ignored in the boundary (mainly for motion corrected data)\n    options.use_parallel = true;    % use parallel computation for parallel computing\n    options.show_init = true;   % show initialization results\n    options.center_psf = true;  % set the value as true when the background fluctuation is large (usually 1p data)\n    % set the value as false when the background fluctuation is small (2p)\n    % ===Residual\n    % Float: 0 to 1, minimum local correlation for initializing a neuron (default: 0.3)\n    options.min_corr_res = 0.7;\n    % Float: stands for minimum peak-to-noise ratio to look for a cell\n    options.min_pnr_res = 6;\n    % Char: method for initializing neurons from the residual. 'auto' or 'manual'\n    options.seed_method_res = 'auto';\n    % Binary: boolean, update noise level for each pixel\n    options.update_sn = true;\n\n    % get options\n    options = getOptions(options,varargin);\n    % ========================\n    options\n\n    % if cvx is not in the path, ask user for file\n    runCvxSetup();\n\n    % Make sure consistent\n    options.bg_ssub = options.ssub;\n\n    %% clear the workspace and select data\n    % clear; clc; close all;\n\n    %% choose data\n    inputFilename = inputMovie;\n    neuron = Sources2D();\n\n    nam = get_fullname(inputFilename);          % this demo data is very small, here we just use it as an example\n    nam = neuron.select_data(nam);  %if nam is [], then select data interactively\n\n    % nams = {inputFilename};          % you can put all file names into a cell array; when it's empty, manually select files\n    % nams = neuron.select_multiple_files(nams);  %if nam is [], then select data interactively\n\n    %% parameters\n    % -------------------------    COMPUTATION    -------------------------  %\n    pars_envs = struct('memory_size_to_use', options.memory_size_to_use, ...   % GB, memory space you allow to use in MATLAB\n        'memory_size_per_patch', options.memory_size_per_patch, ...   % GB, space for loading data within one patch\n        'patch_dims', options.patch_dims);  %GB, patch size\n    % pars_envs = struct('memory_size_to_use', 8, ...   % GB, memory space you allow to use in MATLAB\n    %     'memory_size_per_patch', 0.5, ...   % GB, space for loading data within one patch\n    %     'patch_dims', [64, 64],...  %GB, patch size\n    %     'batch_frames', 1000);           % number of frames per batch\n\n    % -------------------------      SPATIAL      -------------------------  %\n    gSig = options.gSig;           % pixel, gaussian width of a gaussian kernel for filtering the data. 0 means no filtering\n    gSiz = options.gSiz;          % pixel, neuron diameter\n    ssub = options.ssub;           % spatial downsampling factor\n    with_dendrites = options.with_dendrites;   % with dendrites or not\n    if with_dendrites\n        % determine the search locations by dilating the current neuron shapes\n        updateA_search_method = 'dilate';  %#ok<UNRCH>\n        updateA_bSiz = options.updateA_bSiz;\n        updateA_dist = neuron.options.dist;\n    else\n        % determine the search locations by selecting a round area\n        updateA_search_method = 'ellipse'; %#ok<UNRCH>\n        updateA_dist = options.updateA_bSiz;\n        updateA_bSiz = neuron.options.dist;\n    end\n    spatial_constraints = struct('connected', true, 'circular', false);  % you can include following constraints: 'circular'\n    spatial_algorithm = options.spatial_algorithm;\n\n    % -------------------------      TEMPORAL     -------------------------  %\n    Fs = options.Fs;             % frame rate\n    tsub = options.tsub;           % temporal downsampling factor\n    deconv_options = struct('type', 'ar1', ... % model of the calcium traces. {'ar1', 'ar2'}\n        'method', 'foopsi', ... % method for running deconvolution {'foopsi', 'constrained', 'thresholded'}\n        'smin', options.deconv_smin, ...         % minimum spike size. When the value is negative, the actual threshold is abs(smin)*noise level\n        'optimize_pars', true, ...  % optimize AR coefficients\n        'optimize_b', true, ...% optimize the baseline);\n        'max_tau', options.max_tau);    % maximum decay time (unit: frame);\n\n    nk = 3;             % detrending the slow fluctuation. usually 1 is fine (no detrending)\n    % when changed, try some integers smaller than total_frame/(Fs*30)\n    detrend_method = 'spline';  % compute the local minimum as an estimation of trend. method for detrending {'spline', 'local_min'}\n\n    % -------------------------     BACKGROUND    -------------------------  %\n    bg_model = options.bg_model;  % model of the background {'ring', 'svd'(default), 'nmf'}\n    nb = options.nb;             % number of background sources for each patch (only be used in SVD and NMF model)\n    ring_radius = options.ring_radius;  % when the ring model used, it is the radius of the ring used in the background model.\n    %otherwise, it's just the width of the overlapping area\n    num_neighbors = []; % number of neighbors for each neuron\n    bg_ssub = options.bg_ssub;        % downsample background for a faster speed\n\n    % -------------------------      MERGING      -------------------------  %\n    show_merge = false;  % if true, manually verify the merging step\n    merge_thr = options.merge_thr;     % thresholds for merging neurons; [spatial overlap ratio, temporal correlation of calcium traces, spike correlation]\n    method_dist = options.method_dist;   % method for computing neuron distances {'mean', 'max'}\n    dmin = options.dmin;       % minimum distances between two neurons. it is used together with merge_thr\n    dmin_only = options.dmin_only;  % merge neurons if their distances are smaller than dmin_only.\n    merge_thr_spatial = options.merge_thr_spatial;  % merge components with highly correlated spatial shapes (corr=0.8) and small temporal correlations (corr=0.1)\n\n    % -------------------------  INITIALIZATION   -------------------------  %\n    K = options.K;             % maximum number of neurons per patch. when K=[], take as many as possible.\n    min_corr = options.min_corr;     % minimum local correlation for a seeding pixel\n    min_pnr = options.min_pnr;       % minimum peak-to-noise ratio for a seeding pixel\n    min_pixel = gSig^2;      % minimum number of nonzero pixels for each neuron\n    bd = options.bd;             % number of rows/columns to be ignored in the boundary (mainly for motion corrected data)\n    frame_range = [];   % when [], uses all frames\n    save_initialization = false;    % save the initialization procedure as a video.\n    use_parallel = options.use_parallel;    % use parallel computation for parallel computing\n    show_init = options.show_init;   % show initialization results\n    choose_params = false; % manually choose parameters\n    center_psf = options.center_psf;  % set the value as true when the background fluctuation is large (usually 1p data)\n    % set the value as false when the background fluctuation is small (2p)\n\n    % -------------------------  Residual   -------------------------  %\n    min_corr_res = options.min_corr_res;\n    min_pnr_res = options.min_pnr_res;\n    seed_method_res = options.seed_method_res;  % method for initializing neurons from the residual\n    update_sn = options.update_sn;\n\n    % ----------------------  WITH MANUAL INTERVENTION  --------------------  %\n    with_manual_intervention = false;\n\n    % -------------------------  FINAL RESULTS   -------------------------  %\n    save_demixed = true;    % save the demixed file or not\n    kt = 3;                 % frame intervals\n\n    % -------------------------    UPDATE ALL    -------------------------  %\n    neuron.updateParams(...\n        'save_intermediate',false,...\n        'gSig', gSig, ...       % -------- spatial --------\n        'gSiz', gSiz, ...\n        'ring_radius', ring_radius, ...\n        'ssub', ssub, ...\n        'search_method', updateA_search_method, ...\n        'bSiz', updateA_bSiz, ...\n        'dist', updateA_bSiz, ...\n        'spatial_constraints', spatial_constraints, ...\n        'spatial_algorithm', spatial_algorithm, ...\n        'tsub', tsub, ...                       % -------- temporal --------\n        'deconv_options', deconv_options, ...\n        'nk', nk, ...\n        'detrend_method', detrend_method, ...\n        'background_model', bg_model, ...       % -------- background --------\n        'nb', nb, ...\n        'ring_radius', ring_radius, ...\n        'num_neighbors', num_neighbors, ...\n        'bg_ssub', bg_ssub, ...\n        'merge_thr', merge_thr, ...             % -------- merging ---------\n        'dmin', dmin, ...\n        'method_dist', method_dist, ...\n        'min_corr', min_corr, ...               % ----- initialization -----\n        'min_pnr', min_pnr, ...\n        'min_pixel', min_pixel, ...\n        'bd', bd, ...\n        'center_psf', center_psf);\n    neuron.Fs = Fs;\n\n    %% distribute data and be ready to run source extraction\n    neuron.getReady(pars_envs);\n    % neuron.getReady_batch(pars_envs);\n\n    %% initialize neurons from the video data within a selected temporal range\n    if choose_params\n        % change parameters for optimized initialization\n        [gSig, gSiz, ring_radius, min_corr, min_pnr] = neuron.set_parameters();\n    end\n\n    [center, Cn, PNR] = neuron.initComponents_parallel(K, frame_range, save_initialization, use_parallel);\n    neuron.compactSpatial();\n    if show_init\n        figure();\n        ax_init= axes();\n        imagesc(Cn, [0, 1]); colormap gray;\n        hold on;\n        plot(center(:, 2), center(:, 1), '.r', 'markersize', 10);\n    end\n    subfxnDisplayState();\n\n    %% estimate the background components\n    neuron.update_background_parallel(use_parallel);\n    neuron_init = neuron.copy();\n    subfxnDisplayState();\n\n    if options.runMerge==1\n        %%  merge neurons and update spatial/temporal components\n        neuron.merge_neurons_dist_corr(show_merge);\n        neuron.merge_high_corr(show_merge, merge_thr_spatial);\n        subfxnDisplayState();\n    end\n\n    %% update spatial components\n\n    %% pick neurons from the residual\n    [center_res, Cn_res, PNR_res] = neuron.initComponents_residual_parallel([], save_initialization, use_parallel, min_corr_res, min_pnr_res, seed_method_res);\n    if show_init\n        axes(ax_init);\n        plot(center_res(:, 2), center_res(:, 1), '.g', 'markersize', 10);\n    end\n    neuron_init_res = neuron.copy();\n    subfxnDisplayState();\n\n    %% udpate spatial&temporal components, delete false positives and merge neurons\n    % update spatial\n    if update_sn\n        neuron.update_spatial_parallel(use_parallel, true);\n        udpate_sn = false;\n    else\n        neuron.update_spatial_parallel(use_parallel);\n    end\n    subfxnDisplayState();\n    if options.runMerge==1\n        % merge neurons based on correlations\n        neuron.merge_high_corr(show_merge, merge_thr_spatial);\n        subfxnDisplayState();\n    end\n\n    for m=1:2\n        % update temporal\n        neuron.update_temporal_parallel(use_parallel);\n\n        if options.runRemoveFalsePositives==1\n            % delete bad neurons\n            neuron.remove_false_positives();\n        end\n        subfxnDisplayState();\n        if options.runMerge==1\n            % merge neurons based on temporal correlation + distances\n            neuron.merge_neurons_dist_corr(show_merge);\n            subfxnDisplayState();\n        end\n    end\n\n    %% add a manual intervention and run the whole procedure for a second time\n    neuron.options.spatial_algorithm = 'nnls';\n    if with_manual_intervention\n        show_merge = true;\n        neuron.orderROIs('snr');   % order neurons in different ways {'snr', 'decay_time', 'mean', 'circularity'}\n        neuron.viewNeurons([], neuron.C_raw);\n        if options.runMerge==1\n            % merge closeby neurons\n            neuron.merge_close_neighbors(true, dmin_only);\n        end\n\n        % delete neurons\n        tags = neuron.tag_neurons_parallel();  % find neurons with fewer nonzero pixels than min_pixel and silent calcium transients\n        ids = find(tags>0);\n        if ~isempty(ids)\n            neuron.viewNeurons(ids, neuron.C_raw);\n        end\n        subfxnDisplayState();\n    end\n    %% run more iterations\n    neuron.update_background_parallel(use_parallel);\n    neuron.update_spatial_parallel(use_parallel);\n    neuron.update_temporal_parallel(use_parallel);\n    subfxnDisplayState();\n\n    K = size(neuron.A,2);\n    % find neurons with fewer nonzero pixels than min_pixel and silent calcium transients\n    tags = neuron.tag_neurons_parallel();\n\n    if options.runRemoveFalsePositives==1\n        neuron.remove_false_positives();\n        subfxnDisplayState();\n    end\n    if options.runMerge==1\n        neuron.merge_neurons_dist_corr(show_merge);\n        neuron.merge_high_corr(show_merge, merge_thr_spatial);\n        subfxnDisplayState();\n    end\n\n    if K~=size(neuron.A,2)\n        neuron.update_spatial_parallel(use_parallel);\n        neuron.update_temporal_parallel(use_parallel);\n        if options.runRemoveFalsePositives==1\n            neuron.remove_false_positives();\n        end\n        subfxnDisplayState();\n    end\n\n    %%\n    % Get the folder path string\n    [PATHSTR,NAME,EXT] = fileparts(inputFilename);\n    [~,folderName,~] = fileparts(PATHSTR);\n\n    results = neuron.obj2struct();\n    cnmfeAnalysisOutput.success = 1;\n    cnmfeAnalysisOutput.params = results.options;\n    cnmfeAnalysisOutput.inputOptions = options;\n    cnmfeAnalysisOutput.movieList = inputFilename;\n    cnmfeAnalysisOutput.extractedImages = reshape(full(results.A),[neuron.options.d1 neuron.options.d2 size(results.C,1)]);\n    % cnmfeAnalysisOutput.extractedImages = reshape(full(results.A),[size(results.P.sn) size(results.C,1)]);\n    cnmfeAnalysisOutput.extractedSignals = results.C;\n    cnmfeAnalysisOutput.extractedSignalsEst = results.C_raw;\n    cnmfeAnalysisOutput.extractedPeaks = results.S;\n    cnmfeAnalysisOutput.Cn = results.Cn;\n    cnmfeAnalysisOutput.P = results.P;\n    % save([PATHSTR filesep folderName '_cnmfeAnalysis.mat'],'cnmfeAnalysisOutput');\n\n    % cnmfAnalysisOutput = cnmfeAnalysisOutput;\n    % save([PATHSTR filesep folderName '_cnmfAnalysis.mat'],'cnmfAnalysisOutput');\n\n    %% save the workspace for future analysis\n    neuron.orderROIs('snr');\n    try\n        cnmfe_path = neuron.save_workspace();\n    catch err\n        display(repmat('@',1,7))\n        disp(getReport(err,'extended','hyperlinks','on'));\n        display(repmat('@',1,7))\n    end\n    %% show neuron contours\n    % Coor = neuron.show_contours(0.6);\n\n    %% create a video for displaying the\n    % amp_ac = 140;\n    % range_ac = 5+[0, amp_ac];\n    % multi_factor = 10;\n    % range_Y = 1300+[0, amp_ac*multi_factor];\n\n    % avi_filename = neuron.show_demixed_video(save_demixed, kt, [], amp_ac, range_ac, range_Y, multi_factor);\n\n    %% save neurons shapes\n    % neuron.save_neurons();\n    function subfxnDisplayState()\n        disp(['A (space):' num2str(size(neuron.A)) ' | C (time): ' num2str(size(neuron.C)) ' | b (background): ' num2str(size(neuron.b))])\n    end\nend", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/+ciapkg/+signal_extraction/computeCnmfeSignalExtraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.2166193126543675}}
{"text": "function gX = whitefixedKernGradX(kern, X, X2)\n\n% WHITEFIXEDKERNGRADX Gradient of WHITEFIXED kernel with respect to a point x.\n% FORMAT\n% DESC computes the gradient of the fixed parameter white noise\n% kernel with respect to the input positions. \n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x : locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData x numInputs x numData. Where numData is\n% the number of data points and numInputs is the number of input\n% dimensions in X.\n%\n% FORMAT\n% DESC computes the gradident of the fixed parameter white noise\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO whitefixedKernParamInit, kernGradX, whitefixedKernDiagGradX\n%\n% COPYRIGHT : Nathaniel J. King, 2006\n\n% KERN\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/whitefixedKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2165869296246755}}
{"text": "% batch\ntotaltime = tic; %#ok<NASGU>\nisFullData = 1;\ndata_masterdir = GetCurrentDataDir();\n\nM_stimrange = GetStimRange();\n\nrange_fish =  8:18; % range_fish = GetFishRange();\n\n%% custom params here:\n% numK1 = 20; \nmasterthres = 0.7;\n\n%%\nM_regthres = {0.7,0.5};\nM_place = {1,2,3,1,4,5,6,7};\nM_stimname = {'4x4','PT','OMR','defS','Spt','DF','Lm','Dot'};\n%%\nfor i_count = 1,%%%%%%%%%\n    masterthres = M_regthres{i_count};\n%     clusParams = struct('merge',masterthres,'cap',masterthres,'reg1',masterthres,...\n%         'reg2',masterthres,'minSize',10,'k1',numK1);\n    \n    for i_stimrange = 1:8,\n        if i_stimrange == 1,\n            M_stimrange = GetStimRange('5');\n        elseif i_stimrange == 2,\n            M_stimrange = GetStimRange('P');\n        elseif i_stimrange == 3,\n            M_stimrange = GetStimRange('O');\n        elseif i_stimrange == 4,\n            M_stimrange = GetStimRange('M');\n        elseif i_stimrange == 5,\n            M_stimrange = GetStimRange('S');\n        elseif i_stimrange == 6,\n            M_stimrange = GetStimRange('D');\n        elseif i_stimrange == 7,\n            M_stimrange = GetStimRange('L');\n        elseif i_stimrange == 8,\n            M_stimrange = GetStimRange('Y');\n        end\n\n        for i = 1:length(range_fish),\n            i_fish = range_fish(i);\n            disp(i_fish);\n            \n            % check this loop\n            stimrange = M_stimrange{i_fish};\n            if isempty(stimrange),\n                continue;\n            end\n            \n            % Load fish\n            LoadFullFish(hfig,i_fish,isFullData);\n            \n            %% 1.\n            % setup\n            absIX = getappdata(hfig,'absIX');\n\n            i_ClusGroup = 2;\n            i_Cluster = 1;\n\n            % Load cluster data\n            [cIX_load,gIX] = LoadCluster_Direct(i_fish,i_ClusGroup,i_Cluster,absIX);\n                        \n            %% partitions for CV\n            timelists = getappdata(hfig,'timelists');\n            timelists_names = getappdata(hfig,'timelists_names');\n            periods = getappdata(hfig,'periods');\n            \n            M_stim = M_stimrange{i_fish};\n            \n            timelistsCV_raw = cell(length(M_stim),2);\n            timelistsCV = cell(1,2);\n            \n            for k_stim = 1:length(M_stim), % :3\n                i_stim = M_stim(k_stim);\n                TL = timelists{i_stim};\n                period = periods(i_stim);\n                nrep = size(TL,2)/periods(i_stim); % integer\n                n = floor(nrep/2);\n                if n>0,\n                    timelistsCV_raw{k_stim,1} = TL(1:n*period);\n                    timelistsCV_raw{k_stim,2} = TL(1+n*period:2*n*period);% before 12/5/16: TL(1+n*period):TL(2*n*period);\n                else % for spont, only one period\n                    halfperiod = floor(period/2);\n                    timelistsCV_raw{k_stim,1} = TL(1:halfperiod);\n                    timelistsCV_raw{k_stim,2} = TL(1+halfperiod:2*halfperiod);\n                end\n            end\n            timelistsCV{1} = horzcat(timelistsCV_raw{:,1});\n            timelistsCV{2} = horzcat(timelistsCV_raw{:,2});\n            assert(length(timelistsCV{1})==length(timelistsCV{2}));\n            \n            %%\n            for k = 1:2,% CV halves\n                tIX = timelistsCV{k};\n                M = GetTimeIndexedData_Default_Direct(hfig,cIX_load,tIX);\n                M_0 = GetTimeIndexedData_Default_Direct(hfig,[],tIX,'isAllCells');\n\n                % ------custom code here---------\n                isWkmeans = true;\n                isMakeFoxels = true;\n                \n                [cIX,gIX] = AutoClustering(cIX_load,gIX,M_0,cIX_load,isWkmeans,[],...\n                    isMakeFoxels,masterthres);\n                \n                % save cluster\n                name = ['Auto_',M_stimname{i_stimrange},'_M',num2str(masterthres),'_CV',num2str(k)];\n                clusgroupID = 3+k; % 4 and 5\n                clusIDoverride = M_place{i_stimrange};\n                SaveCluster_Direct(cIX,gIX,absIX,i_fish,name,clusgroupID,clusIDoverride);\n            end\n        end\n    end\nend\nSaveVARwithBackup();\ntotaltime = toc;\ndisp(totaltime);\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/Clustering/Batch cluster processing/Batch_crossval_by_stim_consec_halves.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21658692412103975}}
{"text": "function [TorF, vstr, rdate] = have_feature_ktrlink()\n%HAVE_FEATURE_KTRLINK  Detect availability/version info for KTRLINK\n%\n%   Feature detection function implementing 'ktrlink' tag for HAVE_FEATURE\n%   to detect availability/version of Artelys Knitro prior to version 9.0.0,\n%   which required the MATLAB Optimization Toolbox.\n%\n%   See also HAVE_FEATURE, HAVE_FEATURE_KNITRO, KTRLINK.\n\n%   MP-Opt-Model\n%   Copyright (c) 2004-2020, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MP-Opt-Model.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%% ktrlink for pre-Knitro 9.0, requires Optim Toolbox\nTorF = exist('ktrlink', 'file');\nvstr = '';\nrdate = '';\nif TorF\n    try\n        str = evalc(['[x fval] = ktrlink(@(x)1,1);']);\n    end\n    TorF = exist('fval', 'var') && fval == 1;\n    if TorF\n        pat = 'KNITRO ([^\\s]+)\\n|Knitro ([^\\s]+)\\n';\n        [s,e,tE,m,t] = regexp(str, pat);\n        if ~isempty(t)\n            vstr = t{1}{1};\n        end\n    end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/have_feature_ktrlink.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21654558313891034}}
{"text": "function show_mov(in, in2) \n    % ZMAP script show_map.m. Creates Dialog boxes for Z-map calculation\n    % does the calculation and makes displays the map\n    % stefan wiemer 11/94\n    %\n    % make dialog interface and call maxzlta\n    %\n    % turned into function by Celso G Reyes 2017\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    % Input Rubberband\n    %\n    report_this_filefun();\n    \n    if in2 ~= 'calma'\n        \n        %initial values\n        nustep = 10;\n        ZG.compare_window_dur_v3 = years(1.5);\n        it = t0b +1;\n        figure(mess);\n        clf\n        set(gca,'visible','off')\n        set(gcf,'Units','pixel','NumberTitle','off','Name','Input Parameters');\n\n        set(gcf,'pos',[ ZG.welcome_pos, ZG.welcome_len +[200, -50]]);\n        \n        \n        % creates a dialog box to input some parameters\n        %\n        \n        inp2_field=uicontrol('Style','edit',...\n            'Position',[.80 .80 .18 .15],...\n            'Units','normalized','String',num2str(nustep),...\n            'callback',@callbackfun_001);\n        \n        txt2 = text(...\n            'Position',[0. 0.9 0 ],...\n            'FontWeight','bold',...\n            'FontSize',ZmapGlobal.Data.fontsz.m ,...\n            'String','Please input Number of Frames:');\n        \n        if in == 'rub' | in == 'lta'\n            \n            txt3 = text(...\n                'Position',[0. 0.65 0 ],...\n                'FontWeight','bold',...\n                'FontSize',ZmapGlobal.Data.fontsz.m ,...\n                'String','Please input window length in years (e.g. 1.5):');\n            inp3_field=uicontrol('Style','edit',...\n                'Position',[.80 .575 .18 .15],...\n                'Units','normalized','String',num2str(years(ZG.compare_window_dur)),...\n                'callback',@callbackfun_002);\n            \n        end   % if in = rub\n        \n        close_button=uicontrol('Style','Pushbutton',...\n            'Position', [.60 .05 .15 .15 ],...\n            'Units','normalized','Callback',@(~,~)close(),'String','Cancel');\n        \n        go_button=uicontrol('Style','Pushbutton',...\n            'Position',[.25 .05 .15 .15 ],...\n            'Units','normalized',...\n            'callback',@callbackfun_003,...\n            'String','Go');\n        \n        set(gcf,'visible','on');watchoff\n        \n        % do the calculations:\n        %\n        \n    else     % if in2 ~=calma\n        \n        % check if time are with limits\n        %\n        \n        \n        % initial parameter\n        winlen_days = ZG.compare_window_dur/ZG.bin_dur; \n        ti = (it -t0b)/days(ZG.bin_dur);\n        var1 = zeros(1,ncu);\n        var2 = zeros(1,ncu);\n        mean1 = zeros(1,ncu);\n        mean2 = zeros(1,ncu);\n        as = zeros(1,ncu);\n        [len, ncu] = size(cumuall); len = len-2;\n        len = len -2;\n        step = len/nustep;\n        \n        \n        % loop over all frames\n        \n        j = 0;\n        figure\n        rect = [0.10 0.30 0.55 0.50 ];\n        rect1 = rect;\n        axes('position',rect1)\n        axis('off')\n        m = moviein(length(1:step:len-winlen_days));\n        for ti = winlen_days:step:len-winlen_days\n            j = j+1;\n            var1 = zeros(1,ncu);\n            var2 = zeros(1,ncu);\n            mean1 = zeros(1,ncu);\n            mean2 = zeros(1,ncu);\n            as = zeros(1,ncu);\n            \n            % loop over all grid points for percent\n            %\n            %\n            if in =='per'\n                \n                for i = 1:ncu\n                    mean1(i) = mean(cumuall(1:ti,i));\n                    mean2(i) = mean(cumuall(ti:len,i));\n                end    %for i\n                as = -((mean1-mean2)./mean1)*100;\n                \n                strib = 'Change in Percent';\n                stri2 = ['ti=' num2str(ti*days(ZG.bin_dur) + t0b)  ];\n                \n                \n                \n            end  % if in = = per\n            \n            % loop over all point for rubber band\n            %\n            if in =='rub'\n                \n                for i = 1:ncu\n                    mean1(i) = mean(cumuall(1:ti,i));\n                    mean2(i) = mean(cumuall(ti+1:ti+winlen_days,i));\n                    var1(i) = cov(cumuall(1:ti,i));\n                    var2(i) = cov(cumuall(ti+1:ti+winlen_days,i));\n                end %  for i ;\n                as = (mean1 - mean2)./(sqrt(var1/ti+var2/winlen_days));\n                \n            end % if in = rub\n            \n            % make the AST function map\n            if in =='ast'\n                for i = 1:ncu\n                    mean1(i) = mean(cumuall(1:ti,i));\n                    var1(i) = cov(cumuall(1:ti,i));\n                    mean2(i) = mean(cumuall(ti+1:len,i));\n                    var2(i) = cov(cumuall(ti+1:len,i));\n                end    %for i\n                as = (mean1 - mean2)./(sqrt(var1/ti+var2/(len-ti)));\n            end % if in = ast\n            \n            if in =='lta'\n                disp('Calculate LTA')\n                %cu = [cumuall(1:ti-1,:) ; cumuall(ti+winlen_days+1:len,:)];\n                mean1 = mean([cumuall(1:ti-1,:) ; cumuall(ti+winlen_days+1:len,:)]);\n                mean2 = mean(cumuall(ti:ti+winlen_days,:));\n                for i = 1:ncu\n                    var1(i) = cov([cumuall(1:ti-1,i) ; cumuall(ti+winlen_days+1:len,i)]);\n                    var2(i) = cov(cumuall(ti:ti+winlen_days,i));\n                end     % for i\n                as = (mean1 - mean2)./(sqrt(var1/(len-winlen_days)+var2/winlen_days));\n            end % if in = lta\n            \n            \n            normlap1=nan(length(tmpgri(:,1)),1)\n            normlap2=nan(length(tmpgri(:,1)),1)\n            normlap2(ll)= as(:);\n            %construct a matrix for the color plot\n            valueMap=reshape(normlap2,length(yvect),length(xvect));\n            \n            \n            %plot imge\n            % set values gretaer ZG.tresh_km = nan\n            %\n            re4 = valueMap;\n            [len, ncu] = size(cumuall);\n            [n1, n2] = size(cumuall);\n            s = cumuall(n1,:);\n            normlap2(ll)= s(:);\n            r=reshape(normlap2,length(yvect),length(xvect));\n            re4(r > ZG.tresh_km) = nan;\n            \n            orient landscape\n            set(gcf,'PaperPosition',[ 0.1 0.1 8 6])\n            axes('position',rect1)\n            set(gca,'NextPlot','add')\n            pco1 = pcolor(gx,gy,re4);\n            caxis([ZG.minc ZG.maxc]);\n            axis([ s2_west s1_east s4_south s3_north])\n            set(gca,'NextPlot','add')\n            %overlay\n            if in == 'ast'\n                tx2 = text(0.07,0.85 ,['AS; t=' num2str(ti*days(ZG.bin_dur)+t0b)  ] ,...\n                    'Units','Norm','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k','FontWeight','bold');\n            end\n            \n            if in == 'lta'\n                tx2 = text(0.07,0.85 ,['LTA; t=' num2str(ti*days(ZG.bin_dur)+t0b)  ] ,...\n                    'Units','Norm','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k','FontWeight','bold');\n            end\n            \n            if in == 'rub'\n                tx2 = text(0.07,0.85 ,['RUB; t=' num2str(ti*days(ZG.bin_dur)+t0b)  ] ,...\n                    'Units','Norm','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k','FontWeight','bold');\n            end\n            \n            set(gca,'FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n                'FontWeight','bold','LineWidth',1.5,...\n                'Box','on','SortMethod','childorder')\n            \n            \n            shading interp\n            has = gca;\n            disp('now getting frame...')\n            m(:,j) = getframe(has);\n            delete(gca);\n            delete(gca);\n            delete(gca)\n            fs_m = get(gcf,'pos');\n            \n        end  % loop over frames\n        \n        close(gcf)\n        \n        showmovi\n    end   % if calma ~| in2\n    \n    \n    function callbackfun_001(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        nustep=str2double(inp2_field.String);\n        inp2_field.String=num2str(nustep);\n    end\n    \n    function callbackfun_002(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        ZG.compare_window_dur=years(str2double(mysrc.String));\n    end\n    \n    function callbackfun_003(mysrc,myevt)\n\n        callback_tracker(mysrc,myevt,mfilename('fullpath'));\n        nustep=str2num(inp2_field.String);\n        ZG.compare_window_dur=years(str2num(inp3_field.String));\n        watchon;\n        drawnow;\n        in2 = 'calma';\n        fixaxmo;\n    end\n    \nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/show_mov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21649116269402047}}
{"text": "function model = ivmEpUpdateM(model, index)\n\n% IVMEPUPDATEM Update matrix M, L, varSigma and mu for EP.\n% FORMAT\n% DESC performs an EP update on the IVM model's represenations for\n% a given point.\n% ARG model : the mode for which the update will be done.\n% ARG index : the index of the point for which the update will take\n% place.\n%\n% SEEALSO : ivmEpUpdatePoint, ivmDowndateSites\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% IVM\n\nd = length(model.I);\nk = find(model.I == index);\nif k == d % This point has just been included so EP update is irrelevant.\n  return;\nend\nkvector = model.kern.Kstore(:, k);\nfor c = 1:length(model.Sigma)\n  % Compute the kth row of  Sigma\n  a = model.Sigma(c).M(:, index);\n  s = kvector' - a'*model.Sigma(c).M;\n\n  v = model.Sigma(c).Linv(k:end, k);\n  sLambda_k = rocholhFactorise(v);\n  \n  % Update M\n  model.Sigma(c).M(k:end, :) = ...\n      rocholForeSub(sLambda_k, ...\n\t\t    model.Sigma(c).M(k:end, :));\n  model.Sigma(c).M(k:end-1) = model.Sigma(c).M(k+1:end);\n\n  % Update L\n  t2 = model.Sigma(c).Linv(k, 1:k);\n  slambda_11 = sLambda_k.u(1)*sLambda_k.v(1);\n  slambda_21 = sLambda_k.v*sLambda_k.u(1);\n  slambda_21(1) = [];\n  sLambda_22 = sLambda_k;\n  sLambda_22.s(1) = [];\n  sLambda_22.u(1) = [];\n  sLambda_22.v(1) = [];\n  sLambda_22.n = sLambda_22.n-1;\n  T3prime =  rocholForeSub(sLambda_22, model.Sigma(c).Linv(k+1:end, : ...\n                                                    ));\n  T3prime(:, 1:k) = T3prime(:, 1:k) ...\n      - rocholForeSub(sLambda_22, slambda_21*1/slambda_11)*t2;\n  v = T3prime(:, k+1:end)\\T3prime(:, k);\n  sVtilde = rocholFactorise(v);\n  V = rocholTransMultiply(sVtilde, T3prime(:, k+1:end)')';\n  T33inv = rocholTransMultiply(sLambda_22, model.Sigma(c).L(k+1:end, ...\n                                                    k+1:end)')';\n  invV = rocholForeSub(sVtilde, T33inv);\n  model.Sigma(c).Linv(k:end-1, 1:end-1) = [T3prime(:, 1:k-1) V];\n  model.Sigma(c).L(k:end-1, 1:end-1) = [-invV*T3prime(:, 1:k-1)* ...\n                      model.Sigma(c).L(1:k-1, 1:k-1) invV];\n  %/~\n  oldVarSigma = model.varSigma;\n  %~/\n  model.varSigma(:, c) = model.varSigma(:, c) + ((model.nu(index, c)*s).*s)';\n  %/~\n  if any(model.varSigma(:, c)<0)\n    warning('Variance less than zero')\n  end\n  %~/\n  model.mu(:, c) = model.mu(:, c) + model.g(index, c)*s';  \n\nend\nif length(model.Sigma)==1 & size(model.y, 2)>1\n  for c = 2:size(model.y, 2)\n    model.varSigma(:, c) = model.varSigma(:, c) ...\n        - ((model.nu(index, c)*s).*s)';\n    model.mu(:, c) = model.mu(:, c) + model.g(index, c)*s'; \n    %/~\n    if any(model.varSigma(:, c)<0)\n      warning('Variance less than zero')\n    end\n    %~/\n  end\nend\n\n%model = ivmDowndateSites(model, index);\n%model.J = [model.J index];\n\n% Ensure nu and g now accurately reflect mu and varsigma.\nmodel = ivmUpdateNuG(model, index);\n% Update the site parameter.\nmodel = ivmUpdateSites(model, index);\nd = model.d;\n\n% Compute the values of M for the new point\nfor c = 1:length(model.Sigma)\n  a = model.Sigma(c).M(1:end-1, index);\n  s = kvector' - a'*model.Sigma(c).M(1:end-1, ...\n                                                    :);\n  lValInv = sqrt(model.nu(index, c));\n  %/~\n  % If Nu is so low then the included data-point isn't really useful.\n  if lValInv < 1e-16\n    warning(['Square root of nu is ' num2str(lValInv)])\n  end\n  %~/\n  model.Sigma(c).M(end, :) = lValInv*s;\n  ainv = (-a*lValInv)'/tril(model.Sigma(c).L(1:end-1, 1:end-1));\n  model.Sigma(c).L(end, :) = [a' 1/lValInv];\n  model.Sigma(c).Linv(end, :) = [ainv lValInv];\n  % make sure Matlab knows they are lower triangular.\n  model.Sigma(c).L = tril(model.Sigma(c).L);\n  model.Sigma(c).Linv = tril(model.Sigma(c).Linv);\n  %/~\n  oldVarSigma = model.varSigma(:, c);\n  if any(model.varSigma(:, c)<0)\n    warning('Variance less than zero')\n  end\n  %~/\n  model.varSigma(:, c) = model.varSigma(:, c) - ((model.nu(index, c)*s).*s)';\n  %/~\n  if any(model.varSigma(:, c)<0)\n    warning('Variance less than zero')\n  end\n  %~/\n  model.mu(:, c) = model.mu(:, c) + model.g(index, c)*s';  \nend\nif length(model.Sigma)==1 & size(model.y, 2)>1\n  for c = 2:size(model.y, 2)\n    model.varSigma(:, c) = model.varSigma(:, c) ...\n        - ((model.nu(index, c)*s).*s)';\n    model.mu(:, c) = model.mu(:, c) + model.g(index, c)*s'; \n    %/~\n    if any(model.varSigma(:, c)<0)\n      warning('Variance less than zero')\n    end\n    %~/\n  end\nend\n% Swap the columns of the kernel matrix about.\nmodel.kern.Kstore(:, k:end-1) = model.kern.Kstore(:, k+1:end);\nmodel.kern.Kstore(:, end) = kvector;\n\n% Move point to end of active set.\nmodel.I(k:end-1) = model.I(k+1:end);\nmodel.I(end) = index;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ivm/ivmEpUpdateM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2164868652452365}}
{"text": "%% Load the data into MATLAB from a binary log file\n% Usage: >> [datapoints, numpoints] = readdata('datafile.log')\n% Header information format:\n%           String \"MWLOGV##\"\n%           Time/Date 4 bytes (time())\n%           Number of Signals per record Logged 1 bytes (256 max)\n%           Data Type of Signals Logged  1 bytes (1-10)\n%           Number of bytes per record 2 (65535 max)\n% Plot Data Example: plot([1:numpoints], datapoints(1,:), [1:numpoints], datapoints(2,:))\n% MathWorks Pilot Engineering 2015\n% Steve Kuznicki\nfunction [datapts, numpts] = px4_read_binary_file(dataFile)\n%%\ndatapts = 0;\nnumpts = 0;\n\nif nargin == 0\n    dataFile = 'data.bin';\nend\n\nfid = fopen(dataFile, 'r');\n% load the header information\nhdrToken = fread(fid, 8, 'char');\nif strncmp(char(hdrToken),'MWLOGV',6) == true\n    logTime = uint32(fread(fid, 1, 'uint32'));\n    numflds = double(fread(fid, 1, 'uint8'));\n    typefld = uint8(fread(fid, 1, 'uint8'));\n    recSize = uint16(fread(fid, 1, 'uint16'));\n    fieldTypeStr = get_elem_type(typefld);\n    datapts = fread(fid, double([numflds, Inf]), fieldTypeStr);\n    fclose(fid);\n    numpts = size(datapts,2);\nend\n\nend\n\n%% get the element type string\nfunction [dtypeStr] = get_elem_type(dtype)\n    switch(dtype)\n        case 1\n            dtypeStr = 'double';\n        case 2\n            dtypeStr = 'single';\n        case 3\n            dtypeStr = 'int32';\n        case 4\n            dtypeStr = 'uint32';\n        case 5\n            dtypeStr = 'int16';\n        case 6\n            dtypeStr = 'uint16';\n        case 7\n            dtypeStr = 'int8';\n        case 8\n            dtypeStr = 'uint8';\n        case 9\n            dtypeStr = 'logical';\n        case 10\n            dtypeStr = 'embedded.fi';\n    end\nend", "meta": {"author": "RflySim", "repo": "RflyExpCode", "sha": "7dbec4d8796d6e23ee86c523e4ba5712203b1519", "save_path": "github-repos/MATLAB/RflySim-RflyExpCode", "path": "github-repos/MATLAB/RflySim-RflyExpCode/RflyExpCode-7dbec4d8796d6e23ee86c523e4ba5712203b1519/code/e0/2.PSPOfficialExps/px4_read_binary_file.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21638856818137042}}
{"text": "classdef m_45_prms_18p_7s < MARRMoT_model\n% Class for hydrologic conceptual model: PRMS\n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See <https://www.gnu.org/licenses/> for details.\n\n% Model reference\n% Leavesley, G. H., R. Lichty, B. Troutman, and L. Saindon (1983), \u0010\n% Precipitation-Runo\u001b Modeling System: User's Manual.\u0011 U.S. Geological \n% Survey, Water-Resources Investigations Report 83-4238, 207\n%\n% Markstrom, S. L., S. Regan, L. E. Hay, R. J. Viger, R. M. T. Webb, R. A. \n% Payn, and J. H. LaFontaine (2015), PRMS-IV, the Precipitation-Runoff\u001b \n% Modeling System, Version 4.\u0011 In U.S. Geological Survey Techniques and\n% Methods, book 6, chap. B7, 158. doi: http://dx.doi.org/10.3133/tm6B7\n\n    properties\n        % model-specific attributes\n    end\n    methods\n        \n        % creator method\n        function obj = m_45_prms_18p_7s()\n            obj.numStores = 7;                                             % number of model stores\n            obj.numFluxes = 25;                                            % number of model fluxes\n            obj.numParams = 18; \n\n            obj.JacobPattern  = [1,0,0,0,0,0,0;\n                                 0,1,0,0,0,0,0;\n                                 1,0,1,0,0,0,0;\n                                 1,1,1,1,0,0,0;\n                                 1,1,1,1,1,0,0;\n                                 1,1,1,1,1,1,0;\n                                 1,1,1,1,1,1,1];                           % Jacobian matrix of model store ODEs\n            \n            obj.parRanges = [-3,  5;         % tt, Temperature threshold for snowfall and melt [oC]\n                              0, 20;         % ddf,  Degree-day factor for snowmelt [mm/oC/d]\n                              0,  1;         % alpha, Fraction of rainfall on soil moisture going to interception [-] \n                              0,  1;         % beta, Fraction of catchment where rain goes to soil moisture [-]\n                              0,  5;         % stor, Maximum interception capcity [mm]\n                              0, 50;         % retip, Maximum impervious area storage [mm]\n                              0,  1;         % fscn, Fraction of SCX where SCN is located [-]\n                              0,  1;         % scx, Maximum contributing fraction area to saturation excess flow [-]\n                              0.005, 0.995;  % flz, Fraction of total soil moisture that is the lower zone [-]\n                              1, 2000;       % stot, Total soil moisture storage [mm]: REMX+SMAX\n                              0, 20;         % cgw, Constant drainage to deep groundwater [mm/d]\n                              1, 300;        % resmax, Maximum flow routing reservoir storage (used for scaling only, there is no overflow) [mm]\n                              0,  1;         % k1, Groundwater drainage coefficient [d-1]\n                              1,  5;         % k2, Groundwater drainage non-linearity [-]\n                              0,  1;         % k3, Interflow coefficient 1 [d-1]\n                              0,  1;         % k4, Interflow coefficient 2 [mm-1 d-1]\n                              0,  1;         % k5, Baseflow coefficient [d-1]\n                              0,  1];        % k6, Groundwater sink coefficient [d-1]\n\n            obj.StoreNames = {\"S1\", \"S2\" \"S3\" \"S4\" \"S5\" \"S6\" \"S7\"};         % Names for the stores\n            obj.FluxNames  = {\"ps\",   \"pr\",  \"pim\", \"psm\", \"pby\"...\n                              \"pin\",  \"ptf\", \"m\",   \"mim\", \"msm\"...\n                              \"sas\",  \"sro\", \"inf\", \"pc\",  \"excs\"...\n                              \"qres\", \"sep\", \"gad\", \"ras\", \"bas\"...\n                              \"snk\",  \"ein\", \"eim\", \"ea\",  \"et\"};          % Names for the fluxes\n            \n            obj.FluxGroups.Ea = [22 23 24 25];                             % Index or indices of fluxes to add to Actual ET\n            obj.FluxGroups.Q  = [11 12 19 20];                             % Index or indices of fluxes to add to Streamflow\n            obj.FluxGroups.Sink  = 21;                                     % index of sink fluxes\n\n        end\n        \n        % INITialisation function\n        function obj = init(obj)\n        end\n        \n        % MODEL_FUN are the model governing equations in state-space formulation\n        function [dS, fluxes] = model_fun(obj, S)\n            % parameters\n            theta = obj.theta;\n            tt      = theta(1);     % Temperature threshold for snowfall and melt [oC]\n            ddf     = theta(2);     % Degree-day factor for snowmelt [mm/oC/d]\n            alpha   = theta(3);     % Fraction of rainfall on soil moisture going to interception [-] \n            beta    = theta(4);     % Fraction of catchment where rain goes to soil moisture [-]\n            stor    = theta(5);     % Maximum interception capcity [mm]\n            retip   = theta(6);     % Maximum impervious area storage [mm]\n            fscn    = theta(7);     % Fraction of SCX where SCN is located [-]\n            scx     = theta(8);     % Maximum contributing fraction area to saturation excess flow [-]\n            scn     = fscn*scx;     % Minimum contributing fraction area to saturation excess flow [-]\n            flz     = theta(9);     % Fraction of total soil moisture that is the lower zone [-]\n            stot    = theta(10);    % Total soil moisture storage [mm]: REMX+SMAX\n            remx    = (1-flz)*stot; % Maximum upper soil moisture storage [mm]\n            smax    = flz*stot;     % Maximum lower soil moisture storage [mm] \n            cgw     = theta(11);    % Constant drainage to deep groundwater [mm/d]\n            resmax  = theta(12);    % Maximum flow routing reservoir storage (used for scaling only, there is no overflow) [mm]\n            k1      = theta(13);    % Groundwater drainage coefficient [d-1]\n            k2      = theta(14);    % Groundwater drainage non-linearity [-]\n            k3      = theta(15);    % Interflow coefficient 1 [d-1]\n            k4      = theta(16);    % Interflow coefficient 2 [mm-1 d-1]\n            k5      = theta(17);    % Baseflow coefficient [d-1]\n            k6      = theta(18);    % Groundwater sink coefficient [d-1]\n            \n            % delta_t\n            delta_t = obj.delta_t;\n            \n            % stores\n            S1 = S(1);\n            S2 = S(2);\n            S3 = S(3);\n            S4 = S(4);\n            S5 = S(5);\n            S6 = S(6);\n            S7 = S(7);\n            \n            % climate input\n            t = obj.t;                             % this time step\n            climate_in = obj.input_climate(t,:);   % climate at this step\n            P  = climate_in(1);\n            Ep = climate_in(2);\n            T  = climate_in(3);\n            \n            % fluxes functions\n            flux_ps  = snowfall_1(P,T,tt);\n            flux_pr  = rainfall_1(P,T,tt);\n            flux_pim = split_1(1-beta,flux_pr);\n            flux_psm = split_1(beta,flux_pr);\n            flux_pby = split_1(1-alpha,flux_psm);\n            flux_pin = split_1(alpha,flux_psm);\n            flux_ptf = interception_1(flux_pin,S2,stor);\n            flux_m   = melt_1(ddf,tt,T,S1,delta_t);\n            flux_mim = split_1(1-beta,flux_m);\n            flux_msm = split_1(beta,flux_m);\n            flux_sas = saturation_1(flux_pim+flux_mim,S3,retip);\n            flux_sro = saturation_8(scn,scx,S4,remx,flux_msm+flux_ptf+flux_pby);\n            flux_inf = effective_1(flux_msm+flux_ptf+flux_pby,flux_sro);\n            flux_pc  = saturation_1(flux_inf,S4,remx);\n            flux_excs= saturation_1(flux_pc,S5,smax);\n            flux_sep = recharge_7(cgw,flux_excs);\n            flux_qres= effective_1(flux_excs,flux_sep);\n            flux_gad = recharge_2(k2,S6,resmax,k1);\n            flux_ras = interflow_4(k3,k4,S6);\n            flux_bas = baseflow_1(k5,S7);\n            flux_snk = baseflow_1(k6,S7);\n            flux_ein = evap_1(S2,beta*Ep,delta_t);\n            flux_eim = evap_1(S3,(1-beta)*Ep,delta_t);\n            flux_ea  = evap_7(S4,remx,Ep-flux_ein-flux_eim,delta_t);\n            flux_et  = evap_15(Ep-flux_ein-flux_eim-flux_ea,S5,smax,S4,Ep-flux_ein-flux_eim,delta_t);\n\n            % stores ODEs\n            dS1 = flux_ps  - flux_m;\n            dS2 = flux_pin - flux_ein - flux_ptf;    \n            dS3 = flux_pim + flux_mim - flux_eim - flux_sas;\n            dS4 = flux_inf - flux_ea  - flux_pc;\n            dS5 = flux_pc  - flux_et  - flux_excs;\n            dS6 = flux_qres- flux_gad - flux_ras;\n            dS7 = flux_sep + flux_gad - flux_bas - flux_snk;\n            \n            % outputs\n            dS = [dS1 dS2 dS3 dS4 dS5 dS6 dS7];\n            fluxes = [flux_ps,   flux_pr,  flux_pim, flux_psm, flux_pby...\n                      flux_pin,  flux_ptf, flux_m,   flux_mim, flux_msm...\n                      flux_sas,  flux_sro, flux_inf, flux_pc,  flux_excs...\n                      flux_qres, flux_sep, flux_gad, flux_ras, flux_bas...\n                      flux_snk,  flux_ein, flux_eim, flux_ea,  flux_et];\n        end\n        \n        % STEP runs at the end of every timestep.\n        function obj = step(obj)\n        end\n    end\nend", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Model files/m_45_prms_18p_7s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21638856253442645}}
{"text": "function varargout=ceil(varargin)\n%FLOOR (overloaded)\n\nswitch class(varargin{1})\n\n    case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.\n\n        x = varargin{1};\n        [n,m] = size(x);\n        x = reshape(x,n*m,1);\n        y = [];\n        for i = 1:n*m\n            y = [y;yalmip('addextendedvariable',mfilename,extsubsref(x,i))];\n        end\n        y = reshape(y,n,m);\n        varargout{1} = y;\n        \n    case 'char' % YALMIP send 'graph' when it wants the epigraph or hypograph\n        switch varargin{1}\n            case {'milp','graph'}\n                % Description using epigraphs\n                t = varargin{2};\n                X = varargin{3};\n                \n                c = intvar(1,1);\n                F = (x-1 <= c <= x);\n\n                varargout{1} = F;\n                varargout{2} = struct('convexity','milp','monotonicity','milp','definiteness','milp');\n                varargout{3} = X;\n                \n            otherwise\n                error('SDPVAR/SORT called with CHAR argument?');\n        end\n    otherwise\n        error('Strange type on first argument in SDPVAR/SORT');\nend\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/floor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2163793201926002}}
{"text": "function mrk= convert_markers(mrk_old)\n\nmrk= rmfield(mrk_old, {'pos','fs'});\n\nmrk.time= mrk_old.pos*1000/mrk_old.fs;\nmrk.event= struct;\nif isfield(mrk_old, 'toe'),\n  mrk.event.desc= mrk_old.toe(:);\n  mrk= rmfield(mrk, {'toe'});\nend\n\nif isfield(mrk, 'indexedByEpochs'),\n  mrk= rmfield(mrk, setdiff(mrk.indexedByEpochs, 'time'));\n  mrk= rmfield(mrk, 'indexedByEpochs');\n  nEvents= length(mrk.time);\n  for Fld= mrk_old.indexedByEpochs,\n    fld= Fld{1};\n    fieldvar= mrk_old.(fld);\n    sz= size(fieldvar);\n    eventdim= find(sz==nEvents);\n    if isempty(eventdim),\n      error('no event information found in field %s', fld);\n    end\n    if length(eventdim)>1,\n      error('cannot decide event dimension in field %s', fld);\n    end\n    if eventdim~=1,\n      % permute dimensions to make the first one index events\n      dimorder= [eventdim setdiff(1:length(sz), eventdim)];\n      fieldvar= permute(fieldvar, dimorder);\n    end\n    mrk.event= setfield(mrk.event, fld, fieldvar);\n  end\nend\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/transitional/convert_markers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21637932019260017}}
{"text": "function [hdr] = read_bucn_nirshdr(filename)\n\n% READ_BUCN_NIRSHDR reads the header information of ASCII-formatted NIRS\n% data acquired with the UCL-BIRKBECK machine and postprocessed by the\n% Paris group. The first line contains the channel labels and the rest of\n% the file contains per line a time sample. The first column specifies the\n% time axis.\n%\n% Use as\n%   [hdr] = read_bucn_nirshdr(filename)\n%\n% See also READ_BUCN_NIRSDATA, READ_BUCN_NIRSEVENT\n\n% Copyright (C) 2011, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id: read_bucn_nirshdr.m$\n\nfid = fopen_or_error(filename, 'r');\n\n% read the first line\nline1 = textscan(fid, '%[^\\n]',1);\n\n% field delimiter can be space or tab\nlabelspc = textscan(line1{1}{1}, '%[^ ]');\nlabeltab = textscan(line1{1}{1}, '%[^\\t]');\n\n% let tab as a delimiter prevail\nif numel(labeltab{1})>1\n  label = labeltab{1};\nelse\n  label = labelspc{1};\nend\nnchan = numel(label);\nFs    = str2num(strtok(strtok(label{1},'#Time.'),'Hz'));\n\n% test whether the channel labels are non-numeric\nlabelnumber = cellfun(@str2num, label, 'UniformOutput', false);\nlabelstring = cellfun(@isempty, labelnumber, 'UniformOutput', true);\nif ~any(labelstring)\n  ft_error('channel labels were not found in the first line of the file');\nend\n\n% read the rest\ndat = textscan(fid, '%f');\nfclose(fid);\n\ndat  = reshape(dat{1}, nchan, []);\nnsmp = size(dat,2);\n\n% create the output\nhdr          = [];\nhdr.Fs       = Fs;\nhdr.label    = label;\nhdr.nTrials  = 1;\nhdr.nSamples = nsmp;\nhdr.nSamplesPre = 0;\nhdr.nChans   = nchan;\nhdr.time     = dat(1,:); % events in the raw event file have both a sample and a time stamp\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_bucn_nirshdr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21637931414650785}}
{"text": "function x = vec( x )\n\n% VEC   CVX implementation of vec\n\ns = x.size_;\nn = prod(s);\nif s(1) ~= n,\n\tx = cvx( [ n, 1 ], x.basis_ );\nend\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/functions/@cvx/vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21620263719888969}}
{"text": "% Analyzes families of whole-cell simulations\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Created: 11/1/2012\nclassdef MultiGenerations\n    properties (Constant = true)\n        ANCESTRY_COLIDX_CELL = 1\n        ANCESTRY_COLIDX_GEN = 2\n        ANCESTRY_COLIDX_FAMILY = 3\n        ANCESTRY_COLIDX_PARENT = 4\n        ANCESTRY_COLIDX_CHILD1 = 5\n        ANCESTRY_COLIDX_CHILD2 = 6\n    end\n    \n    methods (Static = true)\n        function run(simBatchDir, nGen, nCellFirstGen)\n            %% import\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            import edu.stanford.covert.cell.sim.util.CachedSimulationObjectUtil;\n            import edu.stanford.covert.cell.sim.util.PlotUtil;\n            import edu.stanford.covert.cell.sim.util.SimulationDiskUtil;\n            import edu.stanford.covert.cell.sim.util.SimulationEnsemble;\n            \n            %%\n            if nargin < 3\n                simBatchDir = '2012_11_15_18_48_23';\n                nGen = 3;\n                nCellFirstGen = 8;\n            end\n            \n            outDir = [SimulationDiskUtil.getBaseDir() filesep simBatchDir];\n            \n            if ~exist(outDir, 'dir')\n                mkdir(outDir)\n            end\n            \n            %% load constants\n            sim = CachedSimulationObjectUtil.load();\n            massState = sim.state('Mass');\n            pm = sim.state('ProteinMonomer');\n            pc = sim.state('ProteinComplex');\n            \n            %% load data\n            ancestry = MultiGenerations.calcAncestry(nGen, nCellFirstGen);\n            relations = MultiGenerations.calcAncestryRelations(nGen, nCellFirstGen);\n            \n            [~, simData, simStartTimes, divSimTfs, finSimTfs, finSimIdxs, propNames, ...\n                dnaBndMons, dnaBndCpxs, otherBndCpxs, dnaBndMonTfs, dnaBndCpxTfs, otherBndCpxTfs] = ...\n                MultiGenerations.cacheSimData(simBatchDir);\n            simData = simData{1};\n            simStartTimes = simStartTimes{1};\n            divSimTfs = divSimTfs{1};\n            finSimTfs = finSimTfs{1};\n            finSimIdxs = finSimIdxs{1};\n            dnaBndMons = dnaBndMons{1};\n            dnaBndCpxs = dnaBndCpxs{1};\n            otherBndCpxs = otherBndCpxs{1};\n            dnaBndMonTfs = dnaBndMonTfs{1};\n            dnaBndCpxTfs = dnaBndCpxTfs{1};\n            otherBndCpxTfs = otherBndCpxTfs{1};\n            \n            %% population growth\n            %growth traces\n            for iFamily = 1:nCellFirstGen\n                famIdxs = find(finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == iFamily);\n                colors = MultiGenerations.calcRedGreenColors(numel(famIdxs));\n                [~, order] = sort(simStartTimes(famIdxs));\n                colors(order, :) = colors;\n                tStep = 10;\n                \n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                for i = 1:numel(famIdxs)\n                    tmp = SimulationEnsemble.load(simBatchDir, {'Time' 'values'; 'MetabolicReaction', 'growth'}, [], [], tStep, 'extract', famIdxs(i));\n                    tmpTime = permute(tmp.Time.values, [1 3 2]) / 3600;\n                    tmpGrowth = permute(tmp.MetabolicReaction.growth, [1 3 2]) * ...\n                        massState.cellInitialDryWeight / (1 - massState.fractionWetWeight) * 3600 * 1e15;\n                    plot(axesHandle, simStartTimes(famIdxs(i)) + tmpTime, tmpGrowth, ...\n                        'Color', colors(i, :));\n                end\n                xlabel(axesHandle, 'Time (h)');\n                ylabel(axesHandle, 'Growth (fg h^{-1})');\n                saveas(figHandle, [outDir filesep 'Growth-Family-' num2str(iFamily) '.pdf']);\n                close(figHandle);\n            end\n            \n            %number cells\n            nCells = NaN(nGen, 1);\n            nSurvive = NaN(nGen, 1);\n            for iGen = 0:nGen-1\n                nCells(iGen + 1) = sum(ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & finSimTfs);\n                nSurvive(iGen + 1) = sum(ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & divSimTfs);\n            end\n            fracSurvive = nSurvive ./ nCells;\n            \n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            \n            plot(axesHandle, 0:nGen-1, nCells, 'b.')\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Population');\n            xlim(axesHandle, [-0.5 nGen-0.5]);\n            ylim(axesHandle, [0 75]);\n            \n            expFunc = @(a, b, x) a * exp(x / b);\n            [f, gof] = fit((0:nGen-1)', nCells, ...\n                fittype(expFunc),  ...\n                fitoptions('Method', 'NonlinearLeastSquares', 'lower', [0.5 * nCellFirstGen  0.5], 'upper', [2.0 * nCellFirstGen  3], 'StartPoint', [nCellFirstGen 1/log(2)]));\n            plot(axesHandle, (0:0.1:nGen-1)', expFunc(f.a, f.b, (0:0.1:nGen-1)'), 'Color', 'r');\n            \n            saveas(figHandle, [outDir filesep 'PopulationSize.pdf']);\n            close(figHandle);\n            \n            %% survival\n            %all families\n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            \n            errorbar(0:nGen-1, fracSurvive * 100, sqrt(fracSurvive .* (1 - fracSurvive)) ./ sqrt(nCells) * 100, 'b.', 'Parent', axesHandle);\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Survival (%)');\n            xlim(axesHandle, [-0.5 nGen-0.5]);\n            ylim(axesHandle, [0 100])\n            \n            [f, gof] = fit((0:nGen-1)', fracSurvive * 100, ...\n                fittype('poly1'), ...\n                fitoptions('Method', 'LinearLeastSquares', 'Weights', sqrt(fracSurvive .* (1 - fracSurvive)) ./ sqrt(nCells) * 100));\n            plot(axesHandle, (0:0.1:nGen-1)', (0:0.1:nGen-1)' * f.p1 + f.p2, 'Color', 'r');\n            \n            saveas(figHandle, [outDir filesep 'Survival.pdf']);\n            close(figHandle);\n            \n            %left/right\n            nCellsLR = NaN(nGen, 2);\n            nSurviveLR = NaN(nGen, 2);\n            for iGen = 0:nGen-1\n                nCellsLR(iGen + 1, 1) = sum(ancestry(1:2:end, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & finSimTfs(1:2:end, 1));\n                nCellsLR(iGen + 1, 2) = sum(ancestry(2:2:end, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & finSimTfs(2:2:end, 1));\n                nSurviveLR(iGen + 1, 1) = sum(ancestry(1:2:end, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & divSimTfs(1:2:end, 1));\n                nSurviveLR(iGen + 1, 2) = sum(ancestry(2:2:end, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen & divSimTfs(2:2:end, 1));\n            end\n            fracSurviveLR = nSurviveLR ./ nCellsLR;\n            \n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            \n            h = plot(axesHandle, 1:nGen-1, fracSurviveLR(2:end, :) * 100);\n            legend(h, {'Left', 'Right'}, 'Location', 'NorthEastOutside');\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Survival (%)');\n            xlim(axesHandle, [0.5 nGen-0.5]);\n            ylim(axesHandle, [0 100])\n            \n            saveas(figHandle, [outDir filesep 'Survival-LeftRight.pdf']);\n            close(figHandle);\n            \n            %by family\n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            \n            colors = MultiGenerations.calcRedGreenColors(nCellFirstGen);\n            labels = cell(nCellFirstGen, 1);\n            h = zeros(nCellFirstGen, 1);\n            for i = 1:nCellFirstGen\n                tfs = finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i;\n                fracSurvive = zeros(nGen, 1);\n                for iGen = 0:nGen-1\n                    fracSurvive(iGen + 1) = ...\n                        sum(ancestry(divSimTfs & tfs, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen) / ...\n                        sum(ancestry(tfs, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen);\n                end\n                h(i) = plot(axesHandle, 0:nGen-1, fracSurvive * 100, 'Color', colors(i, :));\n                labels{i} = num2str(i);\n            end\n            \n            legend(h, labels, 'Location', 'NorthEastOutside');\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Survival (%)');\n            xlim(axesHandle, [-0.5 nGen-0.5]);\n            ylim(axesHandle, [0 100])\n            \n            saveas(figHandle, [outDir filesep 'Survival-ByFamily.pdf']);\n            close(figHandle);\n            \n            %% left/right chromosome bias\n            %- bound protein\n            %- methylation\n            %- superhelical density\n            \n            gen_dnaBndMons = NaN(nGen, 2, sum(dnaBndMonTfs));\n            gen_dnaBndCpxs = NaN(nGen, 2, sum(dnaBndCpxTfs));\n            gen_otherBndCpxs = NaN(nGen, 2, sum(otherBndCpxTfs));\n            \n            for iGen = 0:nGen - 1\n                lefts  = find( isodd(finSimIdxs) & ancestry(finSimIdxs, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen);\n                rights = find(~isodd(finSimIdxs) & ancestry(finSimIdxs, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen);\n                \n                gen_dnaBndMons(iGen+1, 1, :) = mean(dnaBndMons(lefts, :), 1);\n                gen_dnaBndMons(iGen+1, 2, :) = mean(dnaBndMons(rights, :), 1);\n                \n                gen_dnaBndCpxs(iGen+1, 1, :) = mean(dnaBndCpxs(lefts, :), 1);\n                gen_dnaBndCpxs(iGen+1, 2, :) = mean(dnaBndCpxs(rights, :), 1);\n                \n                gen_otherBndCpxs(iGen+1, 1, :) = mean(otherBndCpxs(lefts, :), 1);\n                gen_otherBndCpxs(iGen+1, 2, :) = mean(otherBndCpxs(rights, :), 1);\n            end\n            \n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            h = plot(axesHandle, (1:nGen-1)', permute(gen_dnaBndMons(2:end, 1, :), [1 3 2]));\n            g = plot(axesHandle, (1:nGen-1)', permute(gen_dnaBndMons(2:end, 2, :), [1 3 2]));\n            colors = MultiGenerations.calcRedGreenColors(size(gen_dnaBndMons, 3));\n            for i = 1:size(gen_dnaBndMons, 3)\n                set(h(i), 'LineStyle', '-', 'Color', colors(i, :))\n                set(g(i), 'LineStyle', ':', 'Color', colors(i, :))\n            end\n            legend(h, pm.wholeCellModelIDs(pm.boundIndexs(dnaBndMonTfs)), 'Location', 'NorthEastOutside', 'Interpreter', 'none');\n            xlim(axesHandle, [0.5 nGen-0.5])\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Protein monomers')\n            saveas(figHandle, [outDir filesep 'DNABoundMonomerLeftRightBias.pdf']);\n            close(figHandle);\n            \n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            h = plot(axesHandle, (1:nGen-1)', permute(gen_dnaBndCpxs(2:end, 1, :), [1 3 2]));\n            g = plot(axesHandle, (1:nGen-1)', permute(gen_dnaBndCpxs(2:end, 2, :), [1 3 2]));\n            colors = MultiGenerations.calcRedGreenColors(size(gen_dnaBndCpxs, 3));\n            for i = 1:size(gen_dnaBndCpxs, 3)\n                set(h(i), 'LineStyle', '-', 'Color', colors(i, :))\n                set(g(i), 'LineStyle', ':', 'Color', colors(i, :))\n            end\n            legend(h, pc.wholeCellModelIDs(pc.boundIndexs(dnaBndCpxTfs)), 'Location', 'NorthEastOutside', 'Interpreter', 'none');\n            xlim(axesHandle, [0.5 nGen-0.5])\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Protein complexes')\n            saveas(figHandle, [outDir filesep 'DNABoundComplexLeftRightBias.pdf']);\n            close(figHandle);\n            \n            [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n            hold(axesHandle, 'on');\n            h = plot(axesHandle, (1:nGen-1)', permute(gen_otherBndCpxs(2:end, 1, :), [1 3 2]));\n            g = plot(axesHandle, (1:nGen-1)', permute(gen_otherBndCpxs(2:end, 2, :), [1 3 2]));\n            colors = MultiGenerations.calcRedGreenColors(size(gen_otherBndCpxs, 3));\n            for i = 1:size(gen_otherBndCpxs, 3)\n                set(h(i), 'LineStyle', '-', 'Color', colors(i, :))\n                set(g(i), 'LineStyle', ':', 'Color', colors(i, :))\n            end\n            legend(h, pc.wholeCellModelIDs(pc.boundIndexs(otherBndCpxTfs)), 'Location', 'NorthEastOutside', 'Interpreter', 'none');\n            xlim(axesHandle, [0.5 nGen-0.5])\n            xlabel(axesHandle, 'Generation');\n            ylabel(axesHandle, 'Protein complexes')\n            saveas(figHandle, [outDir filesep 'OtherBoundComplexLeftRightBias.pdf']);\n            close(figHandle);\n            \n            %% growth, mass, cell cycle phase durations\n            for iProp = 1:size(simData, 2)\n                %all families\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                boxplot(axesHandle, simData(finSimTfs, iProp), ancestry(finSimTfs, MultiGenerations.ANCESTRY_COLIDX_GEN));\n                title(axesHandle, [propNames{iProp, 1} ' - All Cells'])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'BoxPlot-AllCells.pdf']);\n                close(figHandle);\n                \n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                boxplot(axesHandle, simData(divSimTfs, iProp), ancestry(divSimTfs, MultiGenerations.ANCESTRY_COLIDX_GEN));\n                title(axesHandle, [propNames{iProp, 1} ' - Successful Divisions'])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'BoxPlot-SuccessfulCells.pdf']);\n                close(figHandle);\n                \n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                h = zeros(nGen, 1);\n                x = simData(finSimTfs, iProp);\n                edges = linspace(min(x), max(x), 20);\n                labels = cell(nGen, 1);\n                colors = MultiGenerations.calcRedGreenColors(nGen);\n                for iGen = 0:nGen-1\n                    tfs = finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen;\n                    cnts = histc(simData(tfs, iProp), edges);\n                    cnts = cnts / sum(tfs);\n                    h(iGen + 1) = plot(axesHandle, edges, cnts, 'Color', colors(iGen + 1, :));\n                    labels{iGen + 1} = num2str(iGen);\n                end\n                title(axesHandle, [propNames{iProp, 1} ' - All Cells'])\n                xlabel(axesHandle, propNames{iProp, 2});\n                ylabel(axesHandle, 'Frequency');\n                legend(h, labels);\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'Histogram-AllCells.pdf']);\n                close(figHandle);\n                \n                %left/right bias\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                lefts = false(size(finSimTfs));\n                lefts(1:2:end, 1) = true;\n                yData = NaN(nGen, 1);\n                for iGen = 0:nGen-1\n                    yData(iGen + 1, 1) = nanmean(simData( lefts & finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen, iProp));\n                    yData(iGen + 1, 2) = nanmean(simData(~lefts & finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen, iProp));\n                end\n                h = plot(axesHandle, 1:nGen-1, yData(2:end, :));\n                legend(h, {'Left', 'Right'}, 'Location', 'NorthEastOutside');\n                title(axesHandle, [propNames{iProp, 1}])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'MeanLeftRight.pdf']);\n                close(figHandle);\n                \n                %by family\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                colors = MultiGenerations.calcRedGreenColors(nCellFirstGen);\n                labels = cell(nCellFirstGen, 1);\n                h = zeros(nCellFirstGen, 1);\n                for i = 1:nCellFirstGen\n                    tfs = finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i;\n                    h(i) = plot(axesHandle, ancestry(tfs, MultiGenerations.ANCESTRY_COLIDX_GEN), ...\n                        simData(tfs, iProp), '.', 'Color', colors(i, :));\n                    \n                    labels{i} = num2str(i);\n                end\n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, [propNames{iProp, 1} ' - All Cells'])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                xlim(axesHandle, [-0.5 nGen-0.5]);\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'Distribution.pdf']);\n                close(figHandle);\n                \n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                colors = MultiGenerations.calcRedGreenColors(nCellFirstGen);\n                labels = cell(nCellFirstGen, 1);\n                h = zeros(nCellFirstGen, 1);\n                for i = 1:nCellFirstGen\n                    tfs = finSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i;\n                    gens = ancestry(tfs, MultiGenerations.ANCESTRY_COLIDX_GEN);\n                    x = simData(tfs, iProp);\n                    avgs = zeros(nGen, 1);\n                    for iGen = 0:nGen-1\n                        avgs(iGen + 1) = nanmean(x(gens == iGen));\n                    end\n                    h(i) = plot(axesHandle, 0:nGen-1, avgs, 'Color', colors(i, :));\n                    \n                    labels{i} = num2str(i);\n                end\n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, [propNames{iProp, 1} ' - All Cells'])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                xlim(axesHandle, [-0.25 nGen-0.75]);\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'MeanByLineage-AllCells.pdf']);\n                close(figHandle);\n                \n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                colors = MultiGenerations.calcRedGreenColors(nCellFirstGen);\n                labels = cell(nCellFirstGen, 1);\n                h = zeros(nCellFirstGen, 1);\n                for i = 1:nCellFirstGen\n                    tfs = divSimTfs & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i;\n                    gens = ancestry(tfs, MultiGenerations.ANCESTRY_COLIDX_GEN);\n                    x = simData(tfs, iProp);\n                    avgs = zeros(nGen, 1);\n                    for iGen = 0:nGen-1\n                        avgs(iGen + 1) = nanmean(x(gens == iGen));\n                    end\n                    h(i) = plot(axesHandle, 0:nGen-1, avgs, 'Color', colors(i, :));\n                    \n                    labels{i} = num2str(i);\n                end\n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, [propNames{iProp, 1} ' - Successful Divisions'])\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                xlim(axesHandle, [-0.25 nGen-0.75]);\n                saveas(figHandle, [outDir filesep propNames{iProp, 1} 'MeanByLineage-SuccessfulCells.pdf']);\n                close(figHandle);\n            end\n            \n            %% mother-daughter correlations within cell cycle\n            deltaGenerations = relations(finSimTfs, finSimTfs, 1);\n            removal = relations(finSimTfs, finSimTfs, 2);\n            \n            [idxs1, idxs2] = find(deltaGenerations == 1 & removal == 0);\n            \n            ensemble = SimulationEnsemble(simBatchDir, cell(0, 1), [1 2], find(finSimTfs));\n            simEndTimes = ensemble.stateData.simulationEndTimes;\n            states = SimulationEnsemble.load(simBatchDir, {'MetabolicReaction' 'growth'}, [], [], 1, 'extract', find(finSimTfs));\n            growth = permute(states.MetabolicReaction.growth, [4 3 1 2]);\n            growth(growth == 0) = NaN;\n            growth0 = growth(sub2ind(size(growth), (1:numel(simEndTimes))', simEndTimes));\n                       \n            r = zeros(1, size(growth, 2));\n            n = zeros(1, size(growth, 2));\n            for i = 1:size(growth, 2)\n                tfs = ~isnan(growth(idxs2, i));\n                r(i) = corr(growth0(idxs1(tfs)), growth(idxs2(tfs), i), 'type', 'Pearson');\n                n(i) = sum(simEndTimes >= i);\n            end\n            \n            [~, figHandle] = PlotUtil.newAxesHandle();\n            clf(figHandle);\n            \n            axesHandle = subplot(2, 1, 1);\n            plot(axesHandle, (1:size(growth, 2))/3600, r);\n            xlabel(axesHandle, 'Time (h)');\n            ylabel(axesHandle, 'Corr');\n            \n            axesHandle = subplot(2, 1, 2);\n            plot(axesHandle, (1:size(growth, 2))/3600, n);\n            xlabel(axesHandle, 'Time (h)');\n            ylabel(axesHandle, 'No. cells');\n\n            saveas(figHandle, [outDir filesep 'GrowthCorrelationDecay.pdf']);\n            close(figHandle);\n            \n            %% descendents\n            deltaGenerations = relations(:, :, 1);\n            removal = relations(:, :, 2);\n            \n            colors = MultiGenerations.calcRedGreenColors(nGen - 1);\n            for iProp = 1:size(propNames, 1)\n                %all relationships\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = zeros(nGen - 1, 1);\n                h = zeros(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == iGen & removal == 0);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2);\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('{\\\\Delta}g=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, ['All descendents - ' propNames{iProp, 1}])\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, '{\\Delta}Generation');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'Descendents-all-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n                \n                %relationships from founders\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = zeros(nGen - 1, 1);\n                h = zeros(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == iGen & removal == 0);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2);\n                    tfs = tfs & ancestry(idxs1, MultiGenerations.ANCESTRY_COLIDX_GEN) == 0;\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('{\\\\Delta}g=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, ['Generations from founder - ' propNames{iProp, 1}])\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, '{\\Delta}Generation');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'Descendents-FromFounders-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n                \n                %relationships from founders\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = zeros(nGen - 1, 1);\n                h = zeros(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == 1 & removal == 0);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2);\n                    tfs = tfs & ancestry(idxs1, MultiGenerations.ANCESTRY_COLIDX_GEN) == (iGen - 1);\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('g_1=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, propNames{iProp, 1})\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, '{\\Delta}Generation');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'Descendents-Children-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n            end\n            \n            %% siblings, cousins\n            deltaGenerations = relations(:, :, 1);\n            removal = relations(:, :, 2);\n            \n            colors = MultiGenerations.calcRedGreenColors(nGen - 1);\n            for iProp = 1:size(propNames, 1)\n                %all cousins\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = zeros(nGen - 1, 1);\n                h = zeros(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == 0 & removal == iGen);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2);\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('{\\\\Delta}r=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, ['All cousins - ' propNames{iProp, 1}])\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, 'Removal');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'Cousins-all-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n                \n                %cousins of last generation\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = zeros(nGen - 1, 1);\n                h = zeros(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == 0 & removal == iGen);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2) & ancestry(idxs1, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen;\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('{\\\\Delta}r=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h, labels, 'Location', 'NorthEastOutside');\n                title(axesHandle, ['Cousins of last generation - ' propNames{iProp, 1}])\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, 'Removal');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'Cousins-LastGeneration-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n                \n                %first cousins by generation\n                [~, figHandle] = PlotUtil.newAxesHandle();\n                clf(figHandle);\n                \n                axesHandle = subplot(2, 1, 1);\n                hold(axesHandle, 'on');\n                \n                r = NaN(nGen - 1, 1);\n                h = NaN(nGen - 1, 1);\n                labels = cell(nGen - 1, 1);\n                for iGen = 1:nGen-1\n                    [idxs1, idxs2] = find(deltaGenerations == 0 & removal == 1);\n                    tfs = finSimTfs(idxs1) & finSimTfs(idxs2);\n                    tfs = tfs & ancestry(idxs1, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen;\n                    if ~any(tfs)\n                        continue;\n                    end\n                    idxs1 = idxs1(tfs, :);\n                    idxs2 = idxs2(tfs, :);\n                    \n                    r(iGen) = corr(simData(idxs1, iProp), simData(idxs2, iProp), 'type', 'Pearson');\n                    h(iGen) = plot(simData(idxs1, iProp), simData(idxs2, iProp), '.', 'Color', colors(iGen, :));\n                    labels{iGen} = sprintf('g=%d (n=%d)', iGen, numel(idxs1));\n                end\n                \n                legend(h(~isnan(h)), labels(~isnan(h)), 'Location', 'NorthEastOutside');\n                title(axesHandle, ['All First Cousins - ' propNames{iProp, 1}])\n                xlabel(axesHandle, 'Parent');\n                ylabel(axesHandle, 'Child');\n                \n                axesHandle = subplot(2, 1, 2);\n                plot(axesHandle, 1:nGen-1, r);\n                line([0.5 nGen-0.5], [0 0], 'Color', 0.25 * [1 1 1], 'Parent', axesHandle);\n                xlabel(axesHandle, '{\\Delta}Generation');\n                ylabel(axesHandle, 'Corr');\n                xlim(axesHandle, [0.5 nGen-0.5]);\n                ylim(axesHandle, [-1 1]);\n                set(axesHandle, 'XTick', 1:nGen-1);\n                box(axesHandle, 'off');\n                \n                saveas(figHandle, [outDir filesep 'FirstCousins-all-' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n            end\n            \n            %% Varying effective DnaA copy number\n            MultiGenerations.runEffectiveDnaACopyNumberAnalysis();\n        end\n        \n        function runEffectiveDnaACopyNumberAnalysis(outDir)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            import edu.stanford.covert.cell.sim.util.PlotUtil;\n            import edu.stanford.covert.cell.sim.util.SimulationDiskUtil;\n            \n            [simBatchDirs, simData, ~, ~, finSimTfs, ~, propNames] = MultiGenerations.cacheSimData();\n            \n            nSimBatch = size(simBatchDirs, 1);\n            \n            %% create output directory\n            if nargin < 1\n                outDir = [SimulationDiskUtil.getBaseDir() filesep 'multiGenerations'];\n            end\n            if ~exist(outDir, 'dir')\n                mkdir(outDir)\n            end\n            \n            %% analyze\n            colors = MultiGenerations.calcRedGreenColors(nSimBatch);\n            for iProp = 1:size(propNames, 1)\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                hold(axesHandle, 'on');\n                \n                h = zeros(nSimBatch, 1);\n                for iSimBatch = 1:nSimBatch\n                    nGen = simBatchDirs{iSimBatch, 2};\n                    nCellFirstGen = simBatchDirs{iSimBatch, 3};\n                    ancestry = MultiGenerations.calcAncestry(nGen, nCellFirstGen);\n                    \n                    avgs = zeros(1, nGen);\n                    for iGen = 0:nGen - 1\n                        avgs(1, iGen + 1) = nanmean(simData{iSimBatch}(finSimTfs{iSimBatch} & ancestry(:, MultiGenerations.ANCESTRY_COLIDX_GEN) == iGen, iProp));\n                    end\n                    h(iSimBatch) = plot(axesHandle, 0:nGen-1, avgs, 'Color', colors(iSimBatch, :));\n                end\n                \n                xlim(axesHandle, [-0.5 nGen-0.5]);\n                title(axesHandle, ['DnaA Copy Number vs ' propNames{iProp, 1}]);\n                xlabel(axesHandle, 'Generation');\n                ylabel(axesHandle, propNames{iProp, 2});\n                legend(h, cellfun(@num2str, simBatchDirs(:, 4), 'UniformOutput', false), 'Location', 'NorthEastOutside');\n                \n                saveas(figHandle, [outDir filesep 'DnaACopyNumberVs' propNames{iProp, 1} '.pdf']);\n                close(figHandle);\n            end\n        end\n        \n        function [simBatchDirs, simData, simStartTimes, divSimTfs, finSimTfs, finSimIdxs, propNames, ...\n                dnaBndMons, dnaBndCpxs, otherBndCpxs, dnaBndMonTfs, dnaBndCpxTfs, otherBndCpxTfs] = cacheSimData(simBatchDirs)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            import edu.stanford.covert.cell.sim.util.CachedSimulationObjectUtil;\n            import edu.stanford.covert.cell.sim.util.SimulationDiskUtil;\n            \n            if nargin >= 1\n                if ~iscell(simBatchDirs)\n                    simBatchDirs = {simBatchDirs};\n                end\n            else\n                simBatchDirs = {\n                    '2012_11_15_18_48_23'  3 8  3\n                    '2012_10_24_00_49_53'  6 8  1\n                    };\n            end\n            \n            nSimBatch = size(simBatchDirs, 1);\n            \n            %% load constants\n            sim = CachedSimulationObjectUtil.load();\n            \n            %% get data\n            simData = cell(nSimBatch, 1);\n            simStartTimes = cell(nSimBatch, 1);\n            divSimTfs = cell(nSimBatch, 1);\n            finSimTfs = cell(nSimBatch, 1);\n            finSimIdxs = cell(nSimBatch, 1);\n            dnaBndMons = cell(nSimBatch, 1);\n            dnaBndCpxs = cell(nSimBatch, 1);\n            otherBndCpxs = cell(nSimBatch, 1);\n            dnaBndMonTfs = cell(nSimBatch, 1);\n            dnaBndCpxTfs = cell(nSimBatch, 1);\n            otherBndCpxTfs = cell(nSimBatch, 1);\n            for iSimBatch = 1:nSimBatch\n                simBatchDir = simBatchDirs{iSimBatch, 1};\n                if exist([SimulationDiskUtil.getBaseDir() filesep simBatchDir filesep 'MultiGenerationsData.mat'], 'file')\n                    tmp = load([SimulationDiskUtil.getBaseDir() filesep simBatchDir filesep 'MultiGenerationsData.mat']);\n                else\n                    nGen = simBatchDirs{iSimBatch, 2};\n                    nCellFirstGen = simBatchDirs{iSimBatch, 3};\n                    \n                    [tmp_simData, tmp_simStartTimes, tmp_divSimTfs, tmp_finSimTfs, tmp_finSimIdxs, tmp_propNames, ...\n                        tmp_dnaBndMons, tmp_dnaBndCpxs, tmp_otherBndCpxs, tmp_dnaBndMonTfs, tmp_dnaBndCpxTfs, tmp_otherBndCpxTfs] = ...\n                        MultiGenerations.getSimData(simBatchDir, nGen, nCellFirstGen, sim);\n                    \n                    tmp = struct;\n                    tmp.simData = tmp_simData;\n                    tmp.simStartTimes = tmp_simStartTimes;\n                    tmp.divSimTfs = tmp_divSimTfs;\n                    tmp.finSimTfs = tmp_finSimTfs;\n                    tmp.finSimIdxs = tmp_finSimIdxs;\n                    tmp.propNames = tmp_propNames;\n                    tmp.dnaBndMons = tmp_dnaBndMons;\n                    tmp.dnaBndCpxs = tmp_dnaBndCpxs;\n                    tmp.otherBndCpxs = tmp_otherBndCpxs;\n                    tmp.dnaBndMonTfs = tmp_dnaBndMonTfs;\n                    tmp.dnaBndCpxTfs = tmp_dnaBndCpxTfs;\n                    tmp.otherBndCpxTfs = tmp_otherBndCpxTfs;\n                    save([SimulationDiskUtil.getBaseDir() filesep simBatchDir filesep 'MultiGenerationsData.mat'], '-struct', 'tmp');\n                end\n                simData{iSimBatch} = tmp.simData;\n                simStartTimes{iSimBatch} = tmp.simStartTimes;\n                divSimTfs{iSimBatch} = tmp.divSimTfs;\n                finSimTfs{iSimBatch} = tmp.finSimTfs;\n                finSimIdxs{iSimBatch} = tmp.finSimIdxs;\n                                \n                dnaBndMons{iSimBatch} = tmp.dnaBndMons;\n                dnaBndCpxs{iSimBatch} = tmp.dnaBndCpxs;\n                otherBndCpxs{iSimBatch} = tmp.otherBndCpxs;\n                dnaBndMonTfs{iSimBatch} = tmp.dnaBndMonTfs;\n                dnaBndCpxTfs{iSimBatch} = tmp.dnaBndCpxTfs;\n                otherBndCpxTfs{iSimBatch} = tmp.otherBndCpxTfs;\n                \n                propNames = tmp.propNames;\n            end\n        end\n        \n        function [simData, simStartTimes, divSimTfs, finSimTfs, finSimIdxs, propNames, ...\n                dnaBndMons, dnaBndCpxs, otherBndCpxs, ...\n                dnaBndMonTfs, dnaBndCpxTfs, otherBndCpxTfs] = ...\n                getSimData(simBatchDir, nGen, nCellFirstGen, sim)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            import edu.stanford.covert.cell.sim.util.SimulationDiskUtil;\n            import edu.stanford.covert.cell.sim.util.SimulationEnsemble;\n            import edu.stanford.covert.cell.sim.util.SummaryLogger;\n            \n            ancestry = MultiGenerations.calcAncestry(nGen, nCellFirstGen);\n            nCells = size(ancestry, 1);\n            \n            g = sim.gene;\n            c = sim.compartment;\n            massState = sim.state('Mass');\n            met = sim.state('Metabolite');\n            pm = sim.state('ProteinMonomer');\n            pc = sim.state('ProteinComplex');\n            \n            simStats = SummaryLogger.getSimulationStatistics([SimulationDiskUtil.getBaseDir() filesep simBatchDir], 1:nCells);\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_GROWTH) = ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_GROWTH)' * ...\n                massState.cellInitialDryWeight / (1 - massState.fractionWetWeight) * 3600 * 1e15;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_INIT_TIME) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_INIT_TIME) / 3600;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_REP_TIME) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_REP_TIME) / 3600;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_TIME) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_TIME) / 3600;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_CYTOKINESIS_TIME) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_CYTOKINESIS_TIME) / 3600;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_MASS_DOUBLING_TIME) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_MASS_DOUBLING_TIME) / 3600;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_FIN_MASS) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_FIN_MASS) * 1e15;\n            simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_MASS) = simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_MASS) * 1e15;\n            \n            simStartTimes = zeros(size(ancestry, 1), 1);\n            for i = 1:size(ancestry, 1)\n                if isnan(ancestry(i, MultiGenerations.ANCESTRY_COLIDX_PARENT))\n                    simStartTimes(i) = 0;\n                else\n                    iParent = ancestry(i, MultiGenerations.ANCESTRY_COLIDX_PARENT);\n                    simStartTimes(i) = ...\n                        simStartTimes(iParent) +  ...\n                        simStats(iParent, SummaryLogger.SIM_STATUS_INDEX_CYTOKINESIS_TIME) + ...\n                        1 / 3600;\n                end\n                \n                if ~isnan(ancestry(i, MultiGenerations.ANCESTRY_COLIDX_CHILD1)) &&  ...\n                        simStats(i, SummaryLogger.SIM_STATUS_INDEX_STATUS) ~= SummaryLogger.SIM_STATUS_COMPLETED_WITH_DIVISION\n                    simStats(ancestry(i, MultiGenerations.ANCESTRY_COLIDX_CHILD1), SummaryLogger.SIM_STATUS_INDEX_STATUS) = SummaryLogger.SIM_STATUS_DIDNT_START;\n                    simStats(ancestry(i, MultiGenerations.ANCESTRY_COLIDX_CHILD2), SummaryLogger.SIM_STATUS_INDEX_STATUS) = SummaryLogger.SIM_STATUS_DIDNT_START;\n                end\n            end\n            \n            divSimTfs = simStats(:, SummaryLogger.SIM_STATUS_INDEX_STATUS) == SummaryLogger.SIM_STATUS_COMPLETED_WITH_DIVISION;\n            nonDivSimTfs = simStats(:, SummaryLogger.SIM_STATUS_INDEX_STATUS) == SummaryLogger.SIM_STATUS_COMPLETED_WITHOUT_DIVISION;\n            finSimTfs = divSimTfs | nonDivSimTfs;\n            finSimIdxs = find(finSimTfs);\n            \n            props = {'dnaA_total'; 'dnaA_boxes'; 'rnaPolymerases'; 'ribosomes';\n                'amino_acids'; 'ntps'; 'rnas'; 'immatureRnas'; 'matureMonomers'; 'immatureMonomers';\n                'matureComplexs'; 'immatureComplexs'; 'atp'; 'adp'; 'amp'};\n            ensemble = SimulationEnsemble(simBatchDir, props, [1 2], finSimIdxs);\n            \n            rnaPolMonIdxs = pm.matureIndexs(any(pc.proteinComplexComposition(g.mRNAIndexs, pc.rnaPolymeraseIndexs(1), :), 3));\n            stateNames = {\n                'ProteinMonomer'  'counts'  rnaPolMonIdxs   c.cytosolIndexs\n                };\n            rnaPolSubunitCnts = SimulationEnsemble.load(simBatchDir, stateNames, 1, 1, 1, 'extract', finSimIdxs);\n            \n            stateNames = {\n                'ProteinMonomer'  'counts'                pm.boundIndexs  c.cytosolIndexs\n                'ProteinComplex'  'counts'                pc.boundIndexs  c.cytosolIndexs\n                'Chromosome'      'damagedBases'          ':'  ':'\n                'Chromosome'      'superhelicalDensity'   ':'  ':'\n                };\n            chromState = SimulationEnsemble.load(simBatchDir, stateNames, 1, 1, 1, 'extract', finSimIdxs);\n            \n            dnaBndMonTfs = any(any(any(chromState.ProteinMonomer.counts, 2), 3), 4);\n            dnaBndCpxTfs = any(any(any(chromState.ProteinComplex.counts, 2), 3), 4) & ~any(any(pc.proteinComplexComposition(g.getIndexs('MG_469'), :, :), 1), 3)';\n            otherBndCpxTfs = any(any(any(chromState.ProteinComplex.counts, 2), 3), 4) &  any(any(pc.proteinComplexComposition(g.getIndexs('MG_469'), :, :), 1), 3)';\n            \n            dnaBndMons = NaN(numel(finSimIdxs), sum(dnaBndMonTfs));\n            dnaBndCpxs = NaN(numel(finSimIdxs), sum(dnaBndCpxTfs));\n            otherBndCpxs = NaN(numel(finSimIdxs), sum(otherBndCpxTfs));\n            methylations = NaN(numel(finSimIdxs), 1);\n            sigmas = NaN(numel(finSimIdxs), 1);\n            \n            for i = 1:numel(finSimIdxs)\n                dnaBndMons(i, :) = chromState.ProteinMonomer.counts(dnaBndMonTfs, 1, 1, i);\n                dnaBndCpxs(i, :) = chromState.ProteinComplex.counts(dnaBndCpxTfs, 1, 1, i);\n                otherBndCpxs(i, :) = chromState.ProteinComplex.counts(otherBndCpxTfs, 1, 1, i);\n                methylations(i, 1) = full(sum(sum(chromState.Chromosome.damagedBases(:, :, 1, i) == met.m6ADIndexs, 1), 2));\n                sigmas(i, 1) = full(chromState.Chromosome.superhelicalDensity(1, 1, 1, i));\n            end\n            \n            simData = [\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_GROWTH) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_FIN_MASS) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_INIT_TIME) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_TIME)-simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_INIT_TIME) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_CYTOKINESIS_TIME)-simStats(:, SummaryLogger.SIM_STATUS_INDEX_REP_TIME) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_CYTOKINESIS_TIME) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_INIT_MASS) ...\n                simStats(:, SummaryLogger.SIM_STATUS_INDEX_FIN_MASS) ...\n                zeros(size(simStats, 1), size(ensemble.stateData.values, 1) + size(rnaPolSubunitCnts.ProteinMonomer.counts, 1) + 2)\n                ];\n            simData(finSimTfs, 9:end) = [\n                permute(ensemble.stateData.values(:, :, 1, :), [4 1 2 3]) ...\n                permute(rnaPolSubunitCnts.ProteinMonomer.counts, [4 1 2 3]) ...\n                methylations ...\n                sigmas\n                ];\n            propNames = {\n                'InitialGrowth'                   'Growth (fg h^{-1})'\n                'FinalGrowth'                     'Growth (fg h^{-1})'\n                'ReplicationInitiationDuration'   'Time (h)'\n                'ReplicationDuration'             'Time (h)'\n                'CytokinesisDuration'             'Time (h)'\n                'CellCycleLength'                 'Time (h)'\n                'InitialMass'                     'Mass (fg)'\n                'FinalMass'                       'Mass (fg)'\n                'DnaA'                            'Count'\n                'BoundDnaA'                       'Count'\n                'RNAPolymerases'                  'Count'\n                'Ribosomes'                       'Count'\n                'AminoAcids'                      'Count'\n                'Ntps'                            'Count'\n                'Rnas'                            'Count'\n                'ImmatureRnas'                    'Count'\n                'MatureMonomers'                  'Count'\n                'ImmatureMonomers'                'Count'\n                'MatureComplexes'                 'Count'\n                'ImmatureComplexes'               'Count'\n                'Atp'                             'Count'\n                'Adp'                             'Count'\n                'Amp'                             'Count'\n                'RnaPolDelta'                     'Count'\n                'RnaPolAlpha'                     'Count'\n                'RnaPolBeta1'                     'Count'\n                'RnaPolBeta2'                     'Count'\n                'Methylations'                    'Count'\n                'SuperhelicalDensity'             'dimensionless'\n                };\n        end\n        \n        %Returns matrix with five colums:\n        %- cell index\n        %- generation\n        %- parent index\n        %- child-1 index\n        %- child-2 index\n        function ancestry = calcAncestry(nGen, nCellFirstGen)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            \n            nCells = nCellFirstGen * (2^nGen - 1);\n            \n            ancestry = NaN(nCells, 5);\n            \n            genOffset = 0;\n            iCell = 0;\n            for iGen = 0:nGen-1\n                for iGenCell = 1:nCellFirstGen * 2^iGen\n                    iCell = iCell + 1;\n                    \n                    if iGen == 0\n                        iParent = NaN;\n                        iFamily = iGenCell;\n                    else\n                        iParent = genOffset - nCellFirstGen * 2^(iGen-1) + ceil(iGenCell / 2);\n                        iFamily = ancestry(iParent, MultiGenerations.ANCESTRY_COLIDX_FAMILY);\n                    end\n                    \n                    if iGen < nGen-1\n                        iChild1 = genOffset + nCellFirstGen * 2^iGen + 2 * iGenCell - 1;\n                        iChild2 = genOffset + nCellFirstGen * 2^iGen + 2 * iGenCell;\n                    else\n                        iChild1 = NaN;\n                        iChild2 = NaN;\n                    end\n                    \n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_CELL) = genOffset + iGenCell;\n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_GEN) = iGen;\n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_FAMILY) = iFamily;\n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_PARENT) = iParent;\n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_CHILD1) = iChild1;\n                    ancestry(iCell, MultiGenerations.ANCESTRY_COLIDX_CHILD2) = iChild2;\n                end\n                genOffset = genOffset + nCellFirstGen * 2^iGen;\n            end\n        end\n        \n        function relations = calcAncestryRelations(nGen, nCellFirstGen)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            \n            nCells = 2^nGen - 1;\n            \n            %intergenerational -- difference in generations\n            generations = NaN(nCells, 1);\n            genOffset = 0;\n            for iGen = 0:nGen-1\n                iCell = genOffset + (1:2^iGen);\n                genOffset = genOffset + 2^iGen;\n                generations(iCell) = iGen;\n            end\n            deltaGeneration = -generations(:, ones(nCells, 1)) + generations(:, ones(nCells, 1))';\n            \n            %intragenerational -- number of generations since common ancestor\n            ancestry = MultiGenerations.calcAncestry(nGen, 1);\n            removal = NaN(nCells, nCells);\n            for iCell1 = 1:nCells\n                removal(iCell1, iCell1) = 0;\n                for iCell2 = iCell1+1:nCells\n                    [~, removal(iCell1, iCell2)] = MultiGenerations.calcCommonAncestor(iCell1, iCell2, ancestry);\n                    removal(iCell2, iCell1) = removal(iCell1, iCell2);\n                end\n            end\n            \n            tmp = cat(3, deltaGeneration, removal);\n            relations = NaN(nCellFirstGen * nCells, nCellFirstGen * nCells, 2); %cell-1 x cell-2 x [generation separation,  removal]\n            ancestry = MultiGenerations.calcAncestry(nGen, nCellFirstGen);\n            for i = 1:nCellFirstGen\n                relations(ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i, ancestry(:, MultiGenerations.ANCESTRY_COLIDX_FAMILY) == i, :) = tmp;\n            end\n        end\n        \n        function [iCommonAncestor, removal] = calcCommonAncestor(iCell1, iCell2, ancestry)\n            import edu.stanford.covert.cell.sim.analysis.MultiGenerations;\n            \n            if iCell1 == iCell2\n                iCommonAncestor = iCell1;\n                removal = 0;\n            elseif ancestry(iCell1, MultiGenerations.ANCESTRY_COLIDX_GEN) > ancestry(iCell2, MultiGenerations.ANCESTRY_COLIDX_GEN)\n                [iCommonAncestor, removal] = MultiGenerations.calcCommonAncestor(ancestry(iCell1, MultiGenerations.ANCESTRY_COLIDX_PARENT), iCell2, ancestry);\n            elseif ancestry(iCell1, MultiGenerations.ANCESTRY_COLIDX_GEN) < ancestry(iCell2, MultiGenerations.ANCESTRY_COLIDX_GEN)\n                [iCommonAncestor, removal] = MultiGenerations.calcCommonAncestor(iCell1, ancestry(iCell2, MultiGenerations.ANCESTRY_COLIDX_PARENT), ancestry);\n            else\n                [iCommonAncestor, removal] = MultiGenerations.calcCommonAncestor(...\n                    ancestry(iCell1, MultiGenerations.ANCESTRY_COLIDX_PARENT), ...\n                    ancestry(iCell2, MultiGenerations.ANCESTRY_COLIDX_PARENT), ...\n                    ancestry);\n                removal = removal + 1;\n            end\n        end\n        \n        function colors = calcRedGreenColors(n)\n            tmp = (0:n-1)';\n            r1 = 1;\n            r2 = 0;\n            g1 = 0;\n            g2 = 1;\n            b1 = 0;\n            b2 = 0;\n            colors = [\n                r1*2*max(0, 0.5-tmp/(n-1)) + r2*2*max(0, tmp/(n-1)-0.5) ...\n                g1*2*max(0, 0.5-tmp/(n-1)) + g2*2*max(0, tmp/(n-1)-0.5) ...\n                b1*2*max(0, 0.5-tmp/(n-1)) + b2*2*max(0, tmp/(n-1)-0.5) ...\n                ];\n        end\n    end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+analysis/MultiGenerations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21620263719888969}}
{"text": "function sFileOut = out_fopen_spm(OutputFile, sFileIn, ChannelMat)\n% OUT_FOPEN_SPM: Saves the header of a new empty SPM .mat/.dat file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2017-2022\n\n% Initialize SPM12+CAT12\n[isInstalled, errMsg] = bst_plugin('Install', 'spm12');\nif ~isInstalled\n    error(errMsg);\nend\n\n% Get the two output file names: .mat and .dat\n[fPath, fBase, fExt] = bst_fileparts(OutputFile);\nMatFile = bst_fullfile(fPath, [fBase, '.mat']);\nDatFile = bst_fullfile(fPath, [fBase, '.dat']);\n\n% Create .mat structure\nD.type      = 'continuous';\nD.Nsamples  = round((sFileIn.prop.times(2) - sFileIn.prop.times(1)) .* sFileIn.prop.sfreq) + 1;\nD.Fsample   = sFileIn.prop.sfreq;\nD.timeOnset = sFileIn.prop.times(1);\n% Trials\nD.trials.label  = 'Undefined';\nD.trials.events = repmat(struct('type', [], 'time', [], 'value', [], 'offset', [], 'duration', []),0);\nD.trials.onset  = sFileIn.prop.times(1);\nD.trials.bad    = 0;\nD.trials.tag    = [];\nD.trials.repl   = 1;\n% Events\nfor iEvt = 1:length(sFileIn.events)\n    for iOcc = 1:size(sFileIn.events(iEvt).times,2)\n        i = length(D.trials.events) + 1;\n        D.trials.events(i).type = sFileIn.events(iEvt).label;\n        if ~isempty(sFileIn.events(iEvt).notes) && ~isempty(sFileIn.events(iEvt).notes{iOcc})\n            D.trials.events(i).type = [D.trials.events(i).type '-' sFileIn.events(iEvt).notes{iOcc}];\n        end\n        D.trials.events(i).time = sFileIn.events(iEvt).times(1,iOcc);\n        D.trials.events(i).value = iEvt;\n        D.trials.events(i).offset = 0;\n        if (size(sFileIn.events(iEvt).times,1) == 2)\n            D.trials.events(i).duration = sFileIn.events(iEvt).times(2,iOcc) - sFileIn.events(iEvt).times(1,iOcc);\n        else\n            D.trials.events(i).duration = [];\n        end\n    end\nend\n% Channels\nfor i = 1:length(ChannelMat.Channel)\n    D.channels(i).bad      = (sFileIn.channelflag(i) == -1);\n    D.channels(i).label    = ChannelMat.Channel(i).Name;\n    D.channels(i).type     = ChannelMat.Channel(i).Type;\n    D.channels(i).X_plot2D = [];\n    D.channels(i).Y_plot2D = [];\n    D.channels(i).units    = 'm';\nend\n% Data\nD.data = file_array(DatFile, [length(ChannelMat.Channel), D.Nsamples], 'float32-le');\n% File name\nD.fname = [fBase, '.mat'];\nD.path = fPath;\n\n% Get sensor types\niEeg = channel_find(ChannelMat.Channel, 'EEG, SEEG, ECOG, NIRS');\niMeg = channel_find(ChannelMat.Channel, 'MEG, MEG REG');\nif ~isempty(iMeg)\n    error(['MEG sensors are currently not supported by this function.' 10 ...\n           'Please contact us through the Brainstorm user forum to request this feature.']);\nend\n% If all the channels have other types: consider it's all EEG\nif isempty(iEeg) && isempty(iMeg)\n    iEeg = 1:length(ChannelMat.Channel);\nend\n% Sensors\nfor i = 1:length(iEeg)\n    if ~isempty(ChannelMat.Channel(iEeg(i)).Loc) && ~all(ChannelMat.Channel(iEeg(i)).Loc(:) == 0)\n        D.sensors.eeg.chanpos(i,:) = ChannelMat.Channel(iEeg(i)).Loc(:,1)';\n        D.sensors.eeg.elecpos(i,:) = ChannelMat.Channel(iEeg(i)).Loc(:,1)';\n    else\n        D.sensors.eeg.chanpos(i,:) = [NaN NaN NaN];\n        D.sensors.eeg.elecpos(i,:) = [NaN NaN NaN];\n    end\n    D.sensors.eeg.chantype{i} = lower(ChannelMat.Channel(iEeg(i)).Type);\n    D.sensors.eeg.chanunit{i} = 'V';\n    D.sensors.eeg.label{i}    = ChannelMat.Channel(iEeg(i)).Name;\n    D.sensors.eeg.type        = 'ctf';\n    D.sensors.eeg.unit        = 'm';\n    D.sensors.eeg.balance.current = 'none';\nend\nD.sensors.chantype = 'eeg';\n% Rest of the structure\nD.fiducials    = repmat(struct(), 0);\nD.transform.ID = 'time';\nD.condlist     = {};\nD.montage.M    = [];\nD.montage.Mind = 0;\nD.history      = repmat(struct(), 0);\nD.other        = repmat(struct(), 0);\n\n% Save file\nsave(MatFile, 'D');\n\n% Create a new header structure\nsFileOut = sFileIn;\nsFileOut.filename  = MatFile;\nsFileOut.condition = '';\nsFileOut.format    = 'SPM-DAT';\nsFileOut.byteorder = 'l';\nsFileOut.comment   = fBase;\n% Force the destination compensation level\nsFileOut.prop.currCtfComp = sFileOut.prop.destCtfComp;\nsFileOut.header.ctfcomp   = sFileOut.prop.destCtfComp;\n% Save pointer to the SPM file in the header\nsFileOut.header.file_array = D.data;\nsFileOut.header.nchannels  = length(ChannelMat.Channel);\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_fopen_spm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.21619129953945207}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ============================================\n% write_meta_tri.m\n%\n% write *.meta file\n% \n% Wan Jing\n% 11/08/2008 - create\n%============================================\nfunction write_meta_tri(filename, vertices, faces)\n\nfid = fopen(filename, 'w');\nfprintf(fid, 'ObjectType = Scene\\n');\nfprintf(fid, 'NDims = 3\\n');\nfprintf(fid, 'NObjects = 1\\n');\nfprintf(fid, 'ObjectType = Mesh\\n');\nfprintf(fid, 'NDims = 3\\n');\nfprintf(fid, 'BinaryData = False\\n');\nfprintf(fid, 'TransformMatrix = 1 0 0 0 1 0 0 0 1\\n');\nfprintf(fid, 'Offset = 0 0 0\\n');\nfprintf(fid, 'CenterOfRotation = 0 0 0\\n');\nfprintf(fid, 'ElementSpacing = 1 1 1\\n');\nfprintf(fid, 'PointType = MET_FLOAT\\n');\nfprintf(fid, 'PointDataType = MET_FLOAT\\n');\nfprintf(fid, 'CellDataType = MET_FLOAT\\n');\nfprintf(fid, 'NCellTypes = 1\\n');\nfprintf(fid, 'PointDim = ID x y ...\\n');\nfprintf(fid, 'NPoints = %d\\n', length(vertices));\nfprintf(fid, 'Points = \\n');\nfor i = 0:(length(vertices)-1)\n    fprintf(fid,'%d %g %g %g \\n', i, vertices(i+1,1), vertices(i+1,2), vertices(i+1, 3));\nend\nfprintf(fid, 'CellType = TRI\\n');\nnfaces = 2*length(faces);\nfprintf(fid, 'NCells = %d\\n', nfaces);\nfprintf(fid, 'Cells = \\n'); \nfor i = 0:(length(faces)-1)\n    fprintf(fid, '%d %d %d %d \\n', 2*i, (faces(i+1,1)-1), (faces(i+1,2)-1), (faces(i+1,3)-1));\n    fprintf(fid, '%d %d %d %d \\n', 2*i+1,(faces(i+1,3)-1), (faces(i+1,4)-1), (faces(i+1,1)-1));\nend\nfclose(fid);\n\nreturn;", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/write_meta_tri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21602354846075855}}
{"text": "function p = presolveSOS(p)\nif ~isempty(p.sosgroups)\n    for i = 1:length(p.sosgroups)\n        for j = 1:length(p.sosgroups{i})\n            % Probe what happens if we activate this binary\n            k = p.sosgroups{i}(j);\n            other = setdiff(p.sosgroups{i},k);\n            if p.ub(k) && ~any(p.lb(p.sosgroups{i}))\n                % Still free to be activated\n                p_ = p;\n                p_.ub(other) = 0;\n                p_.lb(k) = 1;\n                p_ = smashFixed(p_);\n                if ~isempty(fixedInfeasibleEquality(p_))      \n                    p.ub(k) = 0;\n                end\n                % Try de-activate too\n                p_ = p;                \n                p_.ub(k) = 0;\n                p_ = smashFixed(p_);\n                if ~isempty(fixedInfeasibleEquality(p_))      \n                    p.lb(k) = 1;\n                end\n            end\n        end\n    end\n    % Prune in case some are presolved completely\n    for i = 1:length(p.sosgroups)\n        if nnz(p.ub(p.sosgroups{i}))==1\n            keep(i) = 0;\n        else\n            keep(i) = 1;\n        end\n    end\n    if ~all(keep)\n        p.sosgroups = {p.sosgroups{find(keep)}};\n    end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/presolveSOS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21602354846075855}}
{"text": "function [ err errFrame errTot SAbsoluteT anim ] = computeError(anim, ...\n  varargin)\n% Compute several SFM errors\n%\n% It can compute:\n%  - the reprojection error\n%  - the 3D error between several recovered 3D shapes and a ground truth 3D\n%  shape\n%\n% USAGE\n%  [ err errFrame errTot ] = computeError( 'reproj', isProj, varargin )\n%  [ err errFrame errTot SBest ] = computeError( '3D', isProj, varargin)\n%\n% INPUTS\n%  anim       - Animation object\n%  varargin   - list of paramaters in quotes alternating with their values\n%       - 'doFillP', false, will replace/create anim.P with the projection\n%       matrices\n%       - 'animGT'   [] the ground truth anim to compare to\n%       - 'doCheckAmbiguity' [true] if true, check for ambiguities due to\n%       the camera model (scale for isProj and necker reversal for ~isProj)\n%       - 'checkTransform' ['camera']. Transform that can be applied to get\n%       a better match. Can be 'rigid', 'rigid+scale', 'homography' or\n%       'camera' (cf the alignTo function)\n%\n% OUTPUTS 'reproj'\n%  err       - [ 1 x 3 ] array of errors:\n%              if no animGT is given:\n%              err = mean( errFrame, 2 );\n%              if an animGT is givne:\n%              err(1) = mean( errFrame{1}(3,:), 2 )\n%              err(2) = mean( errFrame{2}(3,:), 2 )\n%              err(3) = mean( errFrame{3} )\n%  errFrame  - if no animGT is given:\n%              errFrame(1,:) = sum of squared reprojected distance\n%                              differences per frame\n%              errFrame(2,:) = sum of reprojected distances per frame\n%                              divided by the span of the object\n%              errFrame(3,:) = same as first one divided by the sum of\n%                              squared distances\n%  errFrame  - if an animGT is given, cell object:\n%              {1} [ 3 x nFrame ] Bregler, CVPR00 error (SSD)\n%              The rows contain the sums over the features (and for each\n%              frame) of the squared errors in X-Y, in Z, and in 3D.\n%              I.e. the rows contain for each frame:\n%                sum_{i=1}^nPoint  (xReconstructed_i-xOriginal_i)^2\n%                                         +(yReconstructed_i-yOriginal_i)^2\n%                sum_{i=1}^nPoint  (zReconstructed_i-zOriginal_i)^2\n%                row1+row2\n%              {2} [ 3 x nFrame ] Torresani, Bregler, CVPR01 error\n%              Same as above but distances are considered (not squared\n%              distances), average and not sum, and the results are\n%              normalized by the span of the object\n%              {3} [ 1 x nFrame ] Torresani, PAMI08 error\n%              At each frame:\n%              \\Vert SReconstructed-SOriginal \\Vert_F/\n%                               \\Vert SOriginal \\Vert_F\n%  errTot   - [3 x nPoint x nFrame] error for each point at each frame\n%             as a distance (simply abs of diff, not squared)\n%  SAbsoluteT - the best transformed S to match SGTAbsolute (SGT\n%               transformed by its R and t)\n%  anim     - the original Animation object but modified is aksed to be\n%\n% EXAMPLE\n%\n% See also Animation\n%\n% Vincent's Structure From Motion Toolbox      Version 3.1.1\n% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\nglobal IS_EXIST_PDIST;\nif isempty(IS_EXIST_PDIST); IS_EXIST_PDIST=exist('pdist','file'); end\n\n[ doFillP animGT doCheckAmbiguity checkTransform ] = ...\n  getPrmDflt( varargin, ...\n  { 'doFillP' false 'animGT' [] ...\n  'doCheckAmbiguity' true 'checkTransform' 'camera'}, 1 );\n\nnFrame = anim.nFrame; nPoint = anim.nPoint;\nmethod='reproj';\nif ~isempty(animGT); method = '3D'; end\n\nswitch method\n  case 'reproj'\n    % compute the projected points\n    [ W disc anim ]=generateW(anim,'doFillP', doFillP);\n    \n    % precompute stuff for error number 2\n    spanW = zeros(1,nFrame);\n    WIsnan=isnan(W);\n    hasAnyNan=any(WIsnan(:));\n    if hasAnyNan\n      if IS_EXIST_PDIST\n        for i = 1 : nFrame\n          spanW(i) = max(pdist( anim.W(:,~WIsnan(1,:,i),i)));\n        end\n      else\n        for i = 1 : nFrame\n          tmp=anim.W(:,~WIsnan(1,:,i),i);\n          spanW(i) = max(max(pdist2( tmp, tmp)));\n        end\n      end\n    else\n      if IS_EXIST_PDIST\n        for i = 1 : nFrame\n          spanW(i) = max(pdist( anim.W(:,:,i)));\n        end\n      else\n        for i = 1 : nFrame\n          spanW(i) = max(max(pdist2( anim.W(:,:,i), anim.W(:,:,i))));\n        end\n      end\n    end\n    \n    % compute the different errors\n    errFrame = zeros( 3, nFrame );\n    tmp = W - anim.W;\n    \n    % if there is a mask, only keep certain points on certain frames\n    WNorm = W;\n    if ~isempty(anim.mask)\n      % set to 0 the ones that are 0 in the mask\n      mask = repmat(reshape(~anim.mask,1,nPoint,nFrame), [2, 1, 1]);\n      tmp(mask) = 0;\n      WNorm(mask(:)) = 0;\n    end\n    WNorm = sum(reshape(WNorm,[],nFrame).^2, 1);\n    \n    errTot = abs(tmp);\n    errFrame(1,:) = sum(reshape(tmp,[],nFrame).^2,1);\n    errFrame(2,:) = sum(reshape(errTot,[],nFrame),1)./spanW;\n    errFrame(3,:) = sqrt(errFrame(1,:)./WNorm);\n    \n    err = mean( errFrame, 2 );\n  case '3D'\n    [ disc disc disc disc SAbsoluteT SGTAbsolute ] = alignTo(anim, ...\n      animGT, checkTransform);\n    \n    SDiff=SAbsoluteT-SGTAbsolute;\n    \n    % Update the errors\n    errTot=SDiff;\n    \n    errFrame=cell(1,3);\n    % compute the first type of error\n    %            {1} [ 3 x nFrame ] Bregler, CVPR00 error (SSD)\n    %            The rows contain the sums over the features (and for each\n    %            frame) of the squared errors in X-Y, in Z, and in 3D.\n    %            I.e. the rows contain for each frame:\n    %              sum_{i=1}^nPoint  (xReconstructed_i-xOriginal_i)^2\n    %                                     +(yReconstructed_i-yOriginal_i)^2\n    %              sum_{i=1}^nPoint  (zReconstructed_i-zOriginal_i)^2\n    %                row1+row2\n    errFrame{1} = zeros( 3, nFrame );\n    errFrame{1}(1,:) = reshape(sum(sum( SDiff(1:2,:,:).^2, 2 ),1),1,[]);\n    errFrame{1}(2,:) = reshape(sum(SDiff(3,:,:).^2, 2 ),1,[]);\n    errFrame{1}(3,:) = errFrame{1}(1,:)+errFrame{1}(2,:);\n    \n    %       {2} [ 3 x nFrame ] Torresani, Bregler, CVPR01 error\n    %       Same as above but distances are considered (not squared\n    %       distances), average and not sum, and the results are normalized\n    %       by the span of the object\n    normS = sqrt(reshape(sum(sum(animGT.S.^2,1),2),1,[]));\n    errFrame{2} = zeros( 3, nFrame );\n    errFrame{2}(1,:) = mean(sqrt(reshape(sum(sum( SDiff(1:2,:,:).^2, ...\n      2),1),1,[])));\n    errFrame{2}(2,:) = mean(reshape(SDiff(3,:,:),1,[]));\n    errFrame{2}(3,:) = mean(sqrt(reshape(sum(sum( SDiff(:,:,:).^2, ...\n      2),1),1,[])));\n    % precompute stuff for error number 2\n    spanS = zeros(1,size(animGT.S,3));\n    if exist('pdist','file')\n      for i = 1 : size(animGT.S,3)\n        spanS(i) = max(pdist( animGT.S(:,:,i)));\n      end\n    else\n      for i = 1 : size(animGT.S,3)\n        spanS(i) = max(max(pdist2( animGT.S(:,:,i), animGT.S(:,:,i))));\n      end\n    end\n    if size(spanS,2)==1; spanS = repmat(spanS,1,nFrame); end\n    errFrame{2} = bsxfun(@rdivide, errFrame{2}, spanS);\n    \n    %              {3} [ 1 x nFrame ] Torresani, PAMI08 error\n    %              At each frame:\n    %              \\Vert SReconstructed-SOriginal \\Vert_F/\n    %                               \\Vert SOriginal \\Vert_F\n    errFrame{3} = sqrt(errFrame{1}(3,i))./normS;\n    \n    % Update other errors\n    err=[ mean(errFrame{1}(3,:)) mean(errFrame{2}(3,:)) ...\n      mean(errFrame{3}) ];\nend\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/@Animation/computeError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21594799526356653}}
{"text": "function [names,data,data_endo,data_endo_a,data_endo_c,data_endo_c_lags,data_exo,data_exo_a,data_exo_p,data_exo_c,data_exo_c_lags,Fperiods,Fcomp,Fcperiods,Fcenddate,ar,priorexo,lambda4_2,favar]=...\n    gensample(startdate,enddate,VARtype,Fstartdate,Fenddate,Fendsmpl,endo,exo,frequency,lags,F,CF,ar,lambda4,PriorExcel,priorsexogenous,pref,favar,IRFt, numendo)\n\n\n% Phase 1: data loading and error checking\n\n% if we have a FAVAR: read information data, data transformation, create indices, compute factors (PC)\nif favar.FAVAR==1\n    [informationstartlocation,informationendlocation,favar]=bear.favar_gensample1(startdate,enddate,favar,pref);\nend\n\n\n% first read the data from Excel\n[data,names]=xlsread(pref.excelFile,'data');\n\n% now, as a preliminary step: check if there is any Nan in the data; if yes, return an error since the model won't be able to run with missing data\n% a simple way to test for NaN is to check for \"smaller or equal to infinity\": Nan is the only number for which matlab will return 'false' when asked so\n%[r,c]=size(data);\n\n\n% identify the date strings\ndatestrings=names(2:end,1);\n% identify the position of the string corresponding to the start period\nstartlocationData=find(strcmp(datestrings,startdate));\n% identify the position of the string corresponding to the end period\nendlocation=find(strcmp(datestrings,enddate));\nstartlocation=startlocationData;\nif favar.FAVAR==1 % in case we transform the data to first or second differences, we have a different startlocation\n    if favar.transformation==1\n        startlocation=informationstartlocation;\n        endlocation=informationendlocation;\n        % check is correct\n    else\n        startlocation=startlocationData;\n    end\nend\n\n\n% save the whole sample temporarily\ndata1=data;\n% adjust data to startdate and enddate\n% data1=data(startlocationData:endlocation,:);\ndata=data(startlocationData:endlocation,:);\n\n\n% identify the variable strings, endogenous and exogenous\nvariablestrings=names(1,2:end);\n\n% FAVAR: augment data and variablestrings with factors\nif favar.FAVAR==1\n    [data,variablestrings,favar]=bear.favar_gensample2(data1,endo,variablestrings,startlocation,lags,favar);\nend\n\n% if either the start date or the date date is not recognised, return an error message\nif isempty(startlocation)\n    error('bear:BEARmain:UnknownStartDate', ...\n        'Error: unknown start date for the sample. Please check your sample start date (remember that names are case-sensitive).');\nelseif isempty(endlocation)\n    error('bear:BEARmain:UnknownEndDate', ...\n        'Error: unknown end date for the sample. Please check your sample end date (remember that names are case-sensitive).');\nend\n% also, if the start date is posterior to the end date, obviously return an error\nif startlocation>=endlocation==1\n    error('bear:BEARmain:InconsistentStartEndDates', ...\n        'Error: inconsistency between the start and end dates. The start date must be anterior to the end date.');\nend\n\n% identify the position of the strings corresponding to the endogenous variables\n% for each variable, find the corresponding string\nfor ii=1:numendo\n    % check first that the variable ii in endo appears in the list of variable strings\n    % if not, the variable is unknown: return an error\n    var=endo{ii,1};\n    check=find(strcmp(variablestrings,var));\n    if isempty(check)==1\n        message=['Error: endogenous variable ' var ' cannot be found on the excel data spreadsheet.'];\n        error('BEARmain:gensample:EndoVarNotFound', message);\n    end\n    % if the variable is known, go on\n    endolocation(ii,1)=find(strcmp(variablestrings,endo(ii,1)));\nend\n\n% identify the position of the strings corresponding to the exogenous variables\n% proceed similarly to the endogenous variables, but account for the fact that exogenous may be empty\n% so check first whether there are exogenous variables altogether\nif isempty(exo)\n    numexo=0;\nelse\n    % if not empty, repeat what has been done with the exogenous\n    numexo=size(exo,1);\n    % for each variable, find the corresponding string\n    for ii=1:numexo\n        % check first that the variable ii in endo appears in the list of variable strings\n        % if not, the variable is unknown: return an error\n        var=exo{ii,1};\n        check=find(strcmp(variablestrings,var));\n        if isempty(check)==1\n            message=['Error: exogenous variable ' var ' cannot be found on the excel data spreadsheet.'];\n            error('BEARmain:gensample:ExoVarNotFound', message);\n        end\n        % if the variable is known, go on\n        exolocation(ii,1)=find(strcmp(variablestrings,exo(ii,1)));\n    end\nend\n\n% Phase 2: creation of the data matrices data_endo and data_exo\n\n% now create the matrix of endogenous variables for the estimation sample\n% it is simply the concatenation of the vectors of each endogenous variables, over the selected sample dates\ndata_endo=[];\n% loop over endogenous variables\nfor ii=1:numendo\n    data_endo=[data_endo data(:,endolocation(ii,1))];\nend\n\n% Similarly, create the matrix of exogenous variables for the estimation sample\ndata_exo=[];\nfor ii=1:numexo\n%     data_exo=[data_exo data(startlocation:endlocation,exolocation(ii,1))];\n    data_exo=[data_exo data(:,exolocation(ii,1))];\nend\n\n\n\n%% FAVAR\n\nif favar.FAVAR==1\n    if favar.transformation==1\n        % correct order of transformationindex_endo\n        favar.transformationindex_endo=[];\n        for ii=1:size(endo,1)\n            favar.transformationindex_endo=[favar.transformationindex_endo favar.transformationindex_endo_temp(:,endolocation(ii,1))];\n        end\n    end\n    % correct order of stddev\n    favar.data_exfactors_stddev=[];\n    for ii=1:size(endo,1)\n        favar.data_exfactors_stddev=[favar.data_exfactors_stddev favar.data_exfactors_stddev_temp(:,endolocation(ii,1))];\n    end\n    \n    % compute new loadings\n    %favar.L=(mvregress(data_endo,favar.X,'algorithm','cwls'))'; %appears to be not feasible for very large X\n    %favar.L=(olssvd(favar.X,data_endo))';\n    \n    % IRF shock to plot\n    if favar.IRFplot==1\n        favar.IRF.npltXshck=size(favar.IRF.pltXshck,1);\n        if IRFt==1||IRFt==2||IRFt==3\n            plotXshock_indexlogical=ismember(endo,favar.IRF.pltXshck);\n            favar.IRF.plotXshock_index=find(plotXshock_indexlogical==1)';\n            if favar.IRF.npltXshck==0\n                % error if no shock to plot is found, otherwise code crashes at a later stage\n                message=['Error: Shock(' favar.IRF.npltXshck ') cannot be found.'];\n                error('BEARmain:gensample:favar_IRF_npltXshck_error',message);\n            end\n        end\n        % for IRFt 4 & 6 this step is done in loadsignres\n    end\n    \n    % rotate Factors, compute new loadings for onestep, twostep estimation\n    [data_endo,favar]=bear.favar_gensample3(data_endo,favar);\n    \n    \n    \n    \n    \n%%%% stationarity test\nendostrings=endo(favar.variablestrings_exfactors,1);\nallstrings=[favar.informationvariablestrings,endostrings'];\nNSTindex=[];\nNST2index=[];\ncatallstrings=[];\ncatallstrings2=[];\ncount=0;\ncount2=0;\nfor ii=1:size(favar.XY,2)\n    adf(ii,1)=adftest(favar.XY(:,ii));\n    kpss(ii,1)=kpsstest(favar.XY(:,ii));\n    if adf(ii,1)==0 %|| kpss(ii,1)==1\n        count=count+1;\n        NSTallstrings{count,1}=allstrings(1,ii);\n        NSTindex=[NSTindex;ii];\n        catallstrings=strcat(catallstrings,', ',NSTallstrings{count,1});\n    end\n    if kpss(ii,1)==1\n        count2=count2+1;\n        NST2allstrings{count2,1}=allstrings(1,ii);\n        NST2index=[NST2index;ii];\n        catallstrings2=strcat(catallstrings2,', ',NST2allstrings{count2,1});\n    end\nend\nif size(NSTindex,1) > 0\nfprintf('%d%s%s%s\\n',size(NSTindex,1),' series in X are not stationary (ADF test): ',catallstrings{1,1},'.');\nend\nif size(NST2index,1) > 0\nfprintf('%d%s%s%s\\n',size(NST2index,1),' series in X are not stationary (KPSS test): ',catallstrings2{1,1},'.');\nend\n%%%%\n    \n    \nend\n\n\n%% Bens check for missing values in exo and endo\n[t,g]=size(data_endo);\nfor ii=1:t\n    for jj=1:g\n        temp=data_endo(ii,jj);\n        if (temp<=inf)==0\n            % identify the variable and the date %%%%% why is this commented\n            %       NaNvariable=names{1,jj+1};\n            %       NaNdate=names{ii+1,1};\n            %       message=['Error: variable ' NaNvariable ' at date ' NaNdate ' (and possibly other sample entries) is identified as NaN. Please check your Excel spreadsheet: entry may be blank or non-numerical.'];\n            %       msgbox(message);\n            error('programme termination: An endogenous variable entry is missing');\n        end\n    end\nend\n%\n%\n[t,g]=size(data_exo);\nfor ii=1:t\n    for jj=1:g\n        temp=data_exo(ii,jj);\n        if (temp<=inf)==0\n            error('programme termination: An exogenous variable entry is missing');\n        end\n    end\nend\n\n% Prior values settings for the AR coefficients (either default same for all or individually in Excel in AR prior sheet)\nif PriorExcel==0\n    ar_default=NaN(numendo,1);\n    ar_default(:,1)=ar;\n    ar=ar_default;\nelse\n    [ar]=xlsread(pref.excelFile,'AR priors');\nend\n\n\nif priorsexogenous==0\n    exo_default=zeros(numendo,numexo+1);\n    lambda4_default=zeros(numendo,numexo+1);\n    for ii=1:numendo\n        for jj=1:numexo+1\n            priorexo(ii,jj)=0;\n            lambda4_2(ii,jj)=lambda4;\n        end\n    end\nelse\n    [priorexo]=xlsread(pref.excelFile,'exo mean priors');\n    [lambda4]=xlsread(pref.excelFile,'exo tight priors');\n    priorexo=priorexo(1:numendo,1:numexo+1);\n    lambda4_2=lambda4(1:numendo,1:numexo+1);\nend\n\n% Phase 3: determination of the position of the forecast start and end periods\n\n% if both unconditional and conditional forecasts were not selected, there is no need for all the forecast-specific matrices: simply return empty matrices\nif (VARtype==1 && F==0) || ((VARtype==2 || VARtype==3 || VARtype==5 || VARtype==6 ) && (F==0 && CF==0))\n    data_endo_a=[];\n    data_exo_a=[];\n    data_exo_p=[];\n    Fperiods=[];\n    Fcomp=[];\n    Fcperiods=[];\n    data_endo_c=[];\n    data_endo_c_lags=[];\n    data_exo_c=[];\n    data_exo_c_lags=[];\n    Fcenddate=[];\n    \n    % if forecast were selected, create all the required elements\nelse\n    \n    % preliminary tasks\n    % first, identify the date strings, and the variable strings\n    datestrings=names(2:end,1);\n    if favar.FAVAR==1 % in case we transform the data to first or second differences, we have a different datestrings\n        if favar.transformation==1\n            datestrings=names(1+favar.informationstartlocation:end,:); %first row are labels\n        end\n    end\n    \n    % identify the location of the last period in the dataset\n    dataendlocation=size(datestrings,1);\n    \n    % identify the position of the start period (the easy part)\n    % if the start period has been selected as the first period after the sample end, identifies it directly\n    if Fendsmpl==1\n        Fstartlocation=find(strcmp(datestrings,enddate))+1;\n        % if the start period has not been selected as the first period after the sample end, it must be within the sample: look for it\n    elseif Fendsmpl==0\n        Fstartlocation=find(strcmp(datestrings,Fstartdate));\n        % if the start date is not recognised, return an error message\n        if isempty(Fstartlocation)==1\n            msgbox('Error: unknown start date for the forecasts. Select a date within a sample, or select \"Start forecasts after last sample period\"');\n            error('unknown start date for the forecasts');\n        end\n    end\n    \n    % identify the position of the final forecast period (the hard part)\n    % this period can be in or outside the sample, depending on the user's choice\n    \n    % if the data is yearly\n    if frequency==1\n        Fendlocation=str2num(Fenddate(1,1:end-1))-str2num(datestrings{1,1}(1,1:end-1))+1;\n        \n        % if the data is quarterly\n    elseif frequency==2\n        % first identify the year and quarter of the initial date in the whole data set (not just the sample)\n        datastartyear=str2num(datestrings{1,1}(1,1:4));\n        datastartquarter=str2num(datestrings{1,1}(1,6));\n        % convert this date into quarters only\n        datastart=datastartyear*4+datastartquarter;\n        % then identify the year and quarter of the final forecast date\n        forecastendyear=str2num(Fenddate(1,1:4));\n        forecastendquarter=str2num(Fenddate(1,6));\n        % convert this date into quarters only\n        forecastend=forecastendyear*4+forecastendquarter;\n        % finally, compute the number of periods that separate the two dates\n        Fendlocation=forecastend-datastart+1;\n        \n        % if the data is monthly\n    elseif frequency==3\n        % first identify the year and month of the initial date in the whole data set (not just the sample)\n        temp=datestrings{1,1};\n        datastartyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,datastartmonth]=strtok(temp);\n        % convert this date into months only\n        datastart=datastartyear*12+str2num(datastartmonth);\n        % then identify the year and month of the final forecast date\n        temp=Fenddate;\n        forecastendyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,forecastendmonth]=strtok(temp);\n        % convert this date into months only\n        forecastend=forecastendyear*12+str2num(forecastendmonth);\n        Fendlocation=forecastend-datastart+1;\n        \n        % if the data is weekly\n    elseif frequency==4\n        % then identify the year and week corresponding to this final period\n        temp=datestrings{end,1};\n        dataendyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,dataendweek]=strtok(temp);\n        dataendweek=str2num(dataendweek);\n        % identify the year and week corresponding to the end of the forecast period\n        temp=Fenddate;\n        Fendyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,Fendweek]=strtok(temp);\n        Fendweek=str2num(Fendweek);\n        % determine whether the forecast period ends within the data set, or after the end of the data set\n        if Fendyear<dataendyear\n            insmpl=1;\n        elseif Fendyear==dataendyear && Fendweek<=dataendweek\n            insmpl=1;\n        else\n            insmpl=0;\n        end\n        % if the forecast end period lies within the dataset, simply detect its location\n        if insmpl==1\n            Fendlocation=find(strcmp(Fenddate,datestrings));\n            % if it is outside the data set, complete until the forecast end date is reached (assuming 52 weeks per year)\n        elseif insmpl==0\n            % Consider two cases separately\n            % first case: if the end year of the forecast is the same as the end year of the dataset\n            % in this case, simply complete the missing periods\n            if dataendyear==Fendyear\n                complement=Fendweek-dataendweek;\n                Fendlocation=dataendlocation+complement;\n                % if the end year of the forecasts is posterior to the last year of the data\n            elseif dataendyear<Fendyear\n                % complete the first year (the one shared that ends the data set)\n                complement=52-dataendweek;\n                % complete the following years before the last one (if any)\n                for ii=dataendyear+1:Fendyear-1\n                    complement=complement+52;\n                end\n                % complete the final forecast year\n                complement=complement+Fendweek;\n                Fendlocation=dataendlocation+complement;\n            end\n        end\n        \n        % if the data is daily\n    elseif frequency==5\n        % then identify the year and day corresponding to this final period\n        temp=datestrings{end,1};\n        dataendyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,dataendday]=strtok(temp);\n        dataendday=str2num(dataendday);\n        % identify the year and day corresponding to the end of the forecast period\n        temp=Fenddate;\n        Fendyear=str2num(temp(1,1:4));\n        temp(1,5)=' ';\n        [~,Fendday]=strtok(temp);\n        Fendday=str2num(Fendday);\n        % determine whether the forecast period ends within the data set, or after the end of the data set\n        if Fendyear<dataendyear\n            insmpl=1;\n        elseif Fendyear==dataendyear && Fendday<=dataendday\n            insmpl=1;\n        else\n            insmpl=0;\n        end\n        % if the forecast end period lies within the dataset, simply detect its location\n        if insmpl==1\n            Fendlocation=find(strcmp(Fenddate,datestrings));\n            % if it is outside the data set, complete until the forecast end date is reached (assuming 261 opening days per year)\n        elseif insmpl==0\n            % Consider two cases separately\n            % first case: if the end year of the forecast is the same as the end year of the dataset\n            % in this case, simply complete the missing periods\n            if dataendyear==Fendyear\n                complement=Fendday-dataendday;\n                Fendlocation=dataendlocation+complement;\n                % if the end year of the forecasts is posterior to the last year of the data\n            elseif dataendyear<Fendyear\n                % complete the first year (the one shared that ends the data set)\n                complement=261-dataendday;\n                % complete the following years before the last one (if any)\n                for ii=dataendyear+1:Fendyear-1\n                    complement=complement+261;\n                end\n                % complete the final forecast year\n                complement=complement+Fendday;\n                Fendlocation=dataendlocation+complement;\n            end\n        end\n        \n        % finally, if the data is undated\n    elseif frequency==6\n        Fendlocation=str2num(Fenddate(1,1:end-1))-str2num(datestrings{1,1}(1,1:end-1))+1;\n    end\n    \n    % from this, conclude the total number of forecast periods\n    Fperiods=Fendlocation-Fstartlocation+1;\n    \n    if Fperiods<0\n        msgbox('Error: The forecast start date needs to be prior to the forecast end date');\n        error('invalid forecast start or end date');\n    end\n    \n    \n    \n    % Phase 4: generation of the forecast-specific matrices\n    if favar.FAVAR==0\n        % load the full sample in this case\n        data=data1;\n    elseif favar.FAVAR==1\n        data=favar.data_full;\n    end\n    % now create the matrix of endogenous variables for the pre-forecast period\n    % it is simply the concatenation of the vectors of each endogenous variables, over the selected sample dates\n    data_endo_a=[];\n    % loop over endogenous variables\n    for ii=1:numendo\n        data_endo_a=[data_endo_a data(1:Fstartlocation-1,endolocation(ii,1))];\n    end\n    % also, create the matrix of exogenous variables for the pre-forecast period\n    data_exo_a=[];\n    for ii=1:numexo\n        data_exo_a=[data_exo_a data(1:Fstartlocation-1,exolocation(ii,1))];\n    end\n    \n    % create the matrix of endogenous variables for the period common to actual data and forecasts (for forecast evaluation)\n    % first, check that there are such common periods: it is the case if the beginning of the forecast period is anterior to the end of the dataset\n    if Fstartlocation<=dataendlocation\n        % return a scalar value to indicate that forecast evaluation is possible\n        Fcomp=1;\n        % compute the number of common periods\n        % if the forecast period ends before the end of the data set, the common periods end with the end of the forecasts\n        if Fendlocation<=dataendlocation\n            Fcperiods=Fperiods;\n            % record the end date of the common periods\n            Fcenddate=Fenddate;\n            % if the forecast period ends later than the data set, the common periods end at the end of the data set\n        elseif Fendlocation>dataendlocation\n            Fcperiods=dataendlocation-Fstartlocation+1;\n            % record the end date of the common periods\n            Fcenddate=datestrings{end,1};\n        end\n        \n        % create a matrix of endogenous data for the common periods\n        data_endo_c=[];\n        for ii=1:numendo\n            data_endo_c=[data_endo_c data(Fstartlocation:min(dataendlocation,Fendlocation),endolocation(ii,1))];\n        end\n        \n        % create a lagged matrix of endogenous data prior to the common periods\n        % the number of values is equal to \"lags\"; this will be used for computation of the log predictive score\n        data_endo_c_lags=[];\n        for ii=1:numendo\n            data_endo_c_lags=[data_endo_c_lags data(Fstartlocation-lags:Fstartlocation-1,endolocation(ii,1))];\n        end\n        \n        % create a matrix of exogenous data for the common periods\n        data_exo_c=[];\n        for ii=1:numexo\n            data_exo_c=[data_exo_c data(Fstartlocation:min(dataendlocation,Fendlocation),exolocation(ii,1))];\n        end\n        \n        % create a lagged matrix of exogenous data prior to the common periods\n        % the number of values is equal to \"lags\"; this will be used for computation of the log predictive score\n        data_exo_c_lags=[];\n        for ii=1:numexo\n            data_exo_c_lags=[data_exo_c_lags data(Fstartlocation-lags:Fstartlocation-1,exolocation(ii,1))];\n        end\n        % if there are no common periods, return a scalar value to indicate that forecast evaluation is not possible\n    else\n        Fcomp=0;\n        Fcperiods=0;\n        data_exo_c=[];\n        data_endo_c=[];\n        Fcenddate=[];\n        data_endo_c_lags=[];\n        data_exo_c_lags=[];\n    end\n    \n    \n    \n    % now create the matrix data_exo_p\n    % two possible cases\n    \n    % if there are no exogenous variables, simply create an empty matrix\n    if isempty(exo)\n        data_exo_p=[];\n        \n        % if there are exogenous variables, load from excel\n    else\n        % load the data from Excel\n        [num txt strngs]=xlsread(pref.excelFile,'pred exo');\n        \n        % obtain the row location of the forecast start date\n        [Fstartlocation,~]=find(strcmp(strngs,Fstartdate));\n        % check that the start date for the forecast appears in the sheet; if not, return an error\n        if isempty(Fstartlocation)\n            message=['Error: a forecast application is selected for a model that uses exogenous variables. Hence, predicted exogenous values should be supplied over the forecast periods. Yet the start date for forecasts (' Fstartdate ') cannot be found on the ''pred exo'' sheet of the Excel data file. Please verify that this sheet is properly filled, and remember that dates are case-sensitive.'];\n            msgbox(message);\n            error('programme termination: data error');\n        end\n        % obtain the row location of the forecast end date\n        [Fendlocation,~]=find(strcmp(strngs,Fenddate));\n        % check that the end date for the forecast appears in the sheet; if not, return an error\n        if isempty(Fendlocation)\n            message=['Error: a forecast application is selected for a model that uses exogenous variables. Hence, predicted exogenous values should be supplied over the forecast periods. Yet the end date for forecasts (' Fenddate ') cannot be found on the ''pred exo'' sheet of the Excel data file. Please verify that this sheet is properly filled, and remember that dates are case-sensitive.'];\n            msgbox(message);\n            error('programme termination: data error');\n        end\n        \n        % identify the strings for the exogenous variables\n        % loop over exogenous\n        for ii=1:numexo\n            % try to find a column match for exogenous variable ii\n            [~,location]=find(strcmp(strngs,exo{ii,1}));\n            % if no match is found, return an error\n            if isempty(location)\n                message=['Error: a forecast application is selected for a model that uses exogenous variables. Hence, predicted exogenous values should be supplied over the forecast periods. Yet the exogenous variable ''' exo{ii,1} ''' cannot be found on the ''pred exo'' sheet of the Excel data file. Please verify that this sheet is properly filled, and remember that variable names are case-sensitive.'];\n                msgbox(message);\n                error('programme termination: data error');\n                % else, record the value\n            else\n                pexolocation(ii,1)=location;\n            end\n        end\n        \n        % if everything was fine, reconstitute the matrix data_exo_p\n        % initiate\n        data_exo_p=[];\n        % loop over exogenous variables\n        for ii=1:numexo\n            % initiate the predicted values for exogenous variable ii\n            predexo=[];\n            % loop over forecast periods\n            for jj=1:Fperiods\n                temp=strngs{Fstartlocation+jj-1,pexolocation(ii,1)};\n                % if this entry is empty or NaN, return an error\n                if (isempty(temp) || (temp<=inf)==0)\n                    message=['Error: the predicted value for exogenous variable ' exo{ii,1} ' at forecast period ' strngs{Fstartlocation+jj,1} ' (and possibly other entries) is either empty or NaN. Please verify that the ''pred exo'' sheet of the Excel data file is properly filled.'];\n                    msgbox(message);\n                    error('programme termination: data error');\n                    % if this entry is a number, record it\n                else\n                    predexo=[predexo;temp];\n                end\n            end\n            % concatenate\n            data_exo_p=[data_exo_p predexo];\n        end\n        \n        % also, record the exogenous values on Excel\n        % replace NaN entries by blanks\n        strngs(cellfun(@(x) any(isnan(x)),strngs))={[]};\n        % then save on Excel\n        if pref.results==1\n            bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),strngs,'pred exo','A1');\n        end\n    end\n    \n    \n    \n    \nend\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/gensample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2159479952635665}}
{"text": "function [elec, grad] = out_fieldtrip_channel(ChannelFile, isIncludeRef)\n% OUT_FIELDTRIP_CHANNEL: Converts a channel file into elec/grad structures\n% \n% USAGE:  [elec, grad] = out_fieldtrip_channel(ChannelFile, isIncludeRef=1)\n%         [elec, grad] = out_fieldtrip_channel(ChannelMat)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2016-2019\n\n\n% ===== PARSE INPUT =====\nif (nargin < 2) || isempty(isIncludeRef)\n    isIncludeRef = 1;\nend\nif isstruct(ChannelFile)\n    ChannelMat  = ChannelFile;\n    ChannelFile = [];\nelse\n    ChannelMat = [];\nend\n\n% ===== LOAD CHANNEL FILE =====\n% Load channel file\nif ~isempty(ChannelFile) && isempty(ChannelMat)\n    ChannelMat = in_bst_channel(ChannelFile);\nend\n% Make sure that the channel file is defined\nif isempty(ChannelMat)\n    error('No channel file available.');\nend\n% Find MEG and EEG sensors\niEeg = channel_find(ChannelMat.Channel, 'EEG,SEEG,ECOG');\niMeg = channel_find(ChannelMat.Channel, 'MEG');\niRef = channel_find(ChannelMat.Channel, 'MEG REF');\nif isIncludeRef\n    iMegAll = [iMeg, iRef];\nelse\n    iMegAll = iMeg;\nend\n\n% ===== COMPUTE PROJECTOR =====\n% Compute selected SSP projectors\nif ~isempty(ChannelMat.Projector)\n    % Rebuild projector in the expanded form (I-UUt)\n    Proj = process_ssp2('BuildProjector', ChannelMat.Projector, [1 2]);\nelse\n    Proj = [];\nend\n    \n% ===== EEG =====\nif ~isempty(iEeg)\n    % Create electrode structure\n    elec = struct();\n    elec.label = {ChannelMat.Channel(iEeg).Name};\n    elec.unit  = 'm';\n    % Electrode position\n    elec.chanpos = zeros(length(iEeg),3);\n    for i = 1:length(iEeg)\n        if all(size(ChannelMat.Channel(iEeg(i)).Loc) >= [3,1])\n            elec.chanpos(i,:) = ChannelMat.Channel(iEeg(i)).Loc(:,1);\n        else\n            elec.chanpos(i,:) = [0;0;0];\n        end\n    end\n    elec.elecpos = elec.chanpos;\n    % Default montage\n    elec.tra = eye(length(iEeg));\n    % Apply projectors (SSP or ICA)\n    if ~isempty(Proj)\n        elec.tra = Proj(iEeg,iEeg) * elec.tra;\n    end\nelse\n    elec = [];\nend\n\n% ===== MEG =====\nif ~isempty(iMeg)\n    % Average all the intergration points of the various coils\n    chantype = cell(1,length(iMegAll));\n    for i = 1:length(iMegAll)\n        switch (ChannelMat.Channel(iMegAll(i)).Type)\n            case 'MEG'\n                chantype{i} = 'megaxial';\n            case 'MEG MAG'\n                chantype{i} = 'megmag';\n            case 'MEG GRAD'\n                chantype{i} = 'megplanar';\n            case 'MEG REF'\n                chantype{i} = 'megref';\n        end\n    end\n    \n    % Create sensor structure\n    grad = struct();\n    grad.label    = {ChannelMat.Channel(iMegAll).Name};\n    grad.unit     = 'm';\n    grad.chantype = chantype;\n    % Channels positions\n    grad.chanpos = figure_3d('GetChannelPositions', ChannelMat, iMegAll);\n    % Coils positions\n    grad.coilpos = [ChannelMat.Channel(iMegAll).Loc]';\n    grad.coilori = [ChannelMat.Channel(iMegAll).Orient]';\n    % Correspondance channel-coil\n    grad.tra = sparse(length(iMegAll), length(grad.coilpos));\n    k = 1;\n    for i = 1:length(iMegAll)\n        % Dealing with the multiple coils and integration points\n        grad.chanori(i,:) = ChannelMat.Channel(iMegAll(i)).Orient(:,1)';\n        nCoils = size(ChannelMat.Channel(iMegAll(i)).Weight,2);\n        grad.tra(i,k+(0:nCoils-1)) = ChannelMat.Channel(iMegAll(i)).Weight;\n        k = k + nCoils;\n    end\n    % Add MegRefCoef (CTF/4D 3rd order gradient compensation)\n    if isIncludeRef && ~isempty(iRef)\n        % Error: Not all the sensors are selected\n        if (size(ChannelMat.MegRefCoef,1) ~= length(iMeg)) || (size(ChannelMat.MegRefCoef,2) ~= length(iRef))\n            error('CTF compensation can be used only when using all the MEG sensors.');\n        end\n        % Apply compensation matrix to \".tra\" matrix\n        GradComp = eye(length(ChannelMat.Channel)); \n        GradComp(iMeg,iRef) = -ChannelMat.MegRefCoef;\n        grad.tra = GradComp(iMegAll,iMegAll) * grad.tra;\n        % grad.tra is later applied to the leadfield in ft_compute_leadfield:\n        % lf = sens.tra * lf;\n    end\n    % Apply projectors (SSP or ICA)\n    if ~isempty(Proj)\n        grad.tra = Proj(iMegAll,iMegAll) * grad.tra;\n    end\nelse\n    grad = [];\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_fieldtrip_channel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.215911560243039}}
{"text": "classdef CelestialBodySunRelStateDataCache < matlab.mixin.SetGet\n    %CelestialBodySunRelStateDataCache Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        bodyInfo KSPTOT_BodyInfo\n        \n        times(:,1) double = [];\n        stateVects(:,6) double = [];\n        relFrame AbstractReferenceFrame\n        \n        gi %gridded interpolant\n    end\n    \n    methods\n        function obj = CelestialBodySunRelStateDataCache(bodyInfo)\n            obj.bodyInfo = bodyInfo;\n        end\n        \n        function setStateData(obj, times, stateVects, relFrame)\n            obj.times = times;\n            obj.stateVects = stateVects;\n            obj.relFrame = relFrame;\n            \n            obj.gi = griddedInterpolant(obj.times, obj.stateVects, 'spline');\n        end\n        \n        function [rVect, vVect] = getCachedBodyStateAtTime(obj, time)\n            if(numel(obj.times) <= 1 || any(time > max(obj.times)) || any(time < min(obj.times)))\n                maxUT = max(obj.times);\n                boolMaxUT = maxUT - time < 0;\n                worstMaxUTViolation = max(time(boolMaxUT));\n                \n                minUT = min(obj.times);\n                boolMinUT = time - minUT < 0;\n                worstMinUTViolation = min(time(boolMinUT));\n                \n                if(not(isempty(worstMaxUTViolation)) && not(isempty(worstMinUTViolation)))\n                    str = sprintf('Adjust the minimum cache UT to below %0.3f sec and the maximum cache UT to above %0.3f sec.', worstMinUTViolation, worstMaxUTViolation);\n                    \n                elseif(not(isempty(worstMaxUTViolation)))\n                    str = sprintf('Adjust the maximum cache UT to above %0.3f sec.', worstMaxUTViolation);\n                    \n                elseif(not(isempty(worstMinUTViolation)))\n                    str = sprintf('Adjust the minimum cache UT to below %0.3f sec.', worstMinUTViolation);\n                    \n                end\n                \n                msg = sprintf('At least one of the points in time queried are out of the bounds of the numerical integration (%0.3f sec to %0.3f sec).  %s', min(obj.times), max(obj.times), str);\n                \n                errordlg(msg, 'Body State Cache Bounds', 'modal');\n                error(msg);\n            else\n                vq = obj.gi(time);\n                \n                rVect = vq(:,1:3)';\n                vVect = vq(:,4:6)';\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/zz_classes/@CelestialBodySunRelStateDataCache/CelestialBodySunRelStateDataCache.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.566018549837479, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21577734606197874}}
{"text": "function out = spm_shoot_norm(job)\n% Spatially normalise and smooth fMRI/PET data to MNI space, using Shoot deformation fields\n% FORMAT out = spm_shoot_norm(job)\n% job - a structure generated by the configuration file\n%   job.template - Shoot template for aligning to MNI space. Aligns to population\n%                  average if no template is provided.\n%   job.subj(n)  - Subject n\n%       subj(n).def    - Shoot deformation field\n%       subj(n).images - Images for this subject\n%   job.vox      - Voxel sizes for spatially normalised images\n%   job.bb       - Bounding box for spatially normalised images\n%   job.preserve - How to transform\n%                  0 = preserve concentrations\n%                  1 = preserve integral (cf \"modulation\")\n%\n% Normally, Shoot generates deformations that align with the average-\n% shaped template.  This routine includes the option to compose the\n% shoot deformations with an affine transform derived from an affine\n% registration of the template (the final one generated by Shoot),\n% with the TPM data released with SPM.\n%\n% Note that trilinear interpolation is used, and no masking is done.  It\n% is therefore essential that the images are realigned and resliced\n% before they are spatially normalised.  Alternatively, contrast images\n% generated from unsmoothed native-space fMRI/PET data can be spatially\n% normalised for a 2nd level analysis.\n%\n% Two \"preserve\" options are provided.  One of them should do the\n% equavalent of generating smoothed \"modulated\" spatially normalised\n% images.  The other does the equivalent of smoothing the modulated\n% normalised fMRI/PET, and dividing by the smoothed Jacobian determinants.\n%\n%__________________________________________________________________________\n% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_shoot_norm.m 7496 2018-11-23 11:14:43Z john $\n\n% Hard coded stuff, that should maybe be customisable\ntpm  = fullfile(spm('Dir'),'tpm','TPM.nii');\nMmni = spm_get_space(tpm);\n\n% Shoot template\nif ~isempty(job.template{1})\n    Nt     = nifti(job.template{1});\n    do_aff = true;\nelse\n    Nt     = nifti(tpm);\n    do_aff = false;\nend\n\n% Deal with desired bounding box and voxel sizes.\n%--------------------------------------------------------------------------\nbb   = job.bb;\nvox  = job.vox;\nMt   = Nt.mat;\ndimt = size(Nt.dat);\n\nif any(isfinite(bb(:))) || any(isfinite(vox))\n    [bb0,vox0] = spm_get_bbox(Nt, 'old');\n    \n    msk = ~isfinite(vox); vox(msk) = vox0(msk);\n    msk = ~isfinite(bb);   bb(msk) =  bb0(msk);\n\n    bb  = sort(bb);\n    vox = abs(vox);\n\n    % Adjust bounding box slightly - so it rounds to closest voxel.\n    bb(:,1) = round(bb(:,1)/vox(1))*vox(1);\n    bb(:,2) = round(bb(:,2)/vox(2))*vox(2);\n    bb(:,3) = round(bb(:,3)/vox(3))*vox(3);\n    dim = round(diff(bb)./vox+1);\n    of  = -vox.*(round(-bb(1,:)./vox)+1);\n    mat = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];\n    if det(Mt(1:3,1:3)) < 0\n        mat = mat*[-1 0 0 dim(1)+1; 0 1 0 0; 0 0 1 0; 0 0 0 1];\n    end\nelse\n    dim = dimt(1:3);\n    mat = Mt;\nend\n\nif isfield(job.data,'subj') || isfield(job.data,'subjs')\n    if do_aff\n        [pth,nam,ext] = fileparts(Nt.dat.fname); %#ok\n        if exist(fullfile(pth,[nam '_2mni.mat']),'file')\n            load(fullfile(pth,[nam '_2mni.mat']),'mni');\n        else\n            % Affine registration of Shoot Template with MNI space.\n            %--------------------------------------------------------------\n            fprintf('** Affine registering \"%s\" with MNI space **\\n', nam);\n            clear mni\n            mni.affine = Mmni/spm_klaff(Nt,tpm,1);\n            mni.code   = 'MNI152';\n            save(fullfile(pth,[nam '_2mni.mat']),'mni', spm_get_defaults('mat.format'));\n        end\n        M = mat\\mni.affine/Mt;\n        mat_intent = mni.code;\n    else\n        M = mat\\eye(4);\n        mat_intent = 'Aligned';\n    end\n    fprintf('\\n');\n\n    if isfield(job.data,'subjs')\n        % Re-order data\n        %------------------------------------------------------------------\n        subjs = job.data.subjs;\n        subj  = struct('deformation',cell(numel(subjs.deformations),1),...\n                       'images',   cell(numel(subjs.deformations),1));\n        for i=1:numel(subj)\n            subj(i).deformation = {subjs.deformations{i}};\n            subj(i).images   = cell(numel(subjs.images),1);\n            for j=1:numel(subjs.images)\n                subj(i).images{j} = subjs.images{j}{i};\n            end\n        end\n    else\n        subj = job.data.subj;\n    end\n\n    % Loop over subjects\n    %----------------------------------------------------------------------\n    out = cell(1,numel(subj));\n    for i=1:numel(subj)\n        % Spatially normalise data from this subject\n        [pth,nam,ext] = fileparts(subj(i).deformation{1}); %#ok\n        fprintf('** \"%s\" **\\n', nam);\n        out{i} = deal_with_subject(subj(i).deformation,subj(i).images, mat,dim,M,job.preserve,job.fwhm,mat_intent);\n    end\n\n    if isfield(job.data,'subjs')\n        out1 = out;\n        out  = cell(numel(subj),numel(subjs.images));\n        for i=1:numel(subj)\n            for j=1:numel(subjs.images)\n                out{i,j} = out1{i}{j};\n            end\n        end\n    end\nend\n%__________________________________________________________________________\n\n%__________________________________________________________________________\nfunction out = deal_with_subject(Py,PI,mat,dim,M,jactransf,fwhm,mat_intent)\n% Py         - Filename of shoot deformation.\n% PI         - Filenames of images to spatially normalise.\n% mat        - Voxel-to-world matrix for header of warped images.\n% dim        - Dimensions of warped images.\n% M          - Matrix for adjusting the deformation fields (eg when using\n%              different bounding boxes or origins, or when an additional\n%              affine transform is included.\n% jactransf  - Whether or not to \"modulate\".\n% fwhm       - FWHM for smoothing.\n% mat_intent - Something for the header to indicate average space or MNI\n%              space.\n% \n% Generate deformation, which is the inverse of the usual one (it is for \"pushing\"\n% rather than the usual \"pulling\"). This deformation is affine transformed to\n% allow for different voxel sizes and bounding boxes, and also to incorporate\n% the affine mapping between MNI space and the population average shape.\n%--------------------------------------------------------------------------\nNY  = nifti(Py{1});\nM   = M*NY.mat;\ny   = single(squeeze(NY.dat(:,:,:,:,:)));\nd   = size(y);\n\nif norm(M-eye(4))>1e-3 || any(d(1:3) ~= dim(1:3))\n    y0  = zeros([dim(1:3),3],'single');\n    for d=1:3\n        yd = y(:,:,:,d);\n        for x3=1:dim(3)\n            y0(:,:,x3,d) = single(spm_slice_vol(yd,M\\spm_matrix([0 0 x3]),dim(1:2),[1 NaN]));\n        end\n    end\nelse\n    y0 = y;\nend\n\nodm = zeros(1,3);\noM  = zeros(4,4);\nout = cell(1,numel(PI));\nfor m=1:numel(PI)\n\n    % Generate headers etc for output images\n    %----------------------------------------------------------------------\n    [pth,nam,ext,num] = spm_fileparts(PI{m}); %#ok\n    NI = nifti(fullfile(pth,[nam ext]));\n    NO = NI;\n    if jactransf\n        if fwhm==0\n            NO.dat.fname=fullfile(pth,['mw' nam ext]);\n        else\n            NO.dat.fname=fullfile(pth,['smw' nam ext]);\n        end\n        NO.dat.scl_slope = 1.0;\n        NO.dat.scl_inter = 0.0;\n        NO.dat.dtype     = 'float32-le';\n    else\n        if fwhm==0\n            NO.dat.fname=fullfile(pth,['w' nam ext]);\n        else\n            NO.dat.fname=fullfile(pth,['sw' nam ext]);\n        end\n    end\n    NO.dat.dim = [dim NI.dat.dim(4:end)];\n    NO.mat  = mat;\n    NO.mat0 = mat;\n    NO.mat_intent  = mat_intent;\n    NO.mat0_intent = mat_intent;\n\n    if strcmp(mat_intent,'Aligned'), to_what = 'Average';  else\n                                     to_what = mat_intent; end\n    if fwhm==0\n        NO.descrip = ['Shoot-normed (' to_what ')'];\n    else\n        NO.descrip = sprintf('Smoothed (%g) Shoot normed (%s)',fwhm, to_what);\n    end\n    out{m} = NO.dat.fname;\n    NO.extras = [];\n    create(NO);\n\n\n    % Smoothing settings\n    vx  = sqrt(sum(mat(1:3,1:3).^2));\n    krn = max(fwhm./vx,0.1);\n\n    % Loop over volumes within the file\n    %----------------------------------------------------------------------\n    fprintf('%s',nam); drawnow;\n    for j=1:size(NI.dat,4)\n\n        % Check if it is an \"imported\" image to normalise\n        if sum(sum((NI.mat - NY.mat ).^2)) < 0.0001 && ...\n           sum(sum((NI.mat - NI.mat0).^2)) > 0.0001\n            % No affine transform necessary\n            M0 = NI.mat0;\n        else\n            % Need to resample the mapping by an affine transform\n            % so that it maps from voxels in the native space image\n            % to voxels in the spatially normalised image.\n            %--------------------------------------------------------------\n            M0 = NI.mat;\n            if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat')\n                M1 = NI.extras.mat;\n                if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0\n                    M0 = M1(:,:,j);\n                end\n            end\n        end\n        M   = inv(M0);\n        dm  = [size(NI.dat),1,1,1,1];\n        if ~all(dm(1:3)==odm) || ~all(M(:)==oM(:))\n            % Generate new deformation (if needed)\n            y   = zeros(size(y0),'single');\n            y(:,:,:,1) = M(1,1)*y0(:,:,:,1) + M(1,2)*y0(:,:,:,2) + M(1,3)*y0(:,:,:,3) + M(1,4);\n            y(:,:,:,2) = M(2,1)*y0(:,:,:,1) + M(2,2)*y0(:,:,:,2) + M(2,3)*y0(:,:,:,3) + M(2,4);\n            y(:,:,:,3) = M(3,1)*y0(:,:,:,1) + M(3,2)*y0(:,:,:,2) + M(3,3)*y0(:,:,:,3) + M(3,4);\n\n            % Generate Jacobian determinants.\n            c          = abs(spm_diffeo('jacdet',y)*(det(NI.mat(1:3,1:3))/det(NO.mat(1:3,1:3))));\n            c(:,:,[1 end]) = NaN; % Boundary voxels are not handled well - so remove\n            c(:,[1 end],:) = NaN;\n            c([1 end],:,:) = NaN;\n        end\n        odm = dm(1:3);\n        oM  = M;\n\n        % Write the warped data for this time point.\n        %------------------------------------------------------------------\n        for k=1:size(NI.dat,5)\n            for l=1:size(NI.dat,6)\n                f  = single(NI.dat(:,:,:,j,k,l));\n                if ~jactransf\n                    % Unmodulated \n                    f = spm_diffeo('pull',f,y).*c;\n                    if fwhm>0\n                        spm_smooth(f,f,krn); % Side effects\n                        cs = zeros(size(c),'like',c);\n                        spm_smooth(c,cs,krn); % Side effects\n                        f  = f./max(cs,0.000001);\n                    else\n                        f  = f./max(c ,0.000001);\n                    end\n                else\n                    % Modulated, by pushing\n                    f = spm_diffeo('pull',f,y).*c;\n                    spm_smooth(f,f,krn); % Side effects\n                end\n                NO.dat(:,:,:,j,k,l) = f;\n                fprintf('\\t%d,%d,%d', j,k,l); drawnow;\n            end\n        end\n    end\n    fprintf('\\n'); drawnow;\nend\n%__________________________________________________________________________\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/Shoot/spm_shoot_norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175005616831, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.21574254363966816}}
{"text": "classdef PTKAirwayGenerator < handle\n    % PTKAirwayGenerator. Creates an artifical airway tree using a volume-filling\n    % algorithm.\n    %\n    %     This class generates an artificial model of the airway tree. You\n    %     specify the lung volume to fill, and provide a starting tree (such as \n    %     that produced by a CT region-growing algorithm). The airway growing\n    %     starts at the endpoints of the starting tree and grows into the\n    %     provided volume. The resulting tree includes the starting tree.\n    %\n    %     You can also choose to grow specific parts of the tree into specific\n    %     volumes, so for example a lobar region can be exclusively allocated to\n    %     a lobar bronchus and its descendents.\n    %\n    %     This code has in part been adapted from C++ code by Rafel Bordas which\n    %     forms part of the Chaste project at the University of Oxford.\n    %     The algorithm is derived from Tawhai et al. (2004), although some\n    %     changes have been made to the algorithm.\n    %\n    %     Syntax:\n    %         airway_generator = PTKAirwayGenerator(\n    %             lung_mask,              % A binary mask of the whole lung volume\n    %             centreline_tree,          % A PTKModelTree produced from PTKAirwayCentreline\n    %             point_limit_voxels,     % Branches will terminate if the size of the region they grow into in voxels is less than this limit\n    %             approx_number_points,   %\n    %             reporting               % A CoreReportingInterface object for error, warning and progress reporting\n    %         )\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n    %     Author: Tom Doel, 2012.  www.tomdoel.com\n    %     Distributed under the GNU GPL v3 licence. Please see website for details.\n    %\n\n    properties (Constant)\n        LengthLimitMm = 1.2 % A branch is terminated if its length is less than this value. Tawhai et al 2004 use value 2.\n        PointLimitVoxels = 1 % A branch is terminated if the point cloud of the apex has fewer points than this limit\n        NumberOfGenerationsToReallocate = 20  % If ReallocatePointsAtEachGeneration is set to true, this is the number of generations for which points in the volume will be reallocated at each generation\n        PointNumberMultiple = 1 % The desired number of grid points is obtained by multiplying approx_number_points by this value\n        MaximumGenerationNumber = 25     % All branches of the output tree will terminate if they extend beyond this generation number\n        InitialTerminatingBranchLengthLimit = 6\n        BranchingFraction = 0.4 % The fraction a branch extends towards the centre of the point cloud. Value 0.4 from Tawhai et al., 2004\n        ReallocatePointsAtEachGeneration = true % If true, points will be reassigned to apices at each generation up to the generation number set in NumberOfGenerationsToReallocate\n        AngleLimitRadians = 60*(pi/180.0); % Value 60 degrees from Tawhai et al, 2004\n        PointDistanceLimit = 5 % Points greather than a voxel distance of this number multiplied by the number of cloud points are removed from the apex cloud\n        BranchLengthToParentRatioLimit = 1 % Child branches cannot be longer than this factor multiplied by ther parent's length\n        BranchLengthToParentGenerationLimit = 20 % The BranchLengthToParentRatioLimit parameter starts taking effect from this generation number\n    end\n    \n    \n    properties\n        AirwayTree\n        InitialApexImage\n        GridSpacingMm\n    end\n    \n    methods\n        function obj = PTKAirwayGenerator(lung_mask, centreline_tree, approx_number_points, reporting)\n\n            % Compute the grid spacing. We choose to have more grid points than\n            % the minimum required as a finer grid will give better branching\n            approx_number_grid_points = PTKAirwayGenerator.PointNumberMultiple*approx_number_points;\n            obj.GridSpacingMm = lung_mask.ComputeResamplingGridSpacing(approx_number_grid_points);\n            \n            % Initialise airway tree\n            initial_airway_tree = obj.CreateInitialTreeFromSegmentation(centreline_tree, PTKAirwayGenerator.MaximumGenerationNumber, reporting);\n            obj.RemoveSmallTerminatingAirways(initial_airway_tree, PTKAirwayGenerator.InitialTerminatingBranchLengthLimit, reporting);\n            obj.AirwayTree = initial_airway_tree;\n        end\n        \n        function delete(~)\n        end\n        \n        % Starting from the initial airway tree generated from AddTree(),  \n        function GrowTree(obj, growth_volume, starting_segment, reporting)\n            obj.InitialApexImage = PTKAirwayGenerator.GrowTreeUsingThisGridSpacing(obj.AirwayTree, growth_volume, starting_segment, obj.GridSpacingMm, reporting);\n        end        \n    end\n    \n    methods (Static, Access = private)\n        function initial_apex_image = GrowTreeUsingThisGridSpacing(airway_tree, growth_volume, starting_segment, grid_spacing_mm, reporting)\n            \n            reporting.PushProgress;\n            \n            resampled_volume = PTKAirwayGenerator.CreatePointCloud(growth_volume, grid_spacing_mm);\n            disp(['Number of seed points:' int2str(sum(resampled_volume.RawImage(:)))]);\n            \n            initial_apex_image = PTKAirwayGenerator.Grow(resampled_volume, airway_tree, starting_segment, reporting);\n            \n            reporting.PopProgress;\n        end\n        \n        % Use CreateInitialTreeFromSegmentation to create an initial airway tree\n        % from the airway centreline results\n        function airway_tree = CreateInitialTreeFromSegmentation(segmented_centreline_tree, maximum_generation_number, reporting)\n            airway_tree = PTKAirwayGrowingTree;\n            airway_tree.CentrelineTreeSegment = segmented_centreline_tree;\n            segments_to_do = airway_tree;\n            while ~isempty(segments_to_do)\n                segment = segments_to_do(end);\n                segments_to_do(end) = [];\n                \n                % Get the first and last voxel coordinates from the segment of\n                % the centreline airway tree\n                centreline_segment = segment.CentrelineTreeSegment;\n                if isempty(segment.Parent)\n                    first_point = centreline_segment.Centreline(1);\n                else\n                    first_point = centreline_segment.Parent.Centreline(end);\n                end\n                end_point = centreline_segment.Centreline(end);\n                \n                segment.StartPoint = first_point;\n                segment.EndPoint = end_point;\n                \n                if isempty(centreline_segment.GenerationNumber)\n                    error('program error');\n                end\n                \n                if centreline_segment.GenerationNumber >= maximum_generation_number\n                    reporting.ShowWarning('PTKAirwayGenerator:SegmentedBranchesExcluded', 'Initial branches have been excluded due to the maximum generation parameter', []);\n                else\n                    \n                    if ~isempty(centreline_segment.Children)\n                        % Add a new branch to the tree for each child\n                        for child = centreline_segment.Children\n                            % Create a new segment\n                            new_segment = PTKAirwayGrowingTree(segment);\n                            new_segment.CentrelineTreeSegment = child;\n                            new_segment.IsGenerated = false;\n                            segments_to_do = [segments_to_do, new_segment];\n                        end\n                    end\n                end\n                \n            end\n        end\n        \n        function RemoveSmallTerminatingAirways(initial_airway_tree, length_limit, reporting)\n            branches_to_do = initial_airway_tree;\n            has_changed = true;\n            iteration_number = 0;\n            while (has_changed)\n                has_changed = false;\n                iteration_number = iteration_number + 1;\n                while ~isempty(branches_to_do)\n                    branch = branches_to_do(end);\n                    branches_to_do(end) = [];\n                    if isempty(branch.Children)\n                        branch_length = MimImageCoordinateUtilities.DistanceBetweenPoints(branch.StartPoint, branch.EndPoint);\n                        if branch_length < length_limit\n                            if ~isempty(branch.Parent)\n                                reporting.ShowWarning('PTKAirwayGenerator:SegmentedBranchesBelowLimit', 'Initial branches have been excluded due to their length being below the limit', []);\n                                branch.Parent.RemoveChildren;\n                                has_changed = true;\n                            end\n                        end\n                        \n                    else\n                        branches_to_do = [branches_to_do, branch.Children];\n                    end\n                end\n            end\n        end\n        \n        function in_volume = IsInsideVolume(point_mm, lung_volume)\n            global_coordinates = MimImageCoordinateUtilities.GetGlobalCoordinatesForPoints(point_mm, lung_volume);\n            if ~lung_volume.IsPointInImage(global_coordinates)\n                in_volume = false;\n            else\n                in_volume = lung_volume.GetVoxel(global_coordinates);\n            end\n        end\n\n        function apices = GetApicesBelowThisBranchForTerminalSegments(centreline_branches, airway_tree, generation_number, reporting)\n            apices = [];\n            \n            % Find the starting segments\n            segments_to_do = [];\n            for centreline_branch = centreline_branches\n                branch = airway_tree.FindCentrelineBranch(centreline_branch, reporting);\n                segments_to_do = [segments_to_do, branch];\n            end\n            \n            % Now search the tree below the starting segments and create an apex\n            % for each one at the correct generation number\n            while ~isempty(segments_to_do)\n                segment = segments_to_do(end);\n                segments_to_do(end) = [];\n                children = segment.Children;\n                segments_to_do = [segments_to_do, children];\n                \n                % Now search the tree below the starting segments and create an apex\n                % for each one that is a terminal segment\n                if isempty(children) && isempty(segment.IsTerminal)\n                    % Add apices for airway growing\n                    new_apex = PTKAirwayGeneratorApex(segment, PTKCoords, true);\n                    apices = [apices new_apex];\n                end\n            end\n        end\n        \n        function apices = GetApicesBelowThisBranchForThisGeneration(start_centreline_branches, airway_tree, generation_number, reporting)\n            apices = [];\n            \n            % Find the starting segments\n            segments_to_do = [];\n            for centreline_branch = start_centreline_branches\n                branch = airway_tree.FindCentrelineBranch(centreline_branch, reporting);\n                segments_to_do = [segments_to_do, branch];\n            end\n\n            % Now search the tree below the starting segments and create an apex\n            % for each one at the correct generation number\n            while ~isempty(segments_to_do)\n                segment = segments_to_do(end);\n                segments_to_do(end) = [];\n                children = segment.Children;\n                segments_to_do = [segments_to_do, children];\n                \n                % Find all branches of this generation which have not been\n                % terminaetd by the algorithm. This includes branches which\n                % already have child branches - these will not be grown, but\n                % points will be allocated to their apices so that they may\n                % later be available for their child branches to grow\n                if segment.GenerationNumber == generation_number\n                    if isempty(segment.IsTerminal)\n                        is_growing_apex = isempty(children);\n                        new_apex = PTKAirwayGeneratorApex(segment, PTKCoords, is_growing_apex);\n                        apices = [apices new_apex];\n                    end\n                end\n            end\n        end\n        \n        function generation_number = GetMinimumTerminalGeneration(apices)\n            generation_number = [];\n            for apex = apices\n                apex_generation = apex.AirwayGrowingTreeSegment.GenerationNumber;\n                if isempty(generation_number)\n                    generation_number = apex_generation;\n                else\n                    generation_number = min(generation_number, apex_generation);\n                end\n            end\n        end\n        \n        % Find the smallest generation number of a branch in the airway tree\n        % which is still growing. This will return an empty variable if no more\n        % airways are growing\n        function generation_number = GetMinimumActiveTerminalGeneration(airway_tree, start_centreline_branches, reporting)\n            % Find the starting segments\n            segments_to_do = [];\n            for centreline_branch = start_centreline_branches\n                branch = airway_tree.FindCentrelineBranch(centreline_branch, reporting);\n                segments_to_do = [segments_to_do, branch];\n            end\n\n            generation_number = [];\n            while ~isempty(segments_to_do)\n                next_branch = segments_to_do(end);\n                child_branches = next_branch.Children;\n                \n                % A branch is still growing if it has no child branches and it\n                % has not been terminated by the growing algorithm\n                if isempty(child_branches) && isempty(next_branch.IsTerminal)\n                    \n                    % We want the smallest generation number for the tree\n                    if (isempty(generation_number) || (generation_number > next_branch.GenerationNumber))\n                        generation_number = next_branch.GenerationNumber;\n                    end \n                end\n                \n                segments_to_do(end) = [];\n                segments_to_do = [segments_to_do child_branches];\n            end\n        end\n        \n        function centre = GetCentreOfMass(point_cloud)\n            cloud_points = point_cloud.Coords;\n            centre = mean(cloud_points, 1);\n        end\n        \n        function new_image = GetImageFromApex(template, apices)\n            new_image = zeros(template.ImageSize, 'uint16');\n            colour = 1;\n            for apex = apices\n                cloud_points = apex.PointCloud.Coords;\n                if ~isempty(cloud_points)\n                    cloud_points = MimImageCoordinateUtilities.PTKCoordinatesToCoordinatesMm(cloud_points);\n                    point_coord = template.CoordinatesMmToGlobalCoordinates(cloud_points);\n                    point_coord = template.GlobalToLocalCoordinates(point_coord);\n                    indices = sub2ind(template.ImageSize, point_coord(:,1), point_coord(:,2), point_coord(:,3));\n                    new_image(indices) = colour;\n                end\n                colour = colour + 1;\n            end\n        end\n        \n        function centreline_indices_local = CentrelinePointsToLocalIndices(centreline_points, template_image)\n            centreline_indices_global = MimImageCoordinateUtilities.GetGlobalIndicesForPoints(centreline_points, template_image);\n            centreline_indices_local = template_image.GlobalToLocalIndices(centreline_indices_global);\n        end\n        \n        function closest_point = FindClosestPointInCloud(point, cloud)\n            point_coords = [point.CoordX, point.CoordY, point.CoordZ];\n            num_points_in_cloud = size(cloud.Coords, 1);\n            distance = cloud.Coords - repmat(point_coords, [num_points_in_cloud, 1]);\n            distance = sqrt(distance(:,1).^2 + distance(:,2).^2 + distance(:,3).^2);\n            [~, min_index] = min(distance, [], 1);\n            closest_point = cloud.Coords(min_index, :);\n        end\n        \n        % Compute a normalised direction vector for a plane parallel to the\n        % given vector and the direction of the given branch. If the two vectors\n        % are parallel then the direction of the parent branch is used. If this\n        % does not exist or is still parallel, then we choose a guaranteed\n        % non-parallel vector using the null space.\n        function plane_normal = GetValidPlaneNormal(vector_to_com, branch)\n            \n            if ~isempty(branch.Parent)\n                parent_branch_direction = branch.Parent.Direction;\n                plane_normal = cross(vector_to_com, parent_branch_direction);\n            else\n                branch_direction = branch.Direction;\n                plane_normal = cross(vector_to_com, branch_direction);\n            end\n            \n            % This is an implementation of the algorithm described in Tawhai et\n            % al., 2004 for finding the plane. However, this does not work since\n            % the parent branch will often be collinear with the centre of mass\n            % point (since branches are created in the direction of the centre\n            % of mass).\n%             branch_direction = branch.Direction;\n%             \n%             % Find the normal to the plane which passes through the centre\n%             % of mass and the branch start and end points\n%             plane_normal = cross(vector_to_com, branch_direction);\n%             \n%             % If the branch direction is parallel to the vector then we try the\n%             % parent direction\n%             if isequal(plane_normal, [0 0 0])\n%                 disp('parallel - correcting');\n%                 if ~isempty(branch.Parent)\n%                     parent_branch_direction = branch.Parent.Direction;\n%                     plane_normal = cross(vector_to_com, parent_branch_direction);\n%                 end\n%             end\n            \n            % If the vectors are still parallel then we use the null space to\n            % find another vector which is perpendicular\n            if isequal(plane_normal, [0 0 0])\n                disp('still parallel - correcting');\n                plane_null_space = null(vector_to_com/norm(vector_to_com));\n                perpendicular_vector = plane_null_space(:, 1);\n                plane_normal = cross(vector_to_com, perpendicular_vector);\n            end\n            \n            plane_normal = plane_normal / norm(plane_normal);\n        end\n        \n        % Divides the point cloud in two, based on a plane perpendicular to the\n        % direction of the last two branches\n        function [this_plane, other_plane] = SplitPointCloud(point_cloud, normal, origin)\n            points_coords = point_cloud.Coords;\n            p = - dot(normal, origin);\n            \n            % Find which axis is most parallel to the plane\n            [~, ordered_directions] = sort(normal, 'descend');\n            main_direction = ordered_directions(1);\n            other_directions = ordered_directions(2:3);\n            plane_points = - (p + normal(other_directions(1))*points_coords(:, other_directions(1)) + normal(other_directions(2))*points_coords(:, other_directions(2)))/normal(main_direction);\n            in_plane = points_coords(:, main_direction) < plane_points;\n            this_plane = PTKCoords(points_coords(in_plane, :));\n            other_plane = PTKCoords(points_coords(~in_plane, :));\n        end\n        \n        function resampled_volume = CreatePointCloud(growth_volume, grid_spacing_mm)\n            resampled_volume = growth_volume.Copy;\n            grid_spacing = [grid_spacing_mm, grid_spacing_mm, grid_spacing_mm];\n            resampled_volume.Resample(grid_spacing, '*nearest')\n        end\n       \n        % Checks the branch angle of a proposed growth centre and adjusts it within tolerance, if necessary\n        function end_point = CheckBranchAngleLengthAndAdjust(start_point, end_coords, parent_direction, parent_length_mm, generation_number)\n            % calculate vector from apex start to the centre\n            start_coords = [start_point.CoordX, start_point.CoordY, start_point.CoordZ];\n            new_direction = end_coords - start_coords;\n            \n            % Record the branching length\n            branch_length = norm(new_direction);\n            \n            new_direction = new_direction / norm(new_direction);\n            \n            old_direction = parent_direction;\n            old_direction = old_direction / norm(old_direction);\n            \n            % determine branch angle\n            dot_product = dot(new_direction, parent_direction);\n            branch_angle = acos(dot_product/(norm(new_direction)*norm(parent_direction)));\n\n            % If the branch angle is above the limit then set it to the limit\n            if (branch_angle > PTKAirwayGenerator.AngleLimitRadians)\n                perpendicular_one = cross(new_direction, old_direction);\n                perpendicular_one = perpendicular_one/norm(perpendicular_one);\n                perpendicular_two = cross(old_direction, perpendicular_one);\n                perpendicular_two = perpendicular_two/norm(perpendicular_two);\n                old_direction = old_direction*cos(PTKAirwayGenerator.AngleLimitRadians);\n                perpendicular_two = perpendicular_two*sin(PTKAirwayGenerator.AngleLimitRadians);\n                new_direction = old_direction + perpendicular_two;\n            end\n            \n            % Reduce the branch length as required\n            branch_length = branch_length*PTKAirwayGenerator.BranchingFraction;\n            if generation_number >= PTKAirwayGenerator.BranchLengthToParentGenerationLimit\n                branch_length = min(branch_length, parent_length_mm*PTKAirwayGenerator.BranchLengthToParentRatioLimit);\n            end\n            new_direction = new_direction * branch_length;\n            \n            % Update the centre\n            end_coords = start_coords + new_direction;\n            end_point = PTKPoint(end_coords(1), end_coords(2), end_coords(3));\n        end\n        \n        function new_apex = AddBranchAndApex(parent_branch, cloud, lung_volume, lung_mask, generation_number, image_size, reporting)\n            new_apex = [];\n            \n            % Determine the centre of the point cloud\n            centre_of_mass = PTKAirwayGenerator.GetCentreOfMass(cloud);\n            \n            % The new branch starts at the end of the parent branch\n            new_branch_start_point = parent_branch.EndPoint;\n            \n            % Fetch the director vector of the parent branch\n            parent_direction = parent_branch.Direction;\n            \n            % Calculate the end point of the new branch. This is subject both to\n            % a length limit and an angle limit.\n            new_branch_end_point = PTKAirwayGenerator.CheckBranchAngleLengthAndAdjust(new_branch_start_point, centre_of_mass, parent_direction, parent_branch.Length, generation_number);\n\n            if ~PTKAirwayGenerator.IsInsideVolume(new_branch_end_point, lung_mask)\n                reporting.ShowWarning('PTKAirwayGenerator:OutsideVolume', 'Branches terminated because they grew outside the lung volume', []);\n                parent_branch.IsTerminal = true;\n                return;\n            end\n            \n            % Create the new branch in AirwayTree\n            new_branch = PTKAirwayGrowingTree(parent_branch);\n            new_branch.StartPoint = new_branch_start_point;\n            new_branch.EndPoint = new_branch_end_point;\n            new_branch.IsGenerated = true;\n\n            new_branch_length = MimImageCoordinateUtilities.DistanceBetweenPoints(new_branch_end_point, new_branch_start_point);\n\n            % Find closest point in cloud and delete\n            closest_point = PTKAirwayGenerator.FindClosestPointInCloud(new_branch_end_point, cloud);\n            closest_point_global_coords = MimImageCoordinateUtilities.PTKCoordinatesToCoordinatesMm(closest_point);\n            closest_point_global_coords = lung_volume.CoordinatesMmToGlobalCoordinates(closest_point_global_coords);\n            lung_volume.SetVoxelToThis(closest_point_global_coords, 0);\n            \n            % Check if the number of points in the cloud is less than the\n            % required minimum\n            if (size(cloud.Coords, 1) <= PTKAirwayGenerator.PointLimitVoxels)\n                new_branch.IsTerminal = true;\n                reporting.ShowWarning('PTKAirwayGenerator:BelowLengthThreshold', 'Branches terminated because the number of points was below the threshold', []);\n            else\n                if (new_branch_length < PTKAirwayGenerator.LengthLimitMm)\n                    new_branch.IsTerminal = true;\n                    reporting.ShowWarning('PTKAirwayGenerator:BelowLengthThreshold', 'Branches terminated because their length was below the threshold', []);\n                else\n                    % Create new growth branch\n                    new_apex = PTKAirwayGeneratorApex(new_branch, cloud, true);\n                end\n            end\n        end\n        \n        function apices = AssignPointCloudToApices(apices, resampled_volume, reporting)\n            if numel(apices) == 0\n               reporting.Error('PTKAirwayGenerator:AssignPointCloudToApices', 'No starting points');\n            end\n            sample_image = zeros(resampled_volume.ImageSize, 'uint16');\n            apex_start_points = zeros(numel(apices), 3);\n            for apex_number = 1 : numel(apices)\n                apex = apices(apex_number);\n                end_point = apex.AirwayGrowingTreeSegment.EndPoint;\n                end_point_global_coordinates = MimImageCoordinateUtilities.GetGlobalCoordinatesForPoints(end_point, resampled_volume);\n                end_point = resampled_volume.GlobalToLocalCoordinates(end_point_global_coordinates);\n                apex_start_points(apex_number, :) = [end_point(1), end_point(2), end_point(3)];\n                current_value = sample_image(end_point(1), end_point(2), end_point(3));\n                if current_value ~= 0\n                    reporting.ShowWarning('PTKAirwayGenerator:ApexAlreadyUsed', 'The start point for allocating voxels to apices could not be assigned as the point has already been used by another apex', []);\n                end\n                sample_image(end_point(1), end_point(2), end_point(3)) = apex_number;\n            end\n            \n            bw_image = sample_image > 0;\n            \n            [~, IDX] = bwdist(bw_image);\n            mapped_image = sample_image(IDX);\n            mapped_image_masked = zeros(size(bw_image), 'uint16');\n            point_indices = find(resampled_volume.RawImage);\n            mapped_image_masked(point_indices) = mapped_image(point_indices);\n            \n            for apex_number = 1 : numel(apices)\n                local_indices = find(mapped_image_masked == apex_number);\n                if ~isempty(local_indices)\n                    [di, dj, dk] = ind2sub(size(mapped_image_masked), local_indices);\n                    \n                    % Calculate the distance from these new points to the start\n                    % point\n                    root_point = apex_start_points(apex_number, :);\n                    di = di - root_point(1);\n                    dj = dj - root_point(2);\n                    dk = dk - root_point(3);\n                    dist_voxels = sqrt(di.^2 + dj.^2 + dk.^2);\n                    points_too_far_away = dist_voxels > PTKAirwayGenerator.PointDistanceLimit*numel(local_indices);\n                    \n                    % This is a check for distance from root point compared to\n                    % parent length\n%                     di = (di - root_point(1))*resampled_volume.VoxelSize(1);\n%                     dj = (dj - root_point(2))*resampled_volume.VoxelSize(2);\n%                     dk = (dk - root_point(3))*resampled_volume.VoxelSize(3);\n%                     dist_mm = sqrt(di.^2 + dj.^2 + dk.^2);\n%                     last_branch_length = apices(apex_number).AirwayGrowingTreeSegment.Length;\n%                     points_too_far_away = dist_mm > PTKAirwayGenerator.PointDistanceLimit*last_branch_length;\n\n                    number_of_points_to_remove = sum(uint8(points_too_far_away));\n                    if number_of_points_to_remove > 0\n                        disp([int2str(number_of_points_to_remove) ' points removed as they were too far away (generation' int2str(apices(apex_number).AirwayGrowingTreeSegment.GenerationNumber) ')']);\n                    end\n                    local_indices = local_indices(~points_too_far_away, :);\n                    \n                    if ~isempty(local_indices)\n                        global_indices =  resampled_volume.LocalToGlobalIndices(local_indices);\n                        [ic, jc, kc] = resampled_volume.GlobalIndicesToCoordinatesMm(global_indices);\n                        [ptk_x, ptk_y, ptk_z] = MimImageCoordinateUtilities.CoordinatesMmToPTKCoordinates(ic, jc, kc);\n\n                        apices(apex_number).PointCloud.Coords = [ptk_x, ptk_y, ptk_z];\n                    else\n                        apices(apex_number).PointCloud.Coords = [];\n                    end\n                else\n                    apices(apex_number).PointCloud.Coords = [];\n                end\n            end\n        end\n        \n        function [apex_1, apex_2] = GrowApex(current_apex, lung_volume, lung_mask, generation_number, image_size, reporting)\n            branch = current_apex.AirwayGrowingTreeSegment;\n\n            if isempty(current_apex.PointCloud.Coords)\n                branch.IsTerminal = true;\n                reporting.ShowWarning('PTKAirwayGenerator:EmptyPointCloud', 'Branches terminated because they had an empty point cloud', []);\n                apex_1 = [];\n                apex_2 = [];\n            elseif size(current_apex.PointCloud.Coords, 1) < 2\n                branch.IsTerminal = true;\n                reporting.ShowWarning('PTKAirwayGenerator:TooFewPointsInCloud', 'Branches terminated because there was only one point in the point cloud', []);\n                apex_1 = [];\n                apex_2 = [];\n            else\n                \n                % Find the end coordinates for this branch\n                branch_end_point = branch.EndPoint;\n                branch_end_coords = [branch_end_point.CoordX, branch_end_point.CoordY, branch_end_point.CoordZ];\n\n                % Find the centre of mass for the point cloud assigned to this\n                % apex\n                centre_of_mass = PTKAirwayGenerator.GetCentreOfMass(current_apex.PointCloud);\n                \n                % Create a vector from the end branch point to the centre of\n                % mass\n                vector_to_com = centre_of_mass - branch_end_coords;\n                \n                % Get a normalised vector perpendicular to the plane passing\n                % through the centre of pass and the start and end points of the\n                % branch\n                plane_normal = PTKAirwayGenerator.GetValidPlaneNormal(vector_to_com, branch);\n                \n                % Split the point cloud into two, creating a new apex for each if there are enough points\n                [cloud1, cloud2] = PTKAirwayGenerator.SplitPointCloud(current_apex.PointCloud, plane_normal, branch_end_coords);\n                \n                if isempty(cloud1.Coords) || isempty(cloud2.Coords)\n                    reporting.ShowWarning('PTKAirwayGenerator:EmptyPointCloud', 'Branches terminated because the point clouds could not be divided into two nonempty clouds', []);\n                    branch.IsTerminal = true;\n                    apex_1 = [];\n                    apex_2 = [];\n                    return;\n                end\n                \n                % Create new branches\n                apex_1 = PTKAirwayGenerator.AddBranchAndApex(branch, cloud1, lung_volume, lung_mask, generation_number, image_size, reporting);\n                apex_2 = PTKAirwayGenerator.AddBranchAndApex(branch, cloud2, lung_volume, lung_mask, generation_number, image_size, reporting);\n            end\n        end\n        \n        function [apices, initial_apex_image] = Grow(lung_volume, airway_tree, starting_segment, reporting)\n            \n            % We need to keep a copy of the lung mask for checking that airways\n            % are inside. The original image will have points removed as airways are grown. \n            lung_mask = lung_volume.Copy;\n            \n            reporting.ShowProgress('Growing branches');\n            reporting.UpdateProgressValue(0);\n            first_run = true;\n            image_size = lung_volume.ImageSize;\n            \n            % Set this to something non-empty for the first run\n            apices = 1;\n            generation_number = 1;\n            \n            % Step through generations one by one and terminate when there are\n            % no active growing branches left\n            while ~isempty(generation_number)\n                \n                % Find the lowest generation to grow\n                generation_number = PTKAirwayGenerator.GetMinimumActiveTerminalGeneration(airway_tree, starting_segment, reporting);\n                if (first_run)\n                    min_generation_number = generation_number;\n                end\n                \n                % Terminate when there are no active growing branches left\n                if isempty(generation_number)\n                    return;\n                end\n                \n                % Terminate when we have exceeded a generation threshold, and\n                % report how many branches were incomplete\n                if generation_number >= PTKAirwayGenerator.MaximumGenerationNumber\n                    reporting.ShowMessage('PTKAirwayGenerator:IncompleteApices', [num2str(length(apices)) ' branches were incomplete when the terminal generation was reached']);                    \n                    return\n                end\n                \n                % Progress reporting\n                reporting.ShowMessage('PTKAirwayGenerator:GenerationNumber', ['Generation:' int2str(generation_number)]);\n                reporting.UpdateProgressValue(round(100*(generation_number - min_generation_number)/(PTKAirwayGenerator.MaximumGenerationNumber - min_generation_number)));\n                \n                % Allocate/reallocate points to the apices\n                if (first_run) || ((generation_number < PTKAirwayGenerator.NumberOfGenerationsToReallocate) && (PTKAirwayGenerator.ReallocatePointsAtEachGeneration))\n                    \n                    is_this_the_last_reallocation = (generation_number + 1 == PTKAirwayGenerator.NumberOfGenerationsToReallocate) || (~PTKAirwayGenerator.ReallocatePointsAtEachGeneration);\n                    \n                    if is_this_the_last_reallocation\n                        apices = PTKAirwayGenerator.GetApicesBelowThisBranchForTerminalSegments(starting_segment, airway_tree, generation_number, reporting);\n                    else\n                        apices = PTKAirwayGenerator.GetApicesBelowThisBranchForThisGeneration(starting_segment, airway_tree, generation_number, reporting);\n                    end\n                    \n                    num_apices = numel(apices);\n                    apices = PTKAirwayGenerator.AssignPointCloudToApices(apices, lung_volume, reporting);\n%                     disp(['Generation:' int2str(generation_number) ' Number of apices:' int2str(num_apices) ' Apices post-allocation:' int2str(numel(apices))]);\n                    if (first_run)\n                        initial_apex_image = PTKAirwayGenerator.GetImageFromApex(lung_volume, apices);\n                        first_run = false;\n                    end\n                end\n                \n                apices_next_generation = PTKAirwayGeneratorApex.empty(50000,0);\n                for apex = apices\n                    \n                    % Ignore non-growing apices - they are just there to help\n                    % with the point reallocation\n                    if (apex.IsGrowingApex)\n                        % After the final point reallocation, we may have apices\n                        % with higher generation numbers than the current one - this\n                        % will happen if the segmented tree has a higher number of\n                        % generations than the number of generations to reallocate.\n                        % We ignore any apices with a higher generation number than\n                        % the current one, but save these for processing later\n                        if (generation_number == apex.AirwayGrowingTreeSegment.GenerationNumber)\n                            [new_apex_1, new_apex_2] = PTKAirwayGenerator.GrowApex(apex, lung_volume, lung_mask, generation_number, image_size, reporting);\n                            if ~isempty(new_apex_1)\n                                apices_next_generation(end+1) = new_apex_1;\n                            end\n                            if ~isempty(new_apex_2)\n                                apices_next_generation(end+1) = new_apex_2;\n                            end\n                        else\n                            apices_next_generation(end + 1) = apex;\n                        end\n                    end\n                end\n                \n                % The next generation of apices is used when point reallocation\n                % no longer happens (either the point reallocation generation\n                % has been exceeded, or the reallocation flag is switched off).\n                % The list of apices includes newly generated apices, plus any\n                % terminal branhces from the segmented airways which are waiting\n                % to be grown\n                apices = apices_next_generation;\n            end\n        end\n    end\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Airways/PTKAirwayGenerator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.21574253931682486}}
{"text": "function bounds = GetBounds(model, vel_lb, vel_ub, T, x0, xf)\n    \n    \n    if nargin < 2\n        vel_lb = [0.0,0];\n        vel_ub = [0.0,0];\n    end\n    \n    if nargin < 4\n        T = 0.4;\n    end\n    \n    if nargin < 5\n        x0 = zeros(model.numState*2,1);\n    end\n    \n    if nargin < 6\n        xf = zeros(model.numState*2,1);\n    end\n    \n    %% first get the model specific boundary values\n    model_bounds = model.getLimits(); % x, dx, ddx, u\n    \n    \n    \n    model_bounds.options.enforceVirtualConstraints = true;\n    \n    % fixed joint constraint wrench\n    model_bounds.inputs.ConstraintWrench.ffourBar.lb = -1000;\n    model_bounds.inputs.ConstraintWrench.ffourBar.ub = 1000;\n    \n    % fixed joint constraints\n    model_bounds.params.pfourBar.lb = zeros(4,1);\n    model_bounds.params.pfourBar.ub = zeros(4,1);\n\n\n    model_bounds.constrBounds.yaw_initial.lb = 0;\n    model_bounds.constrBounds.yaw_initial.ub = 0;\n    \n    \n    \n    % feedback control gain for virtual constraints\n    model_bounds.gains.kp = 100;\n    model_bounds.gains.kd = 20;\n    \n    \n    %%% Constraint bounds\n    %     vel = [0.0, -0.8].';\n    %     T   = 0.4;\n    \n    %%% Step Duration\n    model_bounds.time.duration.lb = T;\n    model_bounds.time.duration.ub = T;\n    \n    model_bounds.time.t0.lb = 0;\n    model_bounds.time.t0.ub = 0;\n    model_bounds.time.t0.x0 = 0;\n    model_bounds.time.tf.lb = 0;\n    model_bounds.time.tf.ub = T;\n    model_bounds.time.tf.x0 = T;\n    \n    model_bounds.constrBounds.foot_clearance_1.lb = 0.03;\n    model_bounds.constrBounds.foot_clearance_1.ub = 0.3;\n    model_bounds.constrBounds.foot_clearance_2.lb = 0.15;\n    model_bounds.constrBounds.foot_clearance_2.ub = 0.3;\n    model_bounds.constrBounds.foot_clearance_3.lb = 0.05;\n    model_bounds.constrBounds.foot_clearance_3.ub = 0.3;\n    model_bounds.constrBounds.averageVelocity.lb = vel_lb;\n    model_bounds.constrBounds.averageVelocity.ub = vel_ub;\n    \n    %     model_bounds.states.x.lb(1:2) = vel_lb;\n    %     model_bounds.states.x.ub(1:2) = vel_ub;\n    \n    %     model_bounds.constrBounds.stepLength.lb = vel(1)*T;\n    %     model_bounds.constrBounds.stepLength.ub = vel(1)*T;\n    %\n    %     model_bounds.constrBounds.stepWidth.lb = vel(1)*T;\n    %     model_bounds.constrBounds.stepWidth.ub = vel(1)*T;\n    \n    model_bounds.constrBounds.footVelocityBeginning.lb = [-0.15, -0.15, 0]';\n    model_bounds.constrBounds.footVelocityBeginning.ub = [0.15, 0.15, 0.3]';\n    model_bounds.constrBounds.footVelocityEnd.lb = [-0.15, -0.15, -0.25]';\n    model_bounds.constrBounds.footVelocityEnd.ub = [0.15, 0.15, -0.05]';\n    \n    \n    \n    %%% Common Virtual Constraints\n    model_bounds.params.aoutput.lb = -2*pi;\n    model_bounds.params.aoutput.ub = 2*pi;\n    \n    model_bounds.params.poutput.lb = [0, 0];\n    model_bounds.params.poutput.ub = [0, T];\n    model_bounds.params.poutput.x0 = [0, T];\n    \n    model_bounds.params.pRightFoot.lb = [-10, -10, 0, 0];\n    model_bounds.params.pRightFoot.ub = [10, 10, 0, 0];\n    \n    model_bounds.params.pLeftFoot.lb = [-10, -10, 0, 0];\n    model_bounds.params.pLeftFoot.ub = [10, 10, 0, 0];\n    \n    \n    model_bounds.inputs.ConstraintWrench.fRightFoot.lb = [-1000,-1000,300,-1000]';\n    model_bounds.inputs.ConstraintWrench.fRightFoot.ub = [1000,1000,1000,1000]';\n    \n    model_bounds.inputs.ConstraintWrench.fLeftFoot.lb = [-1000,-1000,300,-1000]';\n    model_bounds.inputs.ConstraintWrench.fLeftFoot.ub = [1000,1000,1000,1000]';\n    \n    \n    \n    \n    \n    %% construct the boundary values for each domain \n    bounds = struct();\n    \n    wt = 0.3662;\n    vx_lb = vel_lb(1);\n    vy_lb = vel_lb(2);\n    vx_ub = vel_ub(1);\n    vy_ub = vel_ub(2);\n    \n    %%\n    bounds.RightStance1 = model_bounds;\n    bounds.RightStance1.constrBounds.knee.lb = [deg2rad(50),deg2rad(50)];\n    bounds.RightStance1.constrBounds.knee.ub = [deg2rad(60),deg2rad(150)];\n    \n    bounds.RightStance1.constrBounds.stepWidth.lb = -wt - vx_ub*T;\n    bounds.RightStance1.constrBounds.stepWidth.ub = -wt - vx_lb*T;\n    \n    bounds.RightStance1.constrBounds.stepLength.lb = -vy_ub*T;\n    bounds.RightStance1.constrBounds.stepLength.ub = -vy_lb*T;\n    \n    \n    bounds.RightStance1.constrBounds.full_state.lb = x0;\n    bounds.RightStance1.constrBounds.full_state.ub = x0;\n    idx = [3:9, 12:14, 19:25, 28:30]; \n    bounds.RightStance1.constrBounds.actuated_state.lb = x0(idx);\n    bounds.RightStance1.constrBounds.actuated_state.ub = x0(idx);\n    %%\n    bounds.LeftImpact.states.x = model_bounds.states.x;\n    bounds.LeftImpact.states.xn = model_bounds.states.x;\n    bounds.LeftImpact.states.dx = model_bounds.states.dx;\n    bounds.LeftImpact.states.dxn = model_bounds.states.dx;\n    \n    bounds.LeftImpact.inputs = struct();\n    bounds.LeftImpact.inputs.ConstraintWrench.ffourBar.lb = -20;\n    bounds.LeftImpact.inputs.ConstraintWrench.ffourBar.ub = 20;\n    bounds.LeftImpact.inputs.ConstraintWrench.fLeftFoot.lb = [-20,-20,0,-10]';\n    bounds.LeftImpact.inputs.ConstraintWrench.fLeftFoot.ub = [20,20,150,10]';\n    bounds.LeftImpact.params = struct();\n\n\n    %% Right Stance\n    bounds.LeftStance1 = model_bounds;\n    \n    bounds.LeftStance1.constrBounds.knee.lb = [deg2rad(50),deg2rad(50)];\n    bounds.LeftStance1.constrBounds.knee.ub = [deg2rad(150),deg2rad(60)];\n    \n    bounds.LeftStance1.midState_QFit = zeros(6,3);\n    bounds.LeftStance1.midState_dQFit = zeros(6,3);\n    \n    bounds.LeftStance1.constrBounds.stepWidth.lb = -wt + vx_lb*T;\n    bounds.LeftStance1.constrBounds.stepWidth.ub = -wt + vx_ub*T;\n    \n    bounds.LeftStance1.constrBounds.stepLength.lb = vy_lb*T;\n    bounds.LeftStance1.constrBounds.stepLength.ub = vy_ub*T;\n    \n    \n    %%\n    bounds.RightImpact.states.x = model_bounds.states.x;\n    bounds.RightImpact.states.xn = model_bounds.states.x;\n    bounds.RightImpact.states.dx = model_bounds.states.dx;\n    bounds.RightImpact.states.dxn = model_bounds.states.dx;\n    bounds.RightImpact.inputs = struct();\n    bounds.RightImpact.inputs.ConstraintWrench.ffourBar.lb = -20;\n    bounds.RightImpact.inputs.ConstraintWrench.ffourBar.ub = 20;\n    bounds.RightImpact.inputs.ConstraintWrench.fRightFoot.lb = [-20,-20,0,-10]'';\n    bounds.RightImpact.inputs.ConstraintWrench.fRightFoot.ub = [20,20,150,10]';\n    bounds.RightImpact.params = struct();\n\n    \n    %% \n    bounds.RightStance2 = bounds.RightStance1;\n    \n    bounds.RightStance2.midState_QFit = zeros(6,3);\n    bounds.RightStance2.midState_dQFit = zeros(6,3);\n    \n    \n    bounds.LeftStance2  = bounds.LeftStance1;\n    \n    bounds.LeftStance2.constrBounds.full_state.lb = xf;\n    bounds.LeftStance2.constrBounds.full_state.ub = xf;\n    \n    bounds.LeftStance2.constrBounds.actuated_state.lb = xf(idx);\n    bounds.LeftStance2.constrBounds.actuated_state.ub = xf(idx);\nend\n", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/marlo/+trans_opt/GetBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.21573477968898339}}
{"text": "function STResNet_stage2(varargin)\n\nif ~isempty(gcp('nocreate'))\n    delete(gcp)\nend\n\nopts.train.gpus = [ 1 ] ;\n\n% addpath('../network_surgery');\nopts = cnn_setup_environment(opts);\n\n% opts.dataSet = 'hmdb51';\nopts.dataSet = 'ucf101';\n\nopts.dropOutRatio = NaN;\nopts.backpropFuseFrom = 1;\nopts.nSplit =  1 ;\nopts.addPool3D = 1 ;\nopts.singleSoftMax = 0;\nopts.nFrames = 11 ;\n% opts.train.backpropDepth = 'pool5';\nopts.train.learningRate =  1*[ 1e-4*ones(1,1) 1e-5*ones(1,1)]  ;\nopts.train.augmentation = 'f25noCtr';\n\nopts.train.epochFactor = 1 ;\n\nopts.train.batchSize = 128  ;\nopts.train.numSubBatches = 32 ;\nopts.train.cheapResize = 0 ;\nopts.poolMethod = 'max';\nopts.poolSz=5 ;\nopts.poolStride=2 ;\n\nmodel = ['ST-ResNet50-final-split=' num2str(opts.nSplit)];\n\nopts.train.numSubBatches =  ceil(opts.train.numSubBatches / max(numel(opts.train.gpus),1));\n\nopts.train.memoryMapFile = fullfile(tempdir, 'ramdisk', ['matconvnet' num2str(opts.nSplit ) '.bin']) ;\nopts.dataDir = fullfile(opts.dataPath, opts.dataSet) ;\nopts.splitDir = 'ucf101_splits'; nClasses = 101;\nopts.imdbPath = fullfile(opts.dataDir, [opts.dataSet '_split' num2str(opts.nSplit) 'imdb.mat']);\n    \nopts.model = fullfile(opts.modelPath, [opts.dataSet '-ST-ResNet50-split=' num2str(opts.nSplit) '.mat']) ;\n\nif strcmp(opts.dataSet, 'hmdb51')\n  opts.splitDir = 'hmdb51_splits'; nClasses = 51;\n  opts.flowDir = strrep(opts.flowDir, 'ucf101','hmdb51');\n  opts.imdbPath = fullfile(opts.dataDir, ['hmdb_split' num2str(opts.nSplit) 'imdb.mat']);\nend\n\nopts.expDir = fullfile(opts.dataDir, [opts.dataSet '-' model]) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.train.saveAllPredScores = 1;\nopts.train.denseEval = 1;\nopts.train.plotDiagnostics = 0 ;\nopts.train.continue = 1 ;\nopts.train.prefetch = 1 ;\nopts.train.expDir = opts.expDir ;\nopts.train.numAugments = 1;\nopts.train.frameSample = 'random';\nopts.train.nFramesPerVid = 1;\n\nopts = vl_argparse(opts, varargin) ;\n\n% -------------------------------------------------------------------------\n%                                                   Database initialization\n% -------------------------------------------------------------------------\nif exist(opts.imdbPath)\n  imdb = load(opts.imdbPath) ;\n  imdb.flowDir = opts.flowDir;\nelse\n  imdb = cnn_setup_data(opts) ;\n  save(opts.imdbPath, '-struct', 'imdb', '-v6') ;\nend\n\n% -------------------------------------------------------------------------\n%                                                    Network initialization\n% -------------------------------------------------------------------------\nif ~exist(opts.model,'file')\n  [~, baseModel] = fileparts(opts.model);\n  fprintf('Downloading base model file: %s ...\\n', baseModel);\n  mkdir(fileparts(opts.model)) ;\n  urlwrite(...\n  ['http://ftp.tugraz.at/pub/feichtenhofer/st-res/stage1/' baseModel '.mat'], ...\n    opts.model) ;\nend\nnet = load(opts.model) ;\n\nif isfield(net, 'net'), net=net.net;end\nnet = dagnn.DagNN.loadobj(net);\n\nif opts.addPool3D\n\n%   poolLayers = {'res2a', 'res3a',  'res4a', 'res5a'; };\n%   poolLayers = {'pool5'; };\n  poolLayers = {'res5c_relu'; };\n\n  for j=1:numel(poolLayers)\n    for s = {'spatial', 'temporal'}\n      i_pool = find(strcmp({net.layers.name},[poolLayers{j} '_' char(s)]));    \n      \n      block = dagnn.PoolTime() ;\n      block.poolSize = [1 opts.poolSz];  \n      block.pad = [0 0 0 0]; \n      block.stride = [1 opts.poolStride];     \n      block.method = opts.poolMethod;     \n \n      name = [poolLayers{j} '_pool_' char(s)];\n      \n      disp(['injecting ' name ' as PoolTime'])\n\n      net.addLayerAt(i_pool, name, block, ...\n                    [net.layers(i_pool).outputs], {name}) ; \n\n      % chain input of l that has layer as input\n      for l = 1:numel(net.layers)    \n          if ~strcmp(net.layers(l).name, name)\n            sel = find(strcmp(net.layers(l).inputs, net.layers(i_pool).outputs{1})) ;\n            if any(sel)\n                net.layers(l).inputs{sel} = name;\n            end;   \n          end\n      end\n\n    end\n  end\nend % add pool3d\n\nif opts.addPool3D\n  opts.train.augmentation = 'f25noCtr';\n  opts.train.frameSample = 'temporalStrideRandom';\n  opts.train.nFramesPerVid = opts.nFrames * 1; \n  opts.train.temporalStride = 1:15;  \n  opts.train.valmode = 'temporalStrideRandom';\n  opts.train.numValFrames = 25 ;\n  opts.train.saveAllPredScores = 1 ;\n  opts.train.denseEval = 1;\n  opts.train.temporalFullConvTest = 1;\nend  \n \nnet.meta.normalization.rgbVariance = [];\nopts.train.train = find(ismember(imdb.images.set, [1])) ;\nopts.train.train = repmat(opts.train.train,1,opts.train.epochFactor);\n\nzero_drs =  find(arrayfun(@(x) isa(x.block,'dagnn.DropOut') && x.block.rate == 0, net.layers)) ;\nnet.removeLayer({net.layers(zero_drs).name});\n\nif ~isnan(opts.dropOutRatio)\n  dr_layers = find(arrayfun(@(x) isa(x.block,'dagnn.DropOut'), net.layers)) ;\n  if opts.dropOutRatio > 0\n    net.layers(dr_layers).block.rate = opts.dropOutRatio;\n  else\n    net.removeLayer({net.layers(dr_layers).name});\n  end\nend\n\nif opts.singleSoftMax\n  pred_layers = [];\n  for l=1:numel(net.layers)\n    if isempty( net.layers(l).params ), continue; end;\n    if size(net.params(net.getParamIndex(net.layers(l).params{1})).value,4) == nClasses || ...\n        size(net.params(net.getParamIndex(net.layers(l).params{1})).value,5) == nClasses % 3D FC layer\n          pred_layers = [pred_layers l];\n          net.vars(net.layers(l).outputIndexes).precious = 1;\n    end\n  end\n  pred_layers = fliplr(pred_layers) ; % remove the spatial layer\n  paramsIdx1 = net.getParamIndex(net.layers(pred_layers(1)).params);\n  paramsIdx2 = net.getParamIndex(net.layers(pred_layers(2)).params);\n  for p = 1:numel(paramsIdx1)\n    sz = size(net.params(paramsIdx1(p)).value);\n    if numel(sz) > 2\n      net.params(paramsIdx1(p)).value = cat(3,net.params(paramsIdx1(p)).value, net.params(paramsIdx2(p)).value);\n    else\n      net.params(paramsIdx1(p)).value = net.params(paramsIdx1(p)).value + net.params(paramsIdx2(p)).value;\n    end\n  end\n  block = dagnn.Concat() ;\n  newName = ['singleSoftMaxConcat']; \n  net.addLayer(newName, block, ...\n               [net.layers(pred_layers).inputs], ...\n               newName) ;   \n  net.layers(pred_layers(1)).inputs =    newName ; \n  % remove layers of the other prediction\n  for l = numel(net.layers):-1:1\n    for f = net.layers(pred_layers(2)).outputs\n       sel = find(strcmp(f, net.layers(l).inputs )) ;\n       if ~isempty(sel)\n         fprintf('removing ayer %s \\n', net.layers(l).name);\n         net.removeLayer({net.layers(l).name});\n       end\n    end\n  end\n  net.removeLayer({net.layers(pred_layers(2)).name});\nend\n\nnet.layers(~cellfun('isempty', strfind({net.layers(:).name}, 'err'))) = [] ;\n\nnet.rebuild() ;\n\nopts.train.derOutputs = {} ;\nfor l=1:numel(net.layers)\n  if isa(net.layers(l).block, 'dagnn.Loss') && isempty(strfind(net.layers(l).block.loss, 'err'))\n    if opts.backpropFuseFrom || ~isempty(strfind(net.layers(l).name, opts.train.fuseInto ))\n      fprintf('setting derivative for layer %s \\n', net.layers(l).name);\n      opts.train.derOutputs = [opts.train.derOutputs, net.layers(l).outputs, {1}] ;\n    end\n    net.addLayer(['err1_' net.layers(l).name(end-7:end) ], dagnn.Loss('loss', 'classerror'), ...\n             net.layers(l).inputs, 'error') ;  \n  end\nend\n\nnet.conserveMemory = 1 ;\nfn = getBatchWrapper_rgbflow(net.meta.normalization, opts.numFetchThreads, opts.train) ;\n[info] = cnn_train_dag(net, imdb, fn, opts.train) ;", "meta": {"author": "feichtenhofer", "repo": "st-resnet", "sha": "8b4f28431b5abe881c3b5192c309ac7a303b5c9d", "save_path": "github-repos/MATLAB/feichtenhofer-st-resnet", "path": "github-repos/MATLAB/feichtenhofer-st-resnet/st-resnet-8b4f28431b5abe881c3b5192c309ac7a303b5c9d/STResNet_stage2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.21568616842463864}}
{"text": "%SingleCellVariation\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last Updated: 3/23/2011\nclassdef SingleCellVariation\n    methods (Static)\n        function run(sim, fileName)\n            import edu.stanford.covert.cell.sim.analysis.SingleCellVariation;\n            import edu.stanford.covert.cell.sim.util.PlotUtil;\n            import edu.stanford.covert.cell.sim.util.PrintUtil;\n            \n            %sample growth rate distribution\n            initialGrowthFilterWidth = sim.state('MetabolicReaction').initialGrowthFilterWidth;\n            sim.state('MetabolicReaction').initialGrowthFilterWidth = Inf;\n            growthRates = SingleCellVariation.sampleSingleCellVariationDistribution(sim, 100);\n            sim.state('MetabolicReaction').initialGrowthFilterWidth = initialGrowthFilterWidth;\n            assertElementsAlmostEqual(sim.state('MetabolicReaction').meanInitialGrowthRate, mean(growthRates), 'relative', 0.50, 0);\n            \n            %% excel file\n            [content, colLabels, indentation] = SingleCellVariation.printSingleCellVariationDistribution(sim, growthRates);\n            if nargin == 1\n                PrintUtil.printToStdIO(content, colLabels, struct('indentation', indentation));\n            else\n                PrintUtil.printToFile(content, colLabels, [fileName '.xls'], 'GrowthRate', struct('indentation', indentation));\n            end\n            \n            %% plots\n            if nargin == 1\n                SingleCellVariation.plotSingleCellVariationGrowthRateDistribution(sim, growthRates, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotSingleCellVariationDoublingTimeDistribution(sim, growthRates, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_RNA_Weight_Fractions(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_RNA_Expression(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_rRNAExpression(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_sRNA_Expression(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_tRNA_Expression(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_Monomer_Expression(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_NTP_Incorporation(sim, PlotUtil.newAxesHandle());\n                SingleCellVariation.plotExpected_Vs_Simulated_AA_Incorporation(sim, PlotUtil.newAxesHandle());\n            else\n                [axesHandle, figHandle] = PlotUtil.newAxesHandle();\n                \n                cla(axesHandle);\n                SingleCellVariation.plotSingleCellVariationGrowthRateDistribution(sim, growthRates, axesHandle);\n                saveas(figHandle, [fileName '-GrowthRate.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotSingleCellVariationDoublingTimeDistribution(sim, growthRates, axesHandle);\n                saveas(figHandle, [fileName '-DoublingTime.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_RNA_Weight_Fractions(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_RNA_Weight_Fractions.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_RNA_Expression(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_RNA_Expression.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_rRNAExpression(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_rRNA_Expression.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_sRNA_Expression(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_sRNA_Expression.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_tRNA_Expression(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_tRNA_Expression.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_Monomer_Expression(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_Monomer_Expression.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_NTP_Incorporation(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_NTP_Incorporation.pdf']);\n                \n                cla(axesHandle);\n                SingleCellVariation.plotExpected_Vs_Simulated_AA_Incorporation(sim, axesHandle);\n                saveas(figHandle, [fileName '-Expected_Vs_Simulated_AA_Incorporation.pdf']);\n                \n                close(figHandle);\n            end\n        end\n    end\n    \n    methods (Static = true)\n        function growthRates = sampleSingleCellVariationDistribution(sim, nTrials)\n            warnStatus = warning('query', 'WholeCell:warning');\n            warning('off', 'WholeCell:warning');\n            \n            growthRates = zeros(nTrials, 1);\n            r = sim.state('MetabolicReaction');\n            for i = 1:nTrials\n                %seed rand stream\n                sim.applyOptions(struct('seed', i));\n                for j = 1:numel(sim.states)\n                    o = sim.states{j};\n                    o.seed = i;\n                end\n                for j = 1:numel(sim.processes)\n                    o = sim.processes{j};\n                    o.seed = i;\n                end\n                \n                %calculate growth rate\n                sim.initializeState();\n                growthRates(i) = r.growth;\n            end\n            \n            warning(warnStatus.state, 'WholeCell:warning');\n        end\n    end\n    \n    %printing\n    methods (Static = true)\n        function [content, colLabels, indentation] = printSingleCellVariationDistribution(sim, growthRates)\n            %import classes\n            import edu.stanford.covert.util.ConstantUtil;\n            import edu.stanford.covert.cell.sim.Simulation;\n            \n            content = cell(0, 4);\n            colLabels = {'Trial', 'Growth Rate (cell/s)', 'Doubling Time (hr)'};\n            \n            %time\n            content = [content;\n                num2cell(zeros(size(growthRates)))  cellfun(@(x) num2str(x), num2cell((1:numel(growthRates))'), 'UniformOutput', false)  num2cell(growthRates)  num2cell(1./(growthRates*3600)/sim.state('Mass').timeAveragedCellWeight)\n                ];\n            \n            content = [content;{\n                0 'Mean'          mean(growthRates)  1/(mean(growthRates)*3600)/sim.state('Mass').timeAveragedCellWeight\n                0 'Min'           min(growthRates)   1/(max(growthRates)*3600)/sim.state('Mass').timeAveragedCellWeight\n                0 'Max'           max(growthRates)   1/(min(growthRates)*3600)/sim.state('Mass').timeAveragedCellWeight\n                0 'Experimental'  1/(sim.state('Time').cellCycleLength)/sim.state('Mass').timeAveragedCellWeight sim.state('Time').cellCycleLength/3600\n                }];\n            \n            %format output\n            indentation = cell2mat(content(:, 1));\n            content = content(:, 2:end);\n        end\n    end\n    \n    %plotting\n    methods (Static = true)\n        function plotSingleCellVariationGrowthRateDistribution(sim, growthRates, axesHandle)\n            hist(axesHandle, growthRates, 10);\n            xlims = xlim(axesHandle);\n            ylims = ylim(axesHandle);\n            xlabel('Growth (cell/s)', 'FontSize', 12);\n            ylabel('Frequency', 'FontSize', 12);\n            \n            h2 = line(mean(growthRates) * [1 1], ylims);\n            set(h2, 'Color', 'g');\n            \n            h3 = line(median(growthRates) * [1 1], ylims);\n            set(h3, 'Color', 'c');\n            \n            mu = mean(growthRates);\n            sigma = std(growthRates);\n            h4 = line([mu-sigma; mu-sigma], ylims);\n            h5 = line([mu+sigma; mu+sigma], ylims);\n            set(h4, 'Color', 'r');\n            set(h5, 'Color', 'r');\n            \n            mr = sim.state('MetabolicReaction');\n            mu = mr.meanInitialGrowthRate;\n            wd = mr.initialGrowthFilterWidth;\n            h6 = line(mu*(1-wd)*[1 1], ylims);\n            h7 = line(mu*(1+wd)*[1 1], ylims);\n            set(h6, 'Color', 'y');\n            set(h7, 'Color', 'y');\n            \n            h = legend([h2 h3 h4 h6], 'Mean', 'Median', 'Mean \\pm 1 Std', 'Filter');\n            set(h, 'Location', 'NorthWest');\n            \n            xlim(axesHandle, xlims);\n            ylim(axesHandle, ylims);\n        end\n        \n        function plotSingleCellVariationDoublingTimeDistribution(sim, growthRates, axesHandle)\n            thresh = sim.state('Time').cellCycleLength/3600 * 2;\n            \n            doublingTimes = 1./(growthRates * 3600)/sim.state('Mass').timeAveragedCellWeight;\n            hist(axesHandle, doublingTimes(doublingTimes <= thresh), 10);\n            h1 = findobj(gca, 'Type', 'patch');\n            xlabel('Doubling Time (h)', 'FontSize', 12);\n            ylabel('Frequency', 'FontSize', 12);\n            xlim([floor(min(doublingTimes(doublingTimes <= thresh))) ceil(max(doublingTimes(doublingTimes <= thresh)))]);\n            \n            h2 = line(1/(mean(growthRates) * 3600) / sim.state('Mass').timeAveragedCellWeight * [1 1], [0 max(ylim)]);\n            set(h2, 'Color', 'g');\n            \n            h3 = line(1/(median(growthRates) * 3600) / sim.state('Mass').timeAveragedCellWeight * [1 1], [0 max(ylim)]);\n            set(h3, 'Color', 'c');\n            \n            h4 = line(sim.state('Time').cellCycleLength * [1 1] / 3600, [0 max(ylim)]);\n            set(h4, 'Color', 'r');\n            \n            h = legend([h1(1) h2 h3 h4], sprintf('Simulation, growth (%.1f%%)', 100 * sum(doublingTimes <= thresh) / numel(doublingTimes)), 'Sim-Mean', 'Sim-Median', 'Exp-Mean');\n            set(h, 'Location', 'NorthEast');\n        end\n        \n        function plotExpected_Vs_Simulated_RNA_Weight_Fractions(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            import edu.stanford.covert.util.ConstantUtil;\n            \n            r = sim.state('Rna');\n            \n            weightFractions = [...\n                r.molecularWeights(r.matureIndexs(r.matureMRNAIndexs))' * ...\n                sum(sum(r.counts(r.matureIndexs(r.matureMRNAIndexs), :, :), 3), 2);...\n                r.molecularWeights(r.matureIndexs(r.matureRibosomalRRNAIndexs)) .* ...\n                sum(sum(r.counts(r.matureIndexs(r.matureRibosomalRRNAIndexs), :, :), 3), 2);...\n                r.molecularWeights(r.matureIndexs(r.matureSRNAIndexs))' * ...\n                sum(sum(r.counts(r.matureIndexs(r.matureSRNAIndexs), :, :), 3), 2)\n                r.molecularWeights(r.matureIndexs(r.matureTRNAIndexs))' * ...\n                sum(sum(r.counts(r.matureIndexs(r.matureTRNAIndexs), :, :), 3), 2)] / ...\n                ConstantUtil.nAvogadro;\n            \n            plot(axesHandle, r.expectedWeightFractions, weightFractions, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(weightFractions)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(r.expectedGeneDecayRates) max(r.weightFractions)]);\n            ylim([min(weightFractions) max(weightFractions)]);\n            xlabel(axesHandle, 'Expected Weight Fraction', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Weight (g)', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_RNA_Expression(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            \n            expression = r.expression(r.matureIndexs);\n            \n            RNAs = sum(sum(...\n                r.counts(r.processedIndexs,     :, :) + ...\n                r.counts(r.matureIndexs,        :, :) + ...\n                r.counts(r.boundIndexs,         :, :) + ...\n                r.counts(r.misfoldedIndexs,     :, :) + ...\n                r.counts(r.damagedIndexs,       :, :) + ...\n                r.counts(r.aminoacylatedIndexs, :, :), ...\n                3), 2);\n            \n            plot(axesHandle, expression, RNAs, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(RNAs)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(expression) max(expression)]);\n            ylim([min(RNAs) max(RNAs)]);\n            xlabel(axesHandle, 'Expected Expression', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_rRNAExpression(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            c = sim.state('ProteinComplex');\n            \n            expression = r.geneExpression(sim.gene.rRNAIndexs);\n            expression = expression / sum(expression);\n            \n            RNAs = sum(sum(...\n                r.counts(r.processedIndexs(    r.matureRRNAIndexs), :, :) + ...\n                r.counts(r.matureIndexs(       r.matureRRNAIndexs), :, :) + ...\n                r.counts(r.boundIndexs(        r.matureRRNAIndexs), :, :) + ...\n                r.counts(r.misfoldedIndexs(    r.matureRRNAIndexs), :, :) + ...\n                r.counts(r.damagedIndexs(      r.matureRRNAIndexs), :, :) + ...\n                r.counts(r.aminoacylatedIndexs(r.matureRRNAIndexs), :, :), ...\n                3), 2) + ...\n                sum(c.proteinComplexComposition(sim.gene.rRNAIndexs, :, :), 3) * ...\n                sum(sum(...\n                c.counts(c.matureIndexs,      :, :) + ...\n                c.counts(c.inactivatedIndexs, :, :) + ...\n                c.counts(c.boundIndexs,       :, :) + ...\n                c.counts(c.misfoldedIndexs,   :, :) + ...\n                c.counts(c.damagedIndexs,     :, :), 3), 2);\n            \n            plot(axesHandle, expression, RNAs, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(RNAs)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(0.3, min(expression)) max(0.4, max(expression))]);\n            ylim([min(RNAs)-1 max(RNAs)+1]);\n            xlabel(axesHandle, 'Expected Expression', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_sRNA_Expression(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            \n            expression = r.geneExpression(sim.gene.sRNAIndexs);\n            expression = expression / sum(expression);\n            \n            RNAs = sum(sum(...\n                r.counts(r.processedIndexs(    r.matureSRNAIndexs), :, :) + ...\n                r.counts(r.matureIndexs(       r.matureSRNAIndexs), :, :) + ...\n                r.counts(r.boundIndexs(        r.matureSRNAIndexs), :, :) + ...\n                r.counts(r.misfoldedIndexs(    r.matureSRNAIndexs), :, :) + ...\n                r.counts(r.damagedIndexs(      r.matureSRNAIndexs), :, :) + ...\n                r.counts(r.aminoacylatedIndexs(r.matureSRNAIndexs), :, :), ...\n                3), 2);\n            \n            plot(axesHandle, expression, RNAs, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(RNAs)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(expression) max(expression)]);\n            ylim([min(RNAs) max(RNAs)]);\n            xlabel(axesHandle, 'Expected Expression', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_tRNA_Expression(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            \n            expression = r.geneExpression(sim.gene.tRNAIndexs);\n            expression = expression / sum(expression);\n            \n            RNAs = sum(sum(...\n                r.counts(r.processedIndexs(    r.matureTRNAIndexs), :, :) + ...\n                r.counts(r.matureIndexs(       r.matureTRNAIndexs), :, :) + ...\n                r.counts(r.boundIndexs(        r.matureTRNAIndexs), :, :) + ...\n                r.counts(r.misfoldedIndexs(    r.matureTRNAIndexs), :, :) + ...\n                r.counts(r.damagedIndexs(      r.matureTRNAIndexs), :, :) + ...\n                r.counts(r.aminoacylatedIndexs(r.matureTRNAIndexs), :, :), ...\n                3), 2);\n            \n            plot(axesHandle, expression, RNAs, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(RNAs)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(expression) max(expression)]);\n            ylim([min(RNAs) max(RNAs)]);\n            xlabel(axesHandle, 'Expected Expression', 'fontSize', 16);\n            ylabel(axesHandle, 'Copy Number', 'fontSize', 16);\n        end\n                \n        function plotExpected_Vs_Simulated_Monomer_Expression(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            m = sim.state('ProteinMonomer');\n            c = sim.state('ProteinComplex');\n            \n            expression = r.geneExpression(sim.gene.mRNAIndexs) ./ m.halfLives(m.matureIndexs);\n            expression = expression / sum(expression);\n            \n            monomers = ...\n                sum(sum(...\n                m.counts(m.matureIndexs,      :, :) + ...\n                m.counts(m.inactivatedIndexs, :, :) + ...\n                m.counts(m.boundIndexs,       :, :) + ...\n                m.counts(m.misfoldedIndexs,   :, :) + ...\n                m.counts(m.damagedIndexs,     :, :), 3), 2) + ...\n                sum(c.proteinComplexComposition(sim.gene.mRNAIndexs, :, :), 3) * ...\n                sum(sum(...\n                c.counts(c.matureIndexs,      :, :) + ...\n                c.counts(c.inactivatedIndexs, :, :) + ...\n                c.counts(c.boundIndexs,       :, :) + ...\n                c.counts(c.misfoldedIndexs,   :, :) + ...\n                c.counts(c.damagedIndexs,     :, :), 3), 2);\n            \n            plot(axesHandle, expression, monomers, '.', 'MarkerSize', 10);\n            line([0 1], [0 sum(monomers)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(expression) max(expression)]);\n            ylim([min(monomers) max(monomers)]);\n            xlabel(axesHandle, 'Expected Expression', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_NTP_Incorporation(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            r = sim.state('Rna');\n            m = sim.state('Metabolite');\n            \n            nmpComposition = sum(m.nmpComposition, 2);\n            \n            ntps = sum(sum(multiprod(r.baseCounts(:, sim.state('Metabolite').nmpIndexs)', r.counts, [1 2], [1 2]), 3), 2);\n            \n            plot(axesHandle, nmpComposition, ntps, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(ntps)], 'Parent', axesHandle, 'Color', 'r');\n            xlim([min(nmpComposition) max(nmpComposition)]);\n            ylim([min(ntps) max(ntps)]);\n            xlabel(axesHandle, 'Expected Incorporation', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n        \n        function plotExpected_Vs_Simulated_AA_Incorporation(sim, axesHandle)\n            import edu.stanford.covert.cell.sim.analysis.Constants;\n            \n            met = sim.state('Metabolite');\n            m = sim.state('ProteinMonomer');\n            c = sim.state('ProteinComplex');\n            \n            aaComposition = sum(met.aaComposition, 2);\n            \n            aas = multiprod(m.baseCounts(:, sim.state('Metabolite').aminoAcidIndexs)', m.counts, [1 2], [1 2]) + ...\n                multiprod(c.baseCounts(:, sim.state('Metabolite').aminoAcidIndexs)', c.counts, [1 2], [1 2]);\n            aas = sum(sum(aas, 3), 2);\n            \n            plot(axesHandle, aaComposition, aas, '.', 'MarkerSize', 20);\n            line([0 1], [0 sum(aas)],'Parent', axesHandle, 'Color', 'r');\n            xlim([min(aaComposition) max(aaComposition)]);\n            ylim([min(aas) max(aas)]);\n            xlabel(axesHandle, 'Expected Incorporation', 'fontSize', 16);\n            ylabel(axesHandle, 'Simulated Counts', 'fontSize', 16);\n        end\n    end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+analysis/SingleCellVariation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.21549176579436205}}
{"text": "% io_loadRFwaveform.m\n% Jamie Near, McGill University 2014.\n%\n% USAGE:\n% [RF_struct]=io_loadRFwaveform(filename,type,off_res);\n% \n% DESCRIPTION:\n% Initialize an RF pulse structure to contain an \n% RF Pulse waveform as well as its accompanying header\n% information.  This function finds the time-bandwidth\n% product (tbw) and the time-w1 product (tw1) of the pulse,\n% and stores this information in the header fields of the \n% output RF structure.\n% \n% INPUTS:\n% filename  = filename of RF pulse waveform text file.  Can be in Siemens\n%             format (.pta), Varian/Agilent format (.RF), Bruker format \n%             (.inv, .ref or .exc) or a plain text file (.txt, with two, \n%             three or four columns (amplitude, phase, time-step\n%             (optional),and gradient strength (optional).  Filename can \n%             also be the name of a two, three or four column matlab vector \n%             specifing the phase, amplitude, time vectors (optionally) and \n%             gradient (optionally) of an RF pulse waveform.  Note about \n%             Units: RF amplitude waveform [arbitrary units], B1 intensity \n%             [kHz],  phase waveform [degrees], time step vector [arbitrary \n%             units],  gradient waveform [G/cm].\n% type      = Excitation ('exc'), Refocusing ('ref') or Inversion ('inv'). \n%             Alternatively, 'type' can specify the exact flip angle [in \n%             degrees] of the pulse.  This can be useful if you want to use \n%             a pulse that does not have an exact flip angle of 90 or 180 \n%             degrees (Thanks to Eric Plitman for help with this feature).  \n% off_res   = set to \"1\" if the centre of the RF pulse is not at 0 Hz. \n%             Optional. Default=0.\n%\n% OUTPUTS:\n% RF_struct = RF pulse waveform in FID-A rf pulse structure format.\n\nfunction RF_struct=io_loadRFwaveform(filename,type,off_res);\n\nif nargin<3\n    off_res=0;\nend\n\nif isnumeric(type)\n    %If 'type' was specified to be exactly 90 degrees, set the type to 'exc';\n    if type==90;\n        type='exc';\n    end\n    \n    %If 'type' was specified to be exactly 180 degrees, set the type to 'inv'\n    %(functionally there is no real difference between 'ref' and 'inv', so I\n    %just chose 'Inv';\n    if type==180;\n        type='inv';\n    end\nend\n\n%Now read in the waveform:\nif isstr(filename)\n    if exist(filename)\n        if filename(end-3:end)=='.pta'\n            disp('Siemens format .pta RF pulse file detected!! Loading waveform now.');\n            rf=io_readpta(filename);\n        elseif filename(end-2:end)=='.RF'\n            disp('Varian/Agilent format .RF RF pulse file detected!! Loading waveform now.');\n            rf=io_readRF(filename);\n        elseif filename(end-3:end)=='.inv'\n            disp('Bruker format .inv RF pulse file detected!! Loading waveform now.');\n            rf=io_readRFBruk(filename);\n        elseif filename(end-3:end)=='.rfc'\n            disp('Bruker format .pta RF pulse file detected!! Loading waveform now.');\n            rf=io_readRFBruk(filename);\n        elseif filename(end-3:end)=='.exc'\n            disp('Bruker format .exc RF pulse file detected!! Loading waveform now.');\n            rf=io_readRFBruk(filename);\n        elseif filename(end-3:end)=='.txt'\n            disp('Basic .txt format RF pulse file detected!! Loading waveform now.');\n            rf=io_readRFtxt(filename);\n        else\n            error('ERROR:  RF Pulse file not recognized.  Aborting!');\n        end\n    else\n        error('ERROR:  File not found!  Aborting!');\n    end  \nelse\n    if ismatrix(filename) && ndims(filename)==2 && ( 2 <= size(filename,2) <= 4 )\n        disp('Input is an RF waveform already in the matlab workspace.  Loading waveform now.');\n        if size(filename,2)==2\n            rf=filename;\n            rf(:,3)=ones(length(filename(:,1)),1);\n        elseif size(filename,2)==3 || size(filename,2)==4\n            rf=filename;\n        end\n    end\nend\n\n\nTp=0.005;  %assume a 5 ms rf pulse;\n\n%Frequency shifting the pulse to zero if off_res is 1. To be shifted back\n%afterwards - PT,2021\nif off_res   \n    %Initializations\n    tmp_w1=0.03;\n    tmp_min=1;\n    \n    %Looping through until a min of <-0.98 (inv/ref) or <0.2 (exc) is reached\n    switch type\n        case 'exc'\n            min_floor = 0.2;\n        case {'inv','ref'}\n            min_floor = -0.98;\n    end\n    while tmp_min > min_floor\n        [mv,sc]=bes(rf,Tp*1000,'f',tmp_w1,-5,5,1000); %running bes with bare settings\n        [tmp_min,tmp_min_pos]=min(mv(3,:)); %finding the min and min position\n        freq_shift=sc(tmp_min_pos)*1000;%the freq shift (in Hz) of the pulse @ 5ms\n        tmp_w1=tmp_w1+0.02;\n    end\n    \n    %frequency shifting the pulse to 0 Hz\n    N=size(rf,1);\n    dt=Tp/N;\n    t=[0:dt:Tp-dt];\n    phaseRamp=t*-freq_shift*360;\n    rf(:,1)=rf(:,1)+phaseRamp'; \nend\n\n%Find out if the pulse is phase modulated.  If it is not, then we can\n%determine the time-w1 product of the pulse quite simply.  If it is phase\n%modulated (adiabatic, etc) then the determination of the time-w1 product \n%will need to me more interactive.\na=(round(rf(:,1))==180)|(round(rf(:,1))==0);\n\nif sum(a)<length(rf(:,1))\n    isPhsMod=true;\nelse\n    isPhsMod=false;\nend\n\n%If there are any phase discontinuities in the phase function that are\n%equal to a 360 degree jump we can remove these.  This will make it easier\n%for rf_resample to do it's job later on:\njumps=diff(rf(:,1));\njumpsAbs=(abs(jumps)>355 & abs(jumps)<365);  %Assume jumps within this range are exactly = 360 degrees.\njumpIndex=find(jumpsAbs);\nfor n=1:length(jumpIndex)\n    rf(jumpIndex(n)+1:end,1)=rf(jumpIndex(n)+1:end,1)-(360*(jumps(jumpIndex(n))/abs(jumps(jumpIndex(n)))));\nend\n\n%scale amplitude function so that maximum value is 1:\nrf(:,2)=rf(:,2)./max(rf(:,2));\n\nif ~isPhsMod \n    %The pulse is not phase modulated, so we can calculate the w1max:\n    %find the B1 max of the pulse in [kHz]:\n    if isstr(type)\n        if type=='exc'\n            flipCyc=0.25; %90 degrees is 0.25 cycles;\n        elseif type=='ref'\n            flipCyc=0.5;  %180 degress is 0.5 cycles;\n        elseif type=='inv'\n            flipCyc=0.5;  %180 degrees is 0.5 cycles;\n        end\n    elseif isnumeric(type) %assume that a flip angle (in degrees) was given\n        flipCyc=type/360;\n    end\n    \n    intRF=sum(rf(:,2).*((-2*(rf(:,1)>179))+1))/length(rf(:,2));\n    \n    if intRF~=0\n        w1max=flipCyc/(intRF*Tp); %w1max is in [Hz]\n    else\n        w1max=0;\n    end\n    tw1=Tp*w1max;\nelse\n    %The pulse is phase modulated, so we will need to run some test to find\n    %out the w1max;  To do this, we can plot Mz as a function of w1 and\n    %find the value of w1 that results in the desired flip angle.\n    [mv,sc]=bes(rf,Tp*1000,'b',0,0,5,40000);\n    plot(sc,mv(3,:));\n    xlabel('w1 (kHz)');\n    ylabel('mz');\n    w1max=input('Input desired w1max in kHz (for 5.00 ms pulse):  ');\n    w1max=w1max*1000; %convert w1max to [Hz]\n    tw1=Tp*w1max;\nend\n\n%now it's time to find out the time-bandwidth product:\n%First make a high resolution plot the pulse profile over a wide bandwidth:\n[mv,sc]=bes(rf,Tp*1000,'f',w1max/1000,-5,5,100000);\nif isstr(type)\n    if type=='exc'\n        index=find(abs(mv(1,:)+1i*mv(2,:))>0.5);\n        bw=sc(index(end))-sc(index(1))\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    elseif type=='ref'\n        index=find(mv(3,:)<0);\n        bw=sc(index(end))-sc(index(1));\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    elseif type=='inv'\n        index=find(mv(3,:)<0);\n        bw=sc(index(end))-sc(index(1));\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    end\nelseif isnumeric(type)\n    mz=cos(type); %Find out the Mz value immediately following the pulse.\n    thr=(1+mz)/2;  %Find out the Mz value mid-way between 1 and the mz (half-max):\n    index=find(mv(3,:)<thr);  %Find the indices of the corresponding \"full width\"\n    bw=sc(index(end))-sc(index(1));  %Now find the bandwidth at that point (\"Full width at half max\").  \nend\n\n\n%Now make a very high resolution plot the pulse profile over a narrower bandwidth:\n[mv,sc]=bes(rf,Tp*1000,'f',w1max/1000,-bw,bw,100000);\nif isstr(type)\n    if type=='exc'\n        index=find(abs(mv(1,:)+1i*mv(2,:))>0.5);\n        bw=sc(index(end))-sc(index(1))\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    elseif type=='ref'\n        index=find(mv(3,:)<0);\n        bw=sc(index(end))-sc(index(1));\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    elseif type=='inv'\n        index=find(mv(3,:)<0);\n        bw=sc(index(end))-sc(index(1));\n        %plot(sc(index),mv(3,index),'.-',sc,mv(3,:));\n    end\nelseif isnumeric(type)\n    mz=cos(type); %Find out the Mz value immediately following the pulse.\n    thr=(1+mz)/2;  %Find out the Mz value mid-way between 1 and the mz (half-max):\n    index=find(mv(3,:)<thr);  %Find the indices of the corresponding \"full width\"\n    bw=sc(index(end))-sc(index(1));  %Now find the bandwidth at that point (\"Full width at half max\").\nend\n\n%finally, try to estimate the centre point of the RF pulse 'rfCentre'.  \n%This is a number between 0 and 1 that indicates where the peak of the RF \n%amplitude waveform occurs.  If rfCentre = 0.5, then the pulse is symmetric.\n%If rfCentre<0.5 then the peak occurs near the beginning of the pulse (i.e.\n%a max phase pulse).  If rfCentre >0.5, then the peak occurs near the end\n%of the pulse (i.e. min phase pulse).\nmaxIndex=find(rf(:,2)==max(rf(:,2)));\nrfCentre=mean(maxIndex)/length(rf(:,2));\n\n%Now store the output structure;\nRF_struct.waveform=rf;\nRF_struct.type=type;\nRF_struct.f0=0;\nif size(rf,2)>3 && any(rf(:,4))\n    RF_struct.tbw='N/A - gradient modulated pulse';\n    RF_struct.isGM=true;\n    RF_struct.tthk=bw*Tp; %This is the time x sliceThickness product for \n                         %gradient modulated pulses.  It is in units [cm.s]\nelse\n    RF_struct.tbw=bw*Tp*1000;\n    RF_struct.isGM=false;\n    RF_struct.tthk='N/A - frequency selective pulse';\nend\nRF_struct.tw1=tw1;\nRF_struct.rfCentre=rfCentre;\n\n\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/inputOutput/io_loadRFwaveform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21547722368172897}}
{"text": "function [decimaldates1,decimaldates2,stringdates1,stringdates2,stringdates3,Fstartlocation,Fendlocation]=gendates(names,lags,frequency,startdate,enddate,Fstartdate,Fenddate,Fcenddate,Fendsmpl,F,CF,favar)\n\n\n\n% function [decimaldates1,decimaldates2,stringdates1,stringdates2,stringdates3,Fstartlocation,Fendlocation]=gendates(names,lags,frequency,startdate,enddate,Fstartdate,Fenddate,Fcenddate,Fendsmpl,F)\n% generate cells of date strings and vector of dates converted into decimal numbers; used for plots\n% inputs:  - vector 'decimaldates1': dates converted into decimal values, for the sample period\n%          - vector 'decimaldates2': dates converted into decimal values, for the sample+forecasts period\n%          - cell 'stringdates1': date strings for the sample period\n%          - cell 'stringdates2': date strings for the sample+forecasts period\n%          - cell 'stringdates3': date strings for the forecast evaluation period (i.e. period for which forecast is estimated and actual data exists)\n%          - integer 'Fstartlocation': position of the forecast start date in stringdates2\n%          - integer 'Fendlocation': position of the forecast end date in stringdates2\n% outputs: - cell 'names': cell containing the excel spreadsheet labels (names and dates)\n%          - integer 'lags': number of lags included in the model\n%          - integer 'frequency': frequency of the data set\n%          - string 'startdate': start date of the sample\n%          - string 'enddate': end date of the sample\n%          - string 'Fstartdate': start date of the forecasts\n%          - string 'Fenddate': end date of the forecasts\n%          - string 'Fcenddate': end date of the forecat evaluation (i.e. period for which forecast is estimated and actual data exists)\n%          - integer 'Fendsmpl': 0-1 value to determine if forecasts must start after the final sample period\n%          - integer 'F': 0-1 value to determine if forecasts must be estimated\n\n\n\n\n% preliminary tasks\n% define date strings\ndatestrings=names(2:end,1);\n\nif favar.FAVAR==1 % in case we transform the data to first or second differences, we have a different startlocation\n    if favar.transformation==1\n        datestrings=names(1+favar.informationstartlocation:favar.informationendlocation_sub,:); %first row are labels\n    end\nend\n\n% PHASE 1: CREATION OF DECIMAL DATES AND DATE STRINGS FOR THE ESTIMATION SAMPLE (DECIMALDATES1, STRINGDATES1)\n\n\n% deal first with the data if it is yearly\nif frequency==1\n    % identify the number of years covered by the sample\n    startyear=str2double(startdate(1,1:end-1));\n    endyear=str2double(enddate(1,1:end-1));\n    % create the decimal value vector\n    decimaldates1=(startyear:endyear)';\n    % convert into strings\n    stringdates1=cellfun(@num2str,num2cell(decimaldates1),'UniformOutput',0);\n    % add a 'y' character at the end\n    for ii=1:size(stringdates1,1)\n        stringdates1{ii,1}=[stringdates1{ii,1} 'y'];\n    end\n    % trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\n    \n    % deal now with the data if it is quarterly\nelseif frequency==2\n    % first identify the year and quarter of the initial date\n    startyear=str2double(startdate(1,1:4));\n    startquarter=str2double(startdate(1,6));\n    % proceed similarly for the year and quarter of the final date\n    endyear=str2double(enddate(1,1:4));\n    endquarter=str2double(enddate(1,6));\n    % initiate the decimal value vector and the string cell\n    decimaldates1=[];\n    stringdates1={};\n    % create the decimal vector from start date up to the penultimate year\n    year=startyear;\n    quarter=startquarter;\n    while year<=endyear-1\n        while quarter<=4\n            decimaldates1=[decimaldates1;year+(quarter-1)/4];\n            temp=[num2str(year) 'q' num2str(quarter)];\n            stringdates1{end+1,1}=temp;\n            quarter=quarter+1;\n        end\n        quarter=1;\n        year=year+1;\n    end\n    % complete with final year\n    while quarter<=endquarter\n        decimaldates1=[decimaldates1;year+(quarter-1)/4];\n        temp=[num2str(year) 'q' num2str(quarter)];\n        stringdates1{end+1,1}=temp;\n        quarter=quarter+1;\n    end\n    % finally, trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\n    \n    % deal now with the data if it is monthly\nelseif frequency==3\n    % first identify the year and month of the initial date\n    temp=startdate;\n    temp(1,5)=' ';\n    [startyear,startmonth]=strtok(temp);\n    startyear=str2double(startyear);\n    startmonth=str2double(startmonth);\n    % proceed similarly for the year and month of the final date\n    temp=enddate;\n    temp(1,5)=' ';\n    [endyear,endmonth]=strtok(temp);\n    endyear=str2double(endyear);\n    endmonth=str2double(endmonth);\n    % initiate the decimal value vector and the string cell\n    decimaldates1=[];\n    stringdates1={};\n    % create the decimal vector from start date up to the penultimate year\n    year=startyear;\n    month=startmonth;\n    while year<=endyear-1\n        while month<=12\n            decimaldates1=[decimaldates1;year+(month-1)/12];\n            temp=[num2str(year) 'm' num2str(month)];\n            stringdates1{end+1,1}=temp;\n            month=month+1;\n        end\n        month=1;\n        year=year+1;\n    end\n    % complete with final year\n    while month<=endmonth\n        decimaldates1=[decimaldates1;year+(month-1)/12];\n        temp=[num2str(year) 'm' num2str(month)];\n        stringdates1{end+1,1}=temp;\n        month=month+1;\n    end\n    % finally, trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\n    \n    % deal now with the data if it is weekly\nelseif frequency==4\n    % first identify the first and last years of the sample\n    startyear=str2double(startdate(1,1:4));\n    endyear=str2double(enddate(1,1:4));\n    % calculate the total number of years over the period\n    numyear=endyear-startyear+1;\n    % create a vector of date strings for the sample period\n    start=find(strcmp(datestrings,startdate));\n    finish=find(strcmp(datestrings,enddate));\n    stringdates1=datestrings(start:finish,1);\n    % for each year in the sample, identify the earliest and latest week\n    for ii=startyear:endyear\n        % first identify which periods in the sample correspond to this year\n        periods=strfind(stringdates1,num2str(ii));\n        for jj=1:size(periods,1)\n            if isempty(periods{jj,1})\n                periods{jj,1}=0;\n            end\n        end\n        periods=cell2mat(periods);\n        % identify the position of the first week and the last week of this year\n        first=min(find(periods==1));\n        last=max(find(periods==1));\n        % identify the week number to which these positions correspond\n        temp=char(stringdates1(first,1));\n        temp(1,5)=' ';\n        [~,weeknum]=strtok(temp);\n        week(ii-startyear+1,1)=str2double(weeknum);\n        temp=char(stringdates1(last,1));\n        temp(1,5)=' ';\n        [~,weeknum]=strtok(temp);\n        week(ii-startyear+1,2)=str2double(weeknum);\n    end\n    % now create the vector of decimal data\n    decimaldates1=[];\n    % compute until penultimate year\n    for ii=1:numyear-1\n        for jj=week(ii,1):week(ii,2)\n            decimaldates1=[decimaldates1;(startyear+ii-1)+((jj-1)/week(ii,2))];\n        end\n    end\n    % compute for last year (assuming a year of 52 weeks if the number of weeks is shorter)\n    if week(numyear,2)<52\n        total=52;\n    else\n        total=week(numyear,2);\n    end\n    for jj=week(numyear,1):week(numyear,2)\n        decimaldates1=[decimaldates1;endyear+((jj-1)/total)];\n    end\n    % finally, trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\n    \n    % deal now with the data if it is daily\nelseif frequency==5\n    % first identify the first and last years of the sample\n    startyear=str2double(startdate(1,1:4));\n    endyear=str2double(enddate(1,1:4));\n    % calculate the total number of years over the period\n    numyear=endyear-startyear+1;\n    % create a vector of date strings for the sample period\n    start=find(strcmp(datestrings,startdate));\n    finish=find(strcmp(datestrings,enddate));\n    stringdates1=datestrings(start:finish,1);\n    % for each year in the sample, identify the earliest and latest day\n    for ii=startyear:endyear\n        % first identify which periods in the sample correspond to this year\n        periods=strfind(stringdates1,num2str(ii));\n        for jj=1:size(periods,1)\n            if isempty(periods{jj,1})\n                periods{jj,1}=0;\n            end\n        end\n        periods=cell2mat(periods);\n        % identify the position of the first day and the last day of this year\n        first=min(find(periods==1));\n        last=max(find(periods==1));\n        % indentify the day number to which these positions correspond\n        temp=char(stringdates1(first,1));\n        temp(1,5)=' ';\n        [~,daynum]=strtok(temp);\n        day(ii-startyear+1,1)=str2double(daynum);\n        temp=char(stringdates1(last,1));\n        temp(1,5)=' ';\n        [~,daynum]=strtok(temp);\n        day(ii-startyear+1,2)=str2double(daynum);\n    end\n    % now create the vector of decimal data\n    decimaldates1=[];\n    % compute until penultimate year\n    for ii=1:numyear-1\n        for jj=day(ii,1):day(ii,2)\n            decimaldates1=[decimaldates1;(startyear+ii-1)+((jj-1)/day(ii,2))];\n        end\n    end\n    % compute for last year (assuming a working year of 5 days a week, i.e. 261 opening days a year, if the total number of day is shorter)\n    if day(numyear,2)<261\n        total=261;\n    else\n        total=day(numyear,2);\n    end\n    for jj=day(numyear,1):day(numyear,2)\n        decimaldates1=[decimaldates1;endyear+((jj-1)/total)];\n    end\n    % finally, trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\n    \n    % finally, if the data is undated\nelseif frequency==6\n    % identify the number of periods covered by the sample\n    startperiod=str2double(startdate(1,1:end-1));\n    endperiod=str2double(enddate(1,1:end-1));\n    % create the decimal value vector\n    decimaldates1=(startperiod:endperiod)';\n    % convert into strings\n    stringdates1=cellfun(@num2str,num2cell(decimaldates1),'UniformOutput',0);\n    % add a 'u' character at the end\n    for ii=1:size(stringdates1,1)\n        stringdates1{ii,1}=[stringdates1{ii,1} 'u'];\n    end\n    % trim a number of initial periods equal to the number of lags, as these periods will be used to create initial conditions\n    decimaldates1=decimaldates1(lags+1:end,:);\n    stringdates1=stringdates1(lags+1:end,:);\nend\n\n\n\n\n\n\n% from now on, the code applies only if forecasts have been selected\n% if not, simply return empty matrices\n\nif F==0 && CF==0\n    decimaldates2=[];\n    stringdates2=[];\n    Fstartlocation=[];\n    Fendlocation=[];\n    stringdates3=[];\nelse\n    \n    \n    \n    \n    \n    % PHASE 2: CREATION OF DECIMAL DATES FOR THE FORECAST PERIOD (DECIMALDATES2)\n    \n    % determine first whether the final forecast period is included or not in the sample\n    % first deal with data if it is yearly\n    if frequency==1\n        % simply check wether the sample end year is anterior to the forecast end year\n        if str2double(enddate(1,1:end-1))<str2double(Fenddate(1,1:end-1))\n            included=0;\n        else\n            included=1;\n        end\n        % if data is quarterly\n    elseif frequency==2\n        % first identify the year and quarter of the final sample date\n        smplendyear=str2double(enddate(1,1:4));\n        smplendquarter=str2double(enddate(1,6));\n        % similarly, identify the year and quarter of the final forecast date\n        Fendyear=str2double(Fenddate(1,1:4));\n        Fendquarter=str2double(Fenddate(1,6));\n        if smplendyear<Fendyear\n            included=0;\n        elseif smplendyear==Fendyear && smplendquarter<Fendquarter\n            included=0;\n        else\n            included=1;\n        end\n        % if data is monthly\n    elseif frequency==3\n        % first identify the year and month of the final sample date\n        temp=enddate;\n        temp(1,5)=' ';\n        [smplendyear,smplendmonth]=strtok(temp);\n        smplendyear=str2double(smplendyear);\n        smplendmonth=str2double(smplendmonth);\n        % identify the year and month of the final forecast date\n        temp=Fenddate;\n        temp(1,5)=' ';\n        [Fendyear,Fendmonth]=strtok(temp);\n        Fendyear=str2double(Fendyear);\n        Fendmonth=str2double(Fendmonth);\n        if smplendyear<Fendyear\n            included=0;\n        elseif smplendyear==Fendyear && smplendmonth<Fendmonth\n            included=0;\n        else\n            included=1;\n        end\n        % if data is weekly\n    elseif frequency==4\n        % first identify the year and week of the final sample date\n        temp=enddate;\n        temp(1,5)=' ';\n        [smplendyear,smplendweek]=strtok(temp);\n        smplendyear=str2double(smplendyear);\n        smplendweek=str2double(smplendweek);\n        % identify the year and week of the final forecast date\n        temp=Fenddate;\n        temp(1,5)=' ';\n        [Fendyear,Fendweek]=strtok(temp);\n        Fendyear=str2double(Fendyear);\n        Fendweek=str2double(Fendweek);\n        if smplendyear<Fendyear\n            included=0;\n        elseif smplendyear==Fendyear && smplendweek<Fendweek\n            included=0;\n        else\n            included=1;\n        end\n        % if data is daily\n    elseif frequency==5\n        % first identify the year and day of the final sample date\n        temp=enddate;\n        temp(1,5)=' ';\n        [smplendyear,smplendday]=strtok(temp);\n        smplendyear=str2double(smplendyear);\n        smplendday=str2double(smplendday);\n        % identify the year and day of the final forecast date\n        temp=Fenddate;\n        temp(1,5)=' ';\n        [Fendyear,Fendday]=strtok(temp);\n        Fendyear=str2double(Fendyear);\n        Fendday=str2double(Fendday);\n        if smplendyear<Fendyear\n            included=0;\n        elseif smplendyear==Fendyear && smplendday<Fendday\n            included=0;\n        else\n            included=1;\n        end\n        % finally, if data is undated\n    elseif frequency==6\n        % simply check wether the sample end period is anterior to the forecast end period\n        if str2double(enddate(1,1:end-1))<str2double(Fenddate(1,1:end-1))\n            included=0;\n        else\n            included=1;\n        end\n    end\n    \n    \n    \n    \n    \n    % if the final forecast period is included in the sample, simply define decimaldates2 as decimaldates1\n    if included==1\n        decimaldates2=decimaldates1;\n        stringdates2=stringdates1;\n        \n        \n        % if the final forecast period lies beyond the end of the sample, define a new vector of decimal dates running from the sample start until the last forecast period\n    elseif included==0\n        % deal first with the data if it is yearly\n        if frequency==1\n            % simply complete decimaldates1 up to the final forecast period\n            decimaldates2=[decimaldates1;(decimaldates1(end,1)+1:str2double(Fenddate(1,1:end-1)))'];\n            stringdates2=cellfun(@num2str,num2cell(decimaldates2),'UniformOutput',0);\n            % add a 'y' character at the end\n            for ii=1:size(stringdates2,1)\n                stringdates2{ii,1}=[stringdates2{ii,1} 'y'];\n            end\n            \n            % if the data is quarterly\n        elseif frequency==2\n            % initiate the series\n            decimaldates2=decimaldates1;\n            stringdates2=stringdates1;\n            % identify the year and quarter of the last sample period\n            endyear=str2double(enddate(1,1:4));\n            endquarter=str2double(enddate(1,6));\n            % identify the year and quarter of the last forecast period\n            Fendyear=str2double(Fenddate(1,1:4));\n            Fendquarter=str2double(Fenddate(1,6));\n            % advance sample end by one period\n            year=endyear;\n            quarter=endquarter;\n            if quarter<4\n                quarter=quarter+1;\n            elseif quarter==4\n                year=year+1;\n                quarter=1;\n            end\n            while year<=Fendyear-1\n                while quarter<=4\n                    decimaldates2=[decimaldates2;year+(quarter-1)/4];\n                    temp=[num2str(year) 'q' num2str(quarter)];\n                    stringdates2{end+1,1}=temp;\n                    quarter=quarter+1;\n                end\n                quarter=1;\n                year=year+1;\n            end\n            % complete with final year\n            while quarter<=Fendquarter\n                decimaldates2=[decimaldates2;year+(quarter-1)/4];\n                temp=[num2str(year) 'q' num2str(quarter)];\n                stringdates2{end+1,1}=temp;\n                quarter=quarter+1;\n            end\n            \n            % if the data is monthly\n        elseif frequency==3\n            % initiate the series\n            decimaldates2=decimaldates1;\n            stringdates2=stringdates1;\n            % identify the year and month of the last sample period\n            temp=enddate;\n            temp(1,5)=' ';\n            [endyear,endmonth]=strtok(temp);\n            endyear=str2double(endyear);\n            endmonth=str2double(endmonth);\n            % identify the year and month of the last forecast period\n            temp=Fenddate;\n            temp(1,5)=' ';\n            [Fendyear,Fendmonth]=strtok(temp);\n            Fendyear=str2double(Fendyear);\n            Fendmonth=str2double(Fendmonth);\n            % advance sample end by one period\n            year=endyear;\n            month=endmonth;\n            if month<12\n                month=month+1;\n            elseif month==12\n                year=year+1;\n                month=1;\n            end\n            while year<=Fendyear-1\n                while month<=12\n                    decimaldates2=[decimaldates2;year+(month-1)/12];\n                    temp=[num2str(year) 'm' num2str(month)];\n                    stringdates2{end+1,1}=temp;\n                    month=month+1;\n                end\n                month=1;\n                year=year+1;\n            end\n            % complete with final year\n            while month<=Fendmonth\n                decimaldates2=[decimaldates2;year+(month-1)/12];\n                temp=[num2str(year) 'm' num2str(month)];\n                stringdates2{end+1,1}=temp;\n                month=month+1;\n            end\n            \n            % if the data is weekly\n        elseif frequency==4\n            % first identify the year and week of the final forecast date\n            temp=Fenddate;\n            temp(1,5)=' ';\n            [Fendyear,Fendweek]=strtok(temp);\n            Fendyear=str2double(Fendyear);\n            Fendweek=str2double(Fendweek);\n            % identify the year and week of the final data set date\n            temp=datestrings{end,1};\n            temp(1,5)=' ';\n            [dataendyear,dataendweek]=strtok(temp);\n            dataendyear=str2double(dataendyear);\n            dataendweek=str2double(dataendweek);\n            % now, there are two possibilities: either the forecast period is entirely included in the dataset, or it goes beyond the dataset\n            % if entirely included in the dataset\n            if Fendyear<dataendyear || (Fendyear==dataendyear && Fendweek<dataendweek)\n                % then just copy the date strings from sample start to forecast end\n                % find position for sample start\n                start=find(cellfun(@isempty,strfind(datestrings,startdate))==0);\n                % find position for forecast end\n                finish=find(cellfun(@isempty,strfind(datestrings,Fenddate))==0);\n                % create the strings\n                stringdates2=datestrings(start:finish,1);\n                % if the forecast periods goes beyond the data set\n            else\n                % find position for sample start\n                start=find(cellfun(@isempty,strfind(datestrings,startdate))==0);\n                % copy the dataset from sample start to its end\n                stringdates2=datestrings(start:end,1);\n                % advance the end of the dataset by one period\n                if dataendweek<52\n                    year=dataendyear;\n                    week=dataendweek+1;\n                else\n                    year=dataendyear+1;\n                    week=1;\n                end\n                % now complete stringdates2\n                for ii=dataendyear:Fendyear-1\n                    while week<=52\n                        stringdates2{end+1,1}=[num2str(year) 'w' num2str(week)];\n                        week=week+1;\n                    end\n                    week=1;\n                    year=year+1;\n                end\n                % complete for the final year\n                while week<=Fendweek\n                    stringdates2{end+1,1}=[num2str(year) 'w' num2str(week)];\n                    week=week+1;\n                end\n            end\n            % finally, trim a number of initial conditions equal to the number of lags\n            stringdates2=stringdates2(lags+1:end,1);\n            % now that the strings are obtained, use them to generate the decimal dates\n            % for each year in stringdates2, identify the number of weeks\n            maxweek=zeros(size(stringdates2,1),1);\n            for ii=str2double(startdate(1,1:4)):Fendyear-1\n                periods=strfind(stringdates2,num2str(ii));\n                for jj=1:size(periods,1)\n                    if isempty(periods{jj,1})\n                        periods{jj,1}=0;\n                    end\n                end\n                periods=cell2mat(periods);\n                location=max(find(periods==1));\n                temp=char(stringdates2(location,1));\n                temp(1,5)=' ';\n                [~,weeknum]=strtok(temp);\n                maxweek=maxweek+periods*str2double(weeknum);\n            end\n            % complete for the final year\n            periods=strfind(stringdates2,num2str(Fendyear));\n            for jj=1:size(periods,1)\n                if isempty(periods{jj,1})\n                    periods{jj,1}=0;\n                end\n            end\n            periods=cell2mat(periods);\n            maxweek=maxweek+periods*max(52,Fendweek);\n            % finally, compute the decimal dates\n            for ii=1:size(stringdates2,1)\n                temp=stringdates2{ii,1};\n                temp(1,5)=' ';\n                [~,weeknum]=strtok(temp);\n                decimaldates2(ii,1)=str2double(temp(1,1:4))+str2double(weeknum)/maxweek(ii,1);\n            end\n            \n            % if the data is daily\n        elseif frequency==5\n            % first identify the year and day of the final forecast date\n            temp=Fenddate;\n            temp(1,5)=' ';\n            [Fendyear,Fendday]=strtok(temp);\n            Fendyear=str2double(Fendyear);\n            Fendday=str2double(Fendday);\n            % identify the year and day of the final data set date\n            temp=datestrings{end,1};\n            temp(1,5)=' ';\n            [dataendyear,dataendday]=strtok(temp);\n            dataendyear=str2double(dataendyear);\n            dataendday=str2double(dataendday);\n            % now, there are two possibilities: either the forecast period is entirely included in the dataset, or it goes beyond the dataset\n            % if entirely included in the dataset\n            if Fendyear<dataendyear || (Fendyear==dataendyear && Fendday<dataendday)\n                % then just copy the date strings from sample start to forecast end\n                % find position for sample start\n                start=find(cellfun(@isempty,strfind(datestrings,startdate))==0);\n                % find position for forecast end\n                finish=find(cellfun(@isempty,strfind(datestrings,Fenddate))==0);\n                % create the strings\n                stringdates2=datestrings(start:finish,1);\n                % if the forecast periods goes beyond the data set\n            else\n                % find position for sample start\n                start=find(cellfun(@isempty,strfind(datestrings,startdate))==0);\n                % copy the dataset from sample start to its end\n                stringdates2=datestrings(start:end,1);\n                % advance the day of the dataset by one period\n                if dataendday<261\n                    year=dataendyear;\n                    day=dataendday+1;\n                else\n                    year=dataendyear+1;\n                    day=1;\n                end\n                % now complete stringdates2\n                for ii=dataendyear:Fendyear-1\n                    while day<=261\n                        stringdates2{end+1,1}=[num2str(year) 'd' num2str(day)];\n                        day=day+1;\n                    end\n                    day=1;\n                    year=year+1;\n                end\n                % complete for the final year\n                while day<=Fendday\n                    stringdates2{end+1,1}=[num2str(year) 'd' num2str(day)];\n                    day=day+1;\n                end\n            end\n            % finally, trim a number of initial conditions equal to the number of lags\n            stringdates2=stringdates2(lags+1:end,1);\n            % now that the strings are obtained, use them to generate the decimal dates\n            % for each year in stringdates2, identify the number of day\n            maxday=zeros(size(stringdates2,1),1);\n            for ii=str2double(startdate(1,1:4)):Fendyear-1\n                periods=strfind(stringdates2,num2str(ii));\n                for jj=1:size(periods,1)\n                    if isempty(periods{jj,1})\n                        periods{jj,1}=0;\n                    end\n                end\n                periods=cell2mat(periods);\n                location=max(find(periods==1));\n                temp=char(stringdates2(location,1));\n                temp(1,5)=' ';\n                [~,daynum]=strtok(temp);\n                maxday=maxday+periods*str2double(daynum);\n            end\n            % complete for the final year\n            periods=strfind(stringdates2,num2str(Fendyear));\n            for jj=1:size(periods,1)\n                if isempty(periods{jj,1})\n                    periods{jj,1}=0;\n                end\n            end\n            periods=cell2mat(periods);\n            maxday=maxday+periods*max(261,Fendday);\n            % finally, compute the decimal dates\n            for ii=1:size(stringdates2,1)\n                temp=stringdates2{ii,1};\n                temp(1,5)=' ';\n                [~,daynum]=strtok(temp);\n                decimaldates2(ii,1)=str2double(temp(1,1:4))+str2double(daynum)/maxday(ii,1);\n            end\n            \n            % finally, if the data is undated\n        elseif frequency==6\n            % simply complete decimaldates1 up to the final forecast period\n            decimaldates2=[decimaldates1;(decimaldates1(end,1)+1:str2double(Fenddate(1,1:end-1)))'];\n            stringdates2=cellfun(@num2str,num2cell(decimaldates2),'UniformOutput',0);\n            % add a 'u' character at the end\n            for ii=1:size(stringdates2,1)\n                stringdates2{ii,1}=[stringdates2{ii,1} 'u'];\n            end\n        end\n    end\n    \n    \n    \n    \n    \n    \n    \n    % PHASE 3: IDENTIFICATION OF THE POSITION OF THE INITIAL FORECAST PERIOD (IN TERMS OF THE VECTOR DECIMALDATES2)\n    \n    % identify the position of the start period for the forecasts\n    % if the start period has been selected as the first period after the sample end, identifies it directly\n    if Fendsmpl==1\n        Fstartlocation=size(stringdates1,1)+1;\n        % if the start period has not been selected as the first period after the sample end, it must be within the sample: look for it\n    elseif Fendsmpl==0\n        Fstartlocation=find(strcmp(stringdates1,Fstartdate));\n    end\n    \n    % identify the position of the end period for the forecasts\n    % if the end period is included in the sample, it can be identified directly\n    if included==1\n        Fendlocation=find(strcmp(stringdates1,Fenddate));\n        % if the end period is beyond the sample, then its position is simply the last period of datestrings2\n    elseif included==0\n        Fendlocation=size(stringdates2,1);\n    end\n    \n    \n    \n    \n    \n    % PHASE 3: CREATION OF DATE STRINGS FOR THE COMMON PERIOD\n    \n    \n    % these date strings will be used only at one point: for the display of forecast evaluation\n    % to identify the strings, simply copy from datestrings2 the dates over the common forecast period\n    startfcperiod=find(strcmp(stringdates2,Fstartdate));\n    endfcperiod=find(strcmp(stringdates2,Fcenddate));\n    stringdates3=stringdates2(startfcperiod:endfcperiod,1);\n    \n    \n    \n    \n    \nend\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/gendates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2154772122374626}}
{"text": "\nfunction d2img = draw_2Dskeleton_ICVL(tline, coord_pixel)\n \n    db_path = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Testing/Depth/';\n    jointNum =  16;\n     cubicSz = 200;\n    imgWidth = 320;\n    imgHeight = 240;\n    \n    coord_pixel = squeeze(coord_pixel);\n    rgb_img = zeros(imgHeight,imgWidth,3);\n    refDepths = zeros(1,jointNum);\n    line_width = 4;\n   \n    splitted = strsplit(tline);\n    img_name = splitted{1};\n    bin_name = strcat(db_path,img_name(1:size(img_name,2)-3),'bin');\n   \n    for jid = 1:jointNum\n        refDepths(1,jid) = str2num(splitted{(jid-1)*3+4});\n    end\n    refDepth = (min(refDepths(:)) + max(refDepths(:)))/2;\n    \n    fp_bin = fopen(bin_name,'r');\n    img = fread(fp_bin,[imgWidth imgHeight],'float');\n    img = permute(img,[2,1]);\n    img(img==0) = refDepth+cubicSz/2;\n    fclose(fp_bin);\n    \n    img(img>refDepth+cubicSz/2) = refDepth + cubicSz/2;\n    img(img<refDepth-cubicSz/2) = refDepth - cubicSz/2;\n    img = img - refDepth;\n    img = img/(cubicSz/2);\n    \n    img = img + 1;\n    img = img/2;\n\n    rgb_img(:,:,1) = img*255/255;\n    rgb_img(:,:,2) = img*240/255;\n    rgb_img(:,:,3) = img*204/255;\n    \n    f = figure;\n    set(f, 'visible', 'off');\n    imshow(rgb_img);\n    hold on;\n    \n    plot([coord_pixel(1,1),coord_pixel(1,2)],[coord_pixel(2,1),coord_pixel(2,2)],'Color',[255/255,153/255,153/255],'LineWidth',line_width); %wrist to thumb root\n    plot([coord_pixel(1,2),coord_pixel(1,3)],[coord_pixel(2,2),coord_pixel(2,3)],'Color',[255/255,102/255,102/255],'LineWidth',line_width) %thumb root to thumb mid\n    plot([coord_pixel(1,3),coord_pixel(1,4)],[coord_pixel(2,3),coord_pixel(2,4)],'Color',[255/255,51/255,51/255],'LineWidth',line_width) %thumb mid to thumb tip\n\n    plot([coord_pixel(1,1),coord_pixel(1,5)],[coord_pixel(2,1),coord_pixel(2,5)],'Color',[153/255,255/255,153/255],'LineWidth',line_width) %wrist to index root\n    plot([coord_pixel(1,5),coord_pixel(1,6)],[coord_pixel(2,5),coord_pixel(2,6)],'Color',[102/255,255/255,102/255],'LineWidth',line_width) %index root to index mid\n    plot([coord_pixel(1,6),coord_pixel(1,7)],[coord_pixel(2,6),coord_pixel(2,7)],'Color',[51/255,255/255,51/255],'LineWidth',line_width) %index mid to index tip\n\n    plot([coord_pixel(1,1),coord_pixel(1,8)],[coord_pixel(2,1),coord_pixel(2,8)],'Color',[255/255,204/255,153/255],'LineWidth',line_width) %wrist to middle root\n    plot([coord_pixel(1,8),coord_pixel(1,9)],[coord_pixel(2,8),coord_pixel(2,9)],'Color',[255/255,178/255,102/255],'LineWidth',line_width) %middle root to middle mid\n    plot([coord_pixel(1,9),coord_pixel(1,10)],[coord_pixel(2,9),coord_pixel(2,10)],'Color',[255/255,153/255,51/255],'LineWidth',line_width) %middle mid to middle tip\n\n    plot([coord_pixel(1,1),coord_pixel(1,11)],[coord_pixel(2,1),coord_pixel(2,11)],'Color',[153/255,204/255,255/255],'LineWidth',line_width) %wrist to ring root\n    plot([coord_pixel(1,11),coord_pixel(1,12)],[coord_pixel(2,11),coord_pixel(2,12)],'Color',[102/255,178/255,255/255],'LineWidth',line_width) %ring root to ring mid\n    plot([coord_pixel(1,12),coord_pixel(1,13)],[coord_pixel(2,12),coord_pixel(2,13)],'Color',[51/255,153/255,255/255],'LineWidth',line_width) %ring mid to ring tip\n\n    plot([coord_pixel(1,1),coord_pixel(1,14)],[coord_pixel(2,1),coord_pixel(2,14)],'Color',[255/255,153/255,255/255],'LineWidth',line_width) %wrist to pinky root\n    plot([coord_pixel(1,14),coord_pixel(1,15)],[coord_pixel(2,14),coord_pixel(2,15)],'Color',[255/255,102/255,255/255],'LineWidth',line_width) %pinky root to pinky mid\n    plot([coord_pixel(1,15),coord_pixel(1,16)],[coord_pixel(2,15),coord_pixel(2,16)],'Color',[255/255,51/255,255/255],'LineWidth',line_width) %pinky mid to pinky tip\n\n    colorList = [\n    230/255 230/255 0/255;\n        \n    255/255,153/255,153/255;\n    255/255 102/255 102/255;\n    255/255 51/255 51/255;\n    \n    153/255,255/255,153/255;\n    102/255,255/255,102/255;\n    51/255,255/255,51/255;\n    \n    255/255,204/255,153/255;\n    255/255 178/255 102/255;\n    255/255 153/255 51/255;\n    \n    153/255,204/255,255/255;\n    102/255 178/255 255/255;\n    51/255 153/255 255/255;\n    \n    255/255,153/255,255/255;\n    255/255,102/255,255/255;\n    255/255,51/255,255/255];\n    scatter(coord_pixel(1,:),coord_pixel(2,:),100,colorList,'filled');\n    \n    set(gca,'Units','normalized','Position',[0 0 1 1]);  %# Modify axes size\n    set(gcf,'Units','pixels','Position',[200 200 2*imgWidth 2*imgHeight]);  %# Modify figure size\n\n    frame = getframe(gcf);\n    framedata = frame.cdata;\n    \n    xmin = min(coord_pixel(1,:));\n    xmax = max(coord_pixel(1,:));\n    ymin = min(coord_pixel(2,:));\n    ymax = max(coord_pixel(2,:));\n\n    len = max(xmax-xmin+1,ymax-ymin+1) + 70;\n    xcenter = (xmin + xmax)/2;\n    ycenter = (ymin + ymax)/2;\n    \n    xmin = max(round(xcenter - len/2),1);\n    xmax = min(round(xmin + len),imgWidth);\n    ymin = max(round(ycenter - len/2),1);\n    ymax = min(round(ymin + len),imgHeight);\n    framedata = framedata(2*ymin:2*ymax,2*xmin:2*xmax,:);\n\n    hold off;\n    close(f); \n\n    d2img = framedata;\nend\n", "meta": {"author": "mks0601", "repo": "V2V-PoseNet_RELEASE", "sha": "8b436182161337bba3adb1690e0bc834ef72e9f2", "save_path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE", "path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE/V2V-PoseNet_RELEASE-8b436182161337bba3adb1690e0bc834ef72e9f2/vis/icvl/draw_2Dskeleton_ICVL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.2152131676584609}}
{"text": "function [ output_meta ] = meta2sicd_rs_xml( xml_domnode, beta_domnode, noise_domnode )\n%META2SICD_RS_XML Converts Radarsat product.xml description into a SICD-style metadata structure\n%\n% Takes as input a Document Object Model (DOM) node from the RS2\n% product.xml descriptor file.\n%\n% This function does NOT handle ScanSAR datasets.\n%\n% There is an outstanding question with regard to the meaning of the\n% pulseRepetitionFrequency as provided.  See comments in Timeline section\n% below.\n%\n% Written by: Wade Schwartzkopf, NGA/Research\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n%% Setup\nSECONDS_IN_A_DAY = 24*60*60;\nxp=javax.xml.xpath.XPathFactory.newInstance.newXPath();\n\n%% CollectionInfo\noutput_meta.CollectionInfo.CollectorName=char(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','satellite'}),xml_domnode));\nif strcmpi(output_meta.CollectionInfo.CollectorName, 'RADARSAT-2')\n    gen = 'RS2';\nelseif strncmpi(output_meta.CollectionInfo.CollectorName, 'RCM', 3)\n    gen = 'RCM';\nend\n[rawDataStartTime, rawDataStartTimeFrac] = datenum_w_frac(char(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','rawDataStartTime'}),...\n    xml_domnode)));\nif strcmp(gen,'RS2')\n    output_meta.CollectionInfo.CoreName = [... % Start with NGA-like prefix\n        upper(datestr(rawDataStartTime,'ddmmmyy')) 'RS02' ...\n        char(xp.evaluate(xpath_str({'product','sourceAttributes','imageId'}),xml_domnode))];\nelseif strcmp(gen, 'RCM')\n    output_meta.CollectionInfo.CoreName = [... % Start with NGA-like prefix\n        upper(datestr(rawDataStartTime,'ddmmmyy')) ...\n        'RCM' output_meta.CollectionInfo.CollectorName(end) ...\n        datestr(rawDataStartTime,'HHMMSS')]; % Make time of day unique identier within day\n    % ScanSAR might need multiple CoreNames, one for each burst?\nend\noutput_meta.CollectionInfo.CollectType='MONOSTATIC';\noutput_meta.CollectionInfo.RadarMode.ModeID=char(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','beamModeMnemonic'}),xml_domnode));\nbeamMode = char(xp.evaluate(xpath_str({...\n    'product','sourceAttributes','beamMode'}),xml_domnode));\nacqType = char(xp.evaluate(xpath_str({...\n    'product','sourceAttributes','radarParameters','acquisitionType'}),xml_domnode));\nif ((~isempty(beamMode) && strncmpi(beamMode, 'SPOTLIGHT', 9)) || ...\n   (~isempty(acqType) && strncmpi(acqType, 'SPOTLIGHT', 9)) || ...\n   ~isempty(strfind(output_meta.CollectionInfo.RadarMode.ModeID,'SL')))\n    output_meta.CollectionInfo.RadarMode.ModeType = 'SPOTLIGHT';\nelseif strcmpi(output_meta.CollectionInfo.RadarMode.ModeID(1:2), 'SC')\n    error('META2SICD_RS_XML:RS_SCANSAR', 'ScanSAR mode data is not currently handled.');\nelse % Finally assume it's stripmap\n    output_meta.CollectionInfo.RadarMode.ModeType = 'STRIPMAP';\nend\nif strcmp(gen, 'RS2') % All RS2 data is unclassified\n    output_meta.CollectionInfo.Classification='UNCLASSIFIED';\nelseif strcmp(gen, 'RCM') % RCM has this as a specific field\n    output_meta.CollectionInfo.Classification=upper(char(xp.evaluate(...\n        xpath_str({'product', 'securityAttributes', 'securityClassification'}), xml_domnode)));\nend\n\n%% ImageCreation\noutput_meta.ImageCreation.Application=char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','generalProcessingInformation','softwareVersion'}),...\n    xml_domnode));\noutput_meta.ImageCreation.DateTime=datenum(char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','generalProcessingInformation','processingTime'}),...\n    xml_domnode)),'yyyy-mm-ddTHH:MM:SS.FFF');\noutput_meta.ImageCreation.Site=char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','generalProcessingInformation','processingFacility'}),...\n    xml_domnode));\noutput_meta.ImageCreation.Profile='Prototype';\n\n%% ImageData\nif strcmp(gen, 'RS2')\n    output_meta.ImageData.NumRows=uint32(str2double(xp.evaluate(...\n       xpath_str({'product','imageAttributes','rasterAttributes','numberOfSamplesPerLine'}),...\n       xml_domnode)));\n    output_meta.ImageData.NumCols=uint32(str2double(xp.evaluate(...\n       xpath_str({'product','imageAttributes','rasterAttributes','numberOfLines'}),...\n        xml_domnode)));\nelseif strcmp(gen, 'RCM')\n    output_meta.ImageData.NumRows=uint32(str2double(xp.evaluate(...\n       xpath_str({'product','sceneAttributes','imageAttributes','samplesPerLine'}),...\n       xml_domnode)));\n    output_meta.ImageData.NumCols=uint32(str2double(xp.evaluate(...\n       xpath_str({'product','sceneAttributes','imageAttributes','numLines'}),...\n        xml_domnode)));\nend\noutput_meta.ImageData.FullImage=output_meta.ImageData;\noutput_meta.ImageData.FirstRow=uint32(0); output_meta.ImageData.FirstCol=uint32(0);\noutput_meta.ImageData.PixelType='RE16I_IM16I';  % RS2 always 16-bit\nif strcmp(gen, 'RCM') && str2double(xp.evaluate(...  % RCM can be 16 or 32\n       xpath_str({'product','imageReferenceAttributes','rasterAttributes','bitsPerSample'}),...\n        xml_domnode)) == 32\n    output_meta.ImageData.PixelType='RE32F_IM32F';\nend\n% Seems that all pixels are always valid\noutput_meta.ImageData.ValidData.Vertex(1).Row = uint32(0);\noutput_meta.ImageData.ValidData.Vertex(1).Col = uint32(0);\noutput_meta.ImageData.ValidData.Vertex(2).Row = uint32(0);\noutput_meta.ImageData.ValidData.Vertex(2).Col = output_meta.ImageData.NumCols-1;\noutput_meta.ImageData.ValidData.Vertex(3).Row = output_meta.ImageData.NumRows-1;\noutput_meta.ImageData.ValidData.Vertex(3).Col = output_meta.ImageData.NumCols-1;\noutput_meta.ImageData.ValidData.Vertex(4).Row = output_meta.ImageData.NumRows-1;\noutput_meta.ImageData.ValidData.Vertex(4).Col = uint32(0);\n\n%% SCP\nif strcmp(gen, 'RS2')\n    im_at_str = 'imageAttributes';\nelseif strcmp(gen, 'RCM')\n    im_at_str = 'imageReferenceAttributes';\nend\n% There are many different equally valid options for picking the SCP point.\n% One way is to chose the tie point that is closest to the image center.\nnum_tie_points=str2double(xp.evaluate(...\n    ['count(' xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'}) ')'],...\n    xml_domnode));\ntiePointPixels = zeros(2,num_tie_points);\ntiePointGeo    = zeros(3,num_tie_points);\nfor i=1:num_tie_points\n    tiePointPixels(1,i) = str2double(xp.evaluate(...\n            [xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'})...\n            '[' num2str(i) ']' xpath_str({'imageCoordinate','pixel'})],...\n            xml_domnode));\n    tiePointPixels(2,i) = str2double(xp.evaluate(...\n            [xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'})...\n            '[' num2str(i) ']' xpath_str({'imageCoordinate','line'})],...\n            xml_domnode));\n    tiePointGeo(1,i) = str2double(xp.evaluate(...\n            [xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'})...\n            '[' num2str(i) ']' xpath_str({'geodeticCoordinate','latitude'})],...\n            xml_domnode));\n    tiePointGeo(2,i) = str2double(xp.evaluate(...\n            [xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'})...\n            '[' num2str(i) ']' xpath_str({'geodeticCoordinate','longitude'})],...\n            xml_domnode));\n    tiePointGeo(3,i) = str2double(xp.evaluate(...\n            [xpath_str({'product',im_at_str,'geographicInformation','geolocationGrid','imageTiePoint'})...\n            '[' num2str(i) ']' xpath_str({'geodeticCoordinate','height'})],...\n            xml_domnode));\nend\n% Pick tie point closest to center for SCP\ncenterPoint = [double(output_meta.ImageData.NumRows-1)/2.0; ...\n               double(output_meta.ImageData.NumCols-1)/2.0];\nD = (tiePointPixels - repmat(centerPoint,1,num_tie_points));\n[C,scp_index] = min( sqrt( sum(D.^2) ) );\noutput_meta.ImageData.SCPPixel.Row = uint32(tiePointPixels(1,scp_index));\noutput_meta.ImageData.SCPPixel.Col = uint32(tiePointPixels(2,scp_index));\n\n% Sometimes lines up with SCP in Lockheed SICDs (and sometimes not):\n% output_meta.ImageData.SCPPixel.Col = ceil(output_meta.ImageData.NumCols/2)-1;\n% output_meta.ImageData.SCPPixel.Row = floor(output_meta.ImageData.NumRows/2);\n\n%% GeoData\n% All RS2 and RCM data we know use the WGS84 model, although it is stated\n% in slightly different XML fields in the RS2 and RCM product.xml\noutput_meta.GeoData.EarthModel='WGS_84';\n% Initially, we just seed this with a rough value.  Later we will put in\n% something more precise.\noutput_meta.GeoData.SCP.LLH.Lat = tiePointGeo(1,scp_index);\noutput_meta.GeoData.SCP.LLH.Lon = tiePointGeo(2,scp_index);\noutput_meta.GeoData.SCP.LLH.HAE = tiePointGeo(3,scp_index);\npos_ecf = geodetic_to_ecf(tiePointGeo(:,scp_index));\noutput_meta.GeoData.SCP.ECF.X = pos_ecf(1);\noutput_meta.GeoData.SCP.ECF.Y = pos_ecf(2);\noutput_meta.GeoData.SCP.ECF.Z = pos_ecf(3);\n% Corner coordinates will be computed later by derived_sicd_fields.\n% Corners\n% min_row=min(tiePointPixels(1,:));\n% min_col=min(tiePointPixels(2,:));\n% max_row=max(tiePointPixels(1,:));\n% max_col=max(tiePointPixels(2,:));\n% ll_index=find((tiePointPixels(1,:)==min_row)&(tiePointPixels(2,:)==min_col), 1);\n% ul_index=find((tiePointPixels(1,:)==max_row)&(tiePointPixels(2,:)==min_col), 1);\n% ur_index=find((tiePointPixels(1,:)==max_row)&(tiePointPixels(2,:)==max_col), 1);\n% lr_index=find((tiePointPixels(1,:)==min_row)&(tiePointPixels(2,:)==max_col), 1);\n% output_meta.GeoData.ImageCorners.ICP.FRFC.Lat=tiePointGeo(1,ul_index);\n% output_meta.GeoData.ImageCorners.ICP.FRFC.Lon=tiePointGeo(2,ul_index);\n% output_meta.GeoData.ImageCorners.ICP.FRLC.Lat=tiePointGeo(1,ur_index);\n% output_meta.GeoData.ImageCorners.ICP.FRLC.Lon=tiePointGeo(2,ur_index);\n% output_meta.GeoData.ImageCorners.ICP.LRLC.Lat=tiePointGeo(1,lr_index);\n% output_meta.GeoData.ImageCorners.ICP.LRLC.Lon=tiePointGeo(2,lr_index);\n% output_meta.GeoData.ImageCorners.ICP.LRFC.Lat=tiePointGeo(1,ll_index);\n% output_meta.GeoData.ImageCorners.ICP.LRFC.Lon=tiePointGeo(2,ll_index);\n\n%% State vectors\nnum_state_vectors=str2double(xp.evaluate(...\n    ['count(' xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'}) ')'],...\n    xml_domnode));\nstate_vector_T  = zeros(1,num_state_vectors);\nstate_vector_T_frac  = zeros(1,num_state_vectors);\nstate_vector_X  = zeros(1,num_state_vectors);\nstate_vector_Y  = zeros(1,num_state_vectors);\nstate_vector_Z  = zeros(1,num_state_vectors);\n% state_vector_VX = zeros(1,num_state_vectors);\n% state_vector_VY = zeros(1,num_state_vectors);\n% state_vector_VZ = zeros(1,num_state_vectors);\nfor i=1:num_state_vectors\n    timeStamp = char(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n        '[' num2str(i) ']' xpath_str({'timeStamp'})],...\n        xml_domnode));\n    [state_vector_T(i), state_vector_T_frac(i)] = datenum_w_frac(timeStamp);\n    \n    state_vector_X(i) = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n        '[' num2str(i) ']' xpath_str({'xPosition'})],...\n        xml_domnode));\n    state_vector_Y(i) = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n        '[' num2str(i) ']' xpath_str({'yPosition'})],...\n        xml_domnode));\n    state_vector_Z(i) = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n        '[' num2str(i) ']' xpath_str({'zPosition'})],...\n        xml_domnode));\n%     state_vector_VX(i) = str2double(xp.evaluate(...\n%         [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n%         '[' num2str(i) ']' xpath_str({'xVelocity'})],...\n%         xml_domnode));\n%     state_vector_VY(i) = str2double(xp.evaluate(...\n%         [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n%         '[' num2str(i) ']' xpath_str({'yVelocity'})],...\n%         xml_domnode));\n%     state_vector_VZ(i) = str2double(xp.evaluate(...\n%         [xpath_str({'product','sourceAttributes','orbitAndAttitude','orbitInformation','stateVector'})...\n%         '[' num2str(i) ']' xpath_str({'zVelocity'})],...\n%         xml_domnode));\nend\nstate_vector_T = round((state_vector_T-rawDataStartTime)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n        (state_vector_T_frac-rawDataStartTimeFrac); % Handle fractional seconds\n% sv2poly.m shows ways to determine best polynomial order, but 5th is almost always best\npolyorder = min(5, numel(state_vector_T) - 1);\nP_x = polyfit(state_vector_T, state_vector_X, polyorder);\nP_y = polyfit(state_vector_T, state_vector_Y, polyorder);\nP_z = polyfit(state_vector_T, state_vector_Z, polyorder);\noutput_meta.Position.ARPPoly.X = P_x(end:-1:1).';\noutput_meta.Position.ARPPoly.Y = P_y(end:-1:1).';\noutput_meta.Position.ARPPoly.Z = P_z(end:-1:1).';\n\n%% Grid\nif strcmp(char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','generalProcessingInformation','productType'}),...\n    xml_domnode)),'SLC')\n    output_meta.Grid.ImagePlane = 'SLANT';\n    output_meta.Grid.Type = 'RGZERO';\nelse\n    output_meta.Grid.ImagePlane = 'GROUND';\nend\noutput_meta.Grid.Row.SS = str2double(xp.evaluate(...\n    xpath_str({'product',im_at_str,'rasterAttributes','sampledPixelSpacing'}),...\n    xml_domnode));\n% Col.SS is derived after DRateSFPoly below, rather than used from this\n% given field, so that SICD metadata can be internally consistent.\n% output_meta.Grid.Col.SS = str2double(xp.evaluate(...\n%     xpath_str({'product',im_at_str,'rasterAttributes','sampledLineSpacing'}),...\n%     xml_domnode));\noutput_meta.Grid.Row.Sgn = -1; % Always true for RS2\noutput_meta.Grid.Col.Sgn = -1; % Always true for RS2\nfc = str2double(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','radarParameters','radarCenterFrequency'}),...\n    xml_domnode)); % Center frequency\noutput_meta.Grid.Row.ImpRespBW = 2*str2double(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','totalProcessedRangeBandwidth'}),...\n    xml_domnode))/SPEED_OF_LIGHT;\ndop_bw = str2double(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','totalProcessedAzimuthBandwidth'}),...\n    xml_domnode)); % Doppler bandwidth\n[zd_last, zd_last_frac] = datenum_w_frac(char(xp.evaluate(... \n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','zeroDopplerTimeLastLine'}),...\n    xml_domnode)));\n[zd_first, zd_first_frac] = datenum_w_frac(char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','zeroDopplerTimeFirstLine'}),...\n    xml_domnode)));\nss_zd_s = abs(round((zd_last-zd_first)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n        (zd_last_frac-zd_first_frac))/... % Handle fractional seconds\n        double(output_meta.ImageData.NumCols-1); % Image column spacing in zero doppler time (seconds)\noutput_meta.Grid.Row.KCtr = 2*fc/SPEED_OF_LIGHT;\noutput_meta.Grid.Col.KCtr = 0;\noutput_meta.Grid.Row.DeltaK1 = -output_meta.Grid.Row.ImpRespBW/2;\noutput_meta.Grid.Row.DeltaK2 = -output_meta.Grid.Row.DeltaK1;\noutput_meta.Grid.Row.DeltaKCOAPoly = 0;\n% Constants used to compute weighting parameters\nNUM_SAMPLES = 512;\nOVERSAMPLE = 1024;\noutput_meta.Grid.Row.WgtType.WindowName = upper(char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','rangeWindow','windowName'}),...\n    xml_domnode)));\nif strcmpi(output_meta.Grid.Row.WgtType.WindowName,'KAISER') % The usual RS2 weigting\n    output_meta.Grid.Row.WgtType.Parameter.name = 'BETA';\n    output_meta.Grid.Row.WgtType.Parameter.value = char(xp.evaluate(...\n        xpath_str({'product','imageGenerationParameters','sarProcessingInformation','rangeWindow','windowCoefficient'}),...\n        xml_domnode));\n    beta_row = str2double(output_meta.Grid.Row.WgtType.Parameter.value);\n    % We don't use the Mathworks Kaiser function, so we won't be dependent on the Signal Processing Toolbox\n    output_meta.Grid.Row.WgtFunct = kaiser_nosptb(NUM_SAMPLES,beta_row);\n    imp_resp = abs(fft(output_meta.Grid.Row.WgtFunct, round(NUM_SAMPLES*OVERSAMPLE))); % Oversampled response function\n    imp_resp = imp_resp/sum(output_meta.Grid.Row.WgtFunct); % Normalize to unit peak\n    ind = find(imp_resp<1/sqrt(2),1,'first')+[-1 -0]; % Samples surrounding half-power point\n    ind = interp1(imp_resp(ind), ind, 1/sqrt(2)); % Linear interpolation to solve for half-power point\n    row_broadening_factor = 2*(ind - 1)/OVERSAMPLE;\n    output_meta.Grid.Row.ImpRespWid = row_broadening_factor/output_meta.Grid.Row.ImpRespBW;\nend\noutput_meta.Grid.Col.WgtType.WindowName = upper(char(xp.evaluate(...\n    xpath_str({'product','imageGenerationParameters','sarProcessingInformation','azimuthWindow','windowName'}),...\n    xml_domnode)));\n\n%% Radar Collection\n% Ultrafine and spotlight modes have \"lower\" and \"upper\" parts to the\n% pulse.\n% output_meta.RadarCollection.RefFreqIndex=uint32(0); % Absence of this field means all frequencies are true values\nnum_pulse_parts = str2double(xp.evaluate(...\n    ['count(' xpath_str({'product','sourceAttributes','radarParameters','pulseLength'}) ')'],...\n    xml_domnode));\nfor i=1:num_pulse_parts\n    output_meta.RadarCollection.Waveform.WFParameters(i).TxRFBandwidth = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','radarParameters','pulseBandwidth'}) '[' num2str(i) ']'],...\n        xml_domnode)); % Bandwidth\n    output_meta.RadarCollection.Waveform.WFParameters(i).TxPulseLength = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','radarParameters','pulseLength'}) '[' num2str(i) ']'],...\n        xml_domnode));\n    output_meta.RadarCollection.Waveform.WFParameters(i).RcvDemodType='CHIRP';\n    sample_rate = str2double(xp.evaluate(...\n        [xpath_str({'product','sourceAttributes','radarParameters','adcSamplingRate'}) '[' num2str(i) ']'],...\n        xml_domnode));\n    output_meta.RadarCollection.Waveform.WFParameters(i).RcvWindowLength = str2double(xp.evaluate(...\n        xpath_str({'product','sourceAttributes','radarParameters','samplesPerEchoLine'}),...\n        xml_domnode))/sample_rate;\n    output_meta.RadarCollection.Waveform.WFParameters(i).ADCSampleRate = sample_rate;\n    output_meta.RadarCollection.Waveform.WFParameters(i).RcvFMRate = 0; % True for RcvDemodType='CHIRP'\nend\nbw = sum([output_meta.RadarCollection.Waveform.WFParameters.TxRFBandwidth]);\noutput_meta.RadarCollection.TxFrequency.Min = fc-(bw/2); % fc calculated in Grid section\noutput_meta.RadarCollection.TxFrequency.Max = fc+(bw/2);\n% Assumes pulse parts are exactly adjacent in bandwidth\noutput_meta.RadarCollection.Waveform.WFParameters(1).TxFreqStart = ...\n    output_meta.RadarCollection.TxFrequency.Min;\nfor i=2:num_pulse_parts\n    output_meta.RadarCollection.Waveform.WFParameters(i).TxFreqStart = ...\n        output_meta.RadarCollection.Waveform.WFParameters(i-1).TxFreqStart + ...\n        output_meta.RadarCollection.Waveform.WFParameters(i-1).TxRFBandwidth;\nend\n% Polarization\npols = textscan(char(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','radarParameters','polarizations'}),...\n    xml_domnode)),'%s');\npols = pols{1};\nM = struct('H','H','V','V','C','RHC');\ntx_pols = unique(cellfun(@(x) x(1), pols));\nfor i=1:numel(pols)\n    output_meta.RadarCollection.RcvChannels.ChanParameters(i).TxRcvPolarization = ...\n        [M.(pols{i}(1)) ':' M.(pols{i}(2))];\nend\nif isscalar(tx_pols) % Only one transmit polarization\n    output_meta.RadarCollection.TxPolarization = M.(tx_pols);\nelse % Multiple transmit polarizations\n    output_meta.RadarCollection.TxPolarization = 'SEQUENCE';\n    for i = 1:numel(tx_pols)\n        output_meta.RadarCollection.TxSequence.TxStep(i).TxPolarization = M.(tx_pols(i));\n    end\nend\n% Another way to get polarimetric channels:\n% num_pol_bands = str2double(xp.evaluate(...\n%     ['count(' xpath_str({'product','imageAttributes','fullResolutionImageData'}) ')'],...\n%     xml_domnode));\n% for i=1:num_pol_bands\n%     pol = char(xp.evaluate(...\n%         [xpath_str({'product','imageAttributes','fullResolutionImageData'}) '[' num2str(i) ']/@pole'],...\n%         xml_domnode));\n% end\n\n%% Timeline\noutput_meta.Timeline.CollectStart = rawDataStartTime + (rawDataStartTimeFrac/SECONDS_IN_A_DAY);\nif strcmp(gen, 'RS2')\n    prf_xp_str = {'pulseRepetitionFrequency'};\nelseif strcmp(gen, 'RCM')\n    prf_xp_str = {'prfInformation', 'pulseRepetitionFrequency'};\nend\nprf = str2double(xp.evaluate(...\n    xpath_str([{'product','sourceAttributes', 'radarParameters'} prf_xp_str]),...\n    xml_domnode));\nnum_lines_entries = str2double(xp.evaluate(...\n    ['count(' xpath_str({'product','imageGenerationParameters','sarProcessingInformation','numberOfLinesProcessed'}) ')'],...\n    xml_domnode));\nnum_lines_processed = zeros(num_lines_entries,1);\nfor i = 1:num_lines_entries\n    num_lines_processed(i) = str2double(xp.evaluate(...\n        [xpath_str({'product','imageGenerationParameters','sarProcessingInformation','numberOfLinesProcessed'}) '[@pole=\"' pols{i} '\"]'],...\n        xml_domnode));\nend\nnum_lines_processed = num_lines_processed(1) * numel(tx_pols);\nif num_lines_entries ~= numel(pols) || ~all(num_lines_processed == num_lines_processed(1))\n    % This should never happen, but we'll throw an error if it does.\n    warning('META2SICD_RS_XML:UnableToComputeCollectDuration', 'Unhandled data condition.');\nend\nprf = prf * num_pulse_parts;\nif num_pulse_parts==2 && ...\n        strcmp(output_meta.CollectionInfo.RadarMode.ModeType,'STRIPMAP')\n    % Why????\n    % This seems to be necessary to make CollectDuration match CA ranges\n    % and to make 1/prf roughly equal to ss_zd_s (which is generally true\n    % for STRIPMAP).  But we already doubled the prf above to account for\n    % the pulse parts (to make real vs effective prf), so why do we have to\n    % do it again? And why don't we have to do it for SPOTLIGHT?\n    prf = 2*prf;\nend\noutput_meta.Timeline.CollectDuration = num_lines_processed/prf;\noutput_meta.Timeline.IPP.Set.TStart = 0;\noutput_meta.Timeline.IPP.Set.TEnd = 0; % Apply real value later.  Just a placeholder.\noutput_meta.Timeline.IPP.Set.IPPStart = uint32(0);\noutput_meta.Timeline.IPP.Set.IPPEnd = uint32(num_lines_processed);\noutput_meta.Timeline.IPP.Set.IPPPoly = [0; prf];\noutput_meta.Timeline.IPP.Set.TEnd = output_meta.Timeline.CollectDuration;\n\n%% Image Formation\noutput_meta.ImageFormation.RcvChanProc = ...\n    struct('NumChanProc', uint32(1), ... % Assumes not a MODEX collect\n    'PRFScaleFactor', 1/max(num_pulse_parts, numel(tx_pols))); % Either polarimetric or multi-step, but not both.\noutput_meta.ImageFormation.ImageFormAlgo = 'RMA';\noutput_meta.ImageFormation.TStartProc = 0;\noutput_meta.ImageFormation.TEndProc = output_meta.Timeline.CollectDuration;\noutput_meta.ImageFormation.TxFrequencyProc.MinProc = ...\n    output_meta.RadarCollection.TxFrequency.Min;\noutput_meta.ImageFormation.TxFrequencyProc.MaxProc = ...\n    output_meta.RadarCollection.TxFrequency.Max;\noutput_meta.ImageFormation.STBeamComp = 'GLOBAL';\noutput_meta.ImageFormation.ImageBeamComp = 'SV';\noutput_meta.ImageFormation.AzAutofocus = 'NO';\noutput_meta.ImageFormation.RgAutofocus = 'NO';\n\n%% RMA.INCA\noutput_meta.RMA.RMAlgoType = 'OMEGA_K';\noutput_meta.RMA.ImageType = 'INCA';\noutput_meta.SCPCOA.SideOfTrack = char(xp.evaluate(...\n    xpath_str({'product','sourceAttributes','radarParameters','antennaPointing'}),...\n    xml_domnode));  % Should always be right looking for RCM\noutput_meta.SCPCOA.SideOfTrack = upper(output_meta.SCPCOA.SideOfTrack(1));\nif output_meta.SCPCOA.SideOfTrack=='L'\n    ss_zd_s = -ss_zd_s;\n    % In addition to left/right, RS2 data can independently be in\n    % increasing/decreasing line order.\n    if (round((zd_first-zd_last)*SECONDS_IN_A_DAY) + ...\n        (zd_first_frac-zd_last_frac)) < 0 % zd_last occurred after zd_first\n        zd_first = zd_last;\n        zd_first_frac = zd_last_frac;\n    end\n    look = 1;\nelse\n    if (round((zd_first-zd_last)*SECONDS_IN_A_DAY) + ...\n        (zd_first_frac-zd_last_frac)) > 0 % zd_last occurred before zd_first\n        zd_first = zd_last;\n        zd_first_frac = zd_last_frac;\n    end\n    look = -1;\nend\n% Zero doppler time of SCP relative to collect start\nzd_t_scp = round((zd_first-rawDataStartTime)*SECONDS_IN_A_DAY) + ... % Convert days to seconds\n    (zd_first_frac-rawDataStartTimeFrac) + ... % Handle fractional seconds\n    (double(output_meta.ImageData.SCPPixel.Col) * ss_zd_s);\nif strcmp(gen, 'RS2')\n    near_range = str2double(xp.evaluate(...\n        xpath_str({'product','imageGenerationParameters','sarProcessingInformation','slantRangeNearEdge'}),...\n        xml_domnode)); % in meters\nelseif strcmp(gen, 'RCM')\n    near_range = str2double(xp.evaluate(...\n        xpath_str({'product','sceneAttributes','imageAttributes','slantRangeNearEdge'}),...\n        xml_domnode)); % in meters\nend\noutput_meta.RMA.INCA.R_CA_SCP = near_range + ...\n    (double(output_meta.ImageData.SCPPixel.Row)*output_meta.Grid.Row.SS);\noutput_meta.RMA.INCA.FreqZero = fc;\n% Doppler Rate (We do this first since some other things are dependent on\n% it.)\n% For the purposes of the DRateSFPoly computation, we ignore any\n% changes in velocity over the azimuth dimension.\npos_coefs = [P_x(:) P_y(:) P_z(:)];\n% Velocity is derivate of position.\nvel_coefs=pos_coefs(1:end-1,:).*repmat(((size(pos_coefs,1)-1):-1:1)',[1 3]);\nvel_x = polyval(vel_coefs(:,1), zd_t_scp);\nvel_y = polyval(vel_coefs(:,2), zd_t_scp);\nvel_z = polyval(vel_coefs(:,3), zd_t_scp);\nvm_ca_sq = vel_x.^2 + vel_y.^2 + vel_z.^2; % Magnitude of the velocity squared\nr_ca = [output_meta.RMA.INCA.R_CA_SCP; 1]; % Polynomial representing range as a function of range distance from SCP\nif strcmp(gen, 'RS2')\n    drc_xp_str = {'product','imageGenerationParameters','dopplerRateValues', 'dopplerRateValuesCoefficients'};\nelseif strcmp(gen, 'RCM')\n    drc_xp_str = {'product','dopplerRate','dopplerRateEstimate', 'dopplerRateCoefficients'};\nend\ndrr_xp_str = [drc_xp_str{1:(end-1)} {'dopplerRateReferenceTime'}];\ndop_rate_coefs = str2num(xp.evaluate(xpath_str(drc_xp_str),... % Multiple numbers.  We need str2num instead of str2double\n    xml_domnode)); % Shifted (origin at dop_rate_ref_t, not SCP) and scaled (sec, not m) version of SICD DopCentroidPoly\ndop_rate_ref_t = str2double(xp.evaluate(xpath_str(drr_xp_str),...\n    xml_domnode)); % Reference time of Doppler rate polynomial\ndop_rate_coefs_shifted = polyshift(dop_rate_coefs, ... % Shift so SCP is reference\n    (output_meta.RMA.INCA.R_CA_SCP*2/SPEED_OF_LIGHT) - ... % SICD reference time (SCP)\n    dop_rate_ref_t); % Reference time of native Doppler Centroid polynomial\ndop_rate_coefs_scaled = dop_rate_coefs_shifted .*  ... % Scale from seconds to meters\n    (2/SPEED_OF_LIGHT) .^ (0:(length(dop_rate_coefs)-1));\noutput_meta.RMA.INCA.DRateSFPoly = - conv(dop_rate_coefs_scaled.',r_ca) * ... % Multiplication of two polynomials is just a convolution of their coefficients\n    SPEED_OF_LIGHT / (2 * fc * vm_ca_sq(1)); % Assumes a SGN of -1\n\n%% Fields dependent on Doppler rate\n% This computation of SS is actually better than the claimed SS\n% (sampledLineSpacing) in many ways, because this makes all of the metadata\n% internally consistent.  This must be the sample spacing exactly at SCP\n% (which is the definition for SS in SICD), if the other metadata from\n% which is it computed is correct and consistent. Since column SS can vary\n% slightly over a RGZERO image, we don't know if the claimed sample spacing\n% in the native metadata is at our chosen SCP, or another point, or an\n% average across image or something else.\noutput_meta.Grid.Col.SS = sqrt(vm_ca_sq(1)) * abs(ss_zd_s) * ...\n    output_meta.RMA.INCA.DRateSFPoly(1,1);\noutput_meta.Grid.Col.ImpRespBW = dop_bw*abs(ss_zd_s)/output_meta.Grid.Col.SS; % Convert to azimuth spatial bandwidth (cycles per meter)\noutput_meta.RMA.INCA.TimeCAPoly = [zd_t_scp; ss_zd_s/output_meta.Grid.Col.SS];\nif strcmpi(output_meta.Grid.Col.WgtType.WindowName,'KAISER') % The usual RS2 weigting\n    output_meta.Grid.Col.WgtType.Parameter.name = 'BETA';\n    output_meta.Grid.Col.WgtType.Parameter.value = char(xp.evaluate(...\n        xpath_str({'product','imageGenerationParameters','sarProcessingInformation','azimuthWindow','windowCoefficient'}),...\n        xml_domnode));\n    beta_col = str2double(output_meta.Grid.Col.WgtType.Parameter.value);\n    % We don't use the Mathworks Kaiser function, so we won't be dependent on the Signal Processing Toolbox\n    output_meta.Grid.Col.WgtFunct = kaiser_nosptb(NUM_SAMPLES,beta_col);\n    imp_resp = abs(fft(output_meta.Grid.Col.WgtFunct, round(NUM_SAMPLES*OVERSAMPLE))); % Oversampled response function\n    imp_resp = imp_resp/sum(output_meta.Grid.Col.WgtFunct); % Normalize to unit peak\n    ind = find(imp_resp<1/sqrt(2),1,'first')+[-1 -0]; % Samples surrounding half-power point\n    ind = interp1(imp_resp(ind), ind, 1/sqrt(2)); % Linear interpolation to solve for half-power point\n    col_broadening_factor = 2*(ind - 1)/OVERSAMPLE;\n    output_meta.Grid.Col.ImpRespWid = col_broadening_factor/output_meta.Grid.Col.ImpRespBW;\nend\n\n%% Doppler Centroid\nif strcmp(gen, 'RS2')\n    dc_xp_str = {'product','imageGenerationParameters','dopplerCentroid'};\nelseif strcmp(gen, 'RCM')\n    dc_xp_str = {'product','dopplerCentroid','dopplerCentroidEstimate'};\nend\ndop_cent_coefs = str2num(xp.evaluate(... % Multiple numbers.  We need str2num instead of str2double\n    xpath_str([dc_xp_str,{'dopplerCentroidCoefficients'}]),...\n    xml_domnode)); % Shifted (origin at dop_cent_ref_t, not SCP) and scaled (sec, not m) version of SICD DopCentroidPoly\ndop_cent_ref_t = str2double(xp.evaluate(...\n    xpath_str([dc_xp_str,{'dopplerCentroidReferenceTime'}]),...\n    xml_domnode)); % Reference time of Doppler Centroid polynomial\ndop_cent_coefs_shifted = polyshift(dop_cent_coefs, ... % Shift so SCP is reference\n    (output_meta.RMA.INCA.R_CA_SCP*2/SPEED_OF_LIGHT) - ... % SICD reference time (SCP)\n    dop_cent_ref_t); % Reference time of native Doppler Centroid polynomial\ndop_cent_coefs_scaled = dop_cent_coefs_shifted .*  ... % Scale from seconds to meters\n    (2/SPEED_OF_LIGHT) .^ (0:(length(dop_cent_coefs)-1));\noutput_meta.RMA.INCA.DopCentroidPoly=dop_cent_coefs_scaled.';\n% Adjust Doppler Centroid for spotlight\nif strcmp(output_meta.CollectionInfo.RadarMode.ModeType,'SPOTLIGHT')\n    [dop_est, dop_est_frac] = datenum_w_frac(char(xp.evaluate(...  % Doppler estimate time\n        xpath_str([dc_xp_str 'timeOfDopplerCentroidEstimate']), xml_domnode)));\n    dop_est_t = abs(round((dop_est - rawDataStartTime)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n        (dop_est_frac - rawDataStartTimeFrac)); % Handle fractional seconds\n    dop_est_col = (dop_est_t - zd_t_scp)/ss_zd_s; % This is the column where the doppler centroid was computed.\n    % Column-dependent variation in DopCentroidPoly due to spotlight\n    output_meta.RMA.INCA.DopCentroidPoly(1,2) = ...\n        -look * fc * (2 / SPEED_OF_LIGHT) * sqrt(vm_ca_sq(1)) / ...\n        output_meta.RMA.INCA.R_CA_SCP;\n    % dopplerCentroid in native metadata was defined at specific column,\n    % which might not be our SCP column.  Adjust so that SCP column is\n    % correct.\n    output_meta.RMA.INCA.DopCentroidPoly(1,1) = ...\n        output_meta.RMA.INCA.DopCentroidPoly(1,1) - ...\n        (output_meta.RMA.INCA.DopCentroidPoly(1,2) * ...\n        dop_est_col * output_meta.Grid.Col.SS);\nend\noutput_meta.Grid.Col.DeltaKCOAPoly = ...\n    output_meta.RMA.INCA.DopCentroidPoly * ss_zd_s / output_meta.Grid.Col.SS;\n% Compute Col.DeltaK1/K2 from DeltaKCOAPoly\n% This is not always straightforward to do generically for any possible\n% DeltaKCOAPoly 2D polynomial, since you would have to compute all 2D roots\n% and edge cases.  However, for the RS case, this can be solved exactly,\n% since its usually a 1D polynomial.  Even the spotlight case only brings\n% in a linear variation in the second dimensions, so its still easily\n% solved.\n% Min/max in row/range must exist at edges or internal local min/max\nminmax = roots(polyder(output_meta.Grid.Col.DeltaKCOAPoly(end:-1:1,1)));\nrg_bounds_m = (double([0 (output_meta.ImageData.NumRows-1)]) - ...\n     double(output_meta.ImageData.SCPPixel.Row)) * output_meta.Grid.Row.SS;\npossible_bounds_rg = [rg_bounds_m minmax(minmax>min(rg_bounds_m) & minmax<max(rg_bounds_m))];\n% Constant or (linearly increasing\\decreasing for spotlight) in column, so\n% edges must contain max/min.\npossible_bounds_az = (double([0 (output_meta.ImageData.NumCols-1)]) - ...\n     double(output_meta.ImageData.SCPPixel.Col)) * output_meta.Grid.Col.SS;\npossible_bounds_deltak = sicd_polyval2d(output_meta.Grid.Col.DeltaKCOAPoly, ...\n    possible_bounds_az, possible_bounds_rg);\noutput_meta.Grid.Col.DeltaK1 = min(possible_bounds_deltak(:)) - ...\n    (output_meta.Grid.Col.ImpRespBW/2);\noutput_meta.Grid.Col.DeltaK2 = max(possible_bounds_deltak(:)) + ...\n    (output_meta.Grid.Col.ImpRespBW/2);\n% Wrapped spectrum\nif (output_meta.Grid.Col.DeltaK1 < -(1/output_meta.Grid.Col.SS)/2) || ...\n        (output_meta.Grid.Col.DeltaK2 > (1/output_meta.Grid.Col.SS)/2)\n    output_meta.Grid.Col.DeltaK1 = -(1/output_meta.Grid.Col.SS)/2;\n    output_meta.Grid.Col.DeltaK2 = -output_meta.Grid.Col.DeltaK1;\nend\n%% TimeCOAPoly\n% TimeCOAPoly=TimeCA+(DopCentroid/dop_rate)\n% Since we can't evaluate this equation analytically, we will evaluate\n% samples of it across our image and fit a 2D polynomial to it.\nPOLY_ORDER = 2; % Order of polynomial which we want to compute\ngrid_samples = POLY_ORDER + 1; % in each dimension\ncoords_az_m = linspace(-double(output_meta.ImageData.SCPPixel.Col),...\n    double(output_meta.ImageData.NumCols-output_meta.ImageData.SCPPixel.Col-1), grid_samples) * ...\n    output_meta.Grid.Col.SS;\ncoords_rg_m = linspace(-double(output_meta.ImageData.SCPPixel.Row),...\n    double(output_meta.ImageData.NumRows-output_meta.ImageData.SCPPixel.Row-1), grid_samples) * ...\n    output_meta.Grid.Row.SS;\ntimeca_sampled = sicd_polyval2d(output_meta.RMA.INCA.TimeCAPoly(:).',coords_az_m,coords_rg_m);\ndopcentroid_sampled = sicd_polyval2d(output_meta.RMA.INCA.DopCentroidPoly,coords_az_m,coords_rg_m);\ndoprate_sampled = sicd_polyval2d(dop_rate_coefs_scaled.',coords_az_m,coords_rg_m);\ntimecoapoly_sampled = timeca_sampled+(dopcentroid_sampled./doprate_sampled);\n% Least squares fit for 2D polynomial\n% A*x = b\n[coords_az_m, coords_rg_m] = ndgrid(coords_az_m, coords_rg_m);\na = zeros(grid_samples^2, (POLY_ORDER+1)^2);\nfor i = 0:POLY_ORDER\n    for j = 0:POLY_ORDER\n        a(:,i*(POLY_ORDER+1)+j+1) = (coords_rg_m(:).^j).*(coords_az_m(:).^i);\n    end\nend\nb_coa = zeros((POLY_ORDER+1)^2,1);\nfor i=1:((POLY_ORDER+1)^2)\n   b_coa(i)=sum(timecoapoly_sampled(:).*a(:,i)); % center of aperture\nend\nA=zeros((POLY_ORDER+1)^2);\nfor i=1:((POLY_ORDER+1)^2)\n    for j=1:((POLY_ORDER+1)^2)\n        A(i,j)=sum(a(:,i).*a(:,j));\n    end\nend\nold_warning_state=warning('off','MATLAB:nearlySingularMatrix');\nx=A\\b_coa; % MATLAB often flags this as badly scaled, but results still appear valid\nwarning(old_warning_state);\noutput_meta.Grid.TimeCOAPoly=reshape(x, POLY_ORDER+1, POLY_ORDER+1);\nif strcmp(output_meta.CollectionInfo.RadarMode.ModeType,'SPOTLIGHT')\n    output_meta.Grid.TimeCOAPoly = output_meta.Grid.TimeCOAPoly(1);\n    % This field required to compute TimeCOAPoly, but not allowed for\n    % spotlight in SICD.\n    output_meta.RMA.INCA = rmfield(output_meta.RMA.INCA, 'DopCentroidPoly');\nelse % This field also not allowed for spotlight in SICD.\n    output_meta.RMA.INCA.DopCentroidCOA=true;\nend\n\n%% GeoData\n% Now that sensor model fields have been populated, we can populate\n% GeoData.SCP more precisely.\necf = point_image_to_ground([output_meta.ImageData.SCPPixel.Row;output_meta.ImageData.SCPPixel.Col],output_meta);\noutput_meta.GeoData.SCP.ECF.X=ecf(1);\noutput_meta.GeoData.SCP.ECF.Y=ecf(2);\noutput_meta.GeoData.SCP.ECF.Z=ecf(3);\nllh=ecf_to_geodetic([output_meta.GeoData.SCP.ECF.X output_meta.GeoData.SCP.ECF.Y output_meta.GeoData.SCP.ECF.Z]);\noutput_meta.GeoData.SCP.LLH.Lat=llh(1);\noutput_meta.GeoData.SCP.LLH.Lon=llh(2);\noutput_meta.GeoData.SCP.LLH.HAE=llh(3);\n\n%% Radiometric\nif exist('beta_domnode','var')\n    % Offset always zero for SLC, so we only need gains\n    betas = str2num(xp.evaluate(xpath_str({'lut','gains'}),beta_domnode)); %#ok<ST2NM>\n    % Of the provided LUTs, we really only work with beta here, since it is\n    % the radiometric term most commonly kept constant, and the others\n    % (sigma/gamma) can always be derived from it.\n    % if any(strcmp({'Constant-beta', 'Point Target', 'Point Target-1', ...\n    %         'Calibration-1', 'Calibration-2', 'Ship-1', 'Ship-2', ...\n    %         'Ship-3', 'Unity'}, ... % Known modes with constant beta\n    %         xp.evaluate(xpath_str({'product','imageGenerationParameters', ...\n    %         'sarProcessingInformation','lutApplied'}), xml_domnode)))\n    if all(betas==betas(1)) % In case we missed some modes, this condition may be more reliable\n        output_meta.Radiometric.BetaZeroSFPoly = 1/betas(1)^2;\n    else  % Otherwise fit a 1D polynomial in range\n        % RS2 has value for every row\n        coords_rg_m = (double(0:(output_meta.ImageData.NumRows-1)) - ...\n            double(output_meta.ImageData.SCPPixel.Row)) * output_meta.Grid.Row.SS;\n        if strcmp(gen, 'RCM') % RCM subsamples the rows\n            rng_indices = ((str2double(xp.evaluate(xpath_str({'lut','pixelFirstAnglesValue'}), beta_domnode)):...\n                ... % Should be this, but simulated datasets are inconsistent with spec document\n                ... % crm_indices = (xp.evaluate(xpath_str({'lut','pixelFirstLutValue'}), beta_domnode):...\n                (str2double(xp.evaluate(xpath_str({'lut','numberOfValues'}), beta_domnode))-1)) * ... % First row is zero\n                str2double(xp.evaluate(xpath_str({'lut','stepSize'}), beta_domnode))) + 1;\n            coords_rg_m = coords_rg_m(rng_indices);\n        end\n        % For the datasets we have seen, this function is very close to\n        % linear.  For the \"Mixed\" LUT, there is a tiny linear piecewise\n        % deviation from a single overall linear.\n        betapoly = polyfit(coords_rg_m, 1./betas.^2, 2);\n        output_meta.Radiometric.BetaZeroSFPoly = betapoly(end:-1:1).';\n    end\n    % RCS, Sigma, and Gamma will be computed below in derived_sicd_fields\n    % derived_sicd_fields.\n    output_meta.Radiometric.NoiseLevel.NoiseLevelType = 'ABSOLUTE';\n    if strcmp(gen, 'RS2')\n        beta0_str = [xpath_str({'product', 'sourceAttributes', ...\n            'radarParameters','referenceNoiseLevel'}) ...\n            '[@incidenceAngleCorrection=\"Beta Nought\"]'];\n        noise_domnode = xml_domnode;  % RS2 noise is in main product.xml\n    elseif strcmp(gen, 'RCM') % RCM noise is in separate file\n        beta0_str = [xpath_str({'noiseLevels', 'referenceNoiseLevel'}) ...\n            '/*[text()=''Beta Nought'']/..'];\n    end\n    if exist('noise_domnode','var')\n        pfv = str2double(xp.evaluate([beta0_str ...\n            '/*[local-name()=''pixelFirstNoiseValue'']'], noise_domnode)); % Index of first row defined to be zero\n        step = str2double(xp.evaluate([beta0_str ...\n            '/*[local-name()=''stepSize'']'], noise_domnode));\n        beta0s = str2num(xp.evaluate([beta0_str ...\n            '/*[local-name()=''noiseLevelValues'']'], noise_domnode)); %#ok<ST2NM>\n        range_coords = output_meta.Grid.Row.SS * ...\n            ((((1:numel(beta0s))-1) * step) + pfv - double(output_meta.ImageData.SCPPixel.Row));\n        noisepoly = polyfit(range_coords, beta0s - (10*log10(polyval(...\n            output_meta.Radiometric.BetaZeroSFPoly(end:-1:1), range_coords))), 2);\n        output_meta.Radiometric.NoiseLevel.NoisePoly = noisepoly(end:-1:1).';\n    end\nend\n\n%% SCPCOA\n% All of these fields are derivable for more fundamental fields.\noutput_meta = derived_sicd_fields(output_meta);\n\n%% Process fields specific to each polarimetric band\nband_independent_meta = output_meta; % Values that are consistent across all bands\ngrouped_meta = cell(numel(pols),1);\nfor i=1:numel(pols)\n    output_meta = band_independent_meta;\n    \n    output_meta.ImageFormation.RcvChanProc.ChanIndex = i;\n    output_meta.ImageFormation.TxRcvPolarizationProc = ...\n        output_meta.RadarCollection.RcvChannels.ChanParameters(i).TxRcvPolarization;\n    \n    grouped_meta{i} = output_meta;\nend\noutput_meta = grouped_meta; % Cell array with metadata struct for each band\n\nend\n\n% Creates an XPath query that is a namespace insensitive search for an XML\n% heirachy.  Input is a cell array of strings specifying the XML fields,\n% starting with the root node and working its way down the XML tree to the\n% leaf nodes.  This is required since RS2 XML files specify a default\n% namespace, so XPath queries with no namespace speficied will not work.\n% (That only searches for elements associated with no namespace at all.)\n% Note: This seems to be an issue only in MATLAB 2010a and above, as\n% previous versions used another XPATH library that was more tolerant.\nfunction out_str = xpath_str(in_cell_array)\n    out_str='';\n    for j=1:length(in_cell_array)\n        out_str=[out_str '/*[local-name()=''' in_cell_array{j} ''']'];\n    end\nend\n\n% MATLAB's datenum function won't handle precise times down under a\n% millisecond, because 1) It won't accept a format with more than 3 .FFF in\n% the string description of the date format and 2) the resulting serial\n% date number is stored in days from 00-JAN-0000 and just doesn't have\n% enough bits to handle fractional seconds to the level we want.  Here we\n% handle the fractional seconds separately so we can read date with the\n% precision we need.\nfunction [datenum_s, datenum_frac] = datenum_w_frac(datestring)\n    datenum_s = datenum(datestring,'yyyy-mm-ddTHH:MM:SS');\n    datenum_frac = str2double(regexp(datestring,'\\.\\d*','match'));\n    if isnan(datenum_frac), datenum_frac = 0; end;\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/IO/complex/rs/meta2sicd_rs_xml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.21519998652267525}}
{"text": "function computeModelCoefficients_batchHN_Old(pathExperiments,nExp,imbalance,nBatch,matlabPATH,seed)\n% -------------------------------------------------------------------------\n% function computeModelCoefficients_batchHN(pathExperiments,nExp,fSetNames,imbalance,matlabPATH)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes the final logistic regression coefficients and\n% bootstrap confidence intervals of the final models obtained for all\n% outcomes analyzed in the HN study. See ref.[1] for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n%     early prediction of different tumour outcomes in head and neck cancer.\n%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n%     doi:\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathExperiments: Full path to the directory containing all experiments.\n%                     --> Ex: '/myProject/WORKSPACE/CV-BASED_RESULTS'\n% 2. nExp: Numerical value specifying the number of experiments to analyze.\n%          --> Ex: 10\n% 3. imbalance: String specifying the type of imbalance-adjustement strategy\n%               employed. Either 'IABR' for imbalance-adjusted bootstrap\n%               resampling (see ref.[1]), or 'IALR' for imbalance-adjusted\n%               logistic regression (see ref.[2]).\n%               --> Ex: 'IALR'\n% 4. nBatch: Number of parallel batch.\n%            --> Ex: 8\n% 5. matlabPATH: Full path to the MATLAB excutable on the system.\n%                --> 'matlab' if a symbolic link to the matlab executable\n%                     was previously created.\n% -------------------------------------------------------------------------\n% OUTPUTS: Final coefficients, model response and confidence intervals \n%          saved in the corresponding ../experiment/outcome/fSetName\n%          folder.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ntime = 30; % Number of seconds to wait before checking if parallel computations are done\n\nfor exp = 1:nExp\n    cd(fullfile(pathExperiments,['Experiment',num2str(exp)])), load('training')\n    cd('FINAL_MODELS'), pathFinalModels = pwd;\n    mkdir('batchLog_Coeff'), cd('batchLog_Coeff'), pathBatch = pwd;\n    nameOutcomes = fieldnames(training); nOutcomes = numel(nameOutcomes);\n    for o = 1:nOutcomes\n        outcomes.(nameOutcomes{o}) = training.(nameOutcomes{o}).outcome;\n    end\n    setNames = fieldnames(training.(nameOutcomes{1}).text);\n    [param] = batchExperiments(setNames,outcomes,nBatch); nBatch = length(param);\n    \n    % PRODUCE BATCH COMPUTATIONS\n    save('workspace','pathFinalModels','training','param','pathBatch','imbalance','seed'), pause(3)\n    for i = 1:nBatch\n        nameScript = ['batch',num2str(i),'_script.m'];\n        fid = fopen(nameScript,'w');\n        fprintf(fid,'tic\\n');\n        fprintf(fid,'load(''workspace'')\\n');\n        for j = 1:numel(param{i})\n            fprintf(fid,['cd(fullfile(pathFinalModels,param{',num2str(i),'}{',num2str(j),'}{2},param{',num2str(i),'}{',num2str(j),'}{1}))\\n']);\n            fprintf(fid,'load(''finalModel'')\\n');\n            fprintf(fid,['fprintf(''COMPUTING THE LOGISTIC REGRESSION COEFFICIENTS OF THE FINAL MODEL OF \"',param{i}{j}{2},'\" OUTCOME, \"',param{i}{j}{1},'\" FEATURE SET ... '')']);\n            fprintf(fid,'\\n');\n            fprintf(fid,['[coeff,response,modelCI] = computeModelCoefficients_HN(finalModel.Data,training.',param{i}{j}{2},'.outcome,imbalance,seed);\\n']);\n            fprintf(fid,['fprintf(''DONE!\\\\n'')']);\n            fprintf(fid,'\\n');\n            fprintf(fid,'save(''coeff'',''coeff''), save(''response'',''response''), save(''modelCI'',''modelCI'')\\n');\n        end\n        fprintf(fid,'cd(pathBatch)\\n');\n        fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n        fprintf(fid,'clear all\\n');\n        fprintf(fid,'toc');\n        fclose(fid);\n        system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\n    end\n    waitBatch(pathBatch,time,nBatch)\n    delete('workspace.mat')\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/computeModelCoefficients_batchHN_Old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21518380073760535}}
{"text": "\nHeadModelPath = [hlp_getSiftRoot filesep 'resources' filesep 'headmodels' filesep 'standard-Colin27-385ch.mat'];\nhmObj = hlp_validateHeadModelObject(HeadModelPath);\n\n%% Simulate VAR model\n[EEGsim] = pop_sim_varmodel([]);\nif length(EEGsim)>1\n    EEGtrue = EEGsim(2);\n    EEGsim  = EEGsim(1);\nend\n\n%% Simulate scalp activity using forward model\n\n% these are the source locations\nsourceRois = {'Cingulum_Mid_L','Occipital_Mid_L','Parietal_Sup_L','Frontal_Sup_Medial_R','Precentral_R'};\n\ncfg = arg_guipanel('Function',@sim_simulateSources, ...\n                   'Parameters',{ ...\n                        'hmObj',HeadModelPath, ...\n                        'sourceAtlasLabels', setdiff_bc(hmObj.atlas.label,{'Thalamus_L','Thalamus_R'}), ...\n                        'Channels',hmObj.label, ... \n                        'sourceShape' {'gausspatch' 'roiOrdered' sourceRois, 'sigma', 10}, ...\n                        'addNoise', {'SignalToNoise' 20} ...\n                        },'PanelOnly',false);\n[scalpData srcData LFM] = sim_simulateSources('sourceAmps',EEGsim.data,cfg);\n\n%% \n\nchanlabels = hmObj.getChannelLabels();\nelocs = hmObj.channelSpace;\nEEG = EEGsim;\nEEG.data       = scalpData;\nEEG.nbchan     = size(EEG.data,1);\nEEG.setname    = 'VAR Simulation';\nEEG.condition  = 'VAR Simulation';\nEEG.srcpot_all = srcData;\nEEG = rmfield(EEG,'chanlocs');\nfor k=1:EEG.nbchan\n    EEG.chanlocs(k) = struct(...\n        'X',elocs(k,1), ...\n        'Y',elocs(k,2), ...\n        'Z',elocs(k,3), ...\n        'labels',chanlabels{k}, ...\n        'type','EEG', ...\n        'theta',[], ...\n        'radius',0.5, ...\n        'sph_theta',[],...\n        'sph_phi',[],...\n        'sph_radius',[],...\n        'urchan',k, ...\n        'ref','');\nend\nEEG.chanlocs = convertlocs(EEG.chanlocs,'cart2all');\n\n%% visualize\nlatency = [];\ngobj=vis_csd('hmObj',HeadModelPath, ...\n         'signal',EEG,  ...\n         'cortexMesh',[], ...\n         'times',latency,        ...\n         'avgtimes',false,       ...\n         'frameskip',10,          ...\n         'cortexlims',99,       ...\n         'scalplims',[99], ...\n         'showpower',false, ...\n         'title','True');\n     \n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/scripts/SimulateSources.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.21511973309143606}}
{"text": "function [err, Qd, s, termname, nterms, sindices, dfbothSS, modw, modwo, tnames, dfterm, dfe, Contr] = PreProc(n, NF, group, varnames, FL, Contr, cov, unbalanced)\n%\n%   [err, Qd, Rd, sindices, dfboth, modw, modwo, dfx] = PreProc(n,group,varnames)\n%\n%Purpose:\n%\n%  Returns QR decomposition results for the design matrix projected to null space\n%\n%Input Parameters:\n%   n: number of datasets = total # of combinations including repeats\n%   group: cell array of factor levels\n%   varnames:\n%\n%Output Parameters:\n%   err : 0 No Problem\n%       : 1  Problems\n%\n%\n%\n%Key Terms:\n%\n%More Info :\n%\n%\n%\n%\n%     Author : Gang Chen\n%     Date : Tue Mar 23 13:57:52 EST 2004\n%     SSCC/NIMH/ NIH, Bethesda MD 20892\n\n\n%Define the function name for easy referencing\nFuncName = 'PreProc.m';\n\n%Debug Flag\nDBG = 1;\n\n%initailize return variables\nerr = 1;\n\n% Don't worry about NaN's at this point.\ngroup = group(:);    % what's it for?\nng = length(group);  % number of factors\ntermlist = makemodel(ng, ng);  % Generate terms for all main effects plus various interactions\n\nfor j=1:ng\n   gj = group{j};\n   if (size(gj,1) == 1), gj = gj(:); end\n   if (size(gj,1) ~= n)\n      error('Factor %d must have %d elements.',j,n);\n   end\n   if (ischar(gj)), gj = cellstr(gj); end\n   group{j} = gj;\nend\n\ngdum = cell(ng,1);\ndfvar = zeros(ng,1);\n\nif (unbalanced.yes == 0), % Balanced designs\n   vconstr = cell(ng,1);\n   %vmean = cell(ng,1);   %vmean is never used!!!\nend\n\nfor j=1:ng   % for each factor\n   gj = group{j};\n   [gij,gnj] = grp2idx(gj);   % Create index vector from a grouping variable: gij is a vector\n\t                           % taking integer values from 1 up to the number of unique entries in gj\n\t\t\t\t\t\t\t\t\t\t% gnj is a cell array of names, so that gnj(gij) reproduces gj\n   nlevels = size(gnj,1);     % levels for this factor\n   dfvar(j) = nlevels - 1;    % D. F. for this factor\n\n   if (unbalanced.yes == 0),\t% balanced\n      if (cov.do & j==cov.marker)\n\t      gdum{j} = gj;\n         dfvar(j) = 1;           % D. F. = 1\n         vconstr{j} = zeros(0,1);\n%        vmean{j} = 1;\t\t\n      else\n         gdum{j} = idummy(gij, 3);\n         vconstr{j} = idummy(1:nlevels)';\n%        vmean{j} = ones(1,nlevels) / nlevels;  % array (1Xnlevels) of one ones, but vmean is never used in the code!!!!!!!!!1\n\t   end\n\telse % Unbalanced designs\t\n\t   if (cov.do & j==cov.marker)\n\t      gdum{j} = gj;\n         dfvar(j) = 1;           % D. F. = 1\n         vconstr{j} = zeros(0,1);\n%        vmean{j} = 1;\t\t\n      else\n\t\t   gdum{j} = idummy(gij, 3);\n\t\tend\t\n\tend % if (unbalanced.yes == 0): Only for balanced designs\n\t\t\nend\n\n% Create dummy variable arrays for each term in the model.\nnterms = size(termlist,1);             % Number of rows (1st dimension) in termlist\n[sterms,sindex] = sortrows(termlist);  % Sort terms in ascending order.\nncols = 1;\nnconstr = 0;\n\ntermdum = cell(nterms, 1);        % cell array of dummy variables which are design matrix cols\ntermconstr = cell(nterms,1);      % constraints to make each term well defined\nlevelcodes = cell(nterms, 1);     % codes for levels of each M row\ntnames = cell(nterms, 1);         % name for entire term, e.g. A*B\ndfterm0 = zeros(nterms, 1);       % nominal d.f. for each term\ntermvars = cell(nterms, 1);       % list of vars in each term\ntermlength = zeros(size(sindex)); % length of each term (number of columns)\n\n%randomterm = find(termlist*randomvar > 0);  % indices of random terms\n\n% For each term,\nfor j=1:nterms\n   % Loop over elements of the term\n   df0 = 1;\n   tm = sterms(j,:);\n   tdum = [];         % empty term so far\n   tconstr = 1;       % empty constraints so far\n   tn = '';           % blank name so far\n   vars = find(tm);   % Find indices of nonzero elements\n   for varidx = 1:length(vars)\n      % Process each variable participating in this term\n      varnum = vars(varidx);          % variable name\n      tm(varnum) = 0;                 % term without this variable\n      df0 = df0 * dfvar(varnum);      % d.f. so far\n\n      % Combine its dummy variable with the part computed so far\n      G = gdum{varnum};           % dummy vars for this grouping var\n      nlevterm = size(tdum,2);    % levels for term so far\n      nlevgrp  = size(G,2);       % levels for this grouping var\n      tdum = termcross(G,tdum);   % combine G into term dummy vars\n\n      % Construct the term name and constraints matrix\n%      if (ismember(varnum, NF) & cov.do),    % for the covariate, which is the last factor\n\t\tif (ismember(varnum, cov.marker) & cov.do),    % for the covariate, which is the last factor\n         vconstr = ones(0,1);\n      else\n         vconstr = ones(1, nlevgrp);\n      end\n      if (isempty(tn))\n         tn = varnames{varnum};\n         tconstr = vconstr;\n      else\n         tn = [varnames{varnum} '*' tn];\n         tconstr = [kron(vconstr,eye(size(tconstr,2)));\n                    kron(eye(length(vconstr)),tconstr)];   % Kronecker\n      end\n\n      % If the rest of this term is computed, take advantage of that\n      prevterms = sterms(1:j-1,:);\n      oldtm = find((prevterms * tm') == sum(tm));      % same vars in old term\n      oldtm = oldtm((prevterms(oldtm,:) * ~tm') == 0); % and no others\n      if (length(oldtm) > 0)\n         k = sindex(oldtm(1));\n         tdum = termcross(termdum{k}, tdum);\n         oconstr = termconstr{k};\n         tconstr = [kron(tconstr,              eye(size(oconstr,2)));\n                    kron(eye(size(tconstr,2)), oconstr)];\n         tn = [tn '*' tnames{k}];\n         df0 = df0 * dfterm0(k);\n         break;\n      end\n   end\n\n   % Store this term's dummy variables and name\n   k = size(tdum, 2);\n   termlength(sindex(j),1) = k;\n   ncols = ncols + k;\n   sj = sindex(j);\n   termdum{sj} = tdum;\n   termconstr{sj} = tconstr;\n   termvars{sj} = vars;\n   levelcodes{sj} = fullfact(dfvar(vars)+1);\n   if (isempty(tn)), tn = 'Constant'; end\n   tnames{sj,1} = tn;\n   dfterm0(sj) = df0;\n   nconstr = nconstr + size(tconstr,1);\nend\ntnames{length(tnames)+1,1} = 'Error';\n\n% Create the full design matrix\ndmat = ones(n, ncols);        % to hold design matrix of nXncols\ncmat = zeros(nconstr,ncols);  % to hold constraints matrix\ncbase = 0;                    % base from which to fill in cmat\ntermname = zeros(ncols,1);\ntermstart = cumsum([2; termlength(1:end-1)]);\ntermend = termstart + termlength - 1;\nfor j=1:nterms\n   clist = termstart(j):termend(j);\n   dmat(:, clist) = termdum{j};\n   C = termconstr{j};\n   nC = size(C,1);\n   cmat(cbase+1:cbase+nC,clist) = C;\n   termname(clist) = j;\n   cbase = cbase + nC;\nend\n\n[err, Qd, dfx, dmat2] = QRDecom(dmat, cmat);\n%dfe = n - dfx;\n\n% Determine which models to compare for testing each term\nssw  = -ones(nterms, 1);      % sum of squares with this term\nsswo = ssw;                   % sum of squares without this term\ndfw  = ssw;                   % residual d.f. with this term\ndfwo = ssw;                   % residual d.f. without this term\n\nif (unbalanced.yes == 1)\n   modw = tril(ones(nterms)); % get model with this term\n   k = nterms;                % locations of model with all terms\nelse\n\n% Only apply type III for sums of squares\nmodw = ones(nterms);\n%k = 1:nterms;\n%TnotC = termsnotcontained(termlist);\n\nend % if (unbalanced.yes == 1)\n\nmodw = logical(modw);                  % get model with this term\nmodwo = logical(modw - eye(nterms));   % get model without this term\n\ndfw(1:nterms) = dfx;\n\n% Fit each model separately\ndfboth = [dfw; dfwo];\ndfbothSS = dfboth;  % For usage in ss.m\n\n% Consider interactions before their components for type 3 ss, so\n% examine the terms in decreasing order of the number factors in the term\n\n\nif (unbalanced.yes == 1)\n   sindices = [(1:size(termlist,1)), (1:size(termlist,1))]';\t\nelse\t\ntermsize = sum(termlist,2)';      %sum of all the elements along 2nd dimension (row)\n[stermsize,sindices] = sort(termsize); % sort in ascending order, output is stored in stermsize; sindices is the index for the new array\nsindices = [sindices(:); sindices(:)];\n\nend % if (unbalanced.yes == 1)\n\n% Here QR decomposition is done, which is voxel independent\n\ns(length(sindices)).Qdt = [];\n\nfor j=length(sindices):-1:1\n   % Find the next model index to fit\n   k = sindices(j);\n\n   % Look in unsorted arrays to see if we have already fit this model\n   if j>nterms\n      k0 = k+nterms;\n   else\n      k0 = k;\n   end\n   if dfboth(k0)~=-1\n      continue\n   end\n\n   % Find the model with this index\n   if (j > nterms)\n      thismod = modwo(k, :);\n   else\n      thismod = modw(k, :);\n   end\n\n   % Get the design matrix for this model\n   keepterms = find(thismod);\n   clist = ismember(termname, [0 keepterms]);\n   X = dmat2(:,clist);\n   C = cmat(:,clist);\n\n   % Fit this term\n\t[err, s(j).Qdt, dfx0] = QRDecom(X, C);\t\n\n   % Use these results for each term that requires them\n\n   mod0 = repmat(thismod, nterms, 1);\n   k = find(all(modw == mod0, 2));\n   dfw(k) = dfx0;\n   dfboth(k) = 0;\n\t\n   k = find(all(modwo == mod0, 2));\n   dfwo(k) = dfx0;\n   dfboth(nterms+k) = 0;\nend\nclear mod0\n\ndfterm = dfw - dfwo;\ndfe = n-dfx;   %residual degrees of freedom\n\nif (Contr.do == 1),\n\n   % In design matrix dmat, the first column is all one's, for the total mean. Then there are totally\n   % FL(1).N_level + FL(2).N_level + FL(3).N_level + FL(4).N_level columns for the main effects.\n   % Next 2nd order interactions, 3rd order interaction, and 4th order interactions.\n\n   % Store only those mean columns in design matrix.\n\n   %num_col0 = 1;  % the 1st column is for grand mean (0 order)\n\n   num_col(1) = 0;\n   for (i = 1:1:NF),\n      num_col(1) = num_col(1) + FL(i).N_level;   %\n   end\n\n   %  Ignore 1st col since it is total mean\n   %dmat_mean = dmat(:, (num_col0 + 1):(num_col0 + num_col(1)));\n\n   % Get the number in the sum for each mean, which happens to be in the diagonal of X'X.\n   % This can also be otained through the user input variables, but it is generic with\n   % the matrix operation, especially for unbalanced design.\n   %sum_num = diag(dmat_mean' * dmat_mean);\n\n\n   if (NF > 1),\n      num_col(2) = 0;\n      for (i = 1:1:(NF-1)),\n      for (j = (i+1):1:NF),\n         num_col(2) = num_col(2) + FL(i).N_level*FL(j).N_level;    %Columns for 2nd order interactions\n      end\n      end\n   end\n\n   if (NF > 2),\n      num_col(3) = 0;\n      for (i = 1:1:(NF-2)),\n      for (j = (i+1):1:(NF-1)),\n   \tfor (k = (j+1):1:NF),\n         num_col(3) = num_col(3) + FL(i).N_level*FL(j).N_level*FL(k).N_level;    %Columns for 3rd order interactions\n      end\n      end\n   \tend\n   end\n\n   %if (NF == 4),\n   %   num_col(4) = 1;\n   %\tfor (i = 1:1:NF),\n   %\t   num_col(4) = num_col(4)*FL(i).N_level;  %Columns for 4th order interactions\n   %\tend\t\n   %end\n\n   % for every design\n   if (Contr.ord1.tot > 0),\t\t% 1st order contrasts\n      [err, Contr] = ContrVec(1, n, NF, group, dmat, Contr, FL, num_col);\n   end   % if (Contr1.tot > 0)\n\n   if (NF > 1 & Contr.ord2.tot > 0),  % 2nd order contrasts\n      [err, Contr] = ContrVec(2, n, NF, group, dmat, Contr, FL, num_col);\n   end   % if (Contr2.tot > 0)\n\n   if (NF > 2 & Contr.ord3.tot > 0),  % 3rd order contrasts\n      [err, Contr] = ContrVec(3, n, NF, group, dmat, Contr, FL, num_col);\n   end   % if (Contr3.tot > 0)\n\t\n\tif (NF > 3 & Contr.ord4.tot > 0),  % 4th order contrasts\n      [err, Contr] = ContrVec(4, n, NF, group, dmat, Contr, FL, num_col);\n   end   % if (Contr3.tot > 0)\n\nend % if (Contr.do == 1)\n\nerr = 0;\nreturn;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/PreProc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21501087096214241}}
{"text": "function test_ft_megrealign\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_megrealign ft_prepare_neighbours ft_transform_geometry\n\ndatainfo = ref_datasets;\nsel      = match_str({datainfo.datatype},{'bti148' 'bti248' 'ctf151' 'ctf275' 'itab153' 'yokogawa160'}');\ndatainfo = datainfo(sel);\n\n% as of yet, the code does not explicitly test anything, it just checks\n% whether all runs through smoothly\nfor k = 1:numel(datainfo)\n  fname = fullfile(datainfo(k).origdir,'latest/raw',datainfo(k).type,['preproc_',datainfo(k).datatype]);\n  load(fname);\n  \n  cfg = [];\n  cfg.channel = 'MEG';\n  cfg.demean = 'yes';\n  data = ft_preprocessing(cfg, data);\n  \n  vol      = [];\n  vol.o    = [0 0 4];\n  vol.r    = 10;\n  vol.unit = 'cm';\n  \n  % ensure units in the gradiometer array and volume conductor to be equal\n  data.grad = ft_convert_units(data.grad, 'cm');\n  vol       = ft_convert_units(vol, data.grad.unit);\n  \n  % make 2 copies\n  data2 = data;\n  data3 = data;\n  \n  data2.grad = ft_transform_geometry([[eye(3) [0 0 -2]'];[0 0 0 1]], data.grad);\n  data3.grad = ft_transform_geometry([1 0 0 0;0 cos(0.1) -sin(0.1) 0;0 sin(0.1) cos(0.1) 0;0 0 0 1], data.grad);\n  \n  cfg = [];\n  cfg.template{1} = data.grad;\n  cfg.template{2} = data2.grad;\n  cfg.template{3} = data3.grad;\n  cfg.inwardshift = 1;\n  cfg.headmodel   = vol;\n  \n  interp = ft_megrealign(cfg, data);\n  interp2 = ft_megrealign(cfg, data2);\n  interp3 = ft_megrealign(cfg, data3);\n  \n  \nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_megrealign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.21486379715625514}}
{"text": "function model = yalmip2nonlinearsolver(model)\n\nglobal newmodel\n\nnewmodel = 1;\n\nmodel.dense = 0;\nif ~(model.equalitypresolved || model.presolved)\n    model = propagate_bounds_from_equalities(model);\nend\n\nK = model.K;\nlb = model.lb;\nub = model.ub;\nx0 = model.x0;\nc = model.c;\n\n% Pick out the positive conditions from cones ||Ax+b|| <= c'*x+d which will\n% be treated as (Ax+b)'*(ax+b) <= (c'*x+d)^2,  c'*x+d >= 0\nmodel = bounds_from_cones_to_lp(model);\n\nif isempty(model.evaluation_scheme)\n    model = build_recursive_scheme(model);\nend\nmodel = compress_evaluation_scheme(model);\n\n% Do some pre-calc to be used in calls from fmincon\nnonlinearindicies = union(find(model.variabletype~=0),model.evalVariables);\nlinearindicies    = setdiff(find(model.variabletype==0),nonlinearindicies);\nmodel.nonlinearindicies = nonlinearindicies;\nmodel.linearindicies    = linearindicies;\n\nmodel.Anonlinineq = [];\nmodel.bnonlinineq = [];\nmodel.Anonlineq = [];\nmodel.bnonlineq = [];\n\n% Extract linear and nonlinear equality constraints\nif K.f>0\n    Aeq = -model.F_struc(1:1:K.f,2:end);\n    beq = model.F_struc(1:1:model.K.f,1);\n    \n    nonlinear_equalities_indicies = find(any(Aeq(:,nonlinearindicies),2));\n    model.Anonlineq = Aeq(nonlinear_equalities_indicies,:);\n    model.bnonlineq = beq(nonlinear_equalities_indicies);\n    \n    Aeq(nonlinear_equalities_indicies,:) = [];\n    beq(nonlinear_equalities_indicies,:) = [];\n    Aeq(:,nonlinearindicies) = [];\n    model.F_struc(1:model.K.f,:) = [];\n    model.K.f = 0;\nelse\n    Aeq = [];\n    beq = [];\nend\n\n% Find nonlinear eualities implied by lower and upper bounds\nif ~isempty(ub) && ~isempty(lb)\n    nonlinearequality = find(lb(nonlinearindicies) == ub(nonlinearindicies));\n    if ~isempty(nonlinearequality)\n        for i = 1:length(nonlinearequality)\n          %  model.Anonlineq = [model.Anonlineq;eyev(length(c),nonlinearindicies(nonlinearequality(i)))'];\n            model.Anonlineq = [model.Anonlineq;sparse(1,nonlinearindicies(nonlinearequality(i)),1,1,length(c))];\n            model.bnonlineq = [model.bnonlineq;lb(nonlinearindicies(nonlinearequality(i)))];\n        end\n    end\nend\n\n% Extract linear and nonlinear inequality constraints\nif any(model.K.l)\n    A = -model.F_struc(1:model.K.l,2:end);\n    b = model.F_struc(1:model.K.l,1);\n    \n    nonlinear_inequalities_indicies = find(any(A(:,nonlinearindicies),2));\n    \n    model.Anonlinineq = A(nonlinear_inequalities_indicies,:);\n    model.bnonlinineq = b(nonlinear_inequalities_indicies);\n    \n    A(nonlinear_inequalities_indicies,:) = [];\n    b(nonlinear_inequalities_indicies,:) = [];\n    A(:,nonlinearindicies) = [];\n    \n    model.F_struc(1:model.K.l,:) = [];\n    model.K.l = 0;\nelse\n    A = [];\n    b = [];\nend\n\n% This helps with robustness in bnb in some cases\nx0candidate = zeros(length(c),1);\nif ~isempty(lb) && ~isempty(ub)\n    bounded = find(~isinf(lb) & ~isinf(ub));\n    x0candidate(bounded) = (lb(bounded) + ub(bounded))/2;\n    bounded_below = find(~isinf(lb) & isinf(ub));\n    x0candidate(bounded_below) = lb(bounded_below) + 0.5;\n    bounded_above = find(~isinf(lb) & isinf(ub));\n    x0candidate(bounded_above) = lb(bounded_above) + 0.5;\nend\n\nif isempty(x0)\n    x0 = x0candidate(linearindicies);\nelse\n    if ~isempty(lb) && ~isempty(ub)\n        x0((x0 < lb) | (x0 > ub)) = x0candidate((x0 < lb) | (x0 > ub));\n    end\n    x0 = x0(linearindicies);\nend\n\nif ~isempty(lb)\n    lb = lb(linearindicies);\nend\nif ~isempty(ub)\n    ub = ub(linearindicies);\nend\n\nlb_old = lb;\nub_old = ub;\n[lb,ub,A,b] = remove_bounds_from_Ab(A,b,lb,ub);\n[lb,ub,Aeq,beq] = remove_bounds_from_Aeqbeq(Aeq,beq,lb,ub);\n\nif any(model.variabletype == 4)\n    problematic = find(any(model.monomtable(:,linearindicies) < 0 ,1));\n    if ~isempty(problematic)\n        problematic = problematic(find(x0(problematic)==0));\n        Oneisfeas = problematic(find(ub(problematic) > 1));\n        x0(Oneisfeas) = 1;\n    end\n    \n    problematic = find(any(model.monomtable(:,linearindicies)~=fix(model.monomtable(:,linearindicies)) ,1));\n    lb(problematic) = max(lb(problematic),0);\nend\nx0(find(lb==ub)) = lb(find(lb==ub));\n    \nif size(A,1) == 0\n    A = [];\nend\n\nif size(b,1) == 0\n    b = [];\nend\n\nif size(Aeq,1) == 0\n    Aeq = [];\nend\n\nif size(beq,1) == 0\n    beq = [];\nend\n\nif model.presolveequalities\n    if ~isempty(beq) &  (~model.equalitypresolved | ~(isequal(lb,lb_old) & isequal(ub,ub_old)))\n        % This helps when there are artificial variables introduced to model\n        % nonlinear operators such as log(2*x+1)\n        p.F_struc = [beq -Aeq];\n        p.K.f = size(beq,1);\n        p.lb = lb;\n        p.ub = ub;\n        p.variabletype = zeros(1,length(lb));\n        p.binary_variables = [];\n        p.integer_variables = [];\n        p = propagate_bounds_from_equalities(p);\n        lb = p.lb;\n        ub = p.ub;\n    end\nend\n\nmodel.A = A;\nmodel.b = b;\nmodel.Aeq = Aeq;\nmodel.beq = beq;\nmodel.lb = lb;\nmodel.ub = ub;\nmodel.x0 = x0;\n\nmodel = setup_fmincon_params(model);\n\n% Check if all derivatives are available\nmodel.derivative_available = 1;\nfor i = 1:length(model.evalMap)\n    if isempty(model.evalMap{i}.properties.derivative)\n        model.derivative_available = 0;\n        break\n    end\nend\n\n% Some precomputation of computational scheme for Jacobian\nallA = [model.Anonlineq;model.Anonlinineq];\nif anyCones(model.K)\n    allA = [allA;model.F_struc(startofSOCPCone(model.K):end,2:end)];\nend\nrequested = any(allA',2);\n[i,j] = find((model.deppattern(find(requested),:)));\nrequested(j) = 1;\nif ~isempty(model.evalMap)\n    % Recursive stuff is only possible if we have evaluation-based\n    % operators\n    model.Crecursivederivativeprecompute = precomputeDerivative(model,requested);\nend\n\n% Some precomputation of computational scheme for gradient\nrequested = model.c | any(model.Q,2);\n[i,j,k] = find((model.deppattern(find(requested),:)));\nrequested(j) = 1;\nmodel.frecursivederivativeprecompute = precomputeDerivative(model,requested);\n\n% Precomputed list of bilinear expressions, used in\n% apply_recursive_differentiation\nmodel = compile_bilinearslist(model);\nmodel = compile_quadraticslist(model);\n\nmodel.binary_variables  = find(ismember(linearindicies,model.binary_variables));\nmodel.integer_variables  = find(ismember(linearindicies,model.integer_variables));\nmodel.semicont_variables  = find(ismember(linearindicies,model.semicont_variables));\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/yalmip2nonlinearsolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2148637755828311}}
{"text": "classdef TestTransientAreasSegmentationModule\n    %TestTransientAreasSegmentationModule\n\n    properties (Constant)\n        filename = fullfile(mexopencv.root(),'test','balloon.jpg');\n    end\n\n    methods (Static)\n        function test_run\n            img = cv.imread(TestTransientAreasSegmentationModule.filename, 'Color',true);\n            sz = [size(img,2) size(img,1)];\n\n            retina = cv.Retina(sz);\n            retina.run(img);\n            magno = retina.getMagnoRAW();\n\n            seg = cv.TransientAreasSegmentationModule(sz);\n            seg.clearAllBuffers();\n            seg.run(magno);\n\n            sz = seg.getSize();\n            validateattributes(sz, {'numeric'}, {'vector', 'integer', 'numel',2});\n\n            transientAreas = seg.getSegmentationPicture();\n            validateattributes(transientAreas, {'uint8'}, {'size',[sz(2) sz(1)]});\n            transientAreas = logical(transientAreas);\n        end\n\n        function test_params\n            img = cv.imread(TestTransientAreasSegmentationModule.filename, 'Color',true);\n            seg = cv.TransientAreasSegmentationModule([size(img,2) size(img,1)]);\n\n            fname = [tempname() '.xml'];\n            cObj = onCleanup(@() TestTransientAreasSegmentationModule.deleteFile(fname));\n            seg.write(fname);\n            seg.setup(fname);\n\n            seg.setupParameters('LocalEnergyTemporalConstant',0.5);\n\n            str = seg.printSetup();\n            validateattributes(str, {'char'}, {'row', 'nonempty'});\n\n            params = seg.getParameters();\n            validateattributes(params, {'struct'}, {'scalar'});\n        end\n    end\n\n    %% helper functions\n    methods (Static)\n        function deleteFile(fname)\n            if exist(fname, 'file') == 2\n                delete(fname);\n            end\n        end\n    end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/test/unit_tests/TestTransientAreasSegmentationModule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21482608111446486}}
{"text": "function [obSlice,reflections] = mrReflectObl(obSlice,obSize,reflections,which,update)\n%\n%NAME:\t [obSlice,reflections] = mrReflectObl(obSlice,obSize,reflections,which,update)\n%AUTHOR:  Poirson \n%DATE:    08.09.96\n%HISTORY  11.08.96 SPG added bool update\n%BUGS:\n\nglobal obwin volslimin2 volslimax2;\n\nrow = obSize(1);\ncol = obSize(2);\n\nif which == 1\n\t% First entry tell us left/right flipping\n\treflections(1) = reflections(1) * (-1.0);\n\ttmp = fliplr(reshape(obSlice,row,col));\n\nelseif which == 2\n\t% Second entry tell us up/down flipping\n\treflections(2) = reflections(2) * (-1.0);\n\ttmp = flipud(reshape(obSlice,row,col));\nelse\n\tdisp('mrReflectObl: invalid case');\nend\n obSlice = tmp(:)';\n\nif (update == 1)\n figure(obwin);\n myShowImageVol(obSlice',obSize,max(obSlice)*get(volslimin2,'value'),max(obSlice)*get(volslimax2,'value'));\nend\n\nreturn\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/planes/mrReflectObl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21479363236859841}}
{"text": "close all;\nseqNames = {'14_14', '14_06', '14_20','13_29', '13_30', '13_31'};\njogTsteps = { [42:82], '', '', '', [165:185], [145:165]};\n\njobNames = {'SM+zDD+AnnealLin', 'SM+zDD', 'SM+cDD+AnnealLin', 'SM+cDD', 'Prior'};\njobIDs = [2134873 2134874 2134875 2134876 1515159];\n\nEXPORT_DIR = '/home/mhughes/git/BPARHMM-NEW/figs/Mocap6/';\ntaskID = 1;\n\njj =0;\nfor jobID = jobIDs( [1 end] );\n    jj = jj+1;\n    ss = 0;\n    for seqID = [1 5 6]\n        ss = ss + 1;\n        plotAlignedStateSeqSegment( jobID, taskID, seqNames{seqID}, jogTsteps{ seqID }  );\n        \n        fname = fullfile(EXPORT_DIR, sprintf('JogSegmentation_seq%d_%s', seqID, jobNames{jj}) );\n        export_fig( fname, '-eps');\n        fprintf( 'Exporting %s\\n', fname );\n    end\nend\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/experiments/Mocap6/MakePlots_Mocap6_JogSegmentation_AOAS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21455286627159745}}
{"text": "function bundle  =  readBDL(filename)\n% READBDL Read mesh(es) from a .bdl bundle file\n%\n% bundle  =  readBDL(filename)\n% \n% Input:\n%   filename  path to .bdl file\n% Outputs:\n%   bundle  struct containing mesh data\n\n  function mesh = readBDLMeshChunk(fp)\n  % read a mesh chunk from a file stream \n  %\n  % Usage:\n  %    mesh = readMeshChunk( fp)\n  %\n  % mesh fields: \n  % V  (required)  vertices\n  % F              faces\n  % col            colors\n  % baseColor      a single color for the whole mesh\n  % UV             uv coords\n          \n      magicID   = fread(fp, 1, 'uint32');\n          chunkSize = fread(fp, 1,  'int64');  \n          nV        = fread(fp, 1, 'uint32'); \n          nF        = fread(fp, 1, 'uint32');\n          nVperFace = fread(fp, 1, 'uint32'); \n          nCperPos  = fread(fp, 1, 'uint32'); \n          nCperUV   = fread(fp, 1, 'uint32'); \n          nCperCol  = fread(fp, 1, 'uint32'); \n          nCperNor  = fread(fp, 1, 'uint32'); \n          strip     = fread(fp, 1, 'uchar');\n          mesh.baseColor = fread(fp, 4, 'float32');\n      \n          mesh.V   = fread(fp, [nCperPos,nV],'float32');\n      mesh.V = mesh.V';\n          mesh.UV  = fread(fp, [nCperUV,nV], 'float32');\n      mesh.UV = mesh.V';\n          mesh.col = fread(fp, [nCperCol,nV],'float32');\n      mesh.col = mesh.col';\n          if nCperNor ~= 0 && nCperNor ~= 3 \n            error('nCperNor has to be 0 or 3')\n          end\n          if nCperNor == 3\n            mesh.nor = fread(fp, [nCperNor,nV],'float32');\n        mesh.nor = mesh.nor';\n          end\n          mesh.F = fread(fp,  [nVperFace,nF],'uint32');      \n          mesh.F = mesh.F+1; \n  end\n\n\n    \n  fp = fopen(filename,'r');\n  if fp == -1\n     error('could not open file')\n  end\n\n  chunk = 1;  \n  while ~feof(fp)\n     magicID = fread(fp,1,'uint32');\n     if feof(fp)\n        break\n     end\n     bck =  -sizeof('uint32');\n     fseek(fp, bck, 'cof');  \n     if magicID == 1\n    bundle.meshes{chunk} = readBDLMeshChunk(fp);\n    chunk = chunk+1;\n     else\n        chunkSize = fread(fp, 1, 'uint64');\n        fseek(fp, chunkSize, 'cof');\n     end\n  end\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/readBDL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2145528662715974}}
{"text": "\n% DEMHIGHFIVE1 Demonstration of hierarchical GP-LVM on walking and running data.\n%\n%\tDescription:\n%\n\n%\tCopyright (c) 2007 Neil D. Lawrence\n% \tdemHighFive1.m version 1.1\n\nif exist('diaryFile')\n    diary(diaryFile)\nend\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\nhsvargplvm_init;\n\n\n\ndataSetName = 'highFive';\ncapName = dataSetName;\ncapName(1) = upper(capName(1));\nexperimentNo = 1;\ndirSep = filesep;\nbaseDir = datasetsDirectory;\n\n\n%--- Load data\ntry\n    load([baseDir 'dem' dataSetName]);\ncatch\n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile');\n        skelA = acclaimReadSkel([baseDir 'mocap' dirSep 'cmu' dirSep '20' dirSep '20.asf']);\n        [YA, skelA] = acclaimLoadChannels([baseDir 'mocap' dirSep 'cmu' dirSep '20' dirSep '20_11.amc'], skelA);\n        seqInd = [50:4:113 114:155 156:4:size(YA, 1)];\n        YA = YA(seqInd, :);\n        %    YA(:, [4:end]) = asind(sind(YA(:, [4:end])));\n        skelB = acclaimReadSkel([baseDir 'mocap' dirSep 'cmu' dirSep '21' dirSep '21.asf']);\n        [YB, skelB] = acclaimLoadChannels([baseDir 'mocap' dirSep 'cmu' dirSep '21' dirSep '21_11.amc'], skelB);\n        YB = YB(seqInd, :);\n        %    YB(:, [4:end]) = asind(sind(YB(:, [4:end])));\n        save([baseDir 'dem' dataSetName], 'YA', 'YB', 'skelA', 'skelB', ...\n            'seqInd');\n    else\n        error(lasterr);\n    end\nend\n\nYall{1} = YA;\nYall{2} = YB;\nclear('YA','YB');\n\n%-- Set up model\nnumberOfDatasets = length(Yall);\nglobalOpt.indPoints = min(globalOpt.indPoints, size(Yall{1},1));\n\n%-- Load datasets\nfor i=1:numberOfDatasets\n    Y = Yall{i};\n    dims{i} = size(Y,2);\n    N{i} = size(Y,1);\n    indTr = globalOpt.indTr;\n    if indTr == -1\n        indTr = 1:N{i};\n    end\n    if ~exist('Yts')\n        indTs = setdiff(1:size(Y,1), indTr);\n        Yts{i} = Y(indTs,:);\n    end\n    Ytr{i} = Y(indTr,:);\n    \n    t{i} = linspace(0, 2*pi, size(Y, 1)+1)'; t{i} = t{i}(1:end-1, 1);\n    timeStampsTraining{i} = t{i}(indTr,1); %timeStampsTest = t(indTs,1);\nend\n\nfor i=2:numberOfDatasets\n    if N{i} ~= N{i-1}\n        error('The number of observations in each dataset must be the same!');\n    end\nend\n\n\n\nclear('Y')\n\n\n%%--- Optimise %%--------- TO FIX (from this point and below) (this is now taken from svargplvm)\noptions = svargplvmOptions(Ytr, globalOpt, labelsTrain);\n\n\n\nif ~isempty(globalOpt.dynamicsConstrainType)\n    for i=1:numberOfDatasets\n        % Set up dynamcis (i.e. back-constraints) model\n        optionsDyn{i}.type = 'vargpTime';\n        optionsDyn{i}.inverseWidth=30;\n        %   optionsDyn.vardistCovars = vardistCovarsMult;\n        optionsDyn{i}.initX = globalOpt.initX;\n        optionsDyn{i}.constrainType = globalOpt.dynamicsConstrainType;\n        \n        if exist('timeStampsTraining')\n            optionsDyn{i}.t = timeStampsTraining;\n        end\n        if exist('labelsTrain') && ~isempty(labelsTrain)\n            optionsDyn{i}.labels = labelsTrain;\n        end\n    end\nelse\n    optionsDyn= [];\nend\n\n\n\n\nmodel = svargplvmModelCreate(Ytr, globalOpt, options, optionsDyn);\nif exist('diaryFile')\n    model.diaryFile = diaryFile;\nend\n\nmodel.globalOpt = globalOpt;\nmodel.options = options;\n\n%%%% TEMP\nif exist('whiteVar')\n    model.dynamics.kern.comp{2}.variance = whiteVar;\nend\n%%%%\n\n% Force kernel computations\nparams = svargplvmExtractParam(model);\nmodel = svargplvmExpandParam(model, params);\n\n%%\n%fprintf('# Median of vardist. covars: %d \\n',median(median(model.vardist.covars)));\n%fprintf('# Min of vardist. covars: %d \\n',min(min(model.vardist.covars)));\n%fprintf('# Max of vardist. covars: %d \\n',max(max(model.vardist.covars)));\n\nif displayIters\n    model = svargplvmOptimiseModel(model);\nelse\n    model = svargplvmOptimiseModelNoDisplay(model);\nend\n\n%--------\n\n\n\n\n%%\ncolordef white\nax = hgplvmHierarchicalVisualise(model, visualiseNodes, [], [0.03 ...\n    0.5 0.03 0.03])\ntar = get(ax, 'cameratarget');\npos = get(ax, 'cameraposition');\nnewPos = tar + (rotationMatrix(0, -pi/8, 3*pi/2)*(pos - tar)')';\nset(ax, 'cameraposition', newPos)\nset(ax, 'xlim', [-20 25]);\nset(ax, 'ylim', [-15 8])\nset(ax, 'visible', 'off')\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "deepGP", "sha": "f72410a0fb354451f2bf58cfe247d2b5d3b08e58", "save_path": "github-repos/MATLAB/SheffieldML-deepGP", "path": "github-repos/MATLAB/SheffieldML-deepGP/deepGP-f72410a0fb354451f2bf58cfe247d2b5d3b08e58/deepGP/matlab/demHighFive1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2145528662715974}}
{"text": "function out = spm_run_factorial_design(job)\n% SPM job execution function - factorial design specification\n% Input:\n% job    - harvested job data structure (see matlabbatch help)\n% Output:\n% out    - struct variable containing the path of the saved SPM.mat\n%__________________________________________________________________________\n% Copyright (C) 2005-2014 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_run_factorial_design.m 7739 2019-12-02 14:00:18Z guillaume $\n\n%--------------------------------------------------------------------------\n% This function configures the design matrix (describing the general\n% linear model), data specification, and other parameters necessary for\n% the statistical analysis. These parameters are saved in a\n% configuration file (SPM.mat) in the current directory, and are\n% passed on to spm_spm.m (via the Estimate button) which estimates the\n% design. Inference on these estimated parameters is then handled by the \n% SPM results section.\n%\n% This function, that sets up the necessary SPM structures, has been\n% largely cannibalised from spm_spm_ui.m which we have retained for \n% developmental continuity.\n%\n% It has in common with spm_spm_ui.m its use of the I factor matrix,\n% the H,C,B,G design matrix partitions, the sF,sCFI,CFIforms,sCC,CCforms,\n% sGXcalc,sGloNorm,sGMsca option definition variables and use of the\n% functions spm_DesMtx.m, spm_meanby.m and spm_get_vc.m.\n%\n% It departs from spm_spm_ui.m in that it does not use the design\n% definition data structure D. Also, it uses the new SPM.factor field,\n% which for the case of full factorial designs, is used to automatically\n% generate contrasts testing for main effects and interactions.\n%\n% This function departs from spm_spm_ui.m in that it does not provide\n% the same menu of design options (these were hardcoded in D). Instead it\n% provides a number of options for simple designs (1) One-sample t-test,\n% (2) Two-sample t-test, (3) Paired t-test and (4) Multiple regression.\n% Two facilities are provided for specifying more complicated designs\n% (5) Full-factorial and (6) Flexible-factorial. These should be able to\n% specify all design options (and more) that were available in SPM2.\n% For each of these design types one can additionally specify regressors\n% using the `covariates' option.\n%\n% Options (5) and (6) differ in the efficiency (eg. number of key \n% strokes/button presses) with which a given design can be specified. For \n% example, one-way ANOVAs can be specified using either option, but (5) is \n% usually more efficient.\n%\n% Full-factorial designs\n% ______________________\n%\n% This option is best used when you wish to test for all main effects and\n% interactions in one-way, two-way or three-way ANOVAs.\n%\n% Design specification proceeds in 2 stages. Firstly, by creating new\n% factors and specifying the number of levels and name for each.\n% Nonsphericity, ANOVA-by-factor (for PET data) and scaling options (for\n% PET data) can also be specified at this stage. Secondly, scans are \n% assigned separately to each cell. This accomodates unbalanced designs.\n%\n% For example, if you wish to test for a main effect in the population\n% from which your subjects are drawn and have modelled that effect at the \n% first level using K basis functions (eg. K=3 informed basis functions) \n% you can use a one-way ANOVA with K-levels. Create a single factor with K\n% levels and then assign the data to each cell eg. canonical, temporal\n% derivative and dispersion derivative cells, where each cell is assigned\n% scans from multiple subjects.\n%\n% SPM will automatically generate the contrasts necessary to test for all\n% main effects and interactions.\n%\n% Flexible-factorial designs\n% __________________________\n%\n% In this option the design matrix is created a block at a time. You can\n% decide whether you wish each block to be a main effect or a (two-way)\n% interaction.\n%\n% This option is best used for one-way, two-way or three-way ANOVAs but \n% where you do not wish to test for all possible main effects and\n% interactions. This is perhaps most useful for PET where there is usually\n% not enough data to test for all possible effects. Or for 3-way ANOVAs\n% where you do not wish to test for all of the two-way interactions. A\n% typical example here would be a group-by-drug-by-task analysis where,\n% perhaps, only (i) group-by-drug or (ii) group-by-task interactions are\n% of interest. In this case it is only necessary to have two-blocks in the\n% design matrix - one for each interaction. The three-way interaction can\n% then be tested for using a contrast that computes the difference between\n% (i) and (ii).\n%\n% Design specification then proceeds in 3 stages. Firstly, factors are\n% created and names specified for each. Nonsphericity, ANOVA-by-factor and\n% scaling options can also be specified at this stage.\n%\n% Secondly, a list of scans is produced along with a factor matrix, I. \n% This is an nscan x 4 matrix of factor level indicators (see xX.I below).\n% The first factor must be 'replication' but the other factors can be\n% anything. Specification of I and the scan list can be achieved in one\n% of two ways (a) the 'Specify All' option allows I to be typed in at the\n% user interface or (more likely) loaded in from the matlab workspace. \n% All of the scans are then selected in one go. (b) the 'Subjects' option\n% allows you to enter scans a subject at a time. The corresponding\n% experimental conditions (ie. levels of factors) are entered at the same\n% time. SPM will then create the factor matrix I. This style of interface\n% is similar to that available in SPM2.\n%\n% Thirdly, the design matrix is built up a block at a time. Each block\n% can be a main effect or a (two-way) interaction.\n%\n%--------------------------------------------------------------------------\n%\n% Variables saved in the SPM stucture:\n%\n% xY.VY         - nScan x 1 struct array of memory mapped images\n%                 (see spm_vol for definition of the map structure)\n% xX            - structure describing design matrix\n% xX.I          - nScan x 4 matrix of factor level indicators\n%                 I(n,i) is the level of factor i corresponding to image n\n% xX.sF         - 1x4 cellstr containing the names of the four factors\n%                 xX.sF{i} is the name of factor i\n% xX.X          - design matrix\n% xX.xVi        - correlation constraints for non-spericity correction\n% xX.iH         - vector of H partition (condition effects) indices,\n%                 identifying columns of X corresponding to H\n% xX.iC         - vector of C partition (covariates of interest) indices\n% xX.iB         - vector of B partition (block effects) indices\n% xX.iG         - vector of G partition (nuisance variables) indices\n% xX.name       - p x 1 cellstr of effect names corresponding to columns\n%                 of the design matrix\n%\n% xC            - structure array of covariate details\n% xC(i).rc      - raw (as entered) i-th covariate\n% xC(i).rcname  - name of this covariate (string)\n% xC(i).c       - covariate as appears in design matrix (after any scaling,\n%                 centering of interactions)\n% xC(i).cname   - cellstr containing names for effects corresponding to\n%                 columns of xC(i).c\n% xC(i).iCC     - covariate centering option\n% xC(i).iCFI    - covariate by factor interaction option\n% xC(i).type    - covariate type: 1=interest, 2=nuisance, 3=global\n% xC(i).cols    - columns of design matrix corresponding to xC(i).c\n% xC(i).descrip - cellstr containing a description of the covariate\n%\n% xGX           - structure describing global options and values\n% xGX.iGXcalc   - global calculation option used\n% xGX.sGXcalc   - string describing global calculation used\n% xGX.rg        - raw globals (before scaling and such like)\n% xGX.iGMsca    - grand mean scaling option\n% xGX.sGMsca    - string describing grand mean scaling\n% xGX.GM        - value for grand mean (/proportional) scaling\n% xGX.gSF       - global scaling factor (applied to xGX.rg)\n% xGX.iGC       - global covariate centering option\n% xGX.sGC       - string describing global covariate centering option\n% xGX.gc        - center for global covariate\n% xGX.iGloNorm  - Global normalisation option\n% xGX.sGloNorm  - string describing global normalisation option\n%\n% xM            - structure describing masking options\n% xM.T          - Threshold masking value (-Inf=>None, real=>absolute,\n%                 complex=>proportional (i.e. times global))\n% xM.TH         - nScan x 1 vector of analysis thresholds, one per image\n% xM.I          - Implicit masking (0=>none, 1=>implicit zero/NaN mask)\n% xM.VM         - struct array of explicit mask images\n%                 (empty if no explicit masks)\n% xM.xs         - structure describing masking options\n%                 (format is same as for xsDes described below)\n%\n% xsDes         - structure of strings describing the design:\n%                 Fieldnames are essentially topic strings (use \"_\"'s for\n%                 spaces), and the field values should be strings or cellstr's\n%                 of information regarding that topic. spm_DesRep.m\n%                 uses this structure to produce a printed description\n%                 of the design, displaying the fieldnames (with \"_\"'s\n%                 converted to spaces) in bold as topics, with\n%                 the corresponding text to the right\n%\n%--------------------------------------------------------------------------\n\n%-Output directory\n%--------------------------------------------------------------------------\ncwd = pwd;\nd   = spm_file(job.dir{1},'cpath');\nif ~exist(d,'dir')\n    sts = mkdir(d);\n    if ~sts, error('Error creating output directory \"%s\".',d); end\nend\ncd(d);\n\n%-Ask about overwriting files from previous analyses...\n%--------------------------------------------------------------------------\nif exist(fullfile(job.dir{1},'SPM.mat'),'file')\n    str = { 'Current directory contains existing SPM file:',...\n        'Continuing will overwrite existing file!'};\n    if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename)\n        fprintf('%-40s: %30s\\n\\n',...\n            'Abort...   (existing SPM file)',spm('time'));\n        return\n    end\nend\n\n% If we've gotten to this point we're committed to overwriting files.\n% Delete them so we don't get stuck in spm_spm\n%--------------------------------------------------------------------------\nfiles = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n    '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n    '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n\nfor i=1:length(files)\n    j = spm_select('List',pwd,files{i});\n    for k=1:size(j,1)\n        spm_unlink(deblank(j(k,:)));\n    end\nend\n\n%-Option definitions\n%==========================================================================\n\n%-Generic factor names\n%--------------------------------------------------------------------------\nsF = {'sF1','sF2','sF3','sF4'};\n\n%-Covariate by factor interaction options\nsCFI = {'<none>';...                                        %-1\n    'with sF1';'with sF2';'with sF3';'with sF4';...         %-2:5\n    'with sF2 (within sF4)';'with sF3 (within sF4)'};       %-6,7\n\n%-DesMtx argument components for covariate by factor interaction options\n% (Used for CFI's Covariate Centering (CC), GMscale & Global normalisation)\n%--------------------------------------------------------------------------\nCFIforms = {'[]',   'C',    '{}';...                        %-1\n    'I(:,1)',       'FxC',  '{sF{1}}';...                   %-2\n    'I(:,2)',       'FxC',  '{sF{2}}';...                   %-3\n    'I(:,3)',       'FxC',  '{sF{3}}';...                   %-4\n    'I(:,4)',       'FxC',  '{sF{4}}';...                   %-5\n    'I(:,[4,2])',   'FxC',  '{sF{4},sF{2}}';...             %-6\n    'I(:,[4,3])',   'FxC',  '{sF{4},sF{3}}' };              %-7\n\n%-Centre (mean correction) options for covariates & globals            (CC)\n% (options 9-12 are for centering of global when using AnCova GloNorm) (GC)\n%--------------------------------------------------------------------------\nsCC = {'around overall mean';...                            %-1\n    'around sF1 means';...                                  %-2\n    'around sF2 means';...                                  %-3\n    'around sF3 means';...                                  %-4\n    'around sF4 means';...                                  %-5\n    'around sF2 (within sF4) means';...                     %-6\n    'around sF3 (within sF4) means';...                     %-7\n    '<no centering>';...                                    %-8\n    'around user specified value';...                       %-9\n    '(as implied by AnCova)';...                            %-10\n    'GM';...                                                %-11\n    '(redundant: not doing AnCova)'}';                      %-12\n\n%-DesMtx I forms for covariate centering options\n%--------------------------------------------------------------------------\nCCforms = {'ones(nScan,1)',CFIforms{2:end,1},''}';\n\n%-Global calculation options                                       (GXcalc)\n%--------------------------------------------------------------------------\nsGXcalc  = {'omit';...                                      %-1\n    'user specified';...                                    %-2\n    'mean voxel value (within per image fullmean/8 mask)'}; %-3\n\n%-Global normalization options                                    (GloNorm)\n%--------------------------------------------------------------------------\nsGloNorm = {'AnCova';...                                    %-1\n    'AnCova by sF1';...                                     %-2\n    'AnCova by sF2';...                                     %-3\n    'AnCova by sF3';...                                     %-4\n    'AnCova by sF4';...                                     %-5\n    'AnCova by sF2 (within sF4)';...                        %-6\n    'AnCova by sF3 (within sF4)';...                        %-7\n    'proportional scaling';...                              %-8\n    '<no global normalisation>'};                           %-9\n\n\n%-Grand mean scaling options                                        (GMsca)\n% (NB: Grand mean scaling by subject is redundent for proportional scaling)\n%--------------------------------------------------------------------------\nsGMsca = {'scaling of overall grand mean';...               %-1\n    'scaling of sF1 grand means';...                        %-2\n    'scaling of sF2 grand means';...                        %-3\n    'scaling of sF3 grand means';...                        %-4\n    'scaling of sF4 grand means';...                        %-5\n    'scaling of sF2 (within sF4) grand means';...           %-6\n    'scaling of sF3 (within sF4) grand means';...           %-7\n    '(implicit in PropSca global normalisation)';...        %-8\n    '<no grand Mean scaling>'   };                          %-9\n\n%-Conditions of no interest defaults\n%--------------------------------------------------------------------------\nB      = [];\nBnames = {};\nfactor = [];\n\nswitch char(fieldnames(job.des))\n    \n    %-One sample t-test\n    %======================================================================\n    case 't1',\n        \n        DesName = 'One sample t-test';\n\n        P = job.des.t1.scans;\n        n = length(P);\n        I = (1:n)';\n        I = [I,ones(n,3)];\n\n        [H,Hnames] = spm_DesMtx(I(:,2),'-','mean');\n\n        factor(1).name     = 'Group';\n        factor(1).levels   = 1;\n        factor(1).variance = 0;\n        factor(1).dept     = 0;\n        \n    %-Two-sample t-test\n    %======================================================================\n    case 't2',\n        \n        DesName = 'Two-sample t-test';\n\n        P  = job.des.t2.scans1;\n        n1 = length(job.des.t2.scans1);\n        P  = [P; job.des.t2.scans2];\n        n2 = length(job.des.t2.scans2);\n\n        I  = [(1:n1),(1:n2)]';\n        I  = [I,[ones(n1,1);2*ones(n2,1)]];\n        I  = [I,ones(n1+n2,2)];\n\n        [H,Hnames] = spm_DesMtx(I(:,2),'-','Group');\n\n        % Names and levels\n        factor(1).name     = 'Group';\n        factor(1).levels   = 2;\n\n        % Ancova options\n        factor(1).gmsca    = job.des.t2.gmsca;\n        factor(1).ancova   = job.des.t2.ancova;\n\n        % Nonsphericity options\n        factor(1).variance = job.des.t2.variance;\n        factor(1).dept     = job.des.t2.dept;\n\n        if any([n1 n2]==1) && factor(1).variance == 1\n            warning('Imposing equal variance between groups for 1 vs N comparison.');\n            factor(1).variance = 0;\n        end\n        \n    %-Paired t-test\n    %======================================================================\n    case 'pt',\n        \n        DesName = 'Paired t-test';\n\n        Npairs  = length(job.des.pt.pair);\n        P       = [];\n        for p   = 1:Npairs\n            P   = [P;job.des.pt.pair(p).scans];\n        end\n\n        I       = ones(Npairs*2,1);\n        I(:,2)  = kron([1:Npairs]',ones(2,1));\n        I(:,3)  = kron(ones(Npairs,1),[1 2]');\n        I(:,4)  = I(:,1);\n\n        [B,Bnames] = spm_DesMtx(I(:,2),'-','Subject');\n        [H,Hnames] = spm_DesMtx(I(:,3),'-','Condition');\n\n        % Names and levels\n        factor(1).name     = 'Subject';\n        factor(1).levels   = Npairs;\n        factor(2).name     = 'Condition';\n        factor(2).levels   = 2;\n\n        % Ancova options\n        factor(1).gmsca    = 0;\n        factor(1).ancova   = 0;\n        factor(2).gmsca    = job.des.pt.gmsca;\n        factor(2).ancova   = job.des.pt.ancova;\n\n        % Nonsphericity options\n        factor(1).variance = 0;\n        factor(1).dept     = 0;\n        factor(2).variance = 0;\n        factor(2).dept     = 0;\n\n    %-Multiple regression\n    %======================================================================\n    case 'mreg',\n        \n        DesName = 'Multiple regression';\n\n        P = job.des.mreg.scans;\n        n = length(P);\n        I = (1:n)';\n        I = [I,ones(n,3)];\n\n        % Names and levels\n        factor(1).name     = '';\n        factor(1).levels   = 1;\n\n        % Nonsphericity options\n        factor(1).variance = 0;\n        factor(1).dept     = 0;\n\n        if job.des.mreg.incint==0\n            H = []; Hnames = '';\n        else\n            [H,Hnames] = spm_DesMtx(I(:,2),'-','mean');\n        end\n\n        for i=1:length(job.des.mreg.mcov)\n            job.cov(end+1).c   = job.des.mreg.mcov(i).c;\n            job.cov(end).cname = job.des.mreg.mcov(i).cname;\n            job.cov(end).iCC   = job.des.mreg.mcov(i).iCC;\n            job.cov(end).iCFI  = 1;\n        end\n\n    %-ANOVA\n    %======================================================================\n    case 'anova',\n        \n        DesName = 'ANOVA';\n        \n        job.des.anova.fact.name = 'Groups';\n        \n        % Automatically number cells 1 to levels, so user doesn't have to\n        levels = length(job.des.anova.icell);\n        job.des.anova.fact.levels = levels;\n        for i=1:levels\n            job.des.anova.icell(i).levels = i;\n        end\n        [I,P,H,Hnames] = spm_design_factorial(job.des.anova);\n\n        \n        % Names and levels\n        factor(1).name     = 'Groups';\n        factor(1).levels   = levels;\n        \n        % Ancova options\n        factor(1).gmsca    = job.des.anova.gmsca;\n        factor(1).ancova   = job.des.anova.ancova;\n        \n        % Nonsphericity options\n        factor(1).variance = job.des.anova.variance;\n        factor(1).dept     = job.des.anova.dept;\n        \n    %-ANOVA: within-subject\n    %======================================================================\n    case 'anovaw',\n        \n        DesName = 'ANOVA - within subject';\n        \n        anovaw  = job.des.anovaw;\n        anovaw.fac(1).name      = 'Subject';\n        anovaw.fac(1).dept      = 0;\n        anovaw.fac(1).variance  = 0;\n        anovaw.fac(1).gmsca     = 0;\n        anovaw.fac(1).ancova    = 0;\n        \n        anovaw.fac(2).name      = 'Groups';\n        anovaw.fac(2).dept      = job.des.anovaw.dept;\n        anovaw.fac(2).variance  = job.des.anovaw.variance;\n        anovaw.fac(2).gmsca     = job.des.anovaw.gmsca;\n        anovaw.fac(2).ancova    = job.des.anovaw.ancova;\n        \n        anovaw.fsuball.fsubject = anovaw.fsubject;\n        \n        % Main effect of subject and group\n        anovaw.maininters{1}.fmain.fnum = 1;\n        anovaw.maininters{2}.fmain.fnum = 2;\n        \n        [I,P,job.cov] = spm_design_within_subject(anovaw,job.cov);\n            \n        [H,Hnames,B,Bnames] = spm_design_flexible(anovaw,I);\n        \n        factor           = anovaw.fac;\n        factor(1).levels = length(job.des.anovaw.fsubject);\n        \n    %-Full Factorial Design\n    %======================================================================\n    case 'fd',\n        \n        DesName = 'Full factorial';\n\n        [I,P,H,Hnames] = spm_design_factorial(job.des.fd);\n\n        Nfactors = length(job.des.fd.fact);\n        for i=1:Nfactors\n            % Names and levels\n            factor(i).name     = job.des.fd.fact(i).name;\n            factor(i).levels   = job.des.fd.fact(i).levels;\n\n            % Ancova options\n            factor(i).gmsca    = job.des.fd.fact(i).gmsca;\n            factor(i).ancova   = job.des.fd.fact(i).ancova;\n\n            % Nonsphericity options\n            factor(i).variance = job.des.fd.fact(i).variance;\n            factor(i).dept     = job.des.fd.fact(i).dept;\n        end\n        \n    %-Flexible factorial design\n    %======================================================================\n    case 'fblock',\n        \n        DesName = 'Flexible factorial';\n        \n        if isfield(job.des.fblock.fsuball,'fsubject')\n            % Data has been entered subject by subject\n            nf = length(job.des.fblock.fac);\n            [I,P,job.cov] = spm_design_within_subject(job.des.fblock,job.cov);\n        else\n            % Specify all scans and factor matrix\n            I = job.des.fblock.fsuball.specall.imatrix;\n            [ns,nI] = size(I);\n            % Pad out factorial matrix to cover the four canonical factors\n            if nI < 4\n                warning('Padding factor matrix to have four columns.');\n                I = [I, ones(ns,4-nI)];\n            end\n            % Get number of factors\n            nf = length(job.des.fblock.fac);\n            P  = job.des.fblock.fsuball.specall.scans;\n        end\n\n        if isempty(job.des.fblock.maininters)\n            warning('No main effects or interactions have been specified.');\n        end\n        [H,Hnames,B,Bnames] = spm_design_flexible(job.des.fblock,I);\n        \n        for i=1:nf\n            % Names and levels\n            factor(i).name     = job.des.fblock.fac(i).name;\n            factor(i).levels   = length(unique(I(:,i+1)));\n\n            % Ancova options\n            factor(i).gmsca    = job.des.fblock.fac(i).gmsca;\n            factor(i).ancova   = job.des.fblock.fac(i).ancova;\n\n            % Nonsphericity options\n            factor(i).variance = job.des.fblock.fac(i).variance;\n            factor(i).dept     = job.des.fblock.fac(i).dept;\n        end\n\nend\n\nnScan = size(I,1);\n\n\n%-Covariate partition(s): interest (C) & nuisance (G) excluding global\n%==========================================================================\ndstr = {'covariate','nuisance variable'};\nC  = []; Cnames = {};                 %-Covariate DesMtx partitions & names\nG  = []; Gnames = {};\n\nxC = [];                              %-Struct array to hold raw covariates\n\n%-Multiple covariates\n%--------------------------------------------------------------------------\nfor m=1:numel(job.multi_cov)\n    for n=1:numel(job.multi_cov(m).files)\n        tmp   = load(job.multi_cov(m).files{n});\n        names = {};\n        if isstruct(tmp) % .mat\n            if isfield(tmp,'R')\n                R = tmp.R;\n                if isfield(tmp,'names')\n                    names = tmp.names;\n                end\n            else\n                error(['Variable ''R'' not found in multiple ' ...\n                    'covariates file ''%s''.'], job.multi_cov(m).files{n});\n            end\n        elseif isnumeric(tmp) % .txt\n            R     = tmp;\n            % read names from first line if commented?\n        end\n        for j=1:size(R,2)\n            job.cov(end+1).c   = R(:,j);\n            if isempty(names)\n                job.cov(end).cname = sprintf('R%d%s',j);\n            else\n                job.cov(end).cname = names{j};\n            end\n            job.cov(end).iCFI  = job.multi_cov(m).iCFI;\n            job.cov(end).iCC   = job.multi_cov(m).iCC;\n        end\n    end\nend\n\n\n%-Covariates\n%--------------------------------------------------------------------------\nnc = length(job.cov);                 %-Number of covariates\nfor i=1:nc\n\n    c      = job.cov(i).c;\n    cname  = job.cov(i).cname;\n    rc     = c;                       %-Save covariate value\n    rcname = cname;                   %-Save covariate name\n    if job.cov(i).iCFI==1\n        iCFI=1;\n    else\n        % SPMs internal factor numbers are 1 higher than specified in user\n        % interface as, internally, the first factor is always `replication'\n        iCFI = job.cov(i).iCFI+1;\n    end\n    switch job.cov(i).iCC\n        case 1\n            iCC = 1;\n        case {2,3,4}\n            iCC = job.cov(i).iCC + 1;\n        otherwise\n            iCC = job.cov(i).iCC + 3;\n    end\n\n    %-Centre within factor levels as appropriate\n    if any(iCC == (1:7))\n        c = c - spm_meanby(c,eval(CCforms{iCC}));\n    end\n\n    %-Do any interaction (only for single covariate vectors)\n    %----------------------------------------------------------------------\n    if iCFI > 1                       %-(NB:iCFI=1 if size(c,2)>1)\n        tI        = [eval(CFIforms{iCFI,1}),c];\n        tConst    = CFIforms{iCFI,2};\n        tFnames   = [eval(CFIforms{iCFI,3}),{cname}];\n        [c,cname] = spm_DesMtx(tI,tConst,tFnames);\n    elseif size(c,2)>1                %-Design matrix block\n        [null,cname] = spm_DesMtx(c,'X',cname);\n    else\n        cname     = {cname};\n    end\n\n    %-Store raw covariate details in xC struct for reference\n    %-Pack c into appropriate DesMtx partition\n    %----------------------------------------------------------------------\n    %-Construct description string for covariate\n    str = {sprintf('%s',rcname)};\n    if size(rc,2)>1, str = {sprintf('%s (block of %d covariates)',...\n            str{:},size(rc,2))}; end\n    if iCC < 8, str=[str;{['used centered ',sCC{iCC}]}]; end\n    if iCFI> 1, str=[str;{['fitted as interaction ',sCFI{iCFI}]}]; end\n\n    typ = 1;\n    tmp = struct(...\n        'rc',   rc,    'rcname', rcname,...\n        'c',    c,     'cname',  {cname},...\n        'iCC',  iCC,   'iCFI',   iCFI,...\n        'type', typ,...\n        'cols', [1:size(c,2)] + size([H,C],2) + size([B,G],2)*min(typ-1,1),...\n        'descrip', {str});\n    if isempty(xC), xC = tmp; else xC = [xC,tmp]; end\n    C     = [C,c];\n    Cnames = [Cnames; cname];\n\nend\nclear c tI tConst tFnames\n\n\n%==========================================================================\n% - C O N F I G U R E   D E S I G N -\n%==========================================================================\n\n%-Images & image info: Map Y image files and check consistency of\n% dimensions and orientation / voxel size\n%==========================================================================\nfprintf('%-40s: ','Mapping files')                                      %-#\nVY    = spm_data_hdr_read(char(P));\n\n%-Check compatibility of images\n%--------------------------------------------------------------------------\nspm_check_orientations(VY);\n\nfprintf('%30s\\n','...done')                                             %-#\n\n\n%-Global values, scaling and global normalisation\n%==========================================================================\n%-Compute global values\n%--------------------------------------------------------------------------\nswitch char(fieldnames(job.globalc))\n    case 'g_omit',\n        iGXcalc = 1;\n    case 'g_user',\n        iGXcalc = 2;\n    case 'g_mean',\n        iGXcalc = 3;\nend\n\nswitch job.globalm.glonorm\n    case 1,\n        iGloNorm = 9;\n    case 2,\n        iGloNorm = 8;\n    case 3,\n        iGloNorm = 1;\nend\nif factor(1).levels > 1\n    % Override if factor-specific ANCOVA has been specified\n    for i=1:length(factor)\n        if factor(i).ancova\n            iGloNorm=i+2;\n        end\n    end\nend\n\n%-Analysis threshold mask\n%--------------------------------------------------------------------------\n%-Work out available options:\n% -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)\nM_T = -Inf;\nswitch char(fieldnames(job.masking.tm)),\n    case 'tma',\n        % Absolute\n        M_T = job.masking.tm.tma.athresh;\n    case 'tmr',\n        % Relative\n        M_T = job.masking.tm.tmr.rthresh*sqrt(-1);\n        % Need to force calculation of globals\n        if iGXcalc~=2, iGXcalc=3; end\n    case 'tm_none'\n        % None\n        M_T = -Inf;\nend\n\nif iGXcalc==1 && (any(iGloNorm == [1:5 8]) || ...\n        (factor(1).levels > 1 && any([factor.gmsca])))\n    % Over-ride omission of global calculation if we need it\n    disp(' ');\n    disp('SPM needs estimates of global activity.');\n    disp('But you have specified to omit this computation.');\n    disp('SPM has overridden this omission and will automatically compute ');\n    disp('globals as the mean value of within brain voxels.');\n    disp(' ');\n    iGXcalc = 3;\nend\nsGXcalc = sGXcalc{iGXcalc};\n\nswitch iGXcalc,\n    case 1\n        %-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)\n        g = [];\n    case 2\n        %-User specified globals\n        g = job.globalc.g_user.global_uval;\n    case 3\n        %-Compute as mean voxel value (within per image fullmean/8 mask)\n        g = zeros(nScan,1);\n        fprintf('%-40s: %30s','Calculating globals',' ')                %-#\n        for i = 1:nScan\n            str = sprintf('%3d/%-3d',i,nScan);\n            fprintf('%s%30s',repmat(sprintf('\\b'),1,30),str)            %-#\n            g(i) = spm_global(VY(i)); % FIXME % for meshes\n        end\n        fprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done')        %-#\n    otherwise\n        error('illegal iGXcalc')\nend\nrg = g;\n\nfprintf('%-40s: ','Design configuration')                               %-#\n\n%-Grand mean scaling options                                        (GMsca)\n%--------------------------------------------------------------------------\nif iGloNorm==8\n    iGMsca=8;   %-grand mean scaling implicit in PropSca GloNorm\nelse\n    switch char(fieldnames(job.globalm.gmsca))\n        case 'gmsca_yes',\n            iGMsca=1;\n        case 'gmsca_no',\n            iGMsca=9;\n    end\n    if factor(1).levels > 1\n        % Over-ride if factor-specific scaling has been specified\n        for i=1:numel(factor)\n            if factor(i).gmsca\n                iGMsca=i+2;\n            end\n        end\n    end\nend\n\n%-Value for PropSca / GMsca                                            (GM)\n%--------------------------------------------------------------------------\nswitch iGMsca,\n    case 9                                %-Not scaling (GMsca or PropSca)\n        GM = 0;                           %-Set GM to zero when not scaling\n    case 1                                %-Ask user value of GM\n        GM = job.globalm.gmsca.gmsca_yes.gmscv;\n    otherwise\n        if iGloNorm==8\n            switch char(fieldnames(job.globalm.gmsca))\n                case 'gmsca_yes',\n                    % Proportionally scale to this value\n                    GM = job.globalm.gmsca.gmsca_yes.gmscv;\n                case 'gmsca_no',\n                    GM = 50;\n            end\n        else\n            % Grand mean scaling by factor eg. scans are scaled so that the\n            % mean global value over each level of the factor is set to GM\n            GM=50;\n        end\nend\n\n%-If GM is zero then don't GMsca! or PropSca GloNorm\nif GM==0,\n    iGMsca=9;\n    if iGloNorm==8,\n        iGloNorm=9;\n    end\nend\n\n%-Sort out description strings for GloNorm and GMsca\n%--------------------------------------------------------------------------\nsGloNorm = sGloNorm{iGloNorm};\nsGMsca   = sGMsca{iGMsca};\nif iGloNorm==8\n    sGloNorm = sprintf('%s to %-4g',sGloNorm,GM);\nelseif iGMsca<8\n    sGMsca   = sprintf('%s to %-4g',sGMsca,GM);\nend\n\n%-Scaling: compute global scaling factors gSF required to implement\n% proportional scaling global normalisation (PropSca) or grand mean\n% scaling (GMsca), as specified by iGMsca (& iGloNorm)\n%--------------------------------------------------------------------------\nswitch iGMsca,\n    case 8\n        %-Proportional scaling global normalisation\n        if iGloNorm~=8, error('iGloNorm-iGMsca(8) mismatch for PropSca'), end\n        gSF    = GM./g;\n        g      = GM*ones(nScan,1);\n    case {1,2,3,4,5,6,7}\n        %-Grand mean scaling according to iGMsca\n        if iGXcalc==1, error('Global calculation option is not appropriate.'), end\n        gSF    = GM./spm_meanby(g,eval(CCforms{iGMsca}));\n        g      = g.*gSF;\n    case 9\n        %-No grand mean scaling\n        gSF    = ones(nScan,1);\n    otherwise\n        error('illegal iGMsca')\nend\n\n%-Apply gSF to memory-mapped scalefactors to implement scaling\n%--------------------------------------------------------------------------\nfor i = 1:nScan\n    VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*gSF(i); % FIXME % for meshes\nend\n\n%-Global centering (for AnCova GloNorm)                                (GC)\n%-If not doing AnCova then GC is irrelevant\n%--------------------------------------------------------------------------\nif ~any(iGloNorm == [1:7])\n    iGC = 12;\n    gc  = [];\nelse\n    iGC = 10;\n    gc = 0;\nend\n\n%-AnCova: Construct global nuisance covariates partition (if AnCova)\n%--------------------------------------------------------------------------\nif any(iGloNorm == [1:7])\n\n    %-Centre global covariate as requested\n    %----------------------------------------------------------------------\n    switch iGC, case {1,2,3,4,5,6,7}    %-Standard sCC options\n        gc = spm_meanby(g,eval(CCforms{iGC}));\n        case 8                  %-No centering\n            gc = 0;\n        case 9                  %-User specified centre\n            %-gc set above\n        case 10                 %-As implied by AnCova option\n            gc = spm_meanby(g,eval(CCforms{iGloNorm}));\n        case 11                 %-Around GM\n            gc = GM;\n        otherwise               %-unknown iGC\n            error('unexpected iGC value')\n    end\n\n    %-AnCova - add scaled centred global to DesMtx `G' partition\n    %----------------------------------------------------------------------\n    rcname     = 'global';\n    tI         = [eval(CFIforms{iGloNorm,1}),g - gc];\n    tConst     = CFIforms{iGloNorm,2};\n    tFnames    = [eval(CFIforms{iGloNorm,3}),{rcname}];\n    [f,gnames]  = spm_DesMtx(tI,tConst,tFnames);\n    clear tI tConst tFnames\n\n    %-Save GX info in xC struct for reference\n    %----------------------------------------------------------------------\n    str     = {sprintf('%s: %s',dstr{2},rcname)};\n    if any(iGMsca==[1:7]), str=[str;{['(after ',sGMsca,')']}]; end\n    if iGC ~= 8, str=[str;{['used centered ',sCC{iGC}]}]; end\n    if iGloNorm > 1\n        str=[str;{['fitted as interaction ',sCFI{iGloNorm}]}];\n    end\n    tmp  = struct(  'rc',rg.*gSF,       'rcname',rcname,...\n        'c',f,          'cname' ,{gnames},...\n        'iCC',iGC,      'iCFI'  ,iGloNorm,...\n        'type',         3,...\n        'cols',[1:size(f,2)] + size([H C B G],2),...\n        'descrip',      {str}       );\n\n    G = [G,f]; Gnames = [Gnames; gnames];\n    if isempty(xC), xC = tmp; else xC = [xC,tmp]; end\n\nelseif iGloNorm==8 || iGXcalc>1\n\n    %-Globals calculated, but not AnCova: Make a note of globals\n    %----------------------------------------------------------------------\n    if iGloNorm==8\n        str = { 'global values: (used for proportional scaling)';...\n            '(\"raw\" unscaled globals shown)'};\n    elseif isfinite(M_T) && ~isreal(M_T)\n        str = { 'global values: (used to compute analysis threshold)'};\n    else\n        str = { 'global values: (computed but not used)'};\n    end\n\n    rcname ='global';\n    tmp     = struct('rc',rg,    'rcname',rcname,...\n        'c',{[]},   'cname' ,{{}},...\n        'iCC',0,    'iCFI'  ,0,...\n        'type',     3,...\n        'cols',     {[]},...\n        'descrip',  {str}           );\n\n    if isempty(xC), xC = tmp; else xC = [xC,tmp]; end\nend\n\n%-Save info on global calculation in xGX structure\n%--------------------------------------------------------------------------\nxGX = struct(...\n    'iGXcalc', iGXcalc,  'sGXcalc', sGXcalc,  'rg',rg,...\n    'iGMsca',  iGMsca,   'sGMsca',  sGMsca,   'GM',GM,    'gSF',gSF,...\n    'iGC',     iGC,      'sGC',     sCC{iGC}, 'gc',gc,...\n    'iGloNorm',iGloNorm, 'sGloNorm',sGloNorm);\n\n%-Make a description string\n%--------------------------------------------------------------------------\nif isinf(M_T)\n    xsM.Analysis_threshold = 'None (-Inf)';\nelseif isreal(M_T)\n    xsM.Analysis_threshold = sprintf('images thresholded at %6g',M_T);\nelse\n    xsM.Analysis_threshold = sprintf(['images thresholded at %6g ',...\n        'times global'],imag(M_T));\nend\n\n%-Construct masking information structure and compute actual analysis\n% threshold using scaled globals (rg.*gSF)\n%--------------------------------------------------------------------------\nif isreal(M_T),\n    M_TH = M_T  * ones(nScan,1);    %-NB: -Inf is real\nelse\n    M_TH = imag(M_T) * (rg.*gSF);\nend\n\n%-Implicit masking: Ignore zero voxels in low data-types?\n%--------------------------------------------------------------------------\n% (Implicit mask is NaN in higher data-types.)\nif ~spm_type(VY(1).dt(1),'nanrep')\n    M_I = job.masking.im;  % Implicit mask ?\n    if M_I\n        xsM.Implicit_masking = 'Yes: zero''s treated as missing';\n    else\n        xsM.Implicit_masking = 'No';\n    end\nelse\n    M_I = 1;\n    xsM.Implicit_masking = 'Yes: NaN''s treated as missing';\nend\n\n%-Explicit masking\n%--------------------------------------------------------------------------\nif isempty(job.masking.em{:})\n    VM = [];\n    xsM.Explicit_masking = 'No';\nelse\n    VM = spm_data_hdr_read(char(job.masking.em));\n    xsM.Explicit_masking = 'Yes';\nend\n\nxM     = struct('T',M_T, 'TH',M_TH, 'I',M_I, 'VM',{VM}, 'xs',xsM);\n\n\n%-Construct full design matrix (X), parameter names and structure (xX)\n%==========================================================================\nX      = [H C B G];\ntmp    = cumsum([size(H,2), size(C,2), size(B,2), size(G,2)]);\nxX     = struct(...\n    'X',        X,...\n    'iH',       [1:size(H,2)],...\n    'iC',       [1:size(C,2)] + tmp(1),...\n    'iB',       [1:size(B,2)] + tmp(2),...\n    'iG',       [1:size(G,2)] + tmp(3),...\n    'name',     {[Hnames; Cnames; Bnames; Gnames]},...\n    'I',        I,...\n    'sF',       {sF});\n\n\n%-Design description (an nx2 cellstr) - for saving and display\n%==========================================================================\ntmp = {sprintf('%d condition, +%d covariate, +%d block, +%d nuisance',...\n    size(H,2),size(C,2),size(B,2),size(G,2));...\n    sprintf('%d total, having %d degrees of freedom',...\n    size(X,2),rank(X));...\n    sprintf('leaving %d degrees of freedom from %d images',...\n    size(X,1)-rank(X),size(X,1))};\nxsDes = struct('Design',    {DesName},...\n    'Global_calculation',   {sGXcalc},...\n    'Grand_mean_scaling',   {sGMsca},...\n    'Global_normalisation', {sGloNorm},...\n    'Parameters',           {tmp});\n\nfprintf('%30s\\n','...done')                                             %-#\n\n\n%-Generate error covariance components (non-sphericity)\n%==========================================================================\nVi          = spm_get_vc(I, factor);\n\n\n%-Assemble SPM structure\n%==========================================================================\nSPM.xY.P    = P;            % filenames\nSPM.xY.VY   = VY;           % mapped data\nSPM.nscan   = size(xX.X,1); % scan number\nSPM.xX      = xX;           % design structure\nSPM.xC      = xC;           % covariate structure\nSPM.xGX     = xGX;          % global structure\nSPM.xM      = xM;           % mask structure\nSPM.xsDes   = xsDes;        % description\nSPM.xVi.I   = I;            % factor matrix\nif numel(Vi) == 1\n    SPM.xVi.V  = Vi{1};     % non-sphericity matrix\nelse\n    SPM.xVi.Vi = Vi;        % non-sphericity variance components\nend\n\n%-Automatic contrast generation for 'Full factorial'\n%--------------------------------------------------------------------------\nif strcmp(char(fieldnames(job.des)),'fd') && job.des.fd.contrasts\n    SPM.factor = factor;\nend\n\n%-Save SPM.mat and set output argument\n%--------------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration')                           %-#\nfmt = spm_get_defaults('mat.format');\ns = whos('SPM');\nif s.bytes > 2147483647, fmt = '-v7.3'; end\nsave('SPM.mat', 'SPM', fmt);\nfprintf('%30s\\n','...SPM.mat saved')                                    %-#\n\nout.spmmat{1} = fullfile(pwd, 'SPM.mat');\n\n\n%-Display Design report\n%==========================================================================\nif ~spm('CmdLine') && ~isempty(spm_figure('FindWin','Graphics'))\n    fprintf('%-40s: ','Design reporting')                               %-#\n    fname     = cat(1,{SPM.xY.VY.fname}');\n    spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)\n    fprintf('%30s\\n','...done')                                         %-#\nend\n\nfprintf('%-40s: %30s\\n','Completed',spm('time'))                        %-#\n\n%-Change back directory\n%--------------------------------------------------------------------------\ncd(cwd);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_factorial_design.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2145055134810661}}
{"text": "function [struct_irf_record D_record gamma_record hd_record ETA_record IVcorrelation PofIVcorrelation beta_gibbs_reshuffle sigma_gibbs_reshuffle]=irfres_zeros_magn_correl_fevd_bayesian_stvol4(beta_gibbs, sigma_gibbs, It, Bu,betahat,sigmahat,IRFperiods,n,m,p,k,T,signrestable,signresperiods, relmagnrestable, relmagnresperiods, names, startdate, enddate, ShockwithInstrument, Ycycle, Xcycle, signreslabels, FEVDresperiods, FEVDrestable, data_exo, HD, const, exo, InstrumentforCorrel, IRFt, YincLags, Psi_gibbs, pref)\n%betahat = betahatcycle                                                                                                       irfres_zeros_magn_correl_fevd_bayesian_stvol4(beta_gibbs, sigma_gibbs, It, Bu,betahatcycle,sigmahatcycle,IRFperiods,n,m,p,k,T,signrestable,signresperiods, relmagnrestable, relmagnresperiods, namespostratining, startdateposttraining, enddate, strctident.ShockwithInstrument, Ycycle, Xcycle, signreslabels, FEVDresperiods, FEVDrestable,data_exo, HD, 0, exo, strctident.InstrumentforCorrel, IRFt, YincLags);\n%sigmahat = sigmahatcycle\n%names =namespostraining\n%startdate = startdateposttraining\n%ShockwithInstrument =  strctident.ShockwithInstrument\n%InstrumentforCorrel = strctident.InstrumentforCorrel\n\n% inputs:  - matrix 'betahat': OLS estimate for beta\n%          - matrix 'sigmahats': OLS estimate for sigma\n%          - integer 'IRFperiods': number of periods for IRFs\n%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'm': number of exogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n%          - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n%          - cell 'signrestable': table recording the sign restriction input from the user\n%          - cell 'signresperiods': table containing the periods corresponding to each restriction\n%          - string 'ShockwithInstrument' Name of the shock where the instrument belongs to\n% outputs: - cell 'struct_irf_record': record of the gibbs sampler draws for the orthogonalised IRFs\n%          - matrix 'D_record': record of the gibbs sampler draws for the structural matrix D\n%          - matrix 'gamma_record': record of the gibbs sampler draws for the structural disturbances variance-covariance matrix gamma\n%          - integer 'Qdraw': total number of draws of the Q matrix\n%          - integer 'Qsuccess': number of successful draws of the Q matrix\n\n\n\ntic\n\n%%Phase 1: Preliminary tasks\n\n%% draw from VAR posterior\n%sample beta and sigma from the VAR distribution centered around the OLS estimate\ninv_sigma_hat = inv(sigmahat); %invert sigmahat as it is frequently used afterwards\nAcc=It-Bu; %%number of minimum draws accepted\n\n\n%% Preliminiaries for sign restrictions\n% now identify all the periods concerned with restrictions\n% first expand the non-empty entries in signresperiods since they are only expressed in intervals: transform into list\n% for instance, translate [1 4] into [1 2 3 4]; I don't think this can done without a loop\ntemp=cell2mat(signresperiods(~cellfun(@isempty,signresperiods)));\nperiods=[];\nfor ii=1:size(temp,1)\n    periods=[periods temp(ii,1):temp(ii,2)];\nend\n% suppress duplicates and sort\nperiods=sort(unique(periods))';\n% count the total number of restriction periods (required for IRF matrix)\nnperiods=size(periods,1);\n\n% Identify the restriction matrices\n% create five cells, corresponding to the three possible restrictions:\n% one cell for sign restrictions, three cells for magnitude restrictions, one cell for zero restrictions\nScell=cell(1,n);\nMcell=cell(1,n);\nMlcell=cell(1,n);\nMucell=cell(1,n);\nZcell=cell(1,n);\n\n% Check if value and periods restrictions correspond to each other\nif sum(sum(~cellfun(@isempty,signresperiods) == ~cellfun(@isempty,signrestable))) == n^2\n    % All cells with sign restrictions also specify the horizon over which\n    % these are applied\nelse\n    disp('Warning: Value restrictions do not correspond to period restrictions one to one')\n    pause(1)\nend\n\n% loop over rows and columns of the period matrix\nfor ii=1:n\n    for jj=1:n\n        % if entry (ii,jj) of the period matrix and of the value matrix is not empty...\n        if ~isempty(signresperiods{ii,jj}) && ~isempty(signrestable{ii,jj})\n            % ... then there is a restriction over one (or several) periods\n            % loop overt those periods\n            for kk=signresperiods{ii,jj}(1,1):signresperiods{ii,jj}(1,2)\n                % identify the position of the considered period within the list of all periods (required to build the matrix)\n                position=find(periods==kk);\n                % now create the restriction matrix: this will depend on the type of restriction\n                % if it is a positive sign restriction...\n                if strcmp(signrestable{ii,jj},'+')\n                    % ... then input a 1 entry in the corresponding S matrix\n                    Scell{1,jj}=[Scell{1,jj};zeros(1,n*nperiods)];\n                    Scell{1,jj}(end,(position-1)*n+ii)=1;\n                    % if it is a negative sign restriction...\n                elseif strcmp(signrestable{ii,jj},'-')\n                    % ... then input a -1 entry in the corresponding S matrix\n                    Scell{1,jj}=[Scell{1,jj};zeros(1,n*nperiods)];\n                    Scell{1,jj}(end,(position-1)*n+ii)=-1;\n                    % if it is a zero restriction...\n                elseif strcmp(signrestable{ii,jj},'0')\n                    % ... then input a 1 entry in the corresponding Z matrix\n                    Zcell{1,jj}=[Zcell{1,jj};zeros(1,n*nperiods)];\n                    Zcell{1,jj}(end,(position-1)*n+ii)=1;\n                    % else, a non-empty entry being neither a sign nor a zero restriction has to be a magnitude restriction\n                else\n                    % fill the corresponding M matrices:\n                    % input a 1 in M\n                    Mcell{1,jj}=[Mcell{1,jj};zeros(1,n*nperiods)];\n                    Mcell{1,jj}(end,(position-1)*n+ii)=1;\n                    % input the lower value of the interval in Ml\n                    temp=str2num(signrestable{ii,jj});\n                    Mlcell{1,jj}=[Mlcell{1,jj};temp(1,1)];\n                    % input the upper value of the interval in Mu\n                    Mucell{1,jj}=[Mucell{1,jj};temp(1,2)];\n                end\n            end\n        end\n    end\nend\n\n%% Preliminaries for relative magnitude restrictions\n% now identify all the periods concerned with relative magnitude\n% restrictions\n% first expand the non-empty entries in magresperiods since they are only expressed in intervals: transform into list\n% for instance, translate [1 4] into [1 2 3 4];\ntemp=cell2mat(relmagnresperiods(~cellfun(@isempty,relmagnresperiods)));\nmperiods=[];\nfor ii=1:size(temp,1)\n    mperiods=[mperiods temp(ii,1):temp(ii,2)];\nend\n% suppress duplicates and sort\nmperiods=sort(unique(mperiods))';\n% count the total number of restriction periods (required for IRF matrix)\nrmperiods=size(periods,1);\n\n%create matrix entry for relative magnitude restrictions\n[r clm] = find(~cellfun('isempty',relmagnrestable));\n%2. Indentify which entry corresponds to the positive magnitude\n%restriction (which shock is supposed to have a larger impact on which\n%variable)\nnum_magres=length(r)/2; %number of relative magnitude restrictions\nIndextempL=double.empty;\nkk=1; %number of the restrictions\nIndextempS=double.empty;\nkk=1; %%number of restriction\n\nrowsS = [];\ncolumnsS = [];\nfor jj=1:num_magres %%loop over number of magnitude restrictions\n    strtemp = strcat('S',num2str(jj)); %%find entry in the table corresponding to the Stronger than restriction\n    Stronger = strcmp(relmagnrestable, strtemp);\n    [rowS columnS] = find(Stronger==1);\n    rowsS = [rowsS rowS];\n    columnsS = [columnsS columnS];\nend\n\nrowsW = [];\ncolumnsW = [];\nfor jj=1:num_magres\n    strtemp = strcat('W',num2str(jj));\n    Weaker = strcmp(relmagnrestable, strtemp);\n    [rowW columnW] = find(Weaker==1);\n    rowsW = [rowsW rowW];\n    columnsW = [columnsW columnW];\nend\n\n%% Preliminiaries for IV correlation restrictions\n%%load the instrument\nShockwithIV = find(contains(signreslabels,ShockwithInstrument)); %find index for the Shock with correlation restriction\n\n% check for correlation restrictions\nif isempty(ShockwithIV)%when there is no shock with an extra instrument\n    IVcorrelcheck=0; %there is noting to check\n    IVcorrelation=nan(Acc,1); %empty vector such that the paralel loop doesnt crash\n    IVcorrel=nan(T,1); %empty vector such that the paralel loop doesnt crash\n    PofIVcorrelation=nan(Acc,1); %empty vector such that the paralel loop doesnt crash\n    ETA_record=nan(Acc,1); %empty vector such that the paralel loop doesnt crash\n    IVcorrel='noexist'; %empty vector such that the paralel loop doesnt crash\n    OverlapIVcorrelinY='noexist';%empty vector such that the paralel loop doesnt crash\n    Flipcorrel=0; %there is nothing to flip\nelse\n    IVcorrelcheck=1;\nend\nif IVcorrelcheck==1\n    [IVcorrel txtcorrel]=xlsread(pref.excelFile,'IV');\n    \n    Index = strcmp(txtcorrel(1,:), InstrumentforCorrel);           %find the instrument in the IV sheet\n    IVnum = find(Index==1, 1, 'first')-1;\n    IVcorrel = IVcorrel(:, IVnum);\n    IVcorrel = IVcorrel(~isnan(IVcorrel));\n    txtcorrel = txtcorrel(2:length(IVcorrel)+1,1);              % drop IV names from txt\n    date = names(2:end,1);                                   %get the datevector of the VAR\n    startlocationY_in_Y=find(strcmp(date,startdate));        %location of sample startdate in Y datevector\n    endlocationY_in_Y=find(strcmp(date,enddate));            %location of sample enddate in Y datevector\n    date = date(startlocationY_in_Y+p:endlocationY_in_Y,:);  %cut datevector of Y such that it corresponds to the time dates used in the VAR\n    OverlapIVcorrelinY = ismember(date,txtcorrel);           %Use this to cut EPS\n    OverlapYinIVcorrel = ismember(txtcorrel,date);           %Use this to cut IV\n    IVcorrel = IVcorrel(OverlapYinIVcorrel,:);               %cut all the entries from IV that are not in the sample\nend\n\nIsNotIdentified = find(contains(signreslabels,'shock'));        %find not identified shock\nIsIdentified = find(~contains(signreslabels,'shock'));    %\nif min(IsNotIdentified)==0\n    identified=n;\nelse\n    identified=min(IsNotIdentified)-1;                              %number of identified shocks\nend\n\n%finally check if there are sign restrictions on the shock of interest. If\n%not we can use the flipped entry of the rotation matrix aswell\nif ~isempty(ShockwithIV)\n    if isempty(Scell{1,ShockwithIV})\n        FlipCorrel=1;\n    else\n        FlipCorrel=0;\n    end\nend\n\n\n%% Preliminaries for FEVD restriction\n% now identify all the periods concerned with FEVD restrictions\n% first expand the non-empty entries in FEVDresperiods since they are only expressed in intervals: transform into list\n% for instance, translate [1 4] into [1 2 3 4];\ntemp=cell2mat(FEVDresperiods(~cellfun(@isempty,FEVDresperiods)));\nFEVDperiods=[];\nfor ii=1:size(temp,1)\n    FEVDperiods=[FEVDperiods temp(ii,1):temp(ii,2)];\nend\n% suppress duplicates and sort\nFEVDperiods=sort(unique(FEVDperiods))';\n% count the total number of restriction periods (required for IRF matrix)\nFEVDperiodstot=size(FEVDperiods,1);\n\n%create matrix entry for relative magnitude restrictions\n[rowsFEVD clmFEVD] = find(~cellfun('isempty',FEVDrestable));\nnum_FEVDres=length(rowsFEVD); %number of FEVD restrictions\n\n%check if rows are unique. Two FEVD restrictions for one variable are not\n%included in the algorithm. Two columns (shocks) are fine.\nuniquerows = unique(rowsFEVD);\n\nif length(uniquerows) < length(rowsFEVD)\n    error('Two FEVD restrictions for one variable are not permitted')\nend\n\n\n%now identify if the FEVD restrictions are absolute ones or relative ones\nnumrelativeFEVD =0;\nnumabsoluteFEVD =0;\nfor kk=1:num_FEVDres\n    if strcmp(FEVDrestable{rowsFEVD(kk,1),clmFEVD(kk,1)},'Relative')==1\n        numrelativeFEVD=numrelativeFEVD+1;\n        rowrelativeFEVD(kk,1)=rowsFEVD(kk,1); %rows are the variables for the FEVD\n        clmrelativeFEVD(kk,1)=clmFEVD(kk,1);%Columns are the variables for the FEVD\n    elseif strcmp(FEVDrestable{rowsFEVD(kk,1),clmFEVD(kk,1)},'Absolute')==1\n        numabsoluteFEVD=numabsoluteFEVD+1;\n        rowabsoluteFEVD(kk,1)=rowsFEVD(kk,1);%rows are the variables for the FEVD\n        clmabsoluteFEVD(kk,1)=clmFEVD(kk,1); %Columns are the variables for the FEVD\n    end\nend\n\n%if no restriction of one kind exist,set empty cells\nif numabsoluteFEVD ==0\n    rowabsoluteFEVD = [];\n    clmabsoluteFEVD = [];\nend\n\nif numrelativeFEVD ==0\n    rowrelativeFEVD = [];\n    clmrelativeFEVD = [];\nend\n\n\n%% preliminaries for historical decomposition\ncontributors = n + 1 + 1 + length(exo); %variables + constant + exogenous + initial conditions\nhd_estimates2=cell(contributors+2,n); %shocks+constant+initial values+exogenous+unexplained+to be explained by shocks only\n\n%% Check kind of restrictions\n% now check what kind of restrictions apply among sign, zero and magnitude restrictions\n% check for sign restrictions: if there are any, at least one entry in the cell Scell is non-empty\nif sum(~cellfun(@isempty,Scell))~=0\n    signres=1;\nelse\n    signres=0;\nend\n% similarly check for zero restrictions\nif sum(~cellfun(@isempty,Zcell))~=0\n    zerores=1;\nelse\n    zerores=0;\nend\n% check for absolute magnitude restrictions\nif sum(~cellfun(@isempty,Mcell))~=0\n    magnres=1;\nelse\n    magnres=0;\nend\n% check for relative magnitude restrictions\nif length(columnsS)~=0\n    relmagnres=1;\nelse\n    relmagnres=0;\nend\n% check for correlation restrictions\nif isempty(ShockwithIV)%when there is no shock with an extra instrument\n    IVcorrelcheck=0;\nelse\n    IVcorrelcheck=1;\nend\n% check for FEVD restrictions\nif numabsoluteFEVD ==0 && numrelativeFEVD==0 %when there are no absolute and no relative FEVD restrictions\n    FEVDcheck=0;\nelse\n    FEVDcheck=0;\nend\n\n%%Activate the restriction, that unidentified shocks should not have the\n%%same pattern as identified\npatterncheck=0;\n%%activate the possibility of absolute relative magnitude restriction\n%%(i.e. credit spreads should rise by more than interest rates fall)\n%%--> abs(credit spread) > abs(interes rate) instead of\n%%--> credit spread>interest rate\nABS=0;\n\n%% Storage cells\n% create first the cell that will store the results from the simulations\nstruct_irf_record=cell(n,n);\n% storage cell\nstorage1=cell(Acc,1);\nstorage2=cell(Acc,1);\nstorage3=cell(Acc,1);\nstorage4=cell(Acc,1);\nIn= eye(n);\n\n% initiate rotation draws\nnot_successful = 0;\nhbar = bear.parfor_progressbar(Acc,'Progress of Sign, Magnitude, Zero, Correlation and FEVD Restriction Draws');  %create the progress bar\n\n%rearrange Psidraw such that it can be accessed in a parfor loop\nfor yyy=1:It-Bu\n    for kkk=1:n \nPsi_gibbs_new(:,kkk,yyy) = Psi_gibbs{1,kkk}(:,yyy);\n    end\nend \n\nparfor ii=1:Acc\n    % initiate the variable 'success'; this variable will be used to check whether the restrictions are satisfied\n    % if there are only zero restrictions, they will be satisfied by construction, and 'success' will simply be ignored\n    success=0;\n    % how the algorithm will be conducted will depend on the types of restrictions implemented\n    % if there are only zero restrictions, the algorithm is simple as no checking is required: the conditions are satisfied by construction\n   if zerores==1 && signres==0 && magnres==0 && relmagnres==0\n   % draw beta and sigma\n   beta=beta_gibbs(:,ii);\n   sigma=reshape(sigma_gibbs(:,ii),n,n);\n   hsigma=chol(bear.nspd(sigma),'lower');\n   % obtain orthogonalised IRFs\n   [~, ortirfmatrix]=bear.irfsim(beta,hsigma,n,m,p,k,max(IRFperiods,max(periods)));\n   % generate the stacked IRF matrix\n   stackedirfmat=[];\n      for kk=1:numel(periods)\n      stackedirfmat=[stackedirfmat;ortirfmatrix(:,:,periods(kk,1)+1)];\n      end\n   % draw an entire random matrix Q satisfying the zero restrictions\n   [Q]=bear.qzerores(n,Zcell,stackedirfmat);\n   % there is no need to verify the restrictions: there are satisfied by construction\n\n\n\n   % if there are sign/magnitude/correlation restrictions, possibly associated with zero restrictions\n   else\n        % the algorithm becomes a bit more complicated as conditions now need to be checked\n        % to maintain efficiency, the algorithm proceeds recursively shock by shock, and stops as soon as a condition on the considered shock fails\n        % repeat algorithm for the iteration as long as not all conditions are satisfied\n        while success==0\n            not_successful = not_successful+1;\n            % switch 'success' to 1; it will be turned back to zero if at any time Q is detected as a candidate not satisfying the restrictions\n            success=1;\n            % draw randomly the vector of VAR coefficients: draw a random index\n            index=floor(rand*(Acc))+1;\n            % then draw a random set of beta and sigma corresponding to this index (this is done to make it possible to draw, if required, an infinite number of values from the gibbs sampler record, with equal probability on each value)\n            beta=beta_gibbs(:,index);\n            sigma=reshape(sigma_gibbs(:,index),n,n);\n            hsigma=chol(bear.nspd(sigma),'lower');\n            %also draw the corresponding local mean\n            Psidraw = Psi_gibbs_new(:,:,index)\n            %create the vector Ydraw by subtracting the local mean from the data\n            Ypsi = YincLags(p+1:end,:)-Psidraw(p+1:end,:);\n            %ultimately create the RHS and LHS of the demeaned data VAR\n            temp=bear.lagx(Ypsi,p);\n            % to build X, take off the n initial columns of current data\n            Xdraw=[temp(:,n+1:end)];\n            Ydraw=temp(:,1:n);\n            % obtain orthogonalised IRFs\n            [~, ortirfmatrix]=bear.irfsim(beta,hsigma,n,m,p,k,max(IRFperiods,max(periods)));\n            % generate the stacked IRF matrix\n            stackedirfmat=[];\n            for kk=1:numel(periods)\n                stackedirfmat=[stackedirfmat;ortirfmatrix(:,:,periods(kk,1)+1)];\n            end\n            \n            % now start looping over the shocks and checking sequentially whether conditions on these shocks hold\n            % stop as soon as one restriction fails\n            okay = zeros(n,1); %initiate okay vector\n            Qjstore = [];\n            % initiate Qj\n            Qj=[];\n            jj=1;\n            while success==1 && jj<=n && sum(okay)<n\n                    % draw a random vector from the standard normal\n                    if okay(1,1)==0 %first find the first column\n                        qj=bear.qrandj(n,Zcell{1,jj},stackedirfmat,Qj);\n                        % obtain the candidate column fj\n                        fj=stackedirfmat*qj;\n                        [success qj]=bear.checksignres(Scell{1,jj},qj,fj);\n                        if success==1\n                            Qjstore=[Qj qj];\n                            Qj(:,1) = qj; %set column yy of Qj to qj\n                            jj=1+1;\n                            okay(1,1)=1;\n                        end\n                    else\n                        x=normrnd(0,1,n,1);\n                        qj=(In-Qjstore*Qjstore')*x/norm((In-Qjstore*Qjstore')*x);\n                        %compute the rotated impulse responses\n                        fj=stackedirfmat*qj;\n                        [success, qj, okay, yy]=bear.checksignres_inc_other_shocks(qj, fj, Scell, okay, IRFt, n);\n                        if success==1\n                            Qjstore=[Qj qj];\n                            Qj(:,yy) = qj; %set column yy of Qj to qj\n                            jj=jj+1;\n                        end\n                    end\n\n            \n            %once all n columns are build and fullfill the sign restriction\n            %% if sign and magnitude restrictions are fullfilled, check proxy correlation restriction\n            if size(Qj,2)==n && success==1  && IVcorrelcheck==1\n                %disp('I reached correlation restrictions')\n                D=hsigma*Qj;\n                % recover the VAR coefficients, reshaped for convenience\n                B=reshape(beta,k,n);\n                % obtain the residuals from (this draw)\n                EPS=Ydraw-Xdraw*B;\n                %compute structural shocks\n                ETA=D\\EPS';\n                [success corIV pivShockwithIV Qj] = bear.CheckCorrelWithIV(ETA,n,ShockwithIV, IVcorrel,OverlapIVcorrelinY, FlipCorrel, Qj);\n                if success==1\n                    disp('correlation restriction fulfilled');\n                end\n            end\n            %% check relative magnitudes\n            if size(Qj,2)==n && success==1  && relmagnres==1\n                %              disp('I reached magnitude restrictions')\n                D=hsigma*Qj;\n                [~, ortirfmatrixmagnitude]=bear.irfsim(beta,D,n,m,p,k,max(IRFperiods,max(mperiods)));\n                % generate the stacked IRF matrix\n                stackedirfmatmagn=[];\n                for kk=1:numel(mperiods)\n                    stackedirfmatmagn=[stackedirfmatmagn;ortirfmatrixmagnitude(:,:,mperiods(kk,1)+1)];\n                end\n                [success]=bear.checkrelmag(stackedirfmatmagn,columnsS, columnsW, rowsS, rowsW, n, mperiods, ABS);\n                if success ==1\n                    disp('Magnitude Restrictions fullfilled')\n                end\n            end\n            \n            %% if sign, zero and relative magnitude restrictions are fullfilled, check FEVD restrictions\n            if size(Qj,2)==n && success==1  && FEVDcheck==1\n                disp('I reached FEVD restrictions')\n                D=hsigma*Qj; %again compute D\n                [~,ortirfmatrixFEVD]=bear.irfsim(beta,D,n,m,p,k,IRFperiods); %obtain orthogonalized IRFs\n                % record the results in the cell irf_record\n                %check FEVDrestrictions\n                [success] = bear.CheckFEVDrestriction(ortirfmatrixFEVD,IRFperiods,n,D,FEVDperiodstot, clmrelativeFEVD, rowrelativeFEVD, rowabsoluteFEVD, clmabsoluteFEVD, FEVDresperiods, rowsFEVD);\n                if success==1\n                    disp('FEVD restriction fulfilled');\n                end\n            end\n            \n            end \n            %finally compute the historical decomposition\n            if size(Qj,2)==n && success==1  && HD==1\n                D=hsigma*Qj;\n                B=reshape(beta,k,n);\n                % obtain the residuals from (this draw)\n                EPS=Ydraw-Xdraw*B;\n                %compute structural shocks\n                ETA=D\\EPS';\n                Psidrawcut = Psidraw(2*p:end,:);\n                %decompose the data into trend and cycle and further\n                [hd_estimates] = bear.hd_new_for_signres_stvol4(0,beta,k,n,p,D,m,T,Xdraw,Ydraw, data_exo, contributors, hd_estimates2, Psidrawcut, YincLags(2*p+1:end,:));\n            end\n            % repeat this loop until a succesful draw is obtained\n\n        end %end of while loop \u00b4\n        % with succesful Qj at hand, eventually set Q as Qj\n        Q=Qj;\n   end %end of if loop\n    % store\n    for kk=1:IRFperiods\n        storage1{ii,1}(:,:,kk)=ortirfmatrix(:,:,kk)*Q;\n    end\n    storage2{ii,1}=hsigma*Q;\n    % store historical decompositions\n    if HD==1\n        storage3{ii,1}=hd_estimates;\n        storage4{ii,1}=ETA;\n    end\n    storage5(:,ii) = beta;\n    storage6(:,ii) = bear.vec(sigma);\n\n    %lpdf = irfpdf(hsigma*Q,betahat,aux1,T,sigmahat,beta);\n    %lpdfirf(ii,1)=lpdf;\n    if IVcorrelcheck==1\n        IVcorrelation(ii,1)=corIV;\n        PofIVcorrelation(ii,1)=pivShockwithIV;\n    else \n        IVcorrelation(ii,1)=0;\n        PofIVcorrelation(ii,1)=0;\n    end\n    %  FEVDrestrictionvalue(ii,1) = FEVDrestrictionvalue;\n    hbar.iterate(1);   % update progress by one iteration\nend\nclose(hbar);   %close progress bar\n\n\nbeta_gibbs_reshuffle = storage5; %save the reshuffled beta and sigma such that they correspond to the structural matrix D\nsigma_gibbs_reshuffle = storage6;\n% reorganise storage\n% loop over iterations\nfor ii=1:Acc\n    % loop over IRF periods\n    for jj=1:IRFperiods\n        % loop over variables\n        for kk=1:n\n            % loop over shocks\n            for ll=1:n\n                struct_irf_record{kk,ll}(ii,jj)=storage1{ii,1}(kk,ll,jj);\n            end\n        end\n    end\n    D_record(:,ii)=storage2{ii,1}(:);\n    gamma_record(:,ii)=bear.vec(eye(n));\nend\n%reorganize historical decompositions\nhd_record=cell(contributors+2,n);\nif HD==1\n    for ii=1:Acc %loop over draws\n        for kk=1:contributors+2 %loop over contributors\n            for ll=1:n %loop over variables\n                hd_record{kk,ll}(ii,:) = storage3{ii,1}{kk,ll};\n            end\n        end\n    end\nend\nETA_record=cell(n,1);\nif HD==1\n    for jj=1:Acc\n        for kk=1:n\n            ETA_record{kk,1}(jj,:)= storage4{jj,1}(kk,:);\n        end\n    end\nend\n\n%hdrecord is ordered such that columns are variables and rows are contributors\n%row n+1 = contribution of the constant\n%row n+2 = contribution of initial conditions (past shocks)\n%row n+3 = unexplained part (for partially identified model\n%row n+4 = part that was left to explain by the structural shocks after\n%accounting for exogenous, constant and initial conditions\n\ntoc\nfprintf('Accepted Draws in Percent of Total Number of Draws: %f', 100*(Acc)/(not_successful + Acc))\nend\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/unreachableCode_ToRemove/irfres_zeros_magn_correl_fevd_bayesian_stvol4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.2144987729845691}}
{"text": "clear all; close all;\n\naddpath('../matlab/');\n\nmodel_root_dir = 'DSC_removal_SDR/';\ndefinition_file = [model_root_dir 'deploy.prototxt'];\nbinary_file = [model_root_dir 'snapshot/' 'DSC_iter_160000_lab.caffemodel'];\n\nassert(exist(binary_file, 'file') ~= 0);\nassert(exist(definition_file, 'file') ~= 0);\n\ncaffe.reset_all();\n\ncaffe.set_mode_gpu();\ncaffe.set_device(0);\n\n% Initialize a network\nnet = caffe.Net(definition_file, binary_file, 'test');\n\n%root_dir = '/home/xwhu/dataset/SRD/train_argu/shadow/';\n% root_dir = '/home/xwhu/dataset/ISTD/train_argu/train_A/';\n%imgFiles=dir([root_dir '*.jpg']);\n\nroot_dir = '/home/xwhu/dataset/SRD/test_data/shadow/';\nimage_list=textread('../../data/SRD/test.txt', '%s');\n%root_dir = '/home/xwhu/dataset/ISTD/test/test_A/';\n%image_list=textread('../../data/ISTD/test.txt', '%s');\n\n\nsave_root = [model_root_dir 'result/'];\n\nif exist(save_root, 'dir') == 0\n    mkdir(save_root);\nend\n\n%nImg=length(imgFiles);\nnImg=length(image_list);\n\nimgW = 400; imgH = 400;\nscale = 0.0039212686;\n\nusedtime = 0;\nshow = 0;\n\ncolorTransform = makecform('srgb2lab');\ncolorTransform2 = makecform('lab2srgb');\n\nfor k = 1 : nImg\n    \n    test_image = imread([root_dir image_list{k}]);\n    %test_image = imread([root_dir imgFiles(k).name]);\n    \n    test_image = applycform(test_image, colorTransform);\n    \n    if (show)\n        imshow(test_image);\n    end\n    \n    ori_size = [size(test_image,1), size(test_image,2)];\n    test_image = imresize(test_image,[imgH imgW]);\n    test_image = single(test_image(:,:,[3 2 1]));\n    test_image = test_image.*scale;\n    test_image = permute(test_image, [2 1 3]);\n    \n    % network forward\n    tic; outputs = net.forward({test_image}); pertime=toc;\n    usedtime=usedtime+pertime; avgtime=usedtime/k;\n    \n    res_fuse = net.blobs('upscore-fuse').get_data();\n    res_global = net.blobs('res_g').get_data();\n    final = (res_fuse + res_global)./2;\n\n    \n    final = permute(final, [2 1 3]);\n    final = final./scale;\n    final = uint8(final(:,:,[3 2 1]));\n    final = imresize(final, ori_size);\n    \n    final = applycform(final, colorTransform2);\n    \n    %imwrite(final,[save_root imgFiles(k).name]);\n    imwrite(final,[save_root image_list{k}]);\n    \n    \n    if (mod(k,100)==0), fprintf('idx %i/%i, avgtime=%.4fs\\n',k,nImg,avgtime); end\n    \nend\n\nfprintf('idx %i/%i, avgtime=%.4fs\\n',k,nImg,avgtime);\n", "meta": {"author": "xw-hu", "repo": "DSC", "sha": "0cc0c76411f47c31c909e7b0e6af1f10e11977af", "save_path": "github-repos/MATLAB/xw-hu-DSC", "path": "github-repos/MATLAB/xw-hu-DSC/DSC-0cc0c76411f47c31c909e7b0e6af1f10e11977af/examples/DSC/test_removal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2144844865926637}}
{"text": "function output = bnb_solvelower(lowersolver,relaxed_p,upper,lower,x_min,allSolutions)\n\nif all(relaxed_p.lb==relaxed_p.ub)\n    x = relaxed_p.lb;\n    if checkfeasiblefast(relaxed_p,relaxed_p.lb,relaxed_p.options.bnb.feastol)\n        output.problem = 0;\n    else\n        output.problem = 24;\n    end\n    output.Primal = x;\n    return\nend\n\nif ~(relaxed_p.all_integers && all(relaxed_p.c == fix(relaxed_p.c)) && nnz(relaxed_p.Q)==0)\n     % Objective contains floating-point numbers, so add some margin\n     % if we add an upper bound cut\n     upper = upper + 1e-4;\nend\n\np = relaxed_p;\np.solver.tag = p.solver.lower.tag;\n\nif ~isinf(upper) && nnz(p.Q)==0 && isequal(p.K.m,0) && ~any(p.variabletype)\n    if p.all_integers && all(p.c == fix(p.c))\n        % All integer objective coefficients and all integer\n        % variables, we must find a solution which is at least\n        % 1 better than current upper bound\n        if upper == lower + 1\n            p = addEquality(p,[upper-1-p.f -p.c']);\n        else\n            p = addInequality(p,[upper-1-p.f -p.c']);        \n        end        \n    end\nend\n\nif ~isinf(upper) && p.all_integers && all(p.ub <= 0) && all(p.lb >= -1)   \n    % Exclusion cuts for negated binaries based on some optimal solutions\n    % kept for historical reason on malformed model\n    for i = 1:min(size(allSolutions,2),10)\n        [b,a] = exclusionCut(allSolutions(:,end-i+1),-1);\n        p = addInequality(p,[b a]);        \n    end    \nelseif ~isinf(upper) && p.all_integers && all(p.ub <= 1) && all(p.lb >= 0)   \n    % Normal exclusion on binary\n     for i = 1:min(size(allSolutions,2),10)\n         [b,a] = exclusionCut(allSolutions(:,end-i+1),1);\n         p = addInequality(p,[b a]);        \n     end    \nend\n\n% for i = 1:length(p.cardinalityvariables)\n%     used = p.cardinalityvariables{i};\n%     L = p.lb(used);\n%     if sum(L) == p.cardinalitysize{i}\n%         p.ub(used(p.lb(used) < p.ub(used) )) = 0;  \n%     end\n% end\n\nremovethese = p.lb==p.ub;\n[~,map] = ismember(find(~p.lb==p.ub),1:length(p.c));\nif nnz(removethese)>0 && all(p.variabletype == 0) && isempty(p.evalMap) && p.options.allowsmashing\n \n    % Fixed variables, so let us try to presolve as muh as possible\n    % (needed often in SDPs etc where solvers are less robust to weird\n    % models having no interior etc)    \n    p = smashFixed(p,'delete');\n    p = smashQPOjective(p,removethese);    \n    idx = find(removethese);    \n    \n    % FIX: should be updated\n    % safe fix now where we just remove\n    p.cardinalityvariables = [];\n    p.cardinalitygroups = [];\n    %p.atmost.groups = [];\n    %p = smashAtmost(p,idx);\n    \n    p.lb(idx)=[];\n    p.ub(idx)=[];\n    if ~isempty(p.x0)\n        p.x0(idx)=[];\n    end\n    p.monomtable(:,idx)=[];\n    p.monomtable(idx,:)=[];\n    p.variabletype(idx) = [];  \n       \n    [p,infeasible] = detectRedundantInfeasibleSOCPRows(p);\n    if infeasible\n        output = createOutputStructure(24);\n        return\n    end\n    \n    [p,infeasible] = detectRedundantInfeasibleSDPRows(p);\n    if infeasible\n        output = createOutputStructure(24);\n        return\n    end\n    \n    [p,infeasible] = detectRedundantInfeasibleEXPRows(p);\n    if infeasible\n        output = createOutputStructure(24);\n        return\n    end\n    \n    [p,infeasible] = detectRedundantInfeasiblePOWRows(p);\n    if infeasible\n        output = createOutputStructure(24);\n        return\n    end\n        \n    % We do this last, as the SOCP/EXP/SDP presolve might add trivial\n    % equalities from presolving 0 >= norm(z) etc\n    p = removeEmptyLPRows(p);\n    [p,infeasible] = detectRedundantInfeasibleLPRows(p);\n    if infeasible\n        output = createOutputStructure(24);\n        return\n    end\n                     \n    % Derive bounds from this presolved model, and if we detect new fixed\n    % variables, apply recursively   \n    if ~isempty(p.F_struc)\n        [lb,ub] = find_lp_bounds(p.F_struc,p.K,p.lb,p.ub,1);    \n        p.ub = min(ub,p.ub);\n        p.lb = max(lb,p.lb);\n    end\n    \n    if any(p.lb > p.ub)\n        output = createOutputStructure(24);\n        return\n    end\n    \n    if any(p.lb == p.ub) \n        % Recurse!\n        output = bnb_solvelower(lowersolver,p,inf,lower,x_min,[]);\n    elseif any(p.lb > p.ub-p.options.bnb.feastol)\n        % Infeasible\n        output = createOutputStructure(24);\n        return\n    else\n        % Solve relaxation\n        p.solver.version = p.solver.lower.version;\n        p.solver.subversion = p.solver.lower.subversion;        \n        output = feval(lowersolver,p);        \n    end\n    if output.problem == 1 || output.problem == 24\n        output.Primal = [];\n        return\n    end\n    % Recover\n    x=relaxed_p.c*0;\n    x(removethese)=relaxed_p.lb(removethese);\n    x(~removethese)=output.Primal;\n    output.Primal=x;\nelse\n    p.solver = p.solver.lower;\n    output = feval(lowersolver,p);        \nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/bnb_solvelower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2144844865926637}}
{"text": "function [success,msg] = ConvertMAGATAnalyzer2JAABA(varargin)\n\nSCALE = 10; % centimeters instead of millimeters\nMAXTIMESTAMPERR = .01;\n\nsuccess = false;\nmsg = '';\n\n%% set parameters\n\n[inmoviefile,expfile,...\n  expdir,moviefilestr,trxfilestr,perframedirstr,...\n  arenatype,arenacenterx,arenacentery,...\n  arenaradius,arenawidth,arenaheight,...\n  dosoftlink,dotransposeimage] = myparse(varargin,...\n  'inmoviefile','','expfile','',...\n  'expdir','','moviefilestr','movie.ufmf','trxfilestr','trx.mat','perframedirstr','perframe',...\n  'arenatype','None','arenacenterx',0,'arenacentery',0,...\n  'arenaradius',123,'arenawidth',123,'arenaheight',123,...\n  'dosoftlink',false,...\n  'dotransposeimage',false);\n\n%% make sure that MAGATAnalyzer code is on the path\n\nres = which('Experiment');\nif isempty(res),\n  msg = 'MAGATAnalyzer-Matlab-Analysis code must be on the MATLAB path';\n  return;\nend\nres = which('deg2rad');\nif isempty(res),\n  msg = '\"MAGATAnalyzer-Matlab-Analysis/utility functions\" code must be on the MATLAB path';\n  return;\nend\n  \n\n%% check for files\n\nif isempty(expfile),\n  msg = 'Experiment file is empty';\n  return;\nend\n\nif isempty(inmoviefile),\n  msg = 'Video file is empty';\n  return;\nend\n\nif ~exist(expfile,'file'),\n  msg = sprintf('Experiment file %s does not exist',expfile);\n  return;\nend\n\nif ~exist(inmoviefile,'file'),\n  msg = sprintf('Video file %s does not exist',inmoviefile);\n  return;\nend\n\n% output file locations\nmoviefile = fullfile(expdir,moviefilestr);\ntrxfile = fullfile(expdir,trxfilestr);\nperframedir = fullfile(expdir,perframedirstr);\n\n%% load in experiment data\n\ntry\n  expdata = load(expfile);\ncatch ME,\n  msg = getReport(ME);\n  return;\nend\n\n%% compute trajectories\n\nif dotransposeimage,\n  XIND = 1;\n  YIND = 2;\nelse\n  XIND = 2;\n  YIND = 1;\nend\n\nnflies = numel(expdata.experiment_1.track);\ntrx = [];\nperframedata = struct;\ntimestamps = expdata.experiment_1.elapsedTime';\ndt = diff(timestamps);\n\nallframeidx = cell(1,nflies);\n\nfor i = 1:nflies,\n  \n  fprintf('Larva %d...\\n',i);\n  \n  trk = struct;\n  \n  % sometimes frames are skipped\n  [errt,frameidx] = min(dist2(timestamps',[expdata.experiment_1.track(i).pt.et]'),[],1);\n  allframeidx{i} = frameidx;\n  maxerrt = max(errt);\n  if maxerrt > MAXTIMESTAMPERR,\n    msg = sprintf('Could not match timestamps for larva %d',i);\n    return;\n  end\n  trk.firstframe = min(frameidx);\n  trk.endframe = max(frameidx);\n  trk.nframes = trk.endframe - trk.firstframe+1;\n  % make this start counting at 1\n  frameidx = frameidx - trk.firstframe + 1;\n  \n  if trk.nframes > numel(expdata.experiment_1.track(i).pt),\n    fprintf('%d frames missing for larva %d\\n',trk.nframes - numel(expdata.experiment_1.track(i).pt),i);\n  end\n\n  % centroid\n  loc = double(cat(2,expdata.experiment_1.track(i).pt.loc));\n  trk.x_mm = nan(1,trk.nframes);\n  trk.x_mm(frameidx) = loc(1,:);\n  trk.y_mm = nan(1,trk.nframes);\n  trk.y_mm(frameidx) = loc(2,:);\n\n  % grab other data about the larva\n  mid = double(cat(2,expdata.experiment_1.track(i).pt.mid));\n  head = double(cat(2,expdata.experiment_1.track(i).pt.head));\n  tail = double(cat(2,expdata.experiment_1.track(i).pt.tail));\n  spine = {expdata.experiment_1.track(i).pt.spine};\n  contour = {expdata.experiment_1.track(i).pt.contour};\n  area = double(cat(2,expdata.experiment_1.track(i).pt.area));\n  \n  % convert to pixels, as everything else will be for plotting purposes\n  loc_px = cat(1,expdata.experiment_1.camcalinfo.r2cX(loc(1,:),loc(2,:)),...\n    expdata.experiment_1.camcalinfo.r2cY(loc(1,:),loc(2,:)));\n  trk.x = nan(1,trk.nframes);\n  trk.x(frameidx) = loc_px(XIND,:)+1;\n  trk.y = nan(1,trk.nframes);\n  trk.y(frameidx) = loc_px(YIND,:)+1;\n\n  % area\n  trk.area=nan(1,trk.nframes);\n  trk.area(frameidx)=area;\n  % midpoint\n  xmid_cm = mid(XIND,:);\n  ymid_cm = mid(YIND,:);\n  perframedata.xmid_mm{i} = nan(1,trk.nframes);\n  perframedata.xmid_mm{i}(frameidx) = xmid_cm*SCALE;\n  perframedata.ymid_mm{i} = nan(1,trk.nframes);\n  perframedata.ymid_mm{i}(frameidx) = ymid_cm*SCALE;\n  mid_px = cat(1,expdata.experiment_1.camcalinfo.r2cX(mid(1,:),mid(2,:)),...\n    expdata.experiment_1.camcalinfo.r2cY(mid(1,:),mid(2,:)));\n  trk.xmid = nan(1,trk.nframes);\n  trk.xmid(frameidx) = mid_px(XIND,:)+1;\n  trk.ymid = nan(1,trk.nframes);\n  trk.ymid(frameidx) = mid_px(YIND,:)+1;\n\n  % head\n  xhead_cm = head(XIND,:);\n  yhead_cm = head(YIND,:);\n  perframedata.xhead_mm{i} = nan(1,trk.nframes);\n  perframedata.xhead_mm{i}(frameidx) = xhead_cm*SCALE;\n  perframedata.yhead_mm{i} = nan(1,trk.nframes);\n  perframedata.yhead_mm{i}(frameidx) = yhead_cm*SCALE;\n  head_px = cat(1,expdata.experiment_1.camcalinfo.r2cX(head(1,:),head(2,:)),...\n    expdata.experiment_1.camcalinfo.r2cY(head(1,:),head(2,:)));\n  trk.xhead = nan(1,trk.nframes);\n  trk.xhead(frameidx) = head_px(XIND,:)+1;\n  trk.yhead = nan(1,trk.nframes);  \n  trk.yhead(frameidx) = head_px(YIND,:)+1;\n  \n  % tail\n  xtail_cm = tail(XIND,:);\n  ytail_cm = tail(YIND,:);\n  perframedata.xtail_mm{i} = nan(1,trk.nframes);\n  perframedata.xtail_mm{i}(frameidx) = xtail_cm*SCALE;\n  perframedata.ytail_mm{i} = nan(1,trk.nframes);\n  perframedata.ytail_mm{i}(frameidx) = ytail_cm*SCALE;\n  tail_px = cat(1,expdata.experiment_1.camcalinfo.r2cX(tail(1,:),tail(2,:)),...\n    expdata.experiment_1.camcalinfo.r2cY(tail(1,:),tail(2,:)));\n  trk.xtail = nan(1,trk.nframes);\n  trk.xtail(frameidx) = tail_px(XIND,:)+1;\n  trk.ytail = nan(1,trk.nframes);\n  trk.ytail(frameidx) = tail_px(YIND,:)+1;\n\n  % spine\n  nspinepts = max(cellfun(@(x) size(x,2),spine));\n  isspine = ~cellfun(@isempty,spine);\n  xspine_cm = nan(nspinepts,trk.nframes);\n  yspine_cm = nan(nspinepts,trk.nframes);\n  xspine_cm(:,frameidx(isspine)) = cell2mat(cellfun(@(x) double(x(1,:)'),spine(isspine),'UniformOutput',false));\n  yspine_cm(:,frameidx(isspine)) = cell2mat(cellfun(@(x) double(x(2,:)'),spine(isspine),'UniformOutput',false));\n  % spines are backwards\n  xspine_cm = xspine_cm(end:-1:1,:);\n  yspine_cm = yspine_cm(end:-1:1,:);\n  if dotransposeimage,\n    trk.xspine = expdata.experiment_1.camcalinfo.r2cY(xspine_cm,yspine_cm)+1;\n    trk.yspine = expdata.experiment_1.camcalinfo.r2cX(xspine_cm,yspine_cm)+1;\n    trk.xspine_mm = xspine_cm*SCALE;\n    trk.yspine_mm = yspine_cm*SCALE;\n  else\n    trk.yspine = expdata.experiment_1.camcalinfo.r2cX(xspine_cm,yspine_cm)+1;\n    trk.xspine = expdata.experiment_1.camcalinfo.r2cY(xspine_cm,yspine_cm)+1;\n    trk.xspine_mm = yspine_cm*SCALE;\n    trk.yspine_mm = xspine_cm*SCALE;\n  end\n  \n  % contour\n  xcontour_cm = cellfun(@(x) double(x(1,:)),contour,'UniformOutput',false);\n  ycontour_cm = cellfun(@(x) double(x(2,:)),contour,'UniformOutput',false);\n  trk.xcontour = cell(1,trk.nframes);\n  trk.ycontour = cell(1,trk.nframes);\n  perframedata.xcontour_mm{i} = cell(1,trk.nframes);\n  perframedata.ycontour_mm{i} = cell(1,trk.nframes);\n  if dotransposeimage,\n    trk.xcontour(frameidx) = cellfun(@(x,y) expdata.experiment_1.camcalinfo.r2cY(x,y)+1, xcontour_cm,ycontour_cm,'UniformOutput',false);\n    trk.ycontour(frameidx) = cellfun(@(x,y) expdata.experiment_1.camcalinfo.r2cX(x,y)+1, xcontour_cm,ycontour_cm,'UniformOutput',false);\n    perframedata.xcontour_mm{i}(frameidx) = cellfun(@(x) x*SCALE,xcontour_cm,'UniformOutput',false);\n    perframedata.ycontour_mm{i}(frameidx) = cellfun(@(x) x*SCALE,ycontour_cm,'UniformOutput',false);\n  else\n    trk.ycontour(frameidx) = cellfun(@(x,y) expdata.experiment_1.camcalinfo.r2cX(x,y)+1, xcontour_cm,ycontour_cm,'UniformOutput',false);\n    trk.xcontour(frameidx) = cellfun(@(x,y) expdata.experiment_1.camcalinfo.r2cY(x,y)+1, xcontour_cm,ycontour_cm,'UniformOutput',false);\n    perframedata.xcontour_mm{i}(frameidx) = cellfun(@(x) x*SCALE,ycontour_cm,'UniformOutput',false);\n    perframedata.ycontour_mm{i}(frameidx) = cellfun(@(x) x*SCALE,xcontour_cm,'UniformOutput',false);\n  end\n\n  % covariance matrix is already in pixels; use it to get major, minor,\n  % orientation\n  S = cellfun(@(x) [x(1),x(2);x(2),x(3)], {expdata.experiment_1.track(i).pt.cov},'UniformOutput',false);\n  S = cat(3,S{:});\n  if ~dotransposeimage,\n    S = [S(2,2,:),S(2,1,:);S(1,2,:),S(1,1,:)];\n  end\n  [a,b,theta] = cov2ell(S);\n  % note that we don't worry about the zero-indexing correction because the\n  % difference will cancel out\n  thetahead = atan2(head_px(YIND,:)-tail_px(YIND,:),head_px(XIND,:)-tail_px(XIND,:));\n  thetaflip = modrange(thetahead+modrange(theta-thetahead,-pi/2,pi/2),-pi,pi);\n  trk.a = nan(1,trk.nframes);\n  trk.a(frameidx) = a/2;\n  trk.b = nan(1,trk.nframes);\n  trk.b(frameidx) = b/2;\n  trk.theta = nan(1,trk.nframes);\n  trk.theta(frameidx) = thetaflip;\n  \n  % convert a, b, theta to mm\n  x = loc_px(XIND,:);\n  y = loc_px(XIND,:);\n  if dotransposeimage,\n    x1 = x + a.*cos(thetaflip);\n    x2 = x - a.*cos(thetaflip);\n    y1 = y + a.*sin(thetaflip);\n    y2 = y - a.*sin(thetaflip);\n  else\n    y1 = x + a.*cos(thetaflip);\n    y2 = x - a.*cos(thetaflip);\n    x1 = x + a.*sin(thetaflip);\n    x2 = x - a.*sin(thetaflip);\n  end\n  x1_cm = expdata.experiment_1.camcalinfo.c2rX(x1,y1);\n  y1_cm = expdata.experiment_1.camcalinfo.c2rY(x1,y1);\n  x2_cm = expdata.experiment_1.camcalinfo.c2rX(x2,y2);\n  y2_cm = expdata.experiment_1.camcalinfo.c2rY(x2,y2);\n  trk.theta_mm = nan(1,trk.nframes);\n  trk.theta_mm(frameidx) = atan2(y2_cm-y1_cm,x2_cm-x1_cm);\n  trk.a_mm = nan(1,trk.nframes);\n  trk.a_mm(frameidx) = sqrt((y2_cm-y1_cm).^2+(x2_cm-x1_cm).^2)/4;\n  if dotransposeimage,\n    x1 = x + b.*cos(thetaflip+pi/2);\n    x2 = x - b.*cos(thetaflip+pi/2);\n    y1 = y + b.*sin(thetaflip+pi/2);\n    y2 = y - b.*sin(thetaflip+pi/2);\n  else\n    y1 = x + b.*cos(thetaflip+pi/2);\n    y2 = x - b.*cos(thetaflip+pi/2);\n    x1 = y + b.*sin(thetaflip+pi/2);\n    x2 = y - b.*sin(thetaflip+pi/2);\n  end\n  x1_cm = expdata.experiment_1.camcalinfo.c2rX(x1,y1);\n  y1_cm = expdata.experiment_1.camcalinfo.c2rY(x1,y1);\n  x2_cm = expdata.experiment_1.camcalinfo.c2rX(x2,y2);\n  y2_cm = expdata.experiment_1.camcalinfo.c2rY(x2,y2);\n  trk.b_mm = nan(1,trk.nframes);\n  trk.b_mm(frameidx) = sqrt((y2_cm-y1_cm).^2+(x2_cm-x1_cm).^2)/4;\n    \n  % all this was actually in centimeters, so convert to millimeters\n  trk.x_mm = trk.x_mm*SCALE;\n  trk.y_mm = trk.y_mm*SCALE;\n  trk.a_mm = trk.a_mm*SCALE;\n  trk.b_mm = trk.b_mm*SCALE;\n\n  % approximate pxpermm\n  trk.pxpermm = 1/expdata.experiment_1.camcalinfo.realUnitsPerPixel/SCALE;\n\n  % convert are to square mm from pixels\n  trk.area_mm=trk.area/(trk.pxpermm*trk.pxpermm);\n  % frame rate\n  trk.dt = dt(trk.firstframe:trk.endframe-1);\n  %trk.dt = diff([expdata.experiment_1.track(i).pt.et]);\n  \n  trk.off = 1-trk.firstframe;\n  trk.id = expdata.experiment_1.track(i).trackNum;\n  trx = structappend(trx,trk);\n  \nend\n\n%% arena parameters\n\nswitch lower(arenatype),\n\n  case 'circle',\n    arenacenterx_mm = expdata.experiment_1.camcalinfo.c2rX(arenacentery,arenacenterx)*SCALE;\n    arenacentery_mm = expdata.experiment_1.camcalinfo.c2rY(arenacentery,arenacenterx)*SCALE;\n    arenaradius_mm = arenaradius/trx(1).pxpermm;\n\n    for i = 1:numel(trx),\n      trx(i).arena = struct;\n      trx(i).arena.arena_radius_mm = arenaradius_mm;\n      trx(i).arena.arena_center_mm_x = arenacenterx_mm;\n      trx(i).arena.arena_center_mm_y = arenacentery_mm;\n    end\n    \n  case 'rectangle',\n    \n    tl = [arenacenterx - arenawidth/2,arenacentery - arenaheight/2];\n    tr = [arenacenterx + arenawidth/2,arenacentery - arenaheight/2];\n    bl = [arenacenterx - arenawidth/2,arenacentery + arenaheight/2];\n    br = [arenacenterx + arenawidth/2,arenacentery + arenaheight/2];\n    \n    tl_mm = [expdata.experiment_1.camcalinfo.c2rX(tl(2),tl(1)),...\n      expdata.experiment_1.camcalinfo.c2rY(tl(2),tl(1))]*SCALE;\n    tr_mm = [expdata.experiment_1.camcalinfo.c2rX(tr(2),tr(1)),...\n      expdata.experiment_1.camcalinfo.c2rY(tr(2),tr(1))]*SCALE;\n    bl_mm = [expdata.experiment_1.camcalinfo.c2rX(bl(2),bl(1)),...\n      expdata.experiment_1.camcalinfo.c2rY(bl(2),bl(1))]*SCALE;\n    br_mm = [expdata.experiment_1.camcalinfo.c2rX(br(2),br(1)),...\n      expdata.experiment_1.camcalinfo.c2rY(br(2),br(1))]*SCALE;\n\n    for i = 1:numel(trx),\n      trx(i).arena = struct;\n      trx(i).arena.tl = tl_mm;\n      trx(i).arena.tr = tr_mm;\n      trx(i).arena.bl = bl_mm;\n      trx(i).arena.br = br_mm;\n    end\n\nend\n\n\n%% create the experiment directory\n\nif ~exist(expdir,'dir'),\n  [success1,msg1] = mkdir(expdir);\n  if ~success1,\n    msg = msg1;\n    return;\n  end\nend\n\n%% save the trx file\ntry\n  save(trxfile,'trx','timestamps');\ncatch ME,\n  msg = sprintf('Could not save to file %s: %s',trxfile,getReport(ME));\n  return;\nend\nif ~exist(trxfile,'file'),\n  msg = sprintf('Failed to save trx to file %s',trxfile);\n  return;\nend\n\n%% copy/soft-link movie\n\nif strcmp(fullfile(inmoviefile),fullfile(moviefile)),\n  fprintf('Input and out movie files are the same, not copying/linking.\\n');\nelse\n  \n  if dosoftlink,\n    if isunix,\n      cmd = sprintf('ln -s %s %s',inmoviefile,moviefile);\n      unix(cmd);\n      % test to make sure it worked\n      [status,result] = unix(sprintf('readlink %s',moviefile));\n      result = strtrim(result);\n      if status ~= 0 || ~strcmp(result,inmoviefile),\n        warndlg(sprintf('Failed to make soft link, copying %s to %s instead',inmoviefile,moviefile));\n        dosoftlink = false;\n      end\n    elseif ispc,\n      cmd = sprintf('mkshortcut.vbs /target:\"%s\" /shortcut:\"%s\"',inmoviefile,moviefile);\n      fprintf('Making a Windows shortcut file at \"%s\" with target \"%s\"\\n',inmoviefile,moviefile);\n      system(cmd);\n      % test to make sure that worked\n      [equalmoviefile,didfind] = GetPCShortcutFileActualPath(moviefile);\n      if ~didfind || ~strcmp(equalmoviefile,inmoviefile),\n        warndlg(sprintf('Failed to make shortcut, copying %s to %s instead',inmoviefile,moviefile));\n        dosoftlink = false;\n      end\n    else\n      warndlg(sprintf('Unknown OS, not soft-linking movie file %s',inmoviefile));\n      dosoftlink = false;\n    end\n  end\n  \n  if ~dosoftlink,\n    [success1,msg1] = copyfile(inmoviefile,moviefile);\n    if ~success1,\n      msg = msg1;\n      success = false;\n      return;\n    end\n  end\n  \nend\n\n%% make per-frame directory\nif ~exist(perframedir,'dir'),\n  [success1,msg1] = mkdir(perframedir);\n  if ~success1,\n    msg = msg1;\n    return;\n  end\nend\n\n%% per-frame data\n\n% save the perframedata we computed above\nfns = fieldnames(perframedata);\n% everything is currently in mm\nunits = parseunits('mm'); %#ok<NASGU>\nfor i = 1:numel(fns),\n  fn = fns{i};\n  data = perframedata.(fn); %#ok<NASGU>\n  matfilename = fullfile(perframedir,[fn,'.mat']);\n  fprintf('Saving data to %s...\\n',matfilename);\n  save(matfilename,'data','units');\nend\n\n%\n% % for some reason, the derived measurements have different indices\n% idx = cell(1,nflies);\n% for i = 1:nflies,\n%   idx{i} = expdata.experiment_1.track(i).getDerivedQuantity('mapptstointerped',false);\n% end\n% \n% fielddict = struct;\n% fielddict.vel = 'ma_vel';\n% fielddict.speed = 'ma_speed';\n% fielddict.vnorm = 'ma_vnorm';\n% fielddict.theta = 'ma_theta';\n% fielddict.adjspeed = 'ma_adjspeed';\n% fielddict.lrdtheta = 'ma_lrdtheta';\n% fielddict.pathLength = 'ma_pathLength';\n% fielddict.covRatio = 'ma_covRatio';\n% fielddict.covTheta = 'ma_covTheta';\n% fielddict.covMinor = 'ma_covMinor';\n% fielddict.covMajor = 'ma_covMajor';\n% fielddict.dcovRatio = 'ma_dcovRatio';\n% fielddict.sarea = 'ma_aarea';\n% \n% fnsin = fieldnames(fielddict);\n% \n% for j = 1:numel(fnsin),\n%   fnin = fnsin{j};\n%   fnout = fielddict.(fnin);\n%   matfilename = fullfile(perframedir,[fnout,'.mat']);\n%   fprintf('%s -> %s...\\n',fnin,matfilename);\n% \n%   data = cell(1,nflies);  \n%   for i = 1:nflies,\n%     tmp = expdata.experiment_1.track(i).getDerivedQuantity(fnin);\n%     data{i} = nan(size(tmp,1),trx(i).nframes);\n%     data{i}(:,allframeidx{i}) = tmp(:,idx{i});\n%   end\n%   save(matfilename,'data','units');  \n% end\n\n% also save unsmoothed area\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  data{i} = nan(1,trx(i).nframes);\n  frameidx = allframeidx{i} - trx(i).firstframe + 1;\n  data{i}(frameidx) = [expdata.experiment_1.track(i).pt.area];\nend\nmatfilename = fullfile(perframedir,['area','.mat']);\nsave(matfilename,'data','units');\n\nsuccess = true;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ConvertMAGATAnalyzer2JAABA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.21437848949700158}}
{"text": "function WJ_DistortionCorrection_3D_SItriggered(src,evt,varargin)\n            global filename        \n            filename=[src.hSI.hScan2D.logFilePath,'\\', src.hSI.hScan2D.logFileStem,'_',num2str(src.hSI.hScan2D.logFileCounter-1,'%05d'),'.tif'];                                   \n            disp(['Just saved raw data: ',filename]);\n            disp('Start the distortion correction....');\n            disp('Reloading the raw data....');\n     \n%             filename='97045_20210308_ML-400_AL-400_1Openfiled_00001.tif';\n            \n            [header, RawImage, imgInfo] = scanimage.util.opentif(filename);\n            filename1=imgInfo.filename;\n            disp(['Rawe 2P imaging data: \"' filename1  '\" is loaded']);\n            save([filename(1:end-4),'_tifHeader.mat'],'header');% save the SI information, only necessasy for SI information saving. No need for DJ analysis\n            disp([filename(1:end-4),'_tifHeader.mat',' is saved']);\n            save([filename(1:end-4),'_imgInfo.mat'],'imgInfo');% save the imaging information,only necessasy for SI information saving. No need for DJ analysis\n            disp([filename(1:end-4),'_imgInfo.mat',' is saved']);\n            %\n            Dimention=size(RawImage); \n            Zs=header.SI.hStackManager.zs;\n            % load in 3D transform matrx according to different frame szie\n            if Dimention(1)==512\n                % read 515 3D Tranform matrix\n                TransformMatrix_tem=load('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\TransMatrix_512_3D.mat');\n                % read 512 3D FOV information\n                FOV=csvread('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\FOVreport_512_20211111.csv');\n                Depth=csvread('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\Depth20211111.csv');\n                %\n            elseif Dimention(1)==256\n                % read 256 3D Tranform matrix\n                TransformMatrix_tem=load('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\TransMatrix_256_3D.mat');\n                % read 256 3D FOV information\n                FOV=csvread('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\FOVreport_256_20211111.csv');\n                Depth=csvread('\\\\forskning.it.ntnu.no\\ntnu\\mh-kin\\moser\\open2pmini\\FOV callibration\\RubenWeijianNienke\\MINI2P_L_WJ001\\Report\\Depth20211111.csv');\n\n                %\n            else\n            end\n            %\n            TransformMatrix=struct2cell(TransformMatrix_tem);\n            \n            PlaneMark=[];\n            if length(Dimention)<=3                  \n                ImageStack_corrected=RawImage;\n                PlaneMark=ones(size(ImageStack_corrected(:)),1);\n                disp('Image Stack Size:');\n                disp(num2str(Dimention));\n                disp('No HyperStack Merging is applied');\n            elseif length(Dimention)==4 \n                disp('Image Stack Size:');\n                disp(num2str(Dimention));\n                disp('2D Timelapse imaging was infered.  Channel and Frame merging is applied');\n                ImageStack_corrected=zeros(Dimention(1),Dimention(2),Dimention(3)*Dimention(4));\n                k=1;\n                for j=1:1:Dimention(4)\n                    for i=1:1:Dimention(3)\n                        ImageStack_corrected(:,:,k)=RawImage(:,:,i,j);  \n                        PlaneMark(k)=1;\n                        k=k+1;\n                    end\n                end\n            elseif length(Dimention)==5\n                disp('Image Stack Size:');\n                disp(num2str(Dimention));\n                disp('Multi-layer sinlge TimePoint imaging was infered.  Channel, Frame and Plane merging is applied');\n                ImageStack_corrected=zeros(Dimention(1),Dimention(2),Dimention(3)*Dimention(4)*Dimention(5));    \n                k=1;\n                    for m=1:1:Dimention(5)\n                        for j=1:1:Dimention(4)\n                            for i=1:1:Dimention(3)\n                                ImageStack_corrected(:,:,k)=RawImage(:,:,i,j,m);  \n                                PlaneMark(k)=m;\n                                k=k+1;\n                            end\n                        end\n                    end\n            else\n                disp('Image Stack Size:');\n                disp(num2str(Dimention));\n                disp('Multi-layer Timelapse imaging was infered.  Channel, Frame, Plane and Volume merging is applied');\n                ImageStack_corrected=zeros(Dimention(1),Dimention(2),Dimention(3)*Dimention(4)*Dimention(5)*Dimention(6));\n                k=1;\n                \n                for n=1:1:Dimention(6)                    \n                    for m=1:1:Dimention(5)                        \n                        for j=1:1:Dimention(4)\n                            for i=1:1:Dimention(3)\n                                ImageStack_corrected(:,:,k)=RawImage(:,:,i,j,m,n);   \n                                PlaneMark(k)=m;\n                                k=k+1;\n                            end\n                        end\n                    end\n                end    \n            end\n            clear RawImage\n            % find which matrix to use\n            PlaneClosest=PlaneMark;\n            for i=1:1:size(PlaneMark,2)\n                PlaneClosest(i)=Zs(PlaneMark(i));\n                [minValue,closestIndex]=min(abs(Depth-PlaneClosest(i)));\n                PlaneClosest(i)= closestIndex;\n            end\n\n            fTIF = DataIO.Fast_BigTiff_Write([filename(1:end-4),'_wrappiing-corrected.tif'],1*10000/FOV(3),0);\n            for i=1:1:size(ImageStack_corrected,3)               \n                ImageStack_corrected(:,:,i)=imwarp(ImageStack_corrected(:,:,i),TransformMatrix{PlaneClosest(i),1},'OutputView',imref2d(size(ImageStack_corrected(:,:,1))));            \n                fTIF.WriteIMG(int16(ImageStack_corrected(:,:,i)'));\n                disp(['Unwrapping and saving image number ',num2str(i)]);\n            end \n            fTIF.close;\n            disp(['Distortion correction finished, data saved: ',filename(1:end-4),'_wrappiing corrected.tif']);\n%             clear ImageStack_corrected            \nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Software/SI settings/WJ_DistortionCorrection_3D_SItriggered.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.21434999730896664}}
{"text": "function [model, solutionThermoRecon, solutionRecon, model1] = secondPassDirectionalityAssignment(model)\n% Driver to call model specific code to manually generate a physiological model (if first pass does not result in a physiological model).\n%\n% The second pass directionality assignment needs careful manual curation\n% since the adjustments necessary to get one organism to grow will not\n% necessarily be the same as the ones which will get another\n% organism to grow. There's no avioding manual debugging at this stage.\n%\n% USAGE:\n%\n%    [model, solutionThermoRecon, solutionRecon, model1] = secondPassDirectionalityAssignment(model)\n%\n% INPUTS:\n%    model:\n%\n% OUTPUTS:\n%    model:\n%    solutionThermoRecon:\n%    solutionRecon:\n%    model1:\n%\n% NOTE:\n%\n%    This is the code  used for a number of organisms in order to point out\n%    the kind of issues that arise. This is NOT supposed to work in the\n%    general case.\n%\n% .. Author: - Ronan M. T. Fleming\n\nglobal CBTLPSOLVER\nswitch model.description\n    case 'iAF1260'\n        % now assign reaction directions based on the P(\\Delta_{r}G^{\\primeo}<0)\n        % doing so may prevent the model from growing, therefore at this stage it\n        % is necessary to manually adjust some of the reaction directionalities\n        % such that the model can grow, and grow at a similar rate as observed in\n        % vivo. Therefore this script cannot be made model invariant as there is an\n        % essential manual debugging stage. The script below is for E. coli iAF1260\n        fprintf('%s\\n%s\\n%s\\n','The second pass assignment of reaction directionality should',...\n            'be a compromise between quantitative and qualitative assignment',...\n            'this step requires manual imput as it is specific to each organism.');\n\n        fprintf('%s\\n',['The second pass assignment of reaction directionality is using the ' CBTLPSOLVER ' LP solver.']);\n        fprintf('\\n%s\\n','...setThermoReactionDirectionality (based on the P(\\Delta_{r}G^{\\primeo}<0))');\n        % this will update the model.lb_reconThermo & model.ub_reconThermo\n        [model,solutionThermoRecon,solutionRecon,model1]=setThermoReactionDirectionalityiAF1260(model);\n    otherwise\n        fprintf('No manually generated .m file second pass directionality assignment is available for this model.')\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/thermoDirectionality/secondPassDirectionalityAssignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.2143366888160806}}
{"text": "function [net, info] = cnn_imagenet_se_mcn(varargin)\n% CNN_IMAGENET_SE_MCN Evaluate imported PyTorch models on ImageNet val set\n% (closely based on the mcn cnn_imagenet.m example)\n%\n% Copyright (C) 2017 Samuel Albanie\n% Licensed under The MIT License [see LICENSE.md for details]\n\n  opts.gpus = 3 ;\n  opts.continue = 1 ;\n  opts.batchSize = 256 ;\n  opts.model = 'SE-ResNet-50-mcn' ;\n  opts.modelDir = fullfile(vl_rootnn, 'data/models-import') ;\n  opts.dataDir = fullfile(vl_rootnn, 'data/datasets/ILSVRC2012') ;\n  opts.labelMap = fullfile(vl_rootnn, 'contrib/mcnSENets/misc/label_map.txt') ;\n  [opts, varargin] = vl_argparse(opts, varargin) ;\n\n  opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' opts.model]) ;\n  [opts, varargin] = vl_argparse(opts, varargin) ;\n\n  opts.lite = false ;\n  opts.numFetchThreads = 12 ;\n  opts.imdbPath = fullfile(vl_rootnn, 'data', 'imagenet12', 'imdb.mat');\n  opts = vl_argparse(opts, varargin) ;\n\n  opts.train.gpus = opts.gpus ;\n\n% -------------------------------------------------------------------------\n%                                                              Prepare data\n% -------------------------------------------------------------------------\n\n  if exist(opts.imdbPath, 'file')\n    imdb = load(opts.imdbPath) ;\n    imdb.imageDir = fullfile(opts.dataDir, 'images');\n  else\n    imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n    mkdir(opts.expDir) ;\n    save(opts.imdbPath, '-struct', 'imdb') ;\n  end\n\n  % remap labels to match the order used in training\n  imdb = updateLabelMap(imdb, opts) ;\n\n% -------------------------------------------------------------------------\n%                                                             Prepare model\n% -------------------------------------------------------------------------\n  net = load_model(opts.modelDir, opts.model) ;\n\n  % modify the imdb to skip training images\n  imdb.images.set(imdb.images.set == 1) = 4 ;\n  [net, info] = cnn_train_dag(net, imdb, getBatchFn(opts, net.meta), ...\n                              'expDir', opts.expDir, 'gpus', opts.train.gpus, ...\n                              'numEpochs', 1, 'continue', opts.continue, ...\n                              'batchSize', opts.batchSize) ;\n\n  % hack the checkpoint file to save an empty dag\n  modelPath = fullfile(opts.expDir, 'net-epoch-1.mat') ; tmp = load(modelPath) ;\n  net_ = net ; net = dagnn.DagNN().saveobj() ; stats = tmp.stats ; state = {} ; %#ok\n  save(modelPath, 'net', 'stats', 'state') ; net = net_ ;\n\n% -------------------------------------------------------------------------\nfunction dag = load_model(modelDir, name)\n% -------------------------------------------------------------------------\n  modelPath = fullfile(modelDir, sprintf('%s.mat', name)) ;\n  if ~exist(modelDir, 'dir') , mkdir(modelDir) ; end\n\n  if ~exist(modelPath, 'file')\n    fprintf('Downloading the %s model ... this may take a while\\n', name) ;\n    base = 'http://www.robots.ox.ac.uk/~albanie' ;\n    url = sprintf('%s/models/se-nets/%s.mat', base, name) ;\n    urlwrite(url, modelPath) ;\n  end\n\n  dag = dagnn.DagNN.loadobj(load(modelPath)) ;\n  dag.addLayer('softmax', dagnn.SoftMax(), dag.layers(end).outputs, 'prediction', {}) ;\n  dag.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...\n               {'prediction','label'}, 'top1err') ;\n  dag.addLayer('top5err', dagnn.Loss('loss', 'topkerror', 'opts', {'topK',5}), ...\n               {'prediction','label'}, 'top5err') ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchFn(opts, meta)\n% -------------------------------------------------------------------------\n  bopts = struct('useGpu', numel(opts.train.gpus) > 0, ...\n                 'imageSize', meta.normalization.imageSize(1:2)) ;\n  fn = @(x,y) eval_get_batch(bopts,x,y) ;\n\n% -------------------------------------------------------------------------\nfunction varargout = eval_get_batch(opts, imdb, batch)\n% -------------------------------------------------------------------------\n  images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\n  data = getImageBatch(images, opts, 'prefetch', nargout == 0) ;\n  if nargout > 0\n    labels = imdb.images.label(batch) ;\n    varargout{1} = {'data', data, 'label', labels} ;\n  end\n\n% ----------------------------------------\nfunction imdb = updateLabelMap(imdb, opts) \n% ----------------------------------------\n  labelMap = importdata(opts.labelMap) ; \n  keep = imdb.images.label ~= 0 ;\n  newLabels = labelMap(imdb.images.label(keep)) ;\n  imdb.images.label(keep) = newLabels ;\n\n% -------------------------------------------------\nfunction data = getImageBatch(imagePaths, varargin)\n% -------------------------------------------------\n% GETIMAGEBATCH  Load and jitter a batch of images\nopts.useGpu = false ;\nopts.prefetch = false ;\nopts.numThreads = 10 ;\n\n% Options that were used during PyTorch training\n% Note: that normalisation must occur after the pixel\n% values have been rescaled to [0,1]\nopts.cropSize = 224 / 256 ;\nopts.imageSize = [224, 224] ;\nopts.meanImg = [123, 117, 104] ;\n%opts.std = [0.229, 0.224, 0.225] ;\nopts = vl_argparse(opts, varargin);\n\nargs{1} = {imagePaths, ...\n           'NumThreads', opts.numThreads, ...\n           'Pack', ...\n           'Interpolation', 'bilinear', ... % use bilinear to reproduce trainig resize\n           'Resize', opts.imageSize(1:2), ...\n           'CropSize', opts.cropSize, ...\n           'CropAnisotropy', [1 1], ... % preserve aspect ratio\n           'CropLocation', 'center'} ; % centre crop for testing\n\nif opts.useGpu, args{end+1} = {'Gpu'} ; end\nargs = horzcat(args{:}) ;\n\nif opts.prefetch\n  vl_imreadjpeg(args{:}, 'prefetch') ;\n  data = [] ;\nelse\n  data = vl_imreadjpeg(args{:}) ;\n  data = bsxfun(@minus, data{1}, permute(opts.meanImg, [1 3 2])) ;\n  %data = data{1} / 255 ; % scale to (almost) [0,1]\n  %data = bsxfun(@rdivide, data, permute(opts.std, [1 3 2])) ;\nend\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnSENets/benchmarks/cnn_imagenet_se_mcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.359364145160102, "lm_q1q2_score": 0.2143366877525372}}
{"text": "function [view, mapvol, covol] = polarAngleMap(view, dt, scans, params, legend, W);\n%\n% [view, map, co] = polarAngleMap(view, <dt, scans, params>, <legend>, <W>);\n%\n% AUTHOR: rory\n% PURPOSE:\n% Given corAnal data for a polar angle (\"meridian\")-mapping experiment\n% (single scan or set of scans), produce a parameter map of preferred\n% polar angle in units of degrees of visual field.\n%\n% If a single scan is provided as input, this function saves the\n% parameter map in the scan's data type, assigning it only for that\n% scan.\n%\n% However, if multiple input scans are provided (see below),\n% the code saves the results in a new data type 'Meta_Analysis'.\n% corAnal data from each scan are first converted into real-world\n% units, then overlapping data are averaged together in a weighted\n% average, based on each scan's coherence. (I.e., if one scan's\n% co values for a given voxel are much higher than other scans,\n% it will dominate the determination of what angle is represented.)\n%\n% I wrote this code to use in conjunction with my across-session\n% tools (createCombinedSession, importTSeries) to run meta-analyses\n% on retinotopy data.\n%\n% ARGUMENTS:\n%   INPUT:\n%   view: mrVista view. <Defaults to selected gray view>\n%   dt: for a single scan, name or number of the data type\n%       from which the input data come. If analyzing multiple\n%       scans, a cell of length nScans of data type names/numbers.\n%       <default: cur data type>\n%\n%   scans: scan or scans to use as input. <default: cur scan>\n%\n%   params: struct (or nScans-long struct array) specifying how\n%       the stimulus mapped polar angle during each scan. Needs \n%       the following fields:\n%       params.startAngle: angle of center of wedge stimulus, measured\n%           in degrees clockwise from 12-o-clock, at the start of each\n%           cycle;\n%       params.width: width of wedge stimulus in degrees.\n%       params.direction: 'cw' or 'ccw', direction in which the stimulus\n%       proceeded. (cw=clockwise or ccw=counterclockwise).\n%       params.visualField: number of degrees the stimulus traversed\n%       each cycle (e.g., 360 if it went all the way around).\n%       <default: get these params using retinoCheckParams>\n%       \n%   legend: optional flag which, if set to 1, provides for a separate\n%       figure with a legend image to go with the polar angle map.\n%       <default 0, don't show this>\n%\n%   W: optional vector of weights for each input scan, for use when \n%       doing a meta-analysis across scans. The vector should be\n%       the same length as the input scans, and should specify the\n%       overall weight, on top of the coherence, that that scan's voxels\n%       get. Useful for me, when high-res data produces lower co values,\n%       but is actually more reliable at identifying meridian\n%       representations. <default: all ones.>\n%\n%   OUTPUT:\n%   view: mrVista view, set to the relevant data type / scan and with\n%         the map loaded and set to map mode.\n%\n%   map: the map volume produced (but not the cell-of-scans set in the\n%        view, the numeric matrix).\n%\n%   co: the maximum coherence at each voxel, across all the input scans.\n%       (It may be more sensible to make this the mean, but I'm trying\n%       max for now.) Same format as map.\n%\n%\n% ras, 01/10/06.\nif notDefined('view'),  view = getSelectedGray;                 end\nif notDefined('dt'),    dt = viewGet(view, 'curDataType');      end\nif notDefined('scans'), scans = viewGet(view, 'curScan');       end\nif notDefined('legend'), legend = 0;                            end\nif notDefined('W'),      W = ones(size(scans));                 end\nif notDefined('params')\n    params = retinoCheckParams(view, dt, scans);\nend\n\nmapName = 'Polar Angle (clock position)';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Deal with single input scan instances separately %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif length(scans)==1\n    % this should be easy: just convert the corAnal values into\n    % degrees of polar angle\n    view = selectDataType(view, dt);\n    corAnalPath = fullfile(dataDir(view), 'corAnal.mat');\n    if ~exist(corAnalPath, 'file')\n        error('corAnal not found. Run computeCorAnal first.');\n    end\n    load(corAnalPath, 'ph', 'co');\n    srcPh = ph{scans}; srcCo = co{scans}; clear ph co;\n\n    % map from corAnal ph to polar angle\n    mapvol = polarAngle(srcPh, params) ./ 30; \n\n    % make and set the parameter map\n    mapPath = fullfile(dataDir(view), 'Polar_Angle_Map.mat');\n    if exist(mapPath, 'file')\n        load(mapPath, 'map', 'co');\n    else\n        map = cell(1, numScans(view));\n    end\n\n    map{scans} = mapvol;\n    \n    % let's set the map colormap to be the same as the phase mode\n    % colormap, and save this with the map\n    if checkfields(view, 'ui', 'phMode')\n        view.ui.mapMode.cmap = view.ui.phMode.cmap;\n        view.ui.mapMode.clipMode = [0 12];        \n    end\n\n    view = setParameterMap(view, map, mapName);\n    saveParameterMap(view, mapPath, 1, 1);\n    \n    if legend, polarAngleMapLegend(view); end\n\n    % that should be it!\n    if nargout>=3, covol = co{scans}; end\n    view = refreshScreen(view);\n    return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% if we get here, we have multiple scans: parse the arguments to    %\n% be cell arrays, and get set up:                                   %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nnScans = length(scans);\n\nif ~iscell(dt)\n    mrGlobals;\n    % assume a single dt is specified, and all the scans are\n    % coming from that data type\n    for i = 1:nScans\n        if isnumeric(dt), tmp{i} = dataTYPES(dt).name;\n        else,             tmp{i} = dt;\n        end\n    end\n    dt = tmp; clear tmp;\nelse\n    for i = 1:nScans\n        if isnumeric(dt{i}), dt{i} = dataTYPES(dt{i}).name; end\n    end\nend\n\n%%%%%Get corAnal volumes for each input scan\nsrcCo = cell(1, nScans); srcPh = cell(1, nScans);\nuniqueDts = unique(dt);\nfor i = 1:length(uniqueDts)\n    corAnalPath = fullfile(viewDir(view), uniqueDts{i}, 'corAnal.mat');\n    if ~exist(corAnalPath, 'file')\n        error('corAnal not found. Run computeCorAnal first.');\n    end\n    load(corAnalPath, 'co', 'ph', 'amp')\n    \n    I = cellfind(dt, uniqueDts{i});\n    srcCo(I) = co(scans(I));\n    srcPh(I) = ph(scans(I));\n    srcAmp(I) = amp(scans(I));\nend\n\n%%%%%Set up the target data type for the multi-scan meta-analysis\nview = initScan(view, 'Meta_Analysis', [], {dt{1} scans(1)});\nview = selectDataType(view, 'Meta_Analysis');\nview = setCurScan(view, numScans(view));\nview = setAnnotation(view, sprintf('Meta Analysis for %s scans %s', ...\n                                dt{1}, num2str(scans)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Calculate the Polar Angle Map  %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%Set NaNs to zero -- will be ignored\nfor i = 1:nScans\n    srcCo{i}(isnan(srcCo{i})) = 0;\n    srcAmp{i}(isnan(srcAmp{i})) = 0;\n    srcPh{i}(isnan(srcPh{i})) = 0;\nend\n\n%%%%%Convert each phase map into real-word units\nfor i = 1:nScans\n    srcPh{i} = polarAngle(srcPh{i}, params(i)) ./ 30;\nend\n\n\n%%%%%because we allow an additional level of user-defined weights\n%%%%%(orig. b/c I wanted to weigh high-res scans higher than low-res),\n%%%%%adjust the coherence weights accordingly for each scan\nfor i = 1:nScans, srcCo{i} = srcCo{i} .* W(i); end\n\n%%%%%Set up the weighted average\n% we'll need a volume representing the sum of the coherence\n% for each voxel, across input scans. This will serve as the\n% denominator of the weight formula for each input scan.\ncoSum = zeros(size(srcCo{1})); coMax = zeros(size(srcCo{1}));\nfor i = 1:nScans, \n    coSum = coSum + srcCo{i}; \n    coMax = max(coMax, srcCo{i});\nend\n\n%%%%%initialize the map and co volumes\nmapvol = zeros(size(srcCo{1}));\ncovol = zeros(size(srcCo{1}));\n\n%%%%%compute co volume as the mean across all input co volumes\nfor i = 1:nScans, covol = covol + srcCo{i}; end\ncovol = covol ./ length(srcCo);\n\n%%%%%Compute the weighted average, iteratively across input scans\nfor i = 1:nScans\n    mapvol = mapvol + (srcPh{i} .* srcCo{i} ./ coSum);\n\n%     % alternate attempt: use winner-take-all: scan with the\n%     % highest co value for a given voxel determines the map\n%     % value at that voxel.\n%     Imax = find(srcCo{i}==coMax);\n%     mapvol(Imax) = srcPh{i}(Imax);    \nend\n\ncovol = coMax;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Output the parameter map %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% initialize the output map and co data fields, loading it if it \n% already exists:\nmapPath = fullfile(dataDir(view), 'Polar_Angle_Map.mat');\nif exist(mapPath, 'file')\n    load(mapPath, 'map', 'mapName', 'co');\nelse\n    map = cell(1, numScans(view));\n    co = cell(1, numScans(view));\nend\n\n% append the map volume for the new scans\nmap{numScans(view)} = mapvol;\nco{numScans(view)} = covol;\n\n% before saving the map, copy the view's phase mode color map\n% to the map mode, which will also be saved:\nif checkfields(view, 'ui', 'phMode')\n    view.ui.mapMode.cmap = view.ui.phMode.cmap;\n    view.ui.mapMode.clipMode = [0 12];\nend\n\n% set the map in the view, and save it\nview = setParameterMap(view, map, mapName);\nsaveParameterMap(view, mapPath, 1, 1);\nsave(mapPath, 'co', '-append'); % also add the co field\nview.co = co;\nrefreshScreen(view);\n\n% also set corAnal amp and ph fields, and save a corAnal, so \n% we can view in that mode as well (nice colorbar, can ph-restrict)\n% we map the ph back from degrees to radians:\nphvol = deg2rad(mapvol.*30);\nampvol = srcAmp{1};\nif exist(fullfile(dataDir(view), 'corAnal.mat'), 'file')\n    view = loadCorAnal(view);\nend\nview.co{numScans(view)} = covol;\nview.ph{numScans(view)} = phvol;\nview.amp{numScans(view)} = ampvol;\nview = saveCorAnal(view, 1);\n\nnewParams.type = 'polar_angle';     % set retino params such\nnewParams.startAngle = 0;           % that the default HSV color map\nnewParams.direction = 'clockwise';  % produces a nice wedge color bar\nnewParams.visualField = 360;        \nnewParams.width = 0;  \nretinoSetParams(view, 'Meta_Analysis', numScans(view), newParams);\n\n% show a legend if requested\nif legend, polarAngleMapLegend(view); end\n\n% ok, think that's it!\n\nreturn\n% /--------------------------------------------------------------------/ %\n\n\n\n\n\n% /--------------------------------------------------------------------/ %\nfunction A = polarAngleMapLegend(view);\n% img = polarAngleMapLegend(view);\n% Using the current map mode settings, produce a legend\n% for a polar angle parameter map and plot in a separate figure.\n% Returns a truecolor image if requested.\nmode = view.ui.mapMode;\n\n% generate an angle map A and a radius map R\n% A will start at the 12-o-clock and run clockwise back to 12,\n% ranging from 1 to the number of colors in the cmap.\n[X Y] = meshgrid(1:256, 1:256);\nX = X-128; Y = Y-128;\nA = atan2(X, Y);\nA = fliplr(mod(A-pi, 2*pi));\nA = rescale(A, [], [1 mode.numColors]);\nR = sqrt(X.^2 + Y.^2);\n\n% take cmap from color part of map mode\ncmap = mode.cmap(mode.numGrays+1:end,:);\n\n% convert A to truecolor\nA = ind2rgb(A, cmap);\n\n% for each color channel, mask out region outside radius (128 pixels)\n[I J] = find(R>128);\nfor ch = 1:3\n    ind = sub2ind(size(A), I, J, repmat(ch, size(I)));\n    A(ind) = 1;\nend\n\n% put up the image\nfigure('Color', 'w', 'Name', 'Polar Angle Map Legend');\nimshow(A);\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/VisualField/polarAngleMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.2143366877525372}}
{"text": "% Script: run_loma_yearly_stresstensor.m\n\n% Starting ZMAP\nsPath = pwd\ncd /home/jowoe/zmap\nstartup\ncd(sPath)\n\n% Load the parameter file\nload Params_Loma_ConstRad3km_Nmin50_0.01deg_T365d.mat\n\n% Do loop over different radii to select events\nfor fRadius = 3:1:5\n    sString = ['Radius: ', num2str(fRadius) 'km'];\n    params.fRadius = fRadius;\n    vResults = [];\n    disp(sString)\n    tstart1= cputime\n    !date\n    % Perform the calculation\n    [vResults] = gui_CalcStressInv(params);\n    !date\n    tend1=cputime-tstart1\n    !rm tmp*\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/thomas/seismicrates/loma_yearly_stresstensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21425416085561969}}
{"text": "function [e, edata, eprior, f, L, a, La2, p] = gpla_e(w, gp, varargin)\n%GPLA_E  Do Laplace approximation and return marginal log posterior estimate\n%\n%  Description\n%    E = GPLA_E(W, GP, X, Y, OPTIONS) takes a GP structure GP\n%    together with a matrix X of input vectors and a matrix Y of\n%    target vectors, and finds the Laplace approximation for the\n%    conditional posterior p(Y | X, th), where th is the\n%    parameters. Returns the energy at th (see below). Each\n%    row of X corresponds to one input vector and each row of Y\n%    corresponds to one target vector.\n%\n%    [E, EDATA, EPRIOR] = GPLA_E(W, GP, X, Y, OPTIONS) returns also \n%    the data and prior components of the total energy.\n%\n%    The energy is minus log posterior cost function for th:\n%      E = EDATA + EPRIOR \n%        = - log p(Y|X, th) - log p(th),\n%      where th represents the parameters (lengthScale,\n%      magnSigma2...), X is inputs and Y is observations.\n%\n%    OPTIONS is optional parameter-value pair\n%      z - optional observed quantity in triplet (x_i,y_i,z_i)\n%          Some likelihoods may use this. For example, in case of\n%          Poisson likelihood we have z_i=E_i, that is, expected\n%          value for ith case.\n%\n%  See also\n%    GP_SET, GP_E, GPLA_G, GPLA_PRED\n%\n%  Description 2\n%    Additional properties meant only for internal use.\n%  \n%    GP = GPLA_E('init', GP) takes a GP structure GP and\n%    initializes required fields for the Laplace approximation.\n% \n%    GP = GPLA_E('clearcache', GP) takes a GP structure GP and clears the\n%    internal cache stored in the nested function workspace.\n%\n%    [e, edata, eprior, f, L, a, La2, p] = GPLA_E(w, gp, x, y, varargin)\n%    returns many useful quantities produced by EP algorithm.\n%\n%    The Newton's method is implemented as described in Rasmussen\n%    and Williams (2006).\n%\n%    The stabilized Newton's method is implemented as suggested by\n%    Hannes Nickisch (personal communication).\n  \n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2010 Pasi Jyl\ufffdnki\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n  % parse inputs\n  ip=inputParser;\n  ip.FunctionName = 'GPLA_E';\n  ip.addRequired('w', @(x) ...\n                 isempty(x) || ...\n                 (ischar(x) && strcmp(w, 'init')) || ...\n                 isvector(x) && isreal(x) && all(isfinite(x)) ...\n                 || all(isnan(x)));\n  ip.addRequired('gp',@isstruct);\n  ip.addOptional('x', @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addOptional('y', @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('z', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\n  ip.parse(w, gp, varargin{:});\n  x=ip.Results.x;\n  y=ip.Results.y;\n  z=ip.Results.z;\n  \n  if strcmp(w, 'init')\n    % Initialize cache\n    ch = [];\n\n    % set function handle to the nested function laplace_algorithm\n    % this way each gp has its own peristent memory for EP\n    gp.fh.ne = @laplace_algorithm;\n    % set other function handles\n    gp.fh.e=@gpla_e;\n    gp.fh.g=@gpla_g;\n    gp.fh.pred=@gpla_pred;\n    gp.fh.jpred=@gpla_jpred;\n    gp.fh.looe=@gpla_looe;\n    gp.fh.loog=@gpla_loog;\n    gp.fh.loopred=@gpla_loopred;\n    e = gp;\n    % remove clutter from the nested workspace\n    clear w gp varargin ip x y z\n  elseif strcmp(w, 'clearcache')\n    % clear the cache\n    gp.fh.ne('clearcache');\n  else\n    % call laplace_algorithm using the function handle to the nested function\n    % this way each gp has its own peristent memory for Laplace\n    [e, edata, eprior, f, L, a, La2, p] = gp.fh.ne(w, gp, x, y, z);\n  end\n\n  function [e, edata, eprior, f, L, a, La2, p] = laplace_algorithm(w, gp, x, y, z)\n      \n  if strcmp(w, 'clearcache')\n      ch=[];\n      return\n  end\n  % code for the Laplace algorithm\n\n  % check whether saved values can be used\n    if isempty(z)\n      datahash=hash_sha512([x y]);\n    else\n      datahash=hash_sha512([x y z]);\n    end\n    if ~isempty(ch) && all(size(w)==size(ch.w)) && all(abs(w-ch.w)<1e-8) && ...\n          isequal(datahash,ch.datahash)\n      % The covariance function parameters or data haven't changed so we\n      % can return the energy and the site parameters that are\n      % saved in the cache\n      e = ch.e;\n      edata = ch.edata;\n      eprior = ch.eprior;\n      f = ch.f;\n      L = ch.L;\n      La2 = ch.La2;\n      a = ch.a;\n      p = ch.p;\n    else\n      % The parameters or data have changed since\n      % the last call for gpla_e. In this case we need to\n      % re-evaluate the Laplace approximation\n      gp=gp_unpak(gp, w);\n      ncf = length(gp.cf);\n      n = size(x,1);\n      p = [];\n      maxiter = gp.latent_opt.maxiter;\n      tol = gp.latent_opt.tol;\n\n      % Initialize latent values\n      % zero seems to be a robust choice (Jarno)\n      % with mean functions, initialize to mean function values\n      if ~isfield(gp,'meanf')\n        f = zeros(size(y));\n      else\n        [H,b_m,B_m]=mean_prep(gp,x,[]);\n        f = H'*b_m;\n      end\n      \n      % =================================================\n      % First Evaluate the data contribution to the error\n      switch gp.type\n        % ============================================================\n        % FULL\n        % ============================================================\n        case 'FULL'\n          \n          if ~isfield(gp.lik, 'nondiagW')\n           \n            K = gp_trcov(gp, x);\n            if isfield(gp,'meanf')\n              K=K+H'*B_m*H;\n            end\n            \n            % If K is sparse, permute all the inputs so that evaluations are more efficient\n            if issparse(K)         % Check if compact support covariance is used\n              p = analyze(K);\n              y = y(p);\n              K = K(p,p);\n              if ~isempty(z)\n                z = z(p,:);\n              end\n            end\n            switch gp.latent_opt.optim_method\n                % --------------------------------------------------------------------------------\n                % find the posterior mode of latent variables by Newton method\n              case 'newton'\n                a = f;\n                if isfield(gp,'meanf')\n                  a = a-H'*b_m;\n                end\n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_old = -Inf;\n                if issparse(K)\n                  speyen=speye(n);\n                end\n                \n                iter=0;\n                while abs(lp_new - lp_old) > tol && iter < maxiter\n                  iter = iter + 1;\n                  lp_old = lp_new; a_old = a;\n                  sW = sqrt(W);\n                  if issparse(K)\n                    sW = sparse(1:n, 1:n, sW, n, n);\n                    [L,notpositivedefinite] = ldlchol(speyen+sW*K*sW );\n                  else\n                    %L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW\n                    L=bsxfun(@times,bsxfun(@times,sW,K),sW');\n                    L(1:n+1:end)=L(1:n+1:end)+1;\n                    [L, notpositivedefinite] = chol(L);\n                  end\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  if ~isfield(gp,'meanf')\n                    b = W.*f+dlp;\n                  else\n                    b = W.*f+K\\(H'*b_m)+dlp;\n                  end\n                  if issparse(K)\n                    a = b - sW*ldlsolve(L,sW*(K*b));\n                  else\n                    a = b - sW.*(L\\(L'\\(sW.*(K*b))));\n                  end\n                  if any(isnan(a))\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  f = K*a;\n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  if ~isfield(gp,'meanf')\n                    lp_new = -a'*f/2 + lp;\n                  else\n                    lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp; %f^=f-H'*b_m,\n                  end\n                  i = 0;\n                  while i < 10 && (lp_new < lp_old  || isnan(sum(f)))\n                    % reduce step size by half\n                    a = (a_old+a)/2;\n                    f = K*a;\n                    lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                    if ~isfield(gp,'meanf')\n                      lp_new = -a'*f/2 + lp;\n                    else\n                      lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp;\n                    end\n                    i = i+1;\n                  end\n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                end\n\n                % --------------------------------------------------------------------------------\n                % find the posterior mode of latent variables by stabilized Newton method.\n                % This is implemented as suggested by Hannes Nickisch (personal communication)\n              case 'stabilized-newton'\n                % Gaussian initialization\n                %   sigma=gp.lik.sigma;\n                %   W = ones(n,1)./sigma.^2;\n                %   sW = sqrt(W);\n                %   %B = eye(n) + siV*siV'.*K;\n                %   L=bsxfun(@times,bsxfun(@times,sW,K),sW');\n                %   L(1:n+1:end)=L(1:n+1:end)+1;\n                %   L = chol(L,'lower');\n                %   a=sW.*(L'\\(L\\(sW.*y)));\n                %   f = K*a;\n                \n                % initialize to observations\n                %f=y;\n                \n                switch gp.lik.type\n                  % should be handled inside lik_*\n                  case 'Student-t'\n                    nu=gp.lik.nu;\n                    sigma2=gp.lik.sigma2;\n                    Wmax=(nu+1)/nu/sigma2;\n                  case 'Negbinztr'\n                    r=gp.lik.disper;\n                    Wmax=1./((1+r)./(1*r));\n                  otherwise\n                    Wmax=100;\n                end\n                Wlim=0;\n                \n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp = -(f'*(K\\f))/2 +gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_old = -Inf;\n                f_old = f+1;\n                ge = Inf; %max(abs(a-dlp));\n                if issparse(K)\n                  speyen=speye(n);\n                end\n                \n                iter=0;\n                % begin Newton's iterations\n                while (lp - lp_old > tol || max(abs(f-f_old)) > tol) && iter < maxiter\n                  iter=iter+1;\n                  \n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                  \n                  W(W<Wlim)=Wlim;\n                  sW = sqrt(W);\n                  if issparse(K)\n                    sW = sparse(1:n, 1:n, sW, n, n);\n                    [L, notpositivedefinite] = ldlchol(speyen+sW*K*sW );\n                  else\n                    %L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW\n                    L=bsxfun(@times,bsxfun(@times,sW,K),sW');\n                    L(1:n+1:end)=L(1:n+1:end)+1;\n                    [L, notpositivedefinite] = chol(L);\n                  end\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  b = W.*f+dlp;\n                  if issparse(K)\n                    a = b - sW*ldlsolve(L,sW*(K*b));\n                  else\n                    a = b - sW.*(L\\(L'\\(sW.*(K*b))));\n                  end\n                  \n                  f_new = K*a;\n                  lp_new = -(a'*f_new)/2 + gp.lik.fh.ll(gp.lik, y, f_new, z);\n                  ge_new=max(abs(a-dlp));\n                  \n                  d=lp_new-lp;\n                  if (d<-1e-6 || (abs(d)<1e-6 && ge_new>ge) )  && Wlim<Wmax*0.5\n                    %fprintf('%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \\n',i1,lp,ge,Wlim)\n                    Wlim=Wlim+Wmax*0.05; %Wmax*0.01\n                  else\n                    Wlim=0;\n                    \n                    ge=ge_new;\n                    lp_old = lp;\n                    lp = lp_new;\n                    f_old = f;\n                    f = f_new;\n                    %fprintf('%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \\n',i1,lp,ge,Wlim)\n                    \n                  end\n                  \n                  if Wlim>Wmax\n                    %fprintf('\\n%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \\n',i1,lp,ge,Wlim)\n                    break\n                  end\n                end\n                \n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables by fminunc\n              case 'fminunc_large'\n                if issparse(K)\n                  [LD,notpositivedefinite] = ldlchol(K);\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  fhm = @(W, f, varargin) (ldlsolve(LD,f) + repmat(W,1,size(f,2)).*f);  % W*f; %\n                else\n                  [LD,notpositivedefinite] = chol(K);\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  fhm = @(W, f, varargin) (LD\\(LD'\\f) + repmat(W,1,size(f,2)).*f);  % W*f; %\n                end\n                defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', tol,'TolFun', tol,'LargeScale', 'on','Display', 'off');\n                if ~isfield(gp.latent_opt, 'fminunc_opt')\n                  opt = optimset(defopts);\n                else\n                  opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n                end\n                \n                if issparse(K)\n                  fe = @(f, varargin) (0.5*f*(ldlsolve(LD,f')) - gp.lik.fh.ll(gp.lik, y, f', z));\n                  fg = @(f, varargin) (ldlsolve(LD,f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n                  fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z)); %inv(K) + diag(g2(f', gp.lik)) ; %\n                else\n                  fe = @(f, varargin) (0.5*f*(LD\\(LD'\\f')) - gp.lik.fh.ll(gp.lik, y, f', z));\n                  fg = @(f, varargin) (LD\\(LD'\\f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n                  fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z)); %inv(K) + diag(g2(f', gp.lik)) ; %\n                end\n                \n                mydeal = @(varargin)varargin{1:nargout};\n                [f,fval,exitflag,output] = fminunc(@(ww) mydeal(fe(ww), fg(ww), fh(ww)), f', opt);\n                f = f';\n                \n                if issparse(K)\n                  a = ldlsolve(LD,f);\n                else\n                  a = LD\\(LD'\\f);\n                end\n                \n                % --------------------------------------------------------------------------------\n                % find the posterior mode of latent variables with likelihood specific algorithm\n                % For example, with Student-t likelihood this mean EM-algorithm which is coded in the\n                % lik_t file.\n              case 'lik_specific'\n                [f, a] = gp.lik.fh.optimizef(gp, y, K);\n                if isnan(f)\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n              otherwise\n                error('gpla_e: Unknown optimization method ! ')\n            end\n            \n            % evaluate the approximate log marginal likelihood\n            W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n            if ~isfield(gp,'meanf')\n              logZ = 0.5 *f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n            else\n              logZ = 0.5 *((f-H'*b_m)'*(a-K\\(H'*b_m))) - gp.lik.fh.ll(gp.lik, y, f, z);\n            end\n            if min(W) >= 0 \n              % This is the usual case where likelihood is log concave\n              % for example, Poisson and probit\n              if issparse(K)\n                W = sparse(1:n,1:n, -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z), n,n);\n                sqrtW = sqrt(W);\n                B = sparse(1:n,1:n,1,n,n) + sqrtW*K*sqrtW;\n                [L, notpositivedefinite] = ldlchol(B);\n                \n                % Note that here we use LDL cholesky\n                edata = logZ + 0.5.*sum(log(diag(L))); % 0.5*log(det(eye(size(K)) + K*W)) ; %\n              else\n                sW = sqrt(W);\n                L=bsxfun(@times,bsxfun(@times,sW,K),sW');\n                L(1:n+1:end)=L(1:n+1:end)+1;\n                [L, notpositivedefinite] = chol(L, 'lower');\n                edata = logZ + sum(log(diag(L))); % 0.5*log(det(eye(size(K)) + K*W)) ; %\n              end\n              if notpositivedefinite\n                [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                return\n              end\n            else\n              % We may end up here if the likelihood is not log concave\n              % For example Student-t likelihood.\n              [W2,I] = sort(W, 1, 'descend');\n              \n              if issparse(K)\n                error(['gpla_e: Unfortunately the compact support covariance (CS) functions do not work if'...\n                  'the second gradient of negative likelihood is negative. This happens for example  '...\n                  'with Student-t likelihood. Please use non-CS functions instead (e.g. gpcf_sexp)   ']);\n              end\n              \n              [L, notpositivedefinite] = chol(K);\n              if notpositivedefinite\n                [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                return\n              end\n              L1 = L;\n              for jj=1:size(K,1)\n                i = I(jj);\n                ll = sum(L(:,i).^2);\n                l = L'*L(:,i);\n                upfact = W(i)./(1 + W(i).*ll);\n                \n                % Check that Cholesky factorization will remain positive definite\n                if 1./ll + W(i) < 0 %1 + W(i).*ll <= 0 | abs(upfact) > abs(1./ll) %upfact > 1./ll\n                  warning('gpla_e: 1./Sigma(i,i) + W(i) < 0')\n                  \n                  if ~isfield(gp.lik.fh,'upfact')\n                    % log-concave likelihood, this should not happen\n                    % let's just return NaN\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  \n                  % non-log-concave likelihood, this may happen\n                  % let's try to do something about it\n                  ind = 1:i-1;\n                  if isempty(z)\n                    mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z);\n                    upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll);\n                  else\n                    mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z(I(ind)));\n                    upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll, z(I(i)));\n                  end\n                end\n                if upfact > 0\n                  [L,notpositivedefinite] = cholupdate(L, l.*sqrt(upfact), '-');\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                else\n                  L = cholupdate(L, l.*sqrt(-upfact));\n                end\n              end\n              edata = logZ + sum(log(diag(L1))) - sum(log(diag(L)));\n            end\n            \n            La2 = W;\n            \n          else\n            % Likelihoods with non-diagonal Hessian\n            \n            [n,nout] = size(y);           \n            if isfield(gp, 'comp_cf')  % own covariance for each ouput component\n              multicf = true;\n              if length(gp.comp_cf) ~= nout && nout > 1\n                error('GPLA_ND_E: the number of component vectors in gp.comp_cf must be the same as number of outputs.')\n              end\n            else\n              multicf = false;\n            end            \n            p=[];\n            switch gp.lik.type\n              \n              case {'LGP', 'LGPC'}\n                \n                nl=n;\n                \n                % Initialize latent values\n                % zero seems to be a robust choice (Jarno)\n                % with mean functions, initialize to mean function values\n                if ~isfield(gp,'meanf')\n                  f = zeros(sum(nl),1);\n                else\n                  [H,b_m,B_m]=mean_prep(gp,x,[]);\n                  Hb_m=H'*b_m;\n                  f = Hb_m;\n                end\n                \n                if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                  gptmp=gp; gptmp.jitterSigma2=0;\n                  % Use Kronecker product kron(Ka,Kb) instead of K\n                  Ka = gp_trcov(gptmp, unique(x(:,1)));\n                  % fix the magnitude sigma to 1 for Kb matrix\n                  wtmp=gp_pak(gptmp); wtmp(1)=0; gptmp=gp_unpak(gptmp,wtmp);\n                  Kb = gp_trcov(gptmp, unique(x(:,2)));\n                  clear gptmp\n                  n1=size(Ka,1);\n                  n2=size(Kb,1);\n                  \n                  [Va,Da]=eig(Ka); [Vb,Db]=eig(Kb);\n                  % eigenvalues of K matrix\n                  Dtmp=kron(diag(Da),diag(Db));\n                  [sDtmp,istmp]=sort(Dtmp,'descend');\n                  \n                  % Form the low-rank approximation.  Exclude eigenvalues\n                  % smaller than gp.latent_opt.eig_tol or take\n                  % gp.latent_opt.eig_prct*n eigenvalues at most.\n                  nlr=min([sum(sDtmp>gp.latent_opt.eig_tol) round(gp.latent_opt.eig_prct*n)]);\n                  sDtmp=sDtmp+gp.jitterSigma2;\n                  \n                  itmp1=meshgrid(1:n1,1:n2);\n                  itmp2=meshgrid(1:n2,1:n1)';\n                  ind=[itmp1(:) itmp2(:)];\n                  \n                  % included eigenvalues\n                  Dlr=sDtmp(1:nlr);\n                  % included eigenvectors\n                  Vlr=zeros(n,nlr);\n                  for i1=1:nlr\n                    Vlr(:,i1)=kron(Va(:,ind(istmp(i1),1)),Vb(:,ind(istmp(i1),2)));\n                  end\n                  %L=[];\n                  \n                  % diag(K)-diag(Vlr*diag(Dlr)*Vlr')\n                  Lb=gp_trvar(gp,x)-sum(bsxfun(@times,Vlr.*Vlr,Dlr'),2);\n                  if isfield(gp,'meanf')\n                    Dt=[Dlr; diag(B_m)];\n                    Vt=[Vlr H'];\n                  else\n                    Dt=Dlr;\n                    Vt=Vlr;\n                  end\n                  Dtsq=sqrt(Dt);\n                  \n                elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                  % unique values from covariance matrix\n                  K1 = gp_cov(gp, x(1,:), x);\n                  K1(1)=K1(1)+gp.jitterSigma2;\n                  if size(x,2)==1\n                    % form circulant matrix to avoid border effects\n                    Kcirc=[K1 0 K1(end:-1:2)];\n                    fftKcirc = fft(Kcirc);\n                  elseif size(x,2)==2\n                    n1=gp.latent_opt.gridn(1);\n                    n2=gp.latent_opt.gridn(2);\n                    Ktmp=reshape(K1,n2,n1);\n                    % form circulant matrix to avoid border effects\n                    Ktmp=[Ktmp; zeros(1,n1); flipud(Ktmp(2:end,:))];\n                    fftKcirc=fft2([Ktmp zeros(2*n2,1) fliplr(Ktmp(:,2:end))]);\n                  else\n                    error('FFT speed-up implemented only for 1D and 2D cases.')\n                  end\n                else\n                  K = gp_trcov(gp, x);\n                end\n                \n                % Mean function contribution to K\n                if isfield(gp,'meanf')\n                  if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                    % only zero mean function implemented for Kronecker\n                    % approximation\n                    iKHb_m=zeros(n,1);\n                  elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                    % only zero mean function implemented for FFT speed-up\n                    iKHb_m=zeros(n,1);\n                  else\n                    K=K+H'*B_m*H;\n                    ws=warning('off','MATLAB:singularMatrix');\n                    iKHb_m=K\\Hb_m;\n                    warning(ws);\n                  end\n                end\n                \n                \n                % Main Newton algorithm\n                \n                tol = 1e-12;\n                a = f;\n                if isfield(gp,'meanf')\n                  a = a-Hb_m;\n                end\n                \n                % a vector to form the second gradient\n                g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                g2sq=sqrt(g2);\n                \n                ny=sum(y); % total number of observations\n                \n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_old = -Inf;\n                \n                iter=0;\n                while abs(lp_new - lp_old) > tol && iter < maxiter\n                  iter = iter + 1;\n                  lp_old = lp_new; a_old = a;\n                  \n                  \n                  if ~isfield(gp,'meanf')\n                    if strcmpi(gp.lik.type,'LGPC')\n                      n1=gp.lik.gridn(1); n2=gp.lik.gridn(2);\n                      b=zeros(n,1);\n                      ny2=sum(reshape(y,fliplr(gp.lik.gridn)));\n                      for k1=1:n1\n                        b((1:n2)+(k1-1)*n2) = ny2(k1)*(g2((1:n2)+(k1-1)*n2).*f((1:n2)+(k1-1)*n2)-g2((1:n2)+(k1-1)*n2)*(g2((1:n2)+(k1-1)*n2)'*f((1:n2)+(k1-1)*n2)))+dlp((1:n2)+(k1-1)*n2);\n                      end\n                    else\n                      b = ny*(g2.*f-g2*(g2'*f))+dlp;\n                      %b = W.*f+dlp;\n                    end\n                  else\n                    if strcmpi(gp.lik.type,'LGPC')\n                      n1=gp.lik.gridn(1); n2=gp.lik.gridn(2);\n                      b=zeros(n,1);\n                      ny2=sum(reshape(y,fliplr(gp.lik.gridn)));\n                      for k1=1:n1\n                        b((1:n2)+(k1-1)*n2) = ny2(k1)*(g2((1:n2)+(k1-1)*n2).*f((1:n2)+(k1-1)*n2)-g2((1:n2)+(k1-1)*n2)*(g2((1:n2)+(k1-1)*n2)'*f((1:n2)+(k1-1)*n2)))+iKHb_m((1:n2)+(k1-1)*n2)+dlp((1:n2)+(k1-1)*n2);\n                      end\n                    else\n                      b = ny*(g2.*f-g2*(g2'*f))+iKHb_m+dlp;\n                      %b = W.*f+K\\(H'*b_m)+dlp;\n                    end\n                  end\n                  \n                  if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                    \n                    % Use Kronecker product structure in matrix vector\n                    % multiplications\n                    %-\n                    % q=Kb*reshape(b,n2,n1)*Ka;\n                    % Kg=q(:);\n                    % Kg=Kg+gp.jitterSigma2*b;\n                    %-\n                    % OR use reduced-rank approximation for K\n                    %-\n                    Kg=Lb.*b+Vlr*(Dlr.*(Vlr'*b));\n                    %-\n                    \n                    if isfield(gp,'meanf')\n                      Kg=Kg+H'*(B_m*(H*b));\n                    end\n                    \n                    % % Use Kronecker product structure\n                    %-\n                    % v=sqrt(ny)*(g2sq.*Kg-(g2*(g2'*Kg))./g2sq);\n                    % % fast matrix vector multiplication with\n                    % % Kronecker product for matrix inversion\n                    % if isfield(gp,'meanf')\n                    %   [iSg,~]=pcg(@(z) mvm_kron(g2,ny,Ka,Kb,H,B_m,gp.jitterSigma2,z), v, gp.latent_opt.pcg_tol);\n                    % else\n                    %   [iSg,~]=pcg(@(z) mvm_kron(g2,ny,Ka,Kb,[],[],gp.jitterSigma2,z), v, gp.latent_opt.pcg_tol);\n                    % end\n                    % a=b-sqrt(ny)*(g2sq.*iSg  - g2*(g2'*(iSg./g2sq)));\n                    %-\n                    \n                    % use reduced-rank approximation for K\n                    %-\n                    Zt=1./(1+ny*g2.*Lb);\n                    Ztsq=sqrt(Zt);\n                    Ltmp=bsxfun(@times,Ztsq.*sqrt(ny).*g2sq,bsxfun(@times,Vt,sqrt(Dt)'));\n                    Ltmp=Ltmp'*Ltmp;\n                    Ltmp(1:(size(Dt,1)+1):end)=Ltmp(1:(size(Dt,1)+1):end)+1;\n                    [L,notpositivedefinite] = chol(Ltmp,'lower');\n                    if notpositivedefinite\n                      [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                      return\n                    end\n                    \n                    EKg=ny*g2.*(Zt.*Kg)-sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*(Vt*(Dtsq.*(L'\\(L\\(Dtsq.*(Vt'*(sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*Kg)))))))))));\n                    E1=ny*g2.*(Zt.*ones(n,1))-sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*(Vt*(Dtsq.*(L'\\(L\\(Dtsq.*(Vt'*(sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*ones(n,1))))))))))));\n                    a=b-(EKg-E1*((E1'*Kg)./(ones(1,n)*E1)));\n                    %-\n                    \n                  elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                    \n                    % use FFT speed-up in matrix vector multiplications\n                    if size(x,2)==1\n                      gge=zeros(2*n,1);\n                      gge(1:n)=b;\n                      q=ifft(fftKcirc.*fft(gge'));\n                      Kg=q(1:n)';\n                    elseif size(x,2)==2\n                      gge=zeros(2*n2,2*n1);\n                      gge(1:n2,1:n1)=reshape(b,n2,n1);\n                      \n                      q=ifft2(fftKcirc.*fft2(gge));\n                      q=q(1:n2,1:n1);\n                      Kg=q(:);\n                    else\n                      error('FFT speed-up implemented only for 1D and 2D cases.')\n                    end\n                    \n                    if isfield(gp,'meanf')\n                      Kg=Kg+H'*(B_m*(H*b));\n                    end\n                    v=sqrt(ny)*(g2sq.*Kg-(g2*(g2'*Kg))./g2sq);\n                    \n                    if isfield(gp,'meanf')\n                      % fast matrix vector multiplication with fft for matrix inversion\n                      [iSg,~]=pcg(@(z) mvm_fft(g2,ny,fftKcirc,H,B_m,z), v, gp.latent_opt.pcg_tol);\n                    else\n                      [iSg,~]=pcg(@(z) mvm_fft(g2,ny,fftKcirc,[],[],z), v, gp.latent_opt.pcg_tol);\n                    end\n                    a=b-sqrt(ny)*(g2sq.*iSg  - g2*(g2'*(iSg./g2sq)));\n                    \n                  else\n                    if strcmpi(gp.lik.type,'LGPC')\n                      R=zeros(n);\n                      RKR=K;\n                      for k1=1:n1\n                        R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)=sqrt(ny2(k1))*(diag(g2sq((1:n2)+(k1-1)*n2))-g2((1:n2)+(k1-1)*n2)*g2sq((1:n2)+(k1-1)*n2)');\n                        RKR(:,(1:n2)+(k1-1)*n2)=RKR(:,(1:n2)+(k1-1)*n2)*R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2);\n                      end\n                      for k1=1:n1\n                        RKR((1:n2)+(k1-1)*n2,:)=R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)'*RKR((1:n2)+(k1-1)*n2,:);\n                      end\n                      %RKR=R'*K*R;\n                      RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;\n                      [L,notpositivedefinite] = chol(RKR,'lower');\n                      \n                      if notpositivedefinite\n                        [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                        return\n                      end\n                      \n                      Kb=K*b;\n                      RCb=R'*Kb;\n                      \n                      iRCb=L'\\(L\\RCb);\n                      a=b-R*iRCb;\n                    else\n                      %R=-g2*g2sq'; R(1:(n+1):end)=R(1:(n+1):end)+g2sq';\n                      KR=bsxfun(@times,K,g2sq')-(K*g2)*g2sq';\n                      RKR=ny*(bsxfun(@times,g2sq,KR)-g2sq*(g2'*KR));\n                      RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;\n                      [L,notpositivedefinite] = chol(RKR,'lower');\n                      \n                      if notpositivedefinite\n                        [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                        return\n                      end\n                      \n                      Kb=K*b;\n                      RCb=g2sq.*Kb-g2sq*(g2'*Kb);\n                      iRCb=L'\\(L\\RCb);\n                      a=b-ny*(g2sq.*iRCb-g2*(g2sq'*iRCb));\n                    end\n                  end\n                  \n                  \n                  if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                    \n                    % % Use Kronecker product structure\n                    %-\n                    % f2=Kb*reshape(a,n2,n1)*Ka;\n                    % f=f2(:);\n                    % f=f+gp.jitterSigma2*a;\n                    %-\n                    % use reduced-rank approximation for K\n                    %-\n                    f=Lb.*a+Vlr*(Dlr.*(Vlr'*a));\n                    %-\n                    \n                    if isfield(gp,'meanf')\n                      f=f+H'*(B_m*(H*a));\n                    end\n                  elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                    if size(x,2)==1\n                      a2=zeros(2*n,1);\n                      a2(1:n)=a;\n                      f2=ifft(fftKcirc.*fft(a2'));\n                      f=f2(1:n)';\n                      if isfield(gp,'meanf')\n                        f=f+H'*(B_m*(H*a));\n                      end\n                    elseif size(x,2)==2\n                      a2=zeros(2*n2,2*n1);\n                      a2(1:n2,1:n1)=reshape(a,n2,n1);\n                      \n                      f2=ifft2(fftKcirc.*fft2(a2));\n                      f2=f2(1:n2,1:n1);\n                      f=f2(:);\n                      if isfield(gp,'meanf')\n                        f=f+H'*(B_m*(H*a));\n                      end\n                    else\n                      error('FFT speed-up implemented only for 1D and 2D cases.')\n                    end\n                  else\n                    f = K*a;\n                  end\n                  \n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  if ~isfield(gp,'meanf')\n                    lp_new = -a'*f/2 + lp;\n                  else\n                    %lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp; %f^=f-H'*b_m,\n                    lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp; %f^=f-Hb_m,\n                  end\n                  i = 0;\n                  while i < 10 && lp_new < lp_old && ~isnan(sum(f))\n                    % reduce step size by half\n                    a = (a_old+a)/2;\n                    \n                    if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                      % % Use Kronecker product structure\n                      %-\n                      % f2=Kb*reshape(a,n2,n1)*Ka;\n                      % f=f2(:);\n                      % f=f+gp.jitterSigma2*a;\n                      %-\n                      % use reduced-rank approximation for K\n                      %-\n                      f=Lb.*a+Vlr*(Dlr.*(Vlr'*a));\n                      %-\n                      \n                      if isfield(gp,'meanf')\n                        f=f+H'*(B_m*(H*a));\n                      end\n                    elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                      if size(x,2)==1\n                        a2=zeros(2*n,1);\n                        a2(1:n)=a;\n                        f2=ifft(fftKcirc.*fft(a2'));\n                        f=f2(1:n)';\n                        \n                        if isfield(gp,'meanf')\n                          f=f+H'*(B_m*(H*a));\n                        end\n                      elseif size(x,2)==2\n                        a2=zeros(2*n2,2*n1);\n                        a2(1:n2,1:n1)=reshape(a,n2,n1);\n                        f2=ifft2(fftKcirc.*fft2(a2));\n                        f2=f2(1:n2,1:n1);\n                        f=f2(:);\n                        \n                        if isfield(gp,'meanf')\n                          f=f+H'*(B_m*(H*a));\n                        end\n                      else\n                        error('FFT speed-up implemented only for 1D and 2D cases.')\n                      end\n                    else\n                      f = K*a;\n                    end\n                    \n                    lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                    if ~isfield(gp,'meanf')\n                      lp_new = -a'*f/2 + lp;\n                    else\n                      %lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp;\n                      lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp;\n                    end\n                    i = i+1;\n                  end\n                  \n                  g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  g2sq=sqrt(g2);\n                  \n                  dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                end\n                \n                % evaluate the approximate log marginal likelihood\n                g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                g2sq=sqrt(g2);\n                \n                if ~isfield(gp,'meanf')\n                  logZ = 0.5 *f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n                else\n                  % logZ = 0.5 *((f-H'*b_m)'*(a-K\\(H'*b_m))) - gp.lik.fh.ll(gp.lik, y, f, z);\n                  logZ = 0.5 *((f-Hb_m)'*(a-iKHb_m)) - gp.lik.fh.ll(gp.lik, y, f, z);\n                end\n                \n                \n                if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1\n                  % % Use Kronecker product structure\n                  %-\n                  % tmp=bsxfun(@times,Lb.^(-1/2),bsxfun(@times,Vt,sqrt(Dt)'));\n                  % tmp=tmp'*tmp;\n                  % tmp(1:size(tmp,1)+1:end)=tmp(1:size(tmp,1)+1:end)+1;\n                  % logZa=sum(log(diag(chol(tmp,'lower'))));\n                  %\n                  % Lbt=ny*(g2)+1./Lb;\n                  %\n                  % St=[diag(1./Dt)+Vt'*bsxfun(@times,1./Lb,Vt) zeros(size(Dt,1),1); ...\n                  %   zeros(1,size(Dt,1)) 1];\n                  % Pt=[bsxfun(@times,1./Lb,Vt) sqrt(ny)*g2];\n                  %\n                  % logZb=sum(log(diag(chol(St,'lower'))));\n                  %\n                  % Ptt=bsxfun(@times,1./sqrt(Lbt),Pt);\n                  % logZc=sum(log(diag(chol(St-Ptt'*Ptt,'lower'))));\n                  %\n                  % edata = logZ + logZa - logZb + logZc + 0.5*sum(log(Lb)) + 0.5*sum(log(Lbt));\n                  %-\n                  \n                  % use reduced-rank approximation for K\n                  %-\n                  Zt=1./(1+ny*g2.*Lb);\n                  Ztsq=sqrt(Zt);\n                  Ltmp=bsxfun(@times,Ztsq.*sqrt(ny).*g2sq,bsxfun(@times,Vt,sqrt(Dt)'));\n                  Ltmp=Ltmp'*Ltmp;\n                  Ltmp(1:(size(Dt,1)+1):end)=Ltmp(1:(size(Dt,1)+1):end)+1;\n                  L=chol(Ltmp,'lower');\n                  \n                  LTtmp=L\\( Dtsq.*(Vt'*( (g2sq.*sqrt(ny)).*((1./(1+ny*g2.*Lb)).* (sqrt(ny)*g2sq) ) )) );\n                  edata = logZ + sum(log(diag(L)))+0.5*sum(log(1+ny*g2.*Lb)) ...\n                    -0.5*log(ny) + 0.5*log(sum(((g2*ny)./(ny*g2.*Lb+1)))-LTtmp'*LTtmp);\n                  %-\n                elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1\n                  \n                  K = gp_trcov(gp, x);\n                  if isfield(gp,'meanf')\n                    K=K+H'*B_m*H;\n                  end\n                  \n                  % exact determinant\n                  KR=bsxfun(@times,K,g2sq')-(K*g2)*g2sq';\n                  RKR=ny*(bsxfun(@times,g2sq,KR)-g2sq*(g2'*KR));\n                  RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;\n                  [L,notpositivedefinite] = chol(RKR,'lower');\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  edata = logZ + sum(log(diag(L)));\n                  \n                  % % determinant approximated using only the largest eigenvalues\n                  % opts.issym = 1;\n                  % Deig=eigs(@(z) mvm_fft(g2, ny, fftKcirc, H, B_m, z),n,round(n*0.05),'lm',opts);\n                  % edata = logZ + 0.5*sum(log(Deig));\n                  % L=[];\n                else\n                  \n                  if strcmpi(gp.lik.type,'LGPC')\n                    R=zeros(n);\n                    RKR=K;\n                    for k1=1:n1\n                      R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)=sqrt(ny2(k1))*(diag(g2sq((1:n2)+(k1-1)*n2))-g2((1:n2)+(k1-1)*n2)*g2sq((1:n2)+(k1-1)*n2)');\n                      RKR(:,(1:n2)+(k1-1)*n2)=RKR(:,(1:n2)+(k1-1)*n2)*R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2);\n                    end\n                    for k1=1:n1\n                      RKR((1:n2)+(k1-1)*n2,:)=R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)'*RKR((1:n2)+(k1-1)*n2,:);\n                    end\n                    %RKR=R'*K*R;\n                  else\n                    KR=bsxfun(@times,K,g2sq')-(K*g2)*g2sq';\n                    RKR=ny*(bsxfun(@times,g2sq,KR)-g2sq*(g2'*KR));\n                  end\n                  RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;\n                  [L,notpositivedefinite] = chol(RKR,'lower');\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  edata = logZ + sum(log(diag(L)));\n                end\n                \n                M=[];\n                E=[];\n                \n              case {'Softmax', 'Multinom'}\n                \n                % Initialize latent values\n                % zero seems to be a robust choice (Jarno)\n                f = zeros(size(y(:)));\n                \n                K = zeros(n,n,nout);\n                if multicf\n                  for i1=1:nout\n                    K(:,:,i1) = gp_trcov(gp, x, gp.comp_cf{i1});\n                  end\n                else\n                  Ktmp=gp_trcov(gp, x);\n                  for i1=1:nout\n                    K(:,:,i1) = Ktmp;\n                  end\n                end\n                \n                % Main newton algorithm, see Rasmussen & Williams (2006),\n                % p. 50\n                \n                tol = 1e-12;\n                a = f;\n                \n                f2=reshape(f,n,nout);\n                \n                % lp_new = log(p(y|f))\n                lp_new = gp.lik.fh.ll(gp.lik, y, f2, z);\n                lp_old = -Inf;\n                \n                c=zeros(n*nout,1);\n                ERMMRc=zeros(n*nout,1);\n                E=zeros(n,n,nout);\n                L=zeros(n,n,nout);\n                RER = zeros(n,n,nout);\n                \n                while lp_new - lp_old > tol\n                  lp_old = lp_new; a_old = a;\n                  \n                  % llg = d(log(p(y|f)))/df\n                  llg = gp.lik.fh.llg(gp.lik, y, f2, 'latent', z);\n                  % Second derivatives\n                  [pi2_vec, pi2_mat] = gp.lik.fh.llg2(gp.lik, y, f2, 'latent', z);\n                  % W = -diag(pi2_vec) + pi2_mat*pi2_mat'\n                  pi2 = reshape(pi2_vec,size(y));\n                  \n                  R = repmat(1./pi2_vec,1,n).*pi2_mat;\n                  for i1=1:nout\n                    Dc=sqrt(pi2(:,i1));\n                    Lc=(Dc*Dc').*K(:,:,i1);\n                    Lc(1:n+1:end)=Lc(1:n+1:end)+1;\n                    [Lc,notpositivedefinite]=chol(Lc);\n                    if notpositivedefinite\n                      [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                      return\n                    end\n                    L(:,:,i1)=Lc;\n                    \n                    Ec=Lc'\\diag(Dc);\n                    Ec=Ec'*Ec;\n                    E(:,:,i1)=Ec;\n                    RER(:,:,i1) = R((1:n)+(i1-1)*n,:)'*Ec*R((1:n)+(i1-1)*n,:);\n                  end\n                  [M, notpositivedefinite]=chol(sum(RER,3));\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  \n                  b = pi2_vec.*f - pi2_mat*(pi2_mat'*f) + llg;\n                  for i1=1:nout\n                    c((1:n)+(i1-1)*n)=E(:,:,i1)*(K(:,:,i1)*b((1:n)+(i1-1)*n));\n                  end\n                  \n                  RMMRc=R*(M\\(M'\\(R'*c)));\n                  for i1=1:nout\n                    ERMMRc((1:n)+(i1-1)*n) = E(:,:,i1)*RMMRc((1:n)+(i1-1)*n,:);\n                  end\n                  a=b-c+ERMMRc;\n                  \n                  for i1=1:nout\n                    f((1:n)+(i1-1)*n)=K(:,:,i1)*a((1:n)+(i1-1)*n);\n                  end\n                  f2=reshape(f,n,nout);\n                  \n                  lp_new = -a'*f/2 + gp.lik.fh.ll(gp.lik, y, f2, z);\n                  \n                  i = 0;\n                  while i < 10 && lp_new < lp_old  || isnan(sum(f))\n                    % reduce step size by half\n                    a = (a_old+a)/2;\n                    \n                    for i1=1:nout\n                      f((1:n)+(i1-1)*n)=K(:,:,i1)*a((1:n)+(i1-1)*n);\n                    end\n                    f2=reshape(f,n,nout);\n                    \n                    lp_new = -a'*f/2 + gp.lik.fh.ll(gp.lik, y, f2, z);\n                    i = i+1;\n                  end\n                end\n                \n                [pi2_vec, pi2_mat] = gp.lik.fh.llg2(gp.lik, y, f2, 'latent', z);\n                pi2 = reshape(pi2_vec,size(y));\n                \n                zc=0;\n                Detn=0;\n                R = repmat(1./pi2_vec,1,n).*pi2_mat;\n                for i1=1:nout\n                  Dc=sqrt( pi2(:,i1) );\n                  Lc=(Dc*Dc').*K(:,:,i1);\n                  Lc(1:n+1:end)=Lc(1:n+1:end)+1;\n                  [Lc, notpositivedefinite]=chol(Lc);\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  L(:,:,i1)=Lc;\n                  \n                  pi2i = pi2_mat((1:n)+(i1-1)*n,:);\n                  pipi = pi2i'/diag(Dc);\n                  Detn = Detn + pipi*(Lc\\(Lc'\\diag(Dc)))*K(:,:,i1)*pi2i;\n                  zc = zc + sum(log(diag(Lc)));\n                  \n                  Ec=Lc'\\diag(Dc);\n                  Ec=Ec'*Ec;\n                  E(:,:,i1)=Ec;\n                  RER(:,:,i1) = R((1:n)+(i1-1)*n,:)'*Ec*R((1:n)+(i1-1)*n,:);\n                end\n                [M, notpositivedefinite]=chol(sum(RER,3));\n                if notpositivedefinite\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n                \n                zc = zc + sum(log(diag(chol( eye(size(K(:,:,i1))) - Detn))));\n                \n                logZ = a'*f/2 - gp.lik.fh.ll(gp.lik, y, f2, z) + zc;\n                edata = logZ;\n                \n              otherwise\n                \n                if ~isfield(gp, 'comp_cf') || isempty(gp.comp_cf)\n                  error('Define multiple covariance functions for latent processes using gp.comp_cf (see gp_set)');\n                end\n                \n                if isfield(gp.lik,'xtime')\n                  xtime=gp.lik.xtime;\n                  if isfield(gp.lik, 'stratificationVariables')\n                    ebc_ind=gp.lik.stratificationVariables;\n                    ux = unique(x(:,ebc_ind), 'rows');\n                    gp.lik.n_u = size(ux,1);\n                    for i1=1:size(ux,1)\n                      gp.lik.stratind{i1}=(x(:,ebc_ind)==ux(i1));\n                    end\n                    [xtime1, xtime2] = meshgrid(ux, xtime);\n                    xtime = [xtime2(:) xtime1(:)];\n                    if isfield(gp.lik, 'removeStratificationVariables') && gp.lik.removeStratificationVariables\n                      x(:,ebc_ind)=[];\n                    end\n                  end\n                  ntime = size(xtime,1);\n                  nl=[ntime n];\n                else\n                  nl=repmat(n,1,length(gp.comp_cf));\n                end\n                nlp=length(nl); % number of latent processes\n                \n                % Initialize latent values\n                % zero seems to be a robust choice (Jarno)\n                % with mean functions, initialize to mean function values\n                if ~isfield(gp,'meanf')\n                  f = zeros(sum(nl),1);\n                  if isequal(gp.lik.type, 'Inputdependentnoise')\n                    % Inputdependent-noise needs initialization to mean\n                    Kf = gp_trcov(gp,x,gp.comp_cf{1});\n                    f(1:n) = Kf*((Kf+gp.lik.sigma2.*eye(n))\\y);\n                  end\n                else\n                  [H,b_m,B_m]=mean_prep(gp,x,[]);\n                  Hb_m=H'*b_m;\n                  f = Hb_m;\n                end\n                \n                % K is block-diagonal covariance matrix where blocks\n                % correspond to latent processes\n                K = zeros(sum(nl));\n                if isfield(gp.lik,'xtime')\n                  K(1:ntime,1:ntime)=gp_trcov(gp, xtime, gp.comp_cf{1});\n                  K((1:n)+ntime,(1:n)+ntime) = gp_trcov(gp, x, gp.comp_cf{2});\n                else\n                  for i1=1:nlp\n                    K((1:n)+(i1-1)*n,(1:n)+(i1-1)*n) = gp_trcov(gp, x, gp.comp_cf{i1});\n                  end\n                end\n                \n                % Mean function contribution to K\n                if isfield(gp,'meanf')\n                  K=K+H'*B_m*H;\n                  iKHb_m=K\\Hb_m;\n                end\n                \n                % Main Newton algorithm, see Rasmussen & Williams (2006),\n                % p. 46\n                \n                tol = 1e-12;\n                a = f;\n                if isfield(gp,'meanf')\n                  a = a-Hb_m;\n                end\n                \n                % Second derivatives of log-likelihood\n                if isfield(gp.lik,'xtime')\n                  [llg2diag, llg2mat] = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  % W = [diag(Wdiag(1:ntime)) Wmat; Wmat' diag(Wdiag(ntime+1:end)]\n                  Wdiag=-llg2diag; Wmat=-llg2mat;\n                  W=[];\n                else\n                  Wvec = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  % W = [diag(Wvec(1:n,1)) diag(Wvec(1:n,2)) diag(Wvec(n+1:end,1)) diag(Wvec(n+1:end,2))]\n                  Wdiag=[Wvec(1:nl(1),1); Wvec(nl(1)+(1:nl(2)),2)];\n                end\n                % dlp = d(log(p(y|f)))/df\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                % lp_new = log(p(y|f))\n                lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_old = -Inf;\n                \n                WK=zeros(sum(nl));\n                \n                iter=0;\n                \n                while (abs(lp_new - lp_old) > tol && iter < maxiter)\n                  iter = iter + 1;\n                  lp_old = lp_new; a_old = a;\n                  \n                  \n                  % b = W*f - d(log(p(y|f)))/df\n                  if isfield(gp.lik,'xtime')\n                    b=Wdiag.*f+[Wmat*f((ntime+1):end); Wmat'*f(1:ntime)]+dlp;\n                  else\n                    b = sum(Wvec.*repmat(reshape(f,n,nlp),nlp,1),2)+dlp;\n                  end\n                  \n                  WK(1:nl(1),1:nl(1))=bsxfun(@times, Wdiag(1:nl(1)),K(1:nl(1),1:nl(1)));\n                  WK(nl(1)+(1:nl(2)),nl(1)+(1:nl(2)))=bsxfun(@times, Wdiag(nl(1)+(1:nl(2))),K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2))));\n                  if isfield(gp.lik,'xtime')\n                    WK(1:nl(1),nl(1)+(1:nl(2)))=Wmat*K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2)));\n                    WK(nl(1)+(1:nl(2)),1:nl(1))=Wmat'*K(1:nl(1),1:nl(1));\n                  else\n                    WK(1:nl(1),nl(1)+(1:nl(2)))=bsxfun(@times, Wvec(1:nl(1),2),K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2))));\n                    WK(nl(1)+(1:nl(2)),1:nl(1))=bsxfun(@times, Wvec(nl(1)+(1:nl(2)),1),K(1:nl(1),1:nl(1)));\n                  end\n                  \n                  % B = I + WK\n                  B=WK;\n                  B(1:sum(nl)+1:end) = B(1:sum(nl)+1:end) + 1;\n                  [ll,uu]=lu(B);\n                  \n                  % a = inv(I+WK)*(W*f - d(log(p(y|f)))/df)\n                  a=uu\\(ll\\b);\n                  %                 a=B\\b;\n                  \n                  f = K*a;\n                  \n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  if ~isfield(gp,'meanf')\n                    lp_new = -a'*f/2 + lp;\n                  else\n                    %lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp; %f^=f-H'*b_m,\n                    lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp; %f^=f-Hb_m,\n                  end\n                  i = 0;\n                  while i < 10 && lp_new < lp_old && ~isnan(sum(f))\n                    % reduce step size by half\n                    a = (a_old+a)/2;\n                    f = K*a;\n                    lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                    if ~isfield(gp,'meanf')\n                      lp_new = -a'*f/2 + lp;\n                    else\n                      %lp_new = -(f-H'*b_m)'*(a-K\\(H'*b_m))/2 + lp;\n                      lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp;\n                    end\n                    i = i+1;\n                  end\n                  \n                  if isfield(gp.lik,'xtime')\n                    [llg2diag, llg2mat] = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                    Wdiag=-llg2diag; Wmat=-llg2mat;\n                  else\n                    Wvec = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                    Wdiag=[Wvec(1:nl(1),1); Wvec(nl(1)+(1:nl(2)),2)];\n                  end\n                  dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                end\n                \n                % evaluate the approximate log marginal likelihood\n                \n                if isfield(gp.lik,'xtime')\n                  [llg2diag, llg2mat] = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  Wdiag=-llg2diag; Wmat=-llg2mat;\n                else\n                  Wvec = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  Wdiag=[Wvec(1:nl(1),1); Wvec(nl(1)+(1:nl(2)),2)];\n                end\n                \n                if ~isfield(gp,'meanf')\n                  logZ = 0.5 *f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n                else\n                  % logZ = 0.5 *((f-H'*b_m)'*(a-K\\(H'*b_m))) - gp.lik.fh.ll(gp.lik, y, f, z);\n                  logZ = 0.5 *((f-Hb_m)'*(a-iKHb_m)) - gp.lik.fh.ll(gp.lik, y, f, z);\n                end\n                \n                WK(1:nl(1),1:nl(1))=bsxfun(@times, Wdiag(1:nl(1)),K(1:nl(1),1:nl(1)));\n                WK(nl(1)+(1:nl(2)),nl(1)+(1:nl(2)))=bsxfun(@times, Wdiag(nl(1)+(1:nl(2))),K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2))));\n                if isfield(gp.lik,'xtime')\n                  WK(1:ntime,ntime+(1:n))=Wmat*K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2)));\n                  WK(nl(1)+(1:nl(2)),1:nl(1))=Wmat'*K(1:nl(1),1:nl(1));\n                else\n                  WK(1:nl(1),nl(1)+(1:nl(2)))=bsxfun(@times, Wvec(1:nl(1),2),K(nl(1)+(1:nl(2)),nl(1)+(1:nl(2))));\n                  WK(nl(1)+(1:nl(2)),1:nl(1))=bsxfun(@times, Wvec(nl(1)+(1:nl(2)),1),K(1:nl(2),1:nl(2)));\n                end\n                \n                % B = I + WK\n                B=WK;\n                B(1:sum(nl)+1:end) = B(1:sum(nl)+1:end) + 1;\n                \n                [Ll,Lu]=lu(B);\n                edata = logZ + 0.5*det(Ll)*prod(sign(diag(Lu))).*sum(log(abs(diag(Lu))));\n                \n                % Return help parameters for gradient and prediction\n                % calculations\n                L=B;\n                E=Ll;\n                M=Lu;\n            end\n            La2=E;\n            p=M;\n            \n          end\n\n          % ============================================================\n          % FIC\n          % ============================================================\n        case 'FIC'\n          u = gp.X_u;\n          m = length(u);\n\n          % First evaluate needed covariance matrices\n          % v defines that parameter is a vector\n          [Kv_ff, Cv_ff] = gp_trvar(gp, x);  % f x 1  vector\n          K_fu = gp_cov(gp, x, u);         % f x u                \n          K_uu = gp_trcov(gp, u);    % u x u, noiseles covariance K_uu\n          [Luu, notpositivedefinite] = chol(K_uu, 'lower');\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          % Evaluate the Lambda (La)\n          % Q_ff = K_fu*inv(K_uu)*K_fu'\n          % Here we need only the diag(Q_ff), which is evaluated below\n          B=Luu\\(K_fu');       % u x f\n          Qv_ff=sum(B.^2)';\n          Lav = Cv_ff-Qv_ff;   % f x 1, Vector of diagonal elements\n          iLaKfu = repmat(Lav,1,m).\\K_fu;  % f x u\n          A = K_uu+K_fu'*iLaKfu;  A = (A+A')./2;     % Ensure symmetry\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          L = iLaKfu/A;\n          \n          switch gp.latent_opt.optim_method\n            % --------------------------------------------------------------------------------\n            % find the posterior mode of latent variables by fminunc large scale method\n            case 'fminunc_large'\n              fhm = @(W, f, varargin) (f./repmat(Lav,1,size(f,2)) - L*(L'*f)  + repmat(W,1,size(f,2)).*f);  % hessian*f; %\n              defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', 1e-8,'TolFun', 1e-8,'LargeScale', 'on','Display', 'off');\n              if ~isfield(gp.latent_opt, 'fminunc_opt')\n                opt = optimset(defopts);\n              else\n                opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n              end\n\n              fe = @(f, varargin) (0.5*f*(f'./repmat(Lav,1,size(f',2)) - L*(L'*f')) - gp.lik.fh.ll(gp.lik, y, f', z));\n              fg = @(f, varargin) (f'./repmat(Lav,1,size(f',2)) - L*(L'*f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n              fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z));\n              mydeal = @(varargin)varargin{1:nargout};\n              [f,fval,exitflag,output] = fminunc(@(ww) mydeal(fe(ww), fg(ww), fh(ww)), f', opt);\n              f = f';\n\n              a = f./Lav - L*L'*f;\n              \n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables by Newton method\n            case 'newton'\n              tol = 1e-12;\n              a = f;\n              W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n              dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n              lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n              lp_old = -Inf;\n              \n              iter = 0;\n              while lp_new - lp_old > tol && iter < maxiter\n                iter = iter + 1;\n                lp_old = lp_new; a_old = a; \n                sW = sqrt(W);\n                \n                Lah = 1 + sW.*Lav.*sW;\n                sWKfu = repmat(sW,1,m).*K_fu;\n                A = K_uu + sWKfu'*(repmat(Lah,1,m).\\sWKfu);   A = (A+A')./2;\n                Lb = (repmat(Lah,1,m).\\sWKfu)/chol(A);\n                b = W.*f+dlp;\n                b2 = sW.*(Lav.*b + B'*(B*b));\n                a = b - sW.*(b2./Lah - Lb*(Lb'*b2));\n                \n                f = Lav.*a + B'*(B*a);\n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_new = -a'*f/2 + lp;\n                i = 0;\n                while i < 10 && lp_new < lp_old && ~isnan(sum(f))\n                  % reduce step size by half\n                  a = (a_old+a)/2;                                  \n                  f = Lav.*a + B'*(B*a);\n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  lp_new = -a'*f/2 + lp;\n                  i = i+1;\n                end \n              end\n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables with likelihood specific algorithm\n              % For example, with Student-t likelihood this mean EM-algorithm which is coded in the\n              % lik_t file.\n            case 'lik_specific'\n              [f, a] = gp.lik.fh.optimizef(gp, y, K_uu, Lav, K_fu);\n              if isnan(f)\n                [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                return\n              end\n            otherwise \n              error('gpla_e: Unknown optimization method ! ')\n          end\n          \n          W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n          logZ = 0.5*f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n          \n          if W >= 0\n            sqrtW = sqrt(W);\n            \n            Lah = 1 + sqrtW.*Lav.*sqrtW;\n            sWKfu = repmat(sqrtW,1,m).*K_fu;\n            A = K_uu + sWKfu'*(repmat(Lah,1,m).\\sWKfu);   A = (A+A')./2;\n            [A, notpositivedefinite] = chol(A);\n            if notpositivedefinite\n              [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n              return\n            end\n            edata = sum(log(Lah)) - 2*sum(log(diag(Luu))) + 2*sum(log(diag(A)));\n            edata = logZ + 0.5*edata;\n          else\n            % This is with full matrices. Needs to be rewritten.\n            K = diag(Lav) + B'*B;\n  % $$$                         [W,I] = sort(W, 1, 'descend');\n  % $$$                         K = K(I,I);\n            [W2,I] = sort(W, 1, 'descend');\n            \n            [L, notpositivedefinite] = chol(K);\n            if notpositivedefinite\n              [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n              return\n            end\n            L1 = L;\n            for jj=1:size(K,1)\n              i = I(jj);\n              ll = sum(L(:,i).^2);\n              l = L'*L(:,i);\n              upfact = W(i)./(1 + W(i).*ll);\n              \n              % Check that Cholesky factorization will remain positive definite\n              if 1 + W(i).*ll <= 0 | upfact > 1./ll\n                warning('gpla_e: 1 + W(i).*ll < 0')\n                \n                ind = 1:i-1;\n                if isempty(z)\n                  mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z);\n                else\n                  mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z(I(ind)));\n                end\n                upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll);\n                \n  % $$$                                 W2 = -1./(ll+1e-3);\n  % $$$                                 upfact = W2./(1 + W2.*ll);\n              end\n              if upfact > 0\n                L = cholupdate(L, l.*sqrt(upfact), '-');\n              else\n                L = cholupdate(L, l.*sqrt(-upfact));\n              end\n            end\n            edata = logZ + sum(log(diag(L1))) - sum(log(diag(L)));  % sum(log(diag(chol(K)))) + sum(log(diag(chol((inv(K) + W)))));\n          end\n          \n          \n          La2 = Lav;\n\n          % ============================================================\n          % PIC\n          % ============================================================\n        case {'PIC' 'PIC_BLOCK'}\n          ind = gp.tr_index;\n          u = gp.X_u;\n          m = length(u);\n\n          % First evaluate needed covariance matrices\n          % v defines that parameter is a vector\n          K_fu = gp_cov(gp, x, u);         % f x u\n          K_uu = gp_trcov(gp, u);    % u x u, noiseles covariance K_uu\n          K_uu = (K_uu+K_uu')./2;     % ensure the symmetry of K_uu\n          [Luu, notpositivedefinite] = chol(K_uu, 'lower');\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          % Evaluate the Lambda (La)\n          % Q_ff = K_fu*inv(K_uu)*K_fu'\n          % Here we need only the diag(Q_ff), which is evaluated below\n          B=Luu\\(K_fu');       % u x f\n\n          % First some helper parameters\n          iLaKfu = zeros(size(K_fu));  % f x u\n          for i=1:length(ind)\n            Qbl_ff = B(:,ind{i})'*B(:,ind{i});\n            [Kbl_ff, Cbl_ff] = gp_trcov(gp, x(ind{i},:));\n            Labl{i} = Cbl_ff - Qbl_ff;\n            [LLabl{i}, notpositivedefinite] = chol(Labl{i});\n            if notpositivedefinite\n              [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n              return\n            end\n            iLaKfu(ind{i},:) = LLabl{i}\\(LLabl{i}'\\K_fu(ind{i},:));\n          end\n          A = K_uu+K_fu'*iLaKfu;\n          A = (A+A')./2;     % Ensure symmetry\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          L = iLaKfu/A;\n          % Begin optimization\n          switch gp.latent_opt.optim_method\n            % --------------------------------------------------------------------------------\n            % find the posterior mode of latent variables by fminunc large scale method\n            case 'fminunc_large'\n              fhm = @(W, f, varargin) (iKf(f)  + repmat(W,1,size(f,2)).*f);\n              defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', 1e-8,'TolFun', 1e-8,'LargeScale', 'on','Display', 'off');\n              if ~isfield(gp.latent_opt, 'fminunc_opt')\n                opt = optimset(defopts);\n              else\n                opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n              end\n\n              [f,fval,exitflag,output] = fminunc(@(ww) egh(ww), f', opt);\n              f = f';\n              \n              a = iKf(f);\n              \n              % find the mode by Newton's method\n              % --------------------------------------------------------------------------------\n            case 'newton'\n              tol = 1e-12;\n              a = f;\n              W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n              dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n              lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n              lp_old = -Inf;\n              \n              iter = 0;\n              while lp_new - lp_old > tol && iter < maxiter\n                iter = iter + 1;\n                lp_old = lp_new; a_old = a;\n                sW = sqrt(W);\n\n                V = repmat(sW,1,m).*K_fu;\n                for i=1:length(ind)\n                  Lah{i} = eye(size(Labl{i})) + diag(sW(ind{i}))*Labl{i}*diag(sW(ind{i}));\n                  [LLah{i}, notpositivedefinite] = chol(Lah{i});\n                  if notpositivedefinite\n                    [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                    return\n                  end\n                  V2(ind{i},:) = LLah{i}\\(LLah{i}'\\V(ind{i},:));\n                end                        \n                \n                A = K_uu + V'*V2;   A = (A+A')./2;\n                [A, notpositivedefinite] = chol(A);\n                if notpositivedefinite\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n                Lb = V2/A;\n                b = W.*f+dlp;\n                b2 = B'*(B*b);\n                bt = zeros(size(b2));\n                for i=1:length(ind)\n                  b2(ind{i}) = sW(ind{i}).*(Labl{i}*b(ind{i}) + b2(ind{i})); \n                  bt(ind{i}) = LLah{i}\\(LLah{i}'\\b2(ind{i}));\n                end\n                a = b - sW.*(bt - Lb*(Lb'*b2));\n\n                f = B'*(B*a);\n                for i=1:length(ind)\n                  f(ind{i}) = Labl{i}*a(ind{i}) + f(ind{i}) ;\n                end\n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_new = -a'*f/2 + lp;\n                i = 0;\n                while i < 10 && lp_new < lp_old || isnan(sum(f))\n                  % reduce step size by half\n                  a = (a_old+a)/2;                                  \n                  f = B'*(B*a);\n                  for i=1:length(ind)\n                    f(ind{i}) = Labl{i}*a(ind{i}) + f(ind{i}) ;\n                  end\n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  lp_new = -a'*f/2 + lp;\n                  i = i+1;\n                end \n              end\n            otherwise \n              error('gpla_e: Unknown optimization method ! ')    \n          end\n          \n          W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n          sqrtW = sqrt(W);\n          \n          logZ = 0.5*f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n          \n          WKfu = repmat(sqrtW,1,m).*K_fu;\n          edata = 0;\n          for i=1:length(ind)\n            Lahat = eye(size(Labl{i})) + diag(sqrtW(ind{i}))*Labl{i}*diag(sqrtW(ind{i}));\n            [LLahat, notpositivedefinite] = chol(Lahat);\n            if notpositivedefinite\n              [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n              return\n            end\n            iLahatWKfu(ind{i},:) = LLahat\\(LLahat'\\WKfu(ind{i},:));\n            edata = edata + 2.*sum(log(diag(LLahat)));\n          end\n          A = K_uu + WKfu'*iLahatWKfu;   A = (A+A')./2;\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          edata =  edata - 2*sum(log(diag(Luu))) + 2*sum(log(diag(A)));\n          edata = logZ + 0.5*edata;\n\n          La2 = Labl;              \n          \n          % ============================================================\n          % CS+FIC\n          % ============================================================\n        case 'CS+FIC'\n          u = gp.X_u;\n          m = length(u);\n          cf_orig = gp.cf;\n\n          cf1 = {};\n          cf2 = {};\n          j = 1;\n          k = 1;\n          for i = 1:ncf\n            if ~isfield(gp.cf{i},'cs')\n              cf1{j} = gp.cf{i};\n              j = j + 1;\n            else\n              cf2{k} = gp.cf{i};\n              k = k + 1;\n            end\n          end\n          gp.cf = cf1;\n\n          % First evaluate needed covariance matrices\n          % v defines that parameter is a vector\n          [Kv_ff, Cv_ff] = gp_trvar(gp, x);  % f x 1  vector\n          K_fu = gp_cov(gp, x, u);         % f x u\n          K_uu = gp_trcov(gp, u);    % u x u, noiseles covariance K_uu\n          K_uu = (K_uu+K_uu')./2;     % ensure the symmetry of K_uu\n          [Luu, notpositivedefinite] = chol(K_uu, 'lower');\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n\n          % Evaluate the Lambda (La)\n          % Q_ff = K_fu*inv(K_uu)*K_fu'\n          B=Luu\\(K_fu');       % u x f\n          Qv_ff=sum(B.^2)';\n          Lav = Cv_ff-Qv_ff;   % f x 1, Vector of diagonal elements\n          \n          gp.cf = cf2;\n          K_cs = gp_trcov(gp,x);\n          La = sparse(1:n,1:n,Lav,n,n) + K_cs;\n          gp.cf = cf_orig;\n          \n          % Find fill reducing permutation and permute all the\n          % matrices\n          p = analyze(La);\n          r(p) = 1:n;\n          if ~isempty(z)\n            z = z(p,:);\n          end\n          f = f(p);\n          y = y(p);\n          La = La(p,p);\n          K_fu = K_fu(p,:);\n          B = B(:,p);\n          [VD, notpositivedefinite] = ldlchol(La);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          \n          iLaKfu = ldlsolve(VD,K_fu);\n          %iLaKfu = La\\K_fu;\n\n          A = K_uu+K_fu'*iLaKfu;  A = (A+A')./2;     % Ensure symmetry\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          L = iLaKfu/A;\n          % Begin optimization\n          switch gp.latent_opt.optim_method\n\n            % --------------------------------------------------------------------------------\n            % find the posterior mode of latent variables by fminunc large scale method\n            case 'fminunc_large'\n              fhm = @(W, f, varargin) (ldlsolve(VD,f) - L*(L'*f)  + repmat(W,1,size(f,2)).*f);  % Hessian*f; % La\\f\n              defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', 1e-8,'TolFun', 1e-8,'LargeScale', 'on','Display', 'off');\n              if ~isfield(gp.latent_opt, 'fminunc_opt')\n                opt = optimset(defopts);\n              else\n                opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n              end\n              \n              [f,fval,exitflag,output] = fminunc(@(ww) egh(ww), f', opt);\n              f = f';\n              \n              a = ldlsolve(VD,f) - L*L'*f;\n              \n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables by Newton method\n            case 'newton'\n              tol = 1e-8;\n              a = f;\n              W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n              dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n              lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n              lp_old = -Inf;\n              I = sparse(1:n,1:n,1,n,n);\n              \n              iter = 0;\n              while lp_new - lp_old > tol && iter < maxiter\n                iter = iter + 1;\n                lp_old = lp_new; a_old = a; \n                sW = sqrt(W);\n                sqrtW = sparse(1:n,1:n,sW,n,n);\n                \n                Lah = I + sqrtW*La*sqrtW; \n                [VDh, notpositivedefinite] = ldlchol(Lah);\n                if notpositivedefinite\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n                V = repmat(sW,1,m).*K_fu;\n                Vt = ldlsolve(VDh,V);\n                A = K_uu + V'*Vt;   A = (A+A')./2;\n                [A, notpositivedefinite] = chol(A);\n                if notpositivedefinite\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n                Lb = Vt/A;\n                b = W.*f+dlp;\n                b2 = sW.*(La*b + B'*(B*b));\n                a = b - sW.*(ldlsolve(VDh,b2) - Lb*(Lb'*b2) );\n\n                f = La*a + B'*(B*a);\n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_new = -a'*f/2 + lp;\n                i = 0;\n                while i < 10 && lp_new < lp_old\n                  a = (a_old+a)/2;\n                  f = La*a + B'*(B*a);\n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  lp_new = -a'*f/2 + lp;\n                  i = i+1;\n                end\n              end\n            otherwise \n              error('gpla_e: Unknown optimization method ! ')\n          end\n          \n          \n          W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n          sqrtW = sqrt(W);\n          \n          logZ = 0.5*f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n          \n          WKfu = repmat(sqrtW,1,m).*K_fu;\n          sqrtW = sparse(1:n,1:n,sqrtW,n,n);\n          Lahat = sparse(1:n,1:n,1,n,n) + sqrtW*La*sqrtW;\n          [LDh, notpositivedefinite] = ldlchol(Lahat);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          A = K_uu + WKfu'*ldlsolve(LDh,WKfu);   A = (A+A')./2;\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          edata = sum(log(diag(LDh))) - 2*sum(log(diag(Luu))) + 2*sum(log(diag(A)));\n          edata = logZ + 0.5*edata;\n          \n          La2 = La;\n          \n          % Reorder all the returned and stored values\n          a = a(r);\n          L = L(r,:);\n          La2 = La2(r,r);\n          y = y(r);\n          f = f(r);\n          W = W(r);\n          if ~isempty(z)\n            z = z(r,:);\n          end\n          \n          % ============================================================\n          % DTC, SOR\n          % ============================================================\n        case {'DTC' 'VAR' 'SOR'}\n          u = gp.X_u;\n          m = length(u);\n\n          % First evaluate needed covariance matrices\n          % v defines that parameter is a vector\n          K_fu = gp_cov(gp, x, u);         % f x u                \n          K_uu = gp_trcov(gp, u);    % u x u, noiseles covariance K_uu\n          [Luu, notpositivedefinite] = chol(K_uu, 'lower');\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          % Evaluate the Lambda (La)\n          % Q_ff = K_fu*inv(K_uu)*K_fu'\n          B=Luu\\(K_fu');       % u x f\n%           Qv_ff=sum(B.^2)';\n%           Lav = zeros(size(Qv_ff));\n%           Lav = Cv_ff-Qv_ff;   % f x 1, Vector of diagonal elements\n          La2 = [];\n          \n          switch gp.latent_opt.optim_method\n            % --------------------------------------------------------------------------------\n            % find the posterior mode of latent variables by fminunc large scale method\n            case 'fminunc_large'\n%               fhm = @(W, f, varargin) (f./repmat(Lav,1,size(f,2)) - L*(L'*f)  + repmat(W,1,size(f,2)).*f);  % hessian*f; %\n%               defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', 1e-8,'TolFun', 1e-8,'LargeScale', 'on','Display', 'off');\n%               if ~isfield(gp.latent_opt, 'fminunc_opt')\n%                 opt = optimset(defopts);\n%               else\n%                 opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n%               end\n% \n%               fe = @(f, varargin) (0.5*f*(f'./repmat(Lav,1,size(f',2)) - L*(L'*f')) - gp.lik.fh.ll(gp.lik, y, f', z));\n%               fg = @(f, varargin) (f'./repmat(Lav,1,size(f',2)) - L*(L'*f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n%               fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z));\n%               mydeal = @(varargin)varargin{1:nargout};\n%               [f,fval,exitflag,output] = fminunc(@(ww) mydeal(fe(ww), fg(ww), fh(ww)), f', opt);\n%               f = f';\n% \n%               a = f./Lav - L*L'*f;\n              \n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables by Newton method\n            case 'newton'\n              tol = 1e-12;\n              a = f;\n              W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n              dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n              lp_new = gp.lik.fh.ll(gp.lik, y, f, z);\n              lp_old = -Inf;\n              \n              iter = 0;\n              while lp_new - lp_old > tol && iter < maxiter\n                iter = iter + 1;\n                lp_old = lp_new; a_old = a; \n                sW = sqrt(W);\n                \n                sWKfu = repmat(sW,1,m).*K_fu;\n                A = K_uu + sWKfu'*sWKfu;   A = (A+A')./2;\n                [A, notpositivedefinite]=chol(A);\n                if notpositivedefinite\n                  [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n                  return\n                end\n                Lb = sWKfu/A;\n                b = W.*f+dlp;\n                b2 = sW.*(B'*(B*b));\n                a = b - sW.*(b2 - Lb*(Lb'*b2));\n                \n                f = B'*(B*a);\n                \n                W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n                lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                lp_new = -a'*f/2 + lp;\n                i = 0;\n                while i < 10 && lp_new < lp_old && ~isnan(sum(f))\n                  % reduce step size by half\n                  a = (a_old+a)/2;                                  \n                  f = B'*(B*a);\n                  W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n                  lp = gp.lik.fh.ll(gp.lik, y, f, z);\n                  lp_new = -a'*f/2 + lp;\n                  i = i+1;\n                end \n              end\n              % --------------------------------------------------------------------------------\n              % find the posterior mode of latent variables with likelihood specific algorithm\n              % For example, with Student-t likelihood this mean EM-algorithm which is coded in the\n              % lik_t file.\n            case 'lik_specific'\n              [f, a] = gp.lik.fh.optimizef(gp, y, K_uu, zeros(n,1), K_fu);\n            otherwise \n              error('gpla_e: Unknown optimization method ! ')\n          end\n          \n          W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n          logZ = 0.5*f'*a - gp.lik.fh.ll(gp.lik, y, f, z);\n          \n          if W >= 0\n            sqrtW = sqrt(W);\n            \n%             L = chol(eye(n) + diag(sqrtW)*(B'*B)*diag(sqrtW), 'lower');\n%             edata = logZ + sum(log(diag(L)));\n            \n\n            sWKfu = bsxfun(@times, sqrtW, K_fu);\n            \n            A = K_uu + sWKfu'*sWKfu;   A = (A+A')./2;\n            [A, notpositivedefinite] = chol(A);\n            if notpositivedefinite\n              [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n              return\n            end\n            edata = -sum(log(diag(Luu))) + sum(log(diag(A)));\n            edata = logZ + edata;\n            \n            if strcmp(gp.type,'VAR')\n              Kv_ff = gp_trvar(gp, x); \n              Qv_ff = sum(B.^2)';              \n              edata = edata + 0.5*sum((Kv_ff-Qv_ff).*W);\n              La2=Kv_ff-Qv_ff;\n            end\n          else\n            % This is with full matrices. Needs to be rewritten.\n%             K = diag(Lav) + B'*B;\n%   % $$$                         [W,I] = sort(W, 1, 'descend');\n%   % $$$                         K = K(I,I);\n%             [W2,I] = sort(W, 1, 'descend');\n%             \n%             [L, notpositivedefinite] = chol(K);\n%             if notpositivedefinite\n%               [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n%               return\n%             end\n%             L1 = L;\n%             for jj=1:size(K,1)\n%               i = I(jj);\n%               ll = sum(L(:,i).^2);\n%               l = L'*L(:,i);\n%               upfact = W(i)./(1 + W(i).*ll);\n%               \n%               % Check that Cholesky factorization will remain positive definite\n%               if 1 + W(i).*ll <= 0 | upfact > 1./ll\n%                 warning('gpla_e: 1 + W(i).*ll < 0')\n%                 \n%                 ind = 1:i-1;\n%                 if isempty(z)\n%                   mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z);\n%                 else\n%                   mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z(I(ind)));\n%                 end\n%                 upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll);\n%                 \n%   % $$$                                 W2 = -1./(ll+1e-3);\n%   % $$$                                 upfact = W2./(1 + W2.*ll);\n%               end\n%               if upfact > 0\n%                 L = cholupdate(L, l.*sqrt(upfact), '-');\n%               else\n%                 L = cholupdate(L, l.*sqrt(-upfact));\n%               end\n%             end\n%             edata = logZ + sum(log(diag(L1))) - sum(log(diag(L)));  % sum(log(diag(chol(K)))) + sum(log(diag(chol((inv(K) + W)))));\n          end\n          \n          \n          L=A;\n          \n          % ============================================================\n          % SSGP\n          % ============================================================\n        case 'SSGP'        % Predictions with sparse spectral sampling approximation for GP\n                           % The approximation is proposed by M. Lazaro-Gredilla, J. Quinonero-Candela and A. Figueiras-Vidal\n                           % in Microsoft Research technical report MSR-TR-2007-152 (November 2007)\n                           % NOTE! This does not work at the moment.\n          \n          % First evaluate needed covariance matrices\n          % v defines that parameter is a vector\n          [Phi, S] = gp_trcov(gp, x);        % n x m matrix and nxn sparse matrix\n          Sv = diag(S);\n          \n          m = size(Phi,2);\n          \n          A = eye(m,m) + Phi'*(S\\Phi);\n          [A, notpositivedefinite] = chol(A, 'lower');\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          L = (S\\Phi)/A';\n          \n          switch gp.latent_opt.optim_method\n            % find the mode by fminunc large scale method\n            case 'fminunc_large'\n              fhm = @(W, f, varargin) (f./repmat(Sv,1,size(f,2)) - L*(L'*f)  + repmat(W,1,size(f,2)).*f);  % Hessian*f; %\n              defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', 1e-8,'TolFun', 1e-8,'LargeScale', 'on','Display', 'off');\n              if ~isfield(gp.latent_opt, 'fminunc_opt')\n                opt=optimset(defopts);\n              else\n                opt = optimset(defopts,gp.latent_opt.fminunc_opt);\n              end\n\n              fe = @(f, varargin) (0.5*f*(f'./repmat(Sv,1,size(f',2)) - L*(L'*f')) - gp.lik.fh.ll(gp.lik, y, f', z));\n              fg = @(f, varargin) (f'./repmat(Sv,1,size(f',2)) - L*(L'*f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n              fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z));\n              mydeal = @(varargin)varargin{1:nargout};\n              [f,fval,exitflag,output] = fminunc(@(ww) mydeal(fe(ww), fg(ww), fh(ww)), f', opt);\n              f = f';\n\n              W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n              sqrtW = sqrt(W);\n\n              b = L'*f;\n              logZ = 0.5*(f'*(f./Sv) - b'*b) - gp.lik.fh.ll(gp.lik, y, f, z);\n            case 'Newton'\n              error('The Newton''s method is not implemented for FIC!\\n')\n          end\n          WPhi = repmat(sqrtW,1,m).*Phi;\n          A = eye(m,m) + WPhi'./repmat((1+Sv.*W)',m,1)*WPhi;   A = (A+A')./2;\n          [A, notpositivedefinite] = chol(A);\n          if notpositivedefinite\n            [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite();\n            return\n          end\n          edata = sum(log(1+Sv.*W)) + 2*sum(log(diag(A)));\n          edata = logZ + 0.5*edata;\n\n          La2 = Sv;\n\n        otherwise\n          error('Unknown type of Gaussian process!')\n      end\n\n      % ======================================================================\n      % Evaluate the prior contribution to the error from covariance functions\n      % ======================================================================\n      eprior = 0;\n      for i1=1:ncf\n        gpcf = gp.cf{i1};\n        eprior = eprior - gpcf.fh.lp(gpcf);\n      end\n\n      % ======================================================================\n      % Evaluate the prior contribution to the error from likelihood function\n      % ======================================================================\n      if isfield(gp, 'lik') && isfield(gp.lik, 'p')\n        lik = gp.lik;\n        eprior = eprior - lik.fh.lp(lik);\n      end\n\n      e = edata + eprior;\n    \n      % store values to the cache\n      ch.w = w;\n      ch.e = e;\n      ch.edata = edata;\n      ch.eprior = eprior;\n      ch.f = f;\n      ch.L = L;\n%       ch.W = W;\n      ch.n = size(x,1);\n      ch.La2 = La2;\n      ch.a = a;\n      ch.p=p;\n      ch.datahash=datahash;\n    end\n    \n%    assert(isreal(edata))\n%    assert(isreal(eprior))\n\n%\n% ==============================================================\n% Begin of the nested functions\n% ==============================================================\n%        \nfunction [e, g, h] = egh(f, varargin)\n  ikf = iKf(f');\n  e = 0.5*f*ikf - gp.lik.fh.ll(gp.lik, y, f', z);\n  g = (ikf - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';\n  h = -gp.lik.fh.llg2(gp.lik, y, f', 'latent', z);\nend\nfunction ikf = iKf(f, varargin)\n  \n  switch gp.type\n    case {'PIC' 'PIC_BLOCK'}\n      iLaf = zeros(size(f));\n      for i=1:length(ind)\n        iLaf(ind2depo{i},:) = LLabl{i}\\(LLabl{i}'\\f(ind{i},:));\n      end\n      ikf = iLaf - L*(L'*f);\n    case 'CS+FIC'\n      ikf = ldlsolve(VD,f) - L*(L'*f);\n  end\nend\nend\nfunction [edata,e,eprior,f,L,a,La2,p,ch] = set_output_for_notpositivedefinite()\n  % Instead of stopping to chol error, return NaN\n  edata=NaN;\n  e=NaN;\n  eprior=NaN;\n  f=NaN;\n  L=NaN;\n  a=NaN;\n  La2=NaN;\n  p=NaN;\n  datahash = NaN;\n  w = NaN;\n  ch.e = e;\n  ch.edata = edata;\n  ch.eprior = eprior;\n  ch.f = f;\n  ch.L = L;\n  ch.La2 = La2;\n  ch.a = a;\n  ch.p=p;\n  ch.datahash=datahash;\n  ch.w = NaN;\nend\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/gpla_e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21425416085561966}}
{"text": "function output = callmpt(interfacedata)\n\n% This file is kept for MPT2 compatability\n\n% Speeds up solving LPs in mpmilp\nglobal mptOptions\nif ~isstruct(mptOptions)\n    mpt_error\nend\n\n% Convert\nMatrices = yalmip2mpt(interfacedata);\n\n% Get some MPT options\noptions = interfacedata.options;\noptions.mpt.lpsolver = mptOptions.lpsolver;\noptions.mpt.milpsolver = mptOptions.milpsolver;\noptions.mpt.verbose = options.verbose;\n\nif options.savedebug\n    save mptdebug Matrices\nend\n\nif options.mp.unbounded\n    Matrices = removeExplorationConstraints(Matrices);\nend\n\n[dummy,un] = unique([Matrices.G Matrices.E Matrices.W],'rows');\nMatrices.G = Matrices.G(un,:);\nMatrices.E = Matrices.E(un,:);\nMatrices.W = Matrices.W(un,:);\n\nif isempty(Matrices.binary_var_index)\n\n    showprogress('Calling MPT',options.showprogress);\n    solvertime = clock;\n    if options.mp.presolve\n        [Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);\n    end        \n    \n    if any(Matrices.lb(end-Matrices.nx+1:end) == Matrices.ub(end-Matrices.nx+1:end))\n        model = [];\n    else        \n        model = mpt_solvenode(Matrices,Matrices.lb,Matrices.ub,Matrices,[],options);\n    end\n    solvertime = etime(clock,solvertime);\n\nelse  \n    % Pre-solve required on binary problems\n    options.mp.presolve = 1;\n\n    solvertime = tic;\n         \n    switch options.mp.algorithm\n        case 1\n            showprogress('Calling MPT via enumeration',options.showprogress);\n            model = mpt_enumeration_mpmilp(Matrices,options);\n        case 2\n            % Still experimental and just for fun. Not working!\n            showprogress('Calling MPT via parametric B&B',options.showprogress);\n            model = mpt_parbb(Matrices,options);         \n            \n       case 3\n            showprogress('Calling MPT via delayed enumeration',options.showprogress);\n            %Matrices = initialize_binary_equalities(Matrices)           \n            [Matrices.SOS,Matrices.SOSVariables] =  mpt_detect_sos(Matrices);\n            [Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);                                \n            model = mpt_de_mpmilp(Matrices,options,[]);            \n                                     \n        otherwise\n    end\n    solvertime = toc(solvertime);\nend\n\nif isempty(model)\n    model = {model};\nend\n\nif options.verbose\n    if ~isempty(model{1})\n        if length(model) == 1\n            disp(['-> Generated 1 partition.'])            \n        else\n            disp(['-> Generated ' num2str(length(model)) ' partitions.'])\n        end\n    end\nend\n\nproblem = 0;\n\n% Save all data sent to solver?\nif options.savesolverinput\n    solverinput.Matrices = Matrices;\n    solverinput.options  = [];\nelse\n    solverinput = [];\nend\n\n% Save all data from the solver?\n% This always done\nif options.savesolveroutput\n    solveroutput.model = model;\n    solveroutput.U = interfacedata.used_variables(Matrices.free_var);%(Matrices.free_var <= length( interfacedata.used_variables)));\n    solveroutput.x = interfacedata.used_variables(Matrices.param_var);\nelse\n    solveroutput = [];\nend\n\n% Standard interface\nPrimal      = nan*ones(length(interfacedata.c),1);\nDual        = [];\noutput = createOutputStructure(Primal,Dual,[],problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);\n\nfunction Matrices = initialize_binary_equalities(Matrices)\nbinary_var_index = Matrices.binary_var_index;\nnotbinary_var_index = setdiff(1:Matrices.nu,binary_var_index);\n% Detect and extract pure binary equalities. Used for simple pruning\nnbin = length(binary_var_index);\nonly_binary = ~any(Matrices.Aeq(:,notbinary_var_index),2);\nMatrices.Aeq_bin = Matrices.Aeq(find(only_binary),binary_var_index);\nMatrices.beq_bin = Matrices.beq(find(only_binary),:);\n\nfunction Matrices = removeExplorationConstraints(Matrices);\ncandidates = find((~any(Matrices.G,2)) & (sum(Matrices.E | Matrices.E,2) == 1));\nif ~isempty(candidates)\n    Matrices.bndA = -Matrices.E(candidates,:);\n    Matrices.bndb = Matrices.W(candidates,:);\n    Matrices.G(candidates,:) = [];\n    Matrices.E(candidates,:) = [];\n    Matrices.W(candidates,:) = [];\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callmpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2140200563048936}}
{"text": "function atlas_out = split_atlas_into_contiguous_regions(atlas_obj)\n% Divide regions with multiple contiguous blobs into separate labeled regions for each blob\n%\n% Take an atlas object whose labeled regions contain multiple contiguous blobs and divide each\n% contiguous blob into a separate labeled region.\n% - Note: This version eliminates probability maps - handling them not implemented yet\n%\n% July 2018, Tor Wager\n%\n% \"split_atlas\" method use cases:\n% split_atlas_by_hemisphere: We have a defined set of bilateral regions that \n% we want to \"hard-split\" into left and right. Multiple discontiguous regions \n% with the same label will be kept together. \n%\n% split_atlas_into_contiguous_regions: We want to (1) keep contiguous blobs together \n% that may cross the midline, and (2) separate contiguous blobs with the\n% same label into separate labeled regions.\n\n[n_regions, n_regions_with_data, missing_regions] = num_regions(atlas_obj);\n\natlas_out = atlas_obj;\n\natlas_out.labels = {};\natlas_out.label_descriptions = {};\n\natlas_out.probability_maps = []; % Eliminate probability maps - handling them not implemented yet\n\natlas_out.dat = zeros(size(atlas_out.dat)); % avoid 0 for resampling\n\nfprintf('Splitting %d regions: 000', n_regions)\n\nfor i = 1:n_regions\n    \n    fprintf('%3.0f', i);\n    \n    subatlas = select_atlas_subset(atlas_obj, i);\n    \n    %     wh = logical(subatlas.dat);                      % which voxels in region\n    %\n    %     xyz = subatlas.volInfo.xyzlist(wh, :);           % x-coordinates in voxels\n    %\n    %     XYZmm = voxel2mm(xyz',subatlas.volInfo.mat);\n    \n    % parse into contiguous regions. split if there are multiple.\n    r = atlas2region(subatlas);\n    r = reparse_continguous(r);\n    \n    % clean up left-out voxels\n    wh_omit = cat(1, r.numVox) < 3;\n    r(wh_omit) = [];\n    \n    % newr is atlas object for this original region, with contig regions\n    % divided\n    \n    new_subatlas = region2atlas(r, subatlas);\n    \n    new_subatlas.probability_maps = []; % Eliminate probability maps - handling them not implemented yet\n\n    new_subatlas.labels = get_new_labels(r, subatlas.labels{1});\n    \n    atlas_out = merge_atlases(atlas_out, new_subatlas);\n    \n    \nend % region\n\n%atlas_out.dat(atlas_out.dat == 9999) = 0;\n\natlas_out.references = unique(atlas_out.references, 'rows');\n\ndisp('Done.');\n\n\nend % function\n\n\n\n\n\nfunction new_labels = get_new_labels(r, old_label)\n% later: could merge all L, all R, all M\n\nk = length(r);\n\nfor j = 1:k\n    \n    voxsign = sign(r(j).XYZmm(1, :)); % sign of each x coord. - = left\n    modal_x = mode(voxsign);\n    \n    switch modal_x\n        case -1\n            labelstr = '_L';\n        case 1\n            labelstr = '_R';\n        case 0\n            labelstr = '_M';\n    end\n    \n    % proportional asymmetry. 1 is vary lateralized. 0 is balanced\n    % across L/R.  If symmetrical, then label _M\n    prop_asym = abs(sum(voxsign == -1) - sum(voxsign == 1)) ./ length(voxsign);\n    \n    if prop_asym < .5, labelstr = '_M'; end\n    \n    new_labels{j} = [old_label labelstr];\n    \n    \nend % j\n\n% add left/right/mid\n\n%     % split region into left, right, and midline within 10 mm\n%     isleft = XYZmm(1, :) < 0;\n%     isright = XYZmm(1, :) > 0;   % what to do with midline?\n%     ismid = XYZmm == 0;\n\n\nend % subfunction\n\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@atlas/split_atlas_into_contiguous_regions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21397595361554697}}
{"text": "function varargout = maskToCERRStructure(maskM, isUniform, scanNum, strname, planC)\n%\"maskToCERRStructure\"\n%   Adds to planC a new structure whose contours are derived from maskM.\n%   MaskM must be registered to either the uniform or non uniform CT scan.\n%\n%   Uses nearest neighbor interpolation for slices.\n%\n%   If registered to the uniform, isUniform should be 1, else 0.\n%\n%   The structure is given the name passed into strname, or 'Imported\n%   Structure' if no name is passed.\n%\n%JRA 08/17/04\n%\n%Usage:\n%GENERAL:\n%   function planC = maskToCERRStructure(maskM, isUniform, scanNum, strname, planC)\n%OR if CERR is open:\n%   function planC = maskToCERRStructure(maskM, isUniform, scanNum, strname)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nglobal stateS\n\nif ~exist('planC','var') \n    global planC\nend\nindexS = planC{end};\n\nif ~exist('strname','var')\n    strname = 'Imported Structure';\nend\n\n%Check sizes, auto size detection.\nsiz = size(maskM);\nunisiz = getUniformScanSize(planC{indexS.scan}(scanNum));\nnormsiz = size(getScanArray(planC{indexS.scan}(scanNum)));\nif numel(siz) < 3\n    siz(3) = 1;\nend\nif numel(normsiz) < 3\n    normsiz(3) = 1;\nend\nif ~exist('isUniform','var')\n    if isequal(siz, unisiz)\n        isUniform = 1;\n    elseif isequal(siz, normsiz)\n        isUniform = 0;\n    else\n        error('maskM does not match dimension of uniform or nonuniform dataset.');\n    end\nelse\n    if (isUniform && ~isequal(siz, unisiz)) || (~isUniform && ~isequal(siz, normsiz))\n        error('maskM does not match dimension of uniform or nonuniform dataset.');\n    end    \nend\n\nif ~isUniform\n    %If registered to CT, just get contour info.\n    [contourS, ~] = maskToPoly(maskM, 1:siz(3), scanNum, planC);\nelse\n    %If registered to uniformized data, use nearest slice neighbor\n    %interpolation.\n    [~, ~, zUni] = getUniformScanXYZVals(planC{indexS.scan}(scanNum));\n    \n%     [xUni, yUni, zUni] = getUniformizedXYZVals(planC);\n    [~, ~, zSca] = getScanXYZVals(planC{indexS.scan}(scanNum));\n    \n    tmpM = false(normsiz);\n    \n    for i=1:normsiz(3)\n        zVal = zSca(i);\n        uB = find(zUni > zVal, 1 );\n        lB = find(zUni <= zVal, 1, 'last' );\n        if normsiz(3) > 1 && (isempty(uB) || isempty(lB))\n            continue\n        end\n        if abs(zUni(uB) - zVal) < abs(zUni(lB) - zVal)\n            tmpM(:,:,i) = logical(maskM(:,:,uB));\n        else\n            tmpM(:,:,i) = logical(maskM(:,:,lB));            \n        end\n    end    \n    %Get contour info.\n    [contourS, ~] = maskToPoly(tmpM, 1:normsiz(3), scanNum, planC);\n end\n\n%Make an empty structure, assign name/contour.\nnewstr = newCERRStructure(scanNum, planC);\nnewstr.contour = contourS;\nnewstr.structureName = strname;\nnewstr.associatedScan = scanNum;\nnewstr.assocScanUID = planC{indexS.scan}(scanNum).scanUID;\nnumStructs = length(planC{indexS.structures});\n\n%Append new structure to planC.\nif ~isempty(planC{indexS.structures})\n    planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newstr, numStructs+1, []);\nelse\n    planC{indexS.structures} = newstr;\n    planC{indexS.structureArrayMore}(scanNum).indicesArray = [];\n    planC{indexS.structureArrayMore}(scanNum).bitsArray = [];\nend\n\n%Update uniformized data.\nif strcmpi(stateS.optS.createUniformizedDataset,'yes')\n    planC = updateStructureMatrices(planC, numStructs+1);\nend\n\n%Set varargout if requested.\nif nargout > 0\n    varargout{1} = planC;\nend\n\nif isfield(stateS,'handle') && ishandle(stateS.handle.CERRSliceViewer)\n    stateS.structsChanged = 1;\n    sliceCallBack('refresh');\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/maskToCERRStructure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21397595361554697}}
{"text": "%Thanks for Dr. Ma Zheng's X-ray diffraction Datas.\n%You can test ma.mat, ma2.mat yourself.\n%Enjoy!!!\nload ma3.mat;\nplot(A,B,'-');\ngrid on;\nhold on;\nt=fpeak(A,B,30,[23,90,700,inf]);\nplot(t(:,1),t(:,2),'o');\ntitle('\\fontsize{24}Perfect!');\nhold off;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4242-find-peak-value/ma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21397594788401117}}
{"text": "function [uOutput] = import_gismo_catalog(nfunction, catalog)\n    % import from a GISMO Catalog object\n    % Catalog objects are part of the GISMO suite\n    %\n    % to get helptext:\n    %   [helpstring] = import_gismo_catalog(0)\n    %\n    % to retrieve Catalog stored in file\n    %   [uOutput] = import_gismo_catalog(1, filename)\n    %\n    % to convert Catalog stored in memory\n    %   [uOutput] = import_gismo_catalog(1, catalog) % name will be name of variable\n    \n    % created by Celso G Reyes, 2017\n    \n    % ZMAP format is 10 columns: longitude, latitude, decimal year, month, day,\n    % magnitude, depth, hour, minute, second\n    uOutput = [];\n    \n    if nfunction==0   % Return info about filter\n        uOutput = 'GISMO Catalog - import catalog from the GISMO suite';\n        return\n    end\n    if nfunction ==2\n        uOutput = 'gismo.html';\n        return\n    end\n    \n    if ~exist('Catalog','class')\n        uOutput(['Cannot import catalog, since Catalog class (and probably GISMO) is not installed.',...\n            'Last known whereabouts: https://github.com/geoscience-community-codes/GISMO']);\n        return\n    end\n    if ischar(catalog)\n        % filename\n        if exist(catalog,'file')\n            fn = catalog;\n            catalog=load(fn);\n        end\n    end\n    \n    if exist('catalog','var') && isa(catalog,'Catalog')\n        tb=table(datetime(datevec(catalog.otime)),...\n            catalog.lat,...\n            catalog.lon,...\n            catalog.depth,...\n            catalog.mag,...\n            catalog.magtype,...\n            'VariableNames',{'Date','Latitude','Longitude','Depth','Magnitude','MagnitudeType'});\n        uOutput=ZmapCatalog.from(tb);\n        \n        uOutput.Name=inputname(2);\n            \n\n    else\n        uOutput = 'unable to import Catalog';\n    end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/importfilters/import_gismo_catalog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2139385807064917}}
{"text": "% pop_select() - given an input EEG dataset structure, output a new EEG data structure \n%                retaining and/or excluding specified time/latency, data point, channel, \n%                and/or epoch range(s).\n% Usage:\n%   >> OUTEEG = pop_select(INEEG, 'key1', value1, 'key2', value2 ...);\n%\n% Graphic interface:\n%   \"Time range\" - [edit box] RETAIN only the indicated epoch latency or continuous data \n%                  time range: [low high] in ms, inclusive. For continuous data, several \n%                  time ranges may be specified, separated by semicolons. \n%                  Example: \"5 10; 12 EEG.xmax\" will retain the indicated\n%                  stretches of continuous data, and remove data portions outside\n%                  the indicated ranges, e.g. from 0 s to 5 s and from 10 s to 12 s. \n%                  Command line equivalent: 'time' (or 'notime' - see below)\n%   \"Time range\" - [checkbox] EXCLUDE the indicated latency range(s) from the data.\n%                  For epoched data, it is not possible to remove a range of latencies \n%                  from the middle of the epoch, so either the low and/or the high values \n%                  in the specified latency range (see above) must be at an epoch boundary \n%                  (EEG.xmin, EEGxmax).  Command line equivalent: [if checked] 'notime' \n%   \"Point range\" - [edit box] RETAIN the indicated data point range(s). \n%                  Same options as for the \"Time range\" features (above).\n%                  Command line equivalent: 'point' (or 'nopoint' - see below).\n%   \"Point range\" - [checkbox] EXCLUDE the indicated point range(s).\n%                  Command line equivalent: [if checked] 'nopoint' \n%   \"Epoch range\" - [edit box] RETAIN the indicated data epoch indices in the dataset.\n%                  This checkbox is only visible for epoched datasets. \n%                  Command line equivalent: 'trial' (or 'notrial' - see below)\n%   \"Epoch range\" - [checkbox] EXCLUDE the specified data epochs. \n%                   Command line equivalent: [if checked] 'notrial' \n%   \"Channel range\" - [edit box] RETAIN the indicated vector of data channels \n%                  Command line equivalent: 'channel' (or 'nochannel' - see below)\n%   \"Channel range\" - [checkbox] EXCLUDE the indicated channels.\n%                  Command line equivalent: [if checked] 'nochannel' \n%   \"...\" - [button] select channels by name.\n%   \"Scroll dataset\" - [button] call the eegplot() function to scroll the\n%                  channel activities in a new window for visual inspection.\n%                  Commandline equivalent: eegplot() - see its help for details.\n% Inputs:\n%   INEEG         - input EEG dataset structure\n%\n% Optional inputs\n%   'time'        - [min max] in seconds. Epoch latency or continuous data time range \n%                   to retain in the new dataset, (Note: not ms, as in the GUI text entry \n%                   above). For continuous data (only), several time ranges can be specified, \n%                   separated by semicolons. Example: \"5 10; 12 EEG.xmax\" will retain \n%                   the indicated times ranges, removing data  outside the indicated ranges \n%                   e.g. here from 0 to 5 s and from 10 s to 12 s. (See also, 'notime')\n%   'notime'      - [min max] in seconds. Epoch latency or continuous dataset time range \n%                   to exclude from the new dataset. For continuous data, may be \n%                   [min1 max1; min2 max2; ...] to exclude several time ranges. For epoched \n%                   data, the latency range must include an epoch boundary, as latency \n%                   ranges in the middle of epochs cannot be removed from epoched data.\n%   'point'       - [min max] epoch or continuous data point range to retain in the new \n%                   dataset. For continuous datasets, this may be [min1 max1; min2 max2; ...] \n%                   to retain several point ranges. (Notes: If both 'point'/'nopoint' and \n%                   'time' | 'notime' are specified, the 'point' limit values take precedence. \n%                   The 'point' argument was originally a point vector, now deprecated).\n%   'nopoint'     - [min max] epoch or continuous data point range to exclude in the new dataset. \n%                   For epoched data, the point range must include either the first (0) \n%                   or the last point (EEG.pnts), as a central point range cannot be removed. \n%   'trial'       - array of trial indices to retain in the new dataset\n%   'notrial'     - array of trial indices to exclude from the new dataset\n%   'sorttrial'   - ['on'|'off'] sort trial indices before extracting them (default: 'on').\n%   'channel'     - vector of channel indices to retain in the new \n%                   dataset. Can also be a cell array of channel names.\n%   'nochannel'   - vector of channel indices to exclude from the new\n%                   dataset. Can also be a cell array of channel names.\n%   'newname'     - name for the new dataset (OUTEEG)\n%\n% Outputs:\n%   OUTEEG        - new EEG dataset structure\n%\n% Note: This function performs a conjunction (AND) of all its optional inputs.\n%       Using negative counterparts of all options, any logical combination is\n%       possible.\n% \n% Author: Arnaud Delorme, CNL/Salk Institute, 2001; SCCN/INC/UCSD, 2002-\n% \n% see also: eeglab()\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n% 01-25-02 reformated help & license -ad \n% 01-26-02 changed the format for events and trial conditions -ad\n% 02-04-02 changed display format and allow for negation of inputs -ad \n% 02-17-02 removed the event removal -ad \n% 03-17-02 added channel info subsets selection -ad \n% 03-21-02 added event latency recalculation -ad \n\nfunction [EEG, com] = pop_select( EEG, varargin);\n\ncom = '';\nif nargin < 1\n    help pop_select;\n    return;\nend;\n    \nif nargin < 2\n   geometry = { [1 1 1] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] ...\n           [1 1 0.25 0.23 0.51] [1] [1 1 1]};\n   uilist = { ...\n         { 'Style', 'text', 'string', 'Select data in:', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'Input desired range', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'on->remove these', 'fontweight', 'bold'  }, ...\n         { 'Style', 'text', 'string', 'Time range [min max] (s)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Point range (ex: [1 10])', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Epoch range (ex: 3:2:10)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...\n         { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...\n         ...\n         { 'Style', 'text', 'string', 'Channel range' }, ...\n         { 'Style', 'edit', 'string', '', 'tag', 'chans' }, ...\n         { }, { 'Style', 'checkbox', 'string', '    ' }, ...\n         { 'style' 'pushbutton' 'string'  '...', 'enable' fastif(isempty(EEG.chanlocs), 'off', 'on') ...\n           'callback' 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''chans''), ''string'',tmpval); clear tmp tmpchanlocs tmpval' }, ...\n           { }, { }, { 'Style', 'pushbutton', 'string', 'Scroll dataset', 'enable', fastif(length(EEG)>1, 'off', 'on'), 'callback', ...\n                          'eegplot(EEG.data, ''srate'', EEG.srate, ''winlength'', 5, ''limits'', [EEG.xmin EEG.xmax]*1000, ''position'', [100 300 800 500], ''xgrid'', ''off'', ''eloc_file'', EEG.chanlocs);' } {}};\n   results = inputgui( geometry, uilist, 'pophelp(''pop_select'');', 'Select data -- pop_select()' );\n   if length(results) == 0, return; end;\n\n   \n   % decode inputs\n   % -------------\n   args = {};\n   if ~isempty( results{1} )\n       if ~results{2}, args = { args{:}, 'time', eval( [ '[' results{1} ']' ] ) };\n       else            args = { args{:}, 'notime', eval( [ '[' results{1} ']' ] ) }; end;\n   end;\n\n   if ~isempty( results{3} )\n       if ~results{4}, args = { args{:}, 'point', eval( [ '[' results{3} ']' ] ) };\n       else            args = { args{:}, 'nopoint', eval( [ '[' results{3} ']' ] ) }; end;\n   end;\n\n   if ~isempty( results{5} )\n       if ~results{6}, args = { args{:}, 'trial', eval( [ '[' results{5} ']' ] ) };\n       else            args = { args{:}, 'notrial', eval( [ '[' results{5} ']' ] ) }; end;\n   end;\n\n   if ~isempty( results{7} )\n       [ chaninds chanlist ] = eeg_decodechan(EEG.chanlocs, results{7});\n       if isempty(chanlist), chanlist = chaninds; end;\n       if ~results{8}, args = { args{:}, 'channel'  , chanlist };\n       else            args = { args{:}, 'nochannel', chanlist }; end;\n   end;\n\nelse\n    args = varargin;\nend;\n\n%----------------------------AMICA---------------------------------\nif isfield(EEG.etc,'amica') && isfield(EEG.etc.amica,'prob_added')\n    for index = 1:2:length(args)\n       if strcmpi(args{index}, 'channel')\n           args{index+1} = [ args{index+1} EEG.nbchan-(0:2*EEG.etc.amica.num_models-1)];\n           \n       end;\n       \n       \n    end;\nend;\n%--------------------------------------------------------------------\n        \n% process multiple datasets\n% -------------------------\nif length(EEG) > 1\n    [ EEG com ] = eeg_eval( 'pop_select', EEG, 'warning', 'on', 'params', args);\n    return;\nend;\n\nif isempty(EEG.chanlocs), chanlist = [1:EEG.nbchan];\nelse                      chanlocs = EEG.chanlocs; chanlist = { chanlocs.labels };\nend;\ng = hlp_microcache('popselect',@finputcheck,args, { 'time'    'real'      []         []; ...\n                        'notime'  'real'      []         []; ...\n                        'trial'   'integer'   []         [1:EEG.trials]; ...\n                        'notrial' 'integer'   []         []; ...\n                        'point'   'integer'   []         []; ...\n                        'nopoint' 'integer'   []         []; ...\n                        'channel'   { 'integer' 'cell' }  []  chanlist;\n                        'nochannel' { 'integer' 'cell' }   []  [];\n                        'trialcond'   'integer'   []         []; ...\n                        'notrialcond' 'integer'   []         []; ...\n                        'sorttrial'   'string'    { 'on' 'off' } 'on' }, 'pop_select');\nif isstr(g), error(g); end;\n\nif strcmpi(g.sorttrial, 'on')\n    g.trial = sort(setdiff( g.trial, g.notrial ));\nelse\n    g.trial(ismember(g.trial,g.notrial)) = [];\n    % still warn about & remove duplicate trials (may be removed in the future)\n    [p,q] = unique(g.trial);\n    if length(p) ~= length(g.trial)\n        disp('Warning: trial selection contained duplicated elements, which were removed.'); \n    end    \n    g.trial = g.trial(sort(q));\nend\n\nif isempty(g.channel) && ~iscell(g.nochannel) && ~iscell(chanlist)\n    g.channel = [1:EEG.nbchan];\nend;\n\nif iscell(g.channel) && ~iscell(g.nochannel) && ~isempty(EEG.chanlocs)\n     noChannelAsCell = {};\n     for nochanId = 1:length(g.nochannel)\n         noChannelAsCell{nochanId} = EEG.chanlocs(g.nochannel(nochanId)).labels;\n     end;\n     g.nochannel =   noChannelAsCell; \nend;\n\nif strcmpi(g.sorttrial, 'on')\n    g.channel = sort(setdiff( lower(g.channel), lower(g.nochannel) ));\nelse\n    g.channel(ismember(lower(g.channel),lower(g.nochannel))) = [];\n    % still warn about & remove duplicate channels (may be removed in the future)\n    [p,q] = unique(g.channel);\n    if length(p) ~= length(g.channel)\n        disp('Warning: channel selection contained duplicated elements, which were removed.'); \n    end    \n    g.channel = g.channel(sort(q));    \nend\n\nif ~isempty(EEG.chanlocs)\n    if strcmpi(g.sorttrial, 'on')\n        g.channel = eeg_decodechan(EEG.chanlocs, g.channel);\n    else\n        % we have to protect the channel order against changes by eeg_decodechan\n        if iscell(g.channel)\n            % translate channel names into indices\n            [inds,names] = eeg_decodechan(EEG.chanlocs, g.channel);\n            % and sort the indices back into the original order of channel names            \n            [tmp,I] = ismember(lower(g.channel),lower(names)); \n            g.channel = inds(I);\n        end\n    end\nend;\n\nif ~isempty(g.time) & (g.time(1) < EEG.xmin*1000) & (g.time(2) > EEG.xmax*1000)\n   error('Wrong time range');\nend;\nif min(g.trial) < 1 | max( g.trial ) > EEG.trials  \n   error('Wrong trial range');\nend;\nif min(g.channel) < 1 | max( g.channel ) > EEG.nbchan  \n   error('Wrong channel range');\nend;\n\nif size(g.point,2) > 2, \n    g.point = [g.point(1) g.point(end)];\n    disp('Warning: vector format for point range is deprecated');\nend;\nif size(g.nopoint,2) > 2, \n    g.nopoint = [g.nopoint(1) g.nopoint(end)];\n    disp('Warning: vector format for point range is deprecated');\nend;\nif ~isempty( g.point )\n    g.time = zeros(size(g.point));\n    for index = 1:length(g.point(:))\n        g.time(index) = eeg_point2lat(g.point(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);\n    end;\n    g.notime = [];\nend;\nif ~isempty( g.nopoint )\n    g.notime = zeros(size(g.nopoint));\n    for index = 1:length(g.nopoint(:))\n        g.notime(index) = eeg_point2lat(g.nopoint(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);\n    end;\n    g.time = [];\nend;\nif ~isempty( g.notime )\n    if size(g.notime,2) ~= 2\n        error('Time/point range must contain 2 columns exactly');\n    end;\n    if g.notime(2) == EEG.xmax\n        g.time = [EEG.xmin g.notime(1)];\n    else\n        if g.notime(1) == EEG.xmin\n            g.time = [g.notime(2) EEG.xmax];\n        elseif EEG.trials > 1\n            error('Wrong notime range. Remember that it is not possible to remove a slice of time for data epochs.');\n        end;\n    end;\n    if floor(max(g.notime(:))) > EEG.xmax || min(g.notime(:)) < EEG.xmin\n        error('Time/point range out of data limits');\n    end;\nend;\nif ~isempty(g.time)\n    if size(g.time,2) ~= 2\n        error('Time/point range must contain 2 columns exactly');\n    end;\n    for index = 1:length(g.time)\n        if g.time(index) > EEG.xmax\n            g.time(index) = EEG.xmax;\n            disp('Upper time limits exceed data, corrected');\n        elseif g.time(index) < EEG.xmin\n            g.time(index) = EEG.xmin;\n            disp('Lower time limits exceed data, corrected');\n        end;\n    end;\nend;\n\n% select trial values\n%--------------------\nif ~isempty(g.trialcond)\n   try, tt = struct( g.trialcond{:} ); catch\n      error('Trial conditions format error');\n   end;\n   ttfields = fieldnames (tt);\n   for index = 1:length(ttfields)\n        if ~isfield( EEG.epoch, ttfields{index} )\n            error([ ttfields{index} 'is not a field of EEG.epoch' ]);\n        end;    \n        tmpepoch = EEG.epoch;\n\t    eval( [ 'Itriallow  = find( [ tmpepoch(:).' ttfields{index} ' ] >= tt.' ttfields{index} '(1) );' ] );\n\t    eval( [ 'Itrialhigh = find( [ tmpepoch(:).' ttfields{index} ' ] <= tt.' ttfields{index} '(end) );' ] );\n\t    Itrialtmp = intersect(Itriallow, Itrialhigh);\n\t    g.trial = intersect( g.trial(:)', Itrialtmp(:)');\n   end;\t   \nend;\n\nif isempty(g.trial)\n   error('Empty dataset, no trial');\nend;\nif length(g.trial) ~= EEG.trials\n\tfprintf('Removing %d trial(s)...\\n', EEG.trials - length(g.trial));\nend;\nif length(g.channel) ~= EEG.nbchan\n\tfprintf('Removing %d channel(s)...\\n', EEG.nbchan - length(g.channel));\nend;\n\n% For AMICA probabilities...\n%-----------------------------------------------------\nif isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')\n    if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)\n        if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models\n            \n            EEG = eeg_formatamica(EEG);\n            \n            %-------------------------------------------\n            \n            [EEG com] = pop_select(EEG,args{:});\n            \n            %-------------------------------------------\n            \n            EEG = eeg_reformatamica(EEG);\n            EEG = eeg_checkamica(EEG);\n            return;\n        else\n            disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected')\n            \n            disp('Resuming rejection...')\n        end\n    end\n    \nend\n% ------------------------------------------------------\n\n\n\n% recompute latency and epoch number for events\n% ---------------------------------------------\nif length(g.trial) ~= EEG.trials & ~isempty(EEG.event)\n    if ~isfield(EEG.event, 'epoch')\n        disp('Pop_epoch warning: bad event format with epoch dataset, removing events');\n        EEG.event = [];\n    else\n\t\tif isfield(EEG.event, 'epoch')\n\t\t\tkeepevent = [];\n\t\t\tfor indexevent = 1:length(EEG.event)\n\t\t\t\tnewindex = find( EEG.event(indexevent).epoch == g.trial );\n\t\t\t\tif ~isempty(newindex)\n\t\t\t\t\tkeepevent = [keepevent indexevent];\n\t\t\t\t\tif isfield(EEG.event, 'latency')\n\t\t\t\t\t\tEEG.event(indexevent).latency = EEG.event(indexevent).latency - (EEG.event(indexevent).epoch-1)*EEG.pnts + (newindex-1)*EEG.pnts;\n\t\t\t\t\tend;\n\t\t\t\t\tEEG.event(indexevent).epoch = newindex;\n\t\t\t\tend;                \n\t\t\tend;\n            diffevent = setdiff([1:length(EEG.event)], keepevent);\n\t\t\tif ~isempty(diffevent)\n\t\t\t\tdisp(['Pop_select: removing ' int2str(length(diffevent)) ' unreferenced events']);\n\t\t\t\tEEG.event(diffevent) = [];\n\t\t\tend;    \n\t\tend;\n    end;        \nend;\n\n\n% performing removal\n% ------------------\nif ~isempty(g.time) | ~isempty(g.notime)\n    if EEG.trials > 1\n        % select new time window\n        % ----------------------    \n        try,   tmpevent = EEG.event;\n               tmpeventlatency = [ tmpevent.latency ];\n        catch, tmpeventlatency = [];\n        end;\n        alllatencies = 1-(EEG.xmin*EEG.srate); % time 0 point\n        alllatencies = linspace( alllatencies, EEG.pnts*(EEG.trials-1)+alllatencies, EEG.trials);\n        [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, ...\n                                                     [g.time(1) g.time(2)]*EEG.srate, 'allevents', tmpeventlatency);\n        tmptime = tmptime/EEG.srate;\n        if g.time(1) ~= tmptime(1) & g.time(2)-1/EEG.srate ~= tmptime(2)\n            fprintf('pop_select(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\\n', tmptime(1), tmptime(2)+1/EEG.srate);\n        end;\n        EEG.xmin = tmptime(1);\n        EEG.xmax = tmptime(2);\n        EEG.pnts = size(EEG.data,2);\n        alllatencies = alllatencies(indices);\n        \n        % modify the event structure accordingly (latencies and add epoch field)\n        % ----------------------------------------------------------------------\n        allevents = [];\n        newevent = [];\n        count = 1;\n        if ~isempty(epochevent)\n            newevent = EEG.event(1);\n            for index=1:EEG.trials\n                for indexevent = epochevent{index}\n                    newevent(count)         = EEG.event(indexevent);\n                    newevent(count).epoch   = index;\n                    newevent(count).latency = newevent(count).latency - alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1);\n                    count = count + 1;\n                end;\n            end;\n        end;\n        EEG.event = newevent;\n        \n        % erase event-related fields from the epochs\n        % ------------------------------------------\n        if ~isempty(EEG.epoch)\n            fn = fieldnames(EEG.epoch);\n            EEG.epoch = rmfield(EEG.epoch,{fn{strmatch('event',fn)}});\n        end;\n    else\n        if isempty(g.notime)\n            if length(g.time) == 2 && EEG.xmin < 0\n                disp('Warning: negative minimum time; unchanged to ensure correct latency of initial boundary event');\n            end;\n            g.notime = g.time';\n            g.notime = g.notime(:);\n            if g.notime(1) ~= 0, g.notime = [EEG.xmin g.notime(:)'];\n            else                 g.notime = [g.notime(2:end)'];\n            end;\n            if g.time(end) == EEG.xmax, g.notime(end) = [];\n            else                        g.notime(end+1) = EEG.xmax;\n            end;\n            \n            for index = 1:length(g.notime)\n                if g.notime(index) ~= 0  & g.notime(index) ~= EEG.xmax\n                    if mod(index,2), g.notime(index) = g.notime(index) + 1/EEG.srate;\n                    else             g.notime(index) = g.notime(index) - 1/EEG.srate;\n                    end;\n                end;\n            end;        \n            g.notime = reshape(g.notime, 2, length(g.notime)/2)';\n        end;   \n        \n        nbtimes = length(g.notime(:));\n        points = eeg_lat2point(g.notime(:)', ones(1,nbtimes), EEG.srate, [EEG.xmin EEG.xmax]);\n        points = reshape(points, size(g.notime));\n        EEG = eeg_eegrej(EEG, points);\n    end\nend;\n\n% performing removal\n% ------------------\nif ~isequal(g.channel,1:size(EEG.data,1)) || ~isequal(g.trial,1:size(EEG.data,3))\n    EEG.data  = EEG.data(g.channel, :, g.trial);\n    if isfield(EEG,'srcpot') && ~isempty(EEG.srcpot)\n        EEG.srcpot = EEG.srcpot(:, :, g.trial);  % TODO: this is an ugly hack\n    end\nend\nif ~isempty(EEG.icaact), EEG.icaact = EEG.icaact(:,:,g.trial); end;\nEEG.trials    = length(g.trial);\nEEG.pnts      = size(EEG.data,2);\nEEG.nbchan    = length(g.channel);\nif ~isempty(EEG.chanlocs)\n    EEG.chanlocs = EEG.chanlocs(g.channel);\nend;    \nif ~isempty(EEG.epoch)\n   EEG.epoch = EEG.epoch( g.trial );\nend;\nif ~isempty(EEG.specdata)\n\tif length(g.point) == EEG.pnts\n   \t\tEEG.specdata = EEG.specdata(g.channel, :, g.trial);\n   \telse\n   \t\tEEG.specdata = [];\n   \t\tfprintf('Warning: spectral data were removed because of the change in the numner of points\\n');\n   \tend;\t\t\nend;\n\n% ica specific\n% ------------\nif ~isempty(EEG.icachansind)\n    \n    rmchans = setdiff( EEG.icachansind, g.channel ); % channels to remove\n    \n    % channel sub-indices\n    % -------------------\n    icachans = 1:length(EEG.icachansind);\n    for index = length(rmchans):-1:1\n        chanind           = find(EEG.icachansind == rmchans(index));\n        icachans(chanind) = [];\n    end;\n        \n    % new channels indices\n    % --------------------\n    count   = 1;\n    newinds = [];\n    for index = 1:length(g.channel)\n        if any(EEG.icachansind == g.channel(index))\n            newinds(count) = index;\n            count          = count+1;\n        end;\n    end;\n    EEG.icachansind = newinds;\n    \nelse\n    icachans = 1:size(EEG.icasphere,2);\nend;\n\nif ~isempty(EEG.icasphere)\n    EEG.icasphere = EEG.icasphere(:,icachans);\nend;\nif ~isempty(EEG.icawinv)\n    EEG.icawinv = EEG.icawinv(icachans,:);\nend;\nif ~isempty(EEG.specicaact)\n    if length(g.point) == EEG.pnts\n        EEG.specicaact = EEG.specicaact(icachans, :, g.trial);\n    else\n        EEG.specicaact = [];\n        fprintf('Warning: spectral ICA data were removed because of the change in the numner of points\\n');\n    end;\nend;\n\n% for stats, can adapt remove the selected trials and electrodes\n% in the future to gain time -----------------------------------  \nEEG.reject = struct('rejmanual',{[]});\nEEG.stats = struct('jp',{[]});\nEEG = eeg_checkset(EEG, 'eventconsistency');\n\n% generate command\n% ----------------\nif nargout > 1\ncom = sprintf('EEG = pop_select( %s,%s);', inputname(1), vararg2str(args));\nend\n\nreturn;\n\n% ********* OLD, do not remove any event any more\n% ********* in the future maybe do a pack event to remove events not in the time range of any epoch\n\nif ~isempty(EEG.event)\n    % go to array format if necessary\n    if isstruct(EEG.event), format = 'struct';\n    else                     format = 'array';\n    end;\n    switch format, case 'struct', EEG = eventsformat(EEG, 'array'); end;\n    \n    % keep only events related to the selected trials\n    Indexes = [];\n    Ievent  = [];\n    for index = 1:length( g.trial )\n        currentevents = find( EEG.event(:,2) == g.trial(index));\n        Indexes = [ Indexes ones(1, length(currentevents))*index ];\n        Ievent  = union( Ievent, currentevents );\n    end;\n    EEG.event = EEG.event( Ievent,: );\n    EEG.event(:,2) = Indexes(:);\n    \n    switch format, case 'struct', EEG = eventsformat(EEG, 'struct'); end;\nend;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/pop_select.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.2139385807064916}}
{"text": "function [vertex,face,edge,mesh] = mesh_emse2matlab(file,options)\n\n% mesh_emse2matlab - Convert EMSE mesh (.wfr) to matlab format\n%\n% USEAGE: [vertices,faces,edges,meshtype] = mesh_emse2matlab(file,[options])\n%\n% All values returned are in meters.  With the returned structures, \n% create a vertex & face matrix:\n% \n%   vertex_matrix = [vertices.x; vertices.y; vertices.z]';\n%   face_matrix = [faces.vertex1;faces.vertex2;faces.vertex3]';\n%\n% These can be input to the patch command:\n%\n%    Hpatch = patch('Vertices',vertex_matrix,'Faces',face_matrix,...\n%                   'EdgeColor',[.6 .6 .6],'FaceColor',[0.9 0.9 0.9]);\n%\n% See the patch and light commands to colour this object.\n% \n% 'options' ... a cell array of strings.  By default it contains\n% options = {'vertex','face','edge'}.  By default, this routine\n% reads all available data from the emse file.  If 'options' is given\n% and it doesn't contain one of these strings, that data will not be\n% read or returned.\n%\n% meshtype is: 'unknown','scalp','outer skull','inner skull', or 'cortex'\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  10/98 Abbas Kouzani (egazk@flinders.edu.au)\n%           09/01 Darren.Weber_at_radiology.ucsf.edu\n%                 - created function, rather than script\n%                 - added functionality to handle different\n%                   minor revisions.\n%           03/02 Darren.Weber_at_radiology.ucsf.edu\n%                 - optimised fscanf processes for matlab, the\n%                   function now operates in less than 1/2 time,\n%                   especially for revision 3 data.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~exist('options','var'),\n    options = {'vertex','face','edge'};\nend\n\n[path,name,ext] = fileparts(file);\nfile = fullfile(path,[name ext]);\n\n[fid,msg] = fopen(file,'r');\nif ~isempty(msg), error(msg); end\n\ntic;\n\n% Read prolog\nversion   =fscanf(fid,'%f',1);\nfile_type =fscanf(fid,'%f',1);\nminor_rev =fscanf(fid,'%f',1);\n\nfprintf('...WFR Version = %d, Minor_Revision = %d, File-Type = %d\\n',...\n    version,minor_rev,file_type);\n\nif ~(file_type==8000 | file_type==4000)\n    S=sprintf('Could not convert WFR file type: %d',file_type);\n    error(S);\nend\n\n% Read header (format depends on minor revision)\nif(minor_rev==3)\n    type      =fscanf(fid,'%f',1);\nelse\n\tradius    =fscanf(fid,'%f',1);\n\tvertex_no =fscanf(fid,'%d',1);\n\tface_no   =fscanf(fid,'%d',1);\n\tedge_no   =fscanf(fid,'%d',1);\n    \n    fprintf('...Radius = %f meters\\n',radius);\n    %...Vertices = %d\\n...Patches = %d\\n...Edges = %d\\n',...\n    %    vertex_no,face_no,edge_no);\n\n    if(minor_rev==1), type = 0;\n    else,             type = fscanf(fid,'%f',1);\n    end\nend\n\nif(minor_rev==1)\n    mesh = 'unknown';\nelse\n\tswitch type\n        case 0,             mesh = 'unknown';\n        case { 64,  40},    mesh = 'scalp';\n        case {128,  80},    mesh = 'outer skull';\n        case {256, 100},    mesh = 'inner skull';\n        case {512, 200},    mesh = 'cortex';\n        otherwise,          mesh = 'unknown';\n\tend\nend\n\nfprintf('...Mesh type: %s\\n',mesh);\n\n% Read data (format depends on minor revision)\nvertex = struct([]);\nface = struct([]);\nedge = struct([]);\n\nif(minor_rev==3)\n    \n    % Read the whole file\n    fprintf('...Reading Minor Revision 3 Data File');\n    Tmp = fscanf(fid,'%s%f%f%f',[4,inf]);\n    fprintf('...done\\n');\n    \n    % Vertices\n    if(max(strcmp('vertex',options)) > 0),\n        fprintf('...Creating Vertices Struct');\n        % first get the numeric code for 'v'\n        vcode = Tmp(1,1);\n        % now find all columns of Tmp with vcode in 1st row\n        vindex = find(Tmp(1,:) == vcode);\n        \n        tmp = Tmp(2:4,vindex);\n        tmp = num2cell(tmp);\n        vertex = struct(...\n            'index', [1:length(vindex)],...\n            'x',     tmp( 1,:),...\n            'y',     tmp( 2,:),...\n            'z',     tmp( 3,:));\n        clear tmp;\n        fprintf('...done\\n');\n    else\n        fprintf('...Skipping Vertices Struct\\n');\n    end\n    \n    % Faces\n    if(max(strcmp('face',options)) > 0),\n        fprintf('...Creating Faces Struct');\n        % first get the numeric code for 't'\n        tcode = Tmp(1,length(vindex)+1);\n        % now find all columns of Tmp with tcode in 1st row\n        tindex = find(Tmp(1,:) == tcode);\n        \n        % matlab vertex indices start at one,\n        % not zero, so we add one to these emse values\n        tmp = Tmp(2:4,tindex) + 1;\n        \n        tmp = num2cell(tmp);\n        face = struct(...\n            'index',   [1:length(tindex)],...\n            'vertex1', tmp( 1,:),...\n            'vertex2', tmp( 2,:),...\n            'vertex3', tmp( 3,:));\n        clear tmp;\n        fprintf('...done\\n');\n    else\n        fprintf('...Skipping Faces Struct\\n');\n    end\n    \n    % Edges\n    fprintf('...No edges for minor revision 3\\n');\n    clear Tmp;\n    \nelseif(minor_rev~=4)\n    % minor revision 1 & 2 format\n    disp('...Reading Minor Revision 1 or 2 Data');\n    if(max(strcmp('vertex',options)) > 0),\n        fprintf('...Reading %d Vertices',vertex_no);\n        \n        tmp = zeros(13,vertex_no);\n        tmp = fscanf(fid,'%d%x%d%d%g%g%g%g%g%g%g%g%g',[13,vertex_no]);\n        \n        tmp(1,:) = tmp(1,:) + 1;\n        tmp      = num2cell(tmp);\n        vertex   = struct(...\n            'index',        tmp( 1,:),...\n            'address',      tmp( 2,:),...\n            'channel_index',tmp( 3,:),...\n            'x',            tmp( 5,:),...\n            'y',            tmp( 6,:),...\n            'z',            tmp( 7,:),...\n            'xnormal',      tmp( 9,:),...\n            'ynormal',      tmp(10,:),...\n            'znormal',      tmp(11,:),...\n            'potential',    tmp(12,:),...\n            'curvature',    tmp(13,:));\n        clear tmp;\n        fprintf('...done\\n');\n    else\n        fprintf('...Skipping %d Vertices\\n',vertex_no);\n        tmp = zeros(13,vertex_no);\n        tmp = fscanf(fid,'%d%x%d%d%g%g%g%g%g%g%g%g%g',[13,vertex_no]);\n        clear tmp;\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(max(strcmp('face',options)) > 0),\n        fprintf('...Reading %d Faces',face_no);\n        \n        tmp = zeros(18,face_no);\n        tmp = fscanf(fid,'%d%x%g%g%g%g%g%g%g%g%g%g%x%x%x%x%x%x',[18,face_no]);\n        tmp(1,:) = tmp(1,:) + 1;\n        tmp      = num2cell(tmp);\n        face     = struct(...\n            'index',        tmp( 1,:),...\n            'address',      tmp( 2,:),...\n            'solid_angle',  tmp( 3,:),...\n            'magnitude',    tmp( 4,:),...\n            'potential',    tmp( 5,:),...\n            'area',         tmp( 6,:),...\n            'center_x',     tmp( 7,:),...\n            'center_y',     tmp( 8,:),...\n            'center_z',     tmp( 9,:),...\n            'normal_x',     tmp(10,:),...\n            'normal_y',     tmp(11,:),...\n            'normal_z',     tmp(12,:),...\n            'vertex1',      tmp(13,:),...\n            'vertex2',      tmp(14,:),...\n            'vertex3',      tmp(15,:),...\n            'edge1',        tmp(16,:),...\n            'edge2',        tmp(17,:),...\n            'edge3',        tmp(18,:));\n        clear tmp;\n        fprintf('...done\\n');\n        \n        % In minor rev4, the face vertex and edges\n        % refer to the vertex.address field, so this\n        % is corrected here.  Not sure how to avoid 'for'\n        fprintf('...Converting Face vertices from address to index (this takes a while)');\n        for i=1:face_no,\n            face(i).vertex1 = find([vertex.address] == face(i).vertex1);\n            face(i).vertex2 = find([vertex.address] == face(i).vertex2);\n            face(i).vertex3 = find([vertex.address] == face(i).vertex3);\n        end\n        fprintf('...done\\n');\n        if(max(strcmp('edge',options)) > 0),\n            fprintf('...Converting Face edges from address to index (this takes a while)');\n            for i=1:face_no,\n                face(i).edge1 = find([vertex.address] == face(i).edge1);\n                face(i).edge2 = find([vertex.address] == face(i).edge2);\n                face(i).edge3 = find([vertex.address] == face(i).edge3);\n            end\n            fprintf('...done\\n');\n        end\n    else\n        disp('...Skipping Faces');\n        tmp = zeros(18,face_no);\n        tmp = fscanf(fid,'%d%x%g%g%g%g%g%g%g%g%g%g%x%x%x%x%x%x',[18,face_no]);\n        clear tmp;\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(max(strcmp('edge',options)) > 0),\n        fprintf('...Reading %d Edges',edge_no);\n        \n        tmp = zeros(4,edge_no);\n        tmp = fscanf(fid,'%d%x%x%x',[4,edge_no]);\n        \n        tmp(1,:) = tmp(1,:) + 1;\n        tmp      = num2cell(tmp);\n        edge     = struct(...\n            'index',        tmp(1,:),...\n            'address',      tmp(2,:),...\n            'vertex1',      tmp(3,:),...\n            'vertex2',      tmp(4,:));\n        clear tmp;\n        fprintf('...done\\n');\n        fprintf('...Converting Edge vertices from address to index (this takes a while)');\n        for i=1:edge_no,\n            edge(i).vertex1 = find([vertex.address] == edge(i).vertex1);\n            edge(i).vertex2 = find([vertex.address] == edge(i).vertex2);\n        end\n        fprintf('...done\\n');\n    else\n        disp('...Skipping Edges');\n        %for i=1:edge_no,\n        %    tmp=fscanf(fid,'%*d',1);\n        %    tmp=fscanf(fid,'%*x',3);\n        %end\n    end\nelse\n    % minor revision 4 format\n    disp('...Reading Minor Revision 4 Data');\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(max(strcmp('vertex',options)) > 0),\n        fprintf('...Reading %d Vertices',vertex_no);\n        \n        index = meshgrid(1:1:vertex_no,1);\n        index = num2cell(index);\n        \n        tmp = zeros(11,vertex_no);\n        tmp = fscanf(fid,'%d%d%g%g%g%d%g%g%g%g%g',[11,vertex_no]);\n        \n        tmp      = num2cell(tmp);\n        vertex   = struct(...\n            'index',        index,...\n            'channel_index',tmp( 1,:),...\n            'x',            tmp( 3,:),...\n            'y',            tmp( 4,:),...\n            'z',            tmp( 5,:),...\n            'xnormal',      tmp( 7,:),...\n            'ynormal',      tmp( 8,:),...\n            'znormal',      tmp( 9,:),...\n            'potential',    tmp(10,:),...\n            'curvature',    tmp(11,:));\n        clear tmp index;\n        fprintf('...done\\n');\n    else\n        disp('...Skipping Vertices');\n        tmp = zeros(11,vertex_no);\n        tmp = fscanf(fid,'%d%d%g%g%g%d%g%g%g%g%g',[11,vertex_no]);\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(max(strcmp('face',options)) > 0),\n        fprintf('...Reading %d Faces',face_no);\n        \n        index = meshgrid(1:1:face_no,1);\n        index = num2cell(index);\n        \n        tmp = zeros(16,face_no);\n        tmp = fscanf(fid,'%g%g%g%g%g%g%g%g%g%g%d%d%d%d%d%d',[16,face_no]);\n        \n        tmp(11:16,:) = tmp(11:16,:) + 1;\n        \n        tmp      = num2cell(tmp);\n        face     = struct(...\n            'index',        index,...\n            'solid_angle',  tmp( 1,:),...\n            'magnitude',    tmp( 2,:),...\n            'potential',    tmp( 3,:),...\n            'area',         tmp( 4,:),...\n            'center_x',     tmp( 5,:),...\n            'center_y',     tmp( 6,:),...\n            'center_z',     tmp( 7,:),...\n            'normal_x',     tmp( 8,:),...\n            'normal_y',     tmp( 9,:),...\n            'normal_z',     tmp(10,:),...\n            'vertex1',      tmp(11,:),...\n            'vertex2',      tmp(12,:),...\n            'vertex3',      tmp(13,:),...\n            'edge1',        tmp(14,:),...\n            'edge2',        tmp(15,:),...\n            'edge3',        tmp(16,:));\n        clear tmp index;\n        fprintf('...done\\n');\n    else\n        disp('...Skipping Faces');\n        tmp = zeros(16,face_no);\n        tmp = fscanf(fid,'%g%g%g%g%g%g%g%g%g%g%d%d%d%d%d%d',[16,face_no]);\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if(max(strcmp('edge',options)) > 0),\n        fprintf('...Reading %d Edges',edge_no);\n        \n        index = meshgrid(1:1:edge_no,1);\n        address = num2cell(index * 0);\n        index = num2cell(index);\n        \n        tmp = zeros(2,edge_no);\n        tmp = fscanf(fid,'%d%d',[2,edge_no]);\n        tmp = tmp + 1;\n        tmp = num2cell(tmp);\n        \n        edge = struct(...\n            'index',   index,...\n            'address', address,...\n            'vertex1', tmp(1,:),...\n            'vertex2', tmp(2,:));\n        clear tmp index address;\n        fprintf('...done\\n');\n    else\n        fprintf('...Skipping Edges\\n');\n        %tmp=fscanf(fid,'%*d',2*edge_no);\n    end\nend\n\nfclose(fid);\nt=toc;\nfprintf('...done (%5.2f sec)\\n',t);\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_emse2matlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.21393010790330647}}
{"text": "classdef SingleTargetMeasurementSimulatorX < MeasurementSimulatorX\n% SingleTargetMeasurementSimulatorX class\n% \n% Summary of SingleTargetMeasurementSimulatorX:\n%   Class implementation of a single-target measurement simulator\n%\n% SingleTargetMeasurementSimulatorX Properties:\n%   + Model - A StateSpaceModelX object defining the base models used by the simulator\n%\n% SingleTargetMeasurementSimulatorX Methods:\n%   + SingleTargetMeasurementSimulatorX - Constructor method\n%   + simulate() - Generate measurements from ground-truth data\n%\n% (+) denotes puplic properties/methods\n% \n% See also MeasurementModelX and ClutterModelX template classes\n    \n    methods\n        function this = SingleTargetMeasurementSimulatorX(varargin)\n        % SingleTargetMeasurementSimulatorX Construct a measurement simulator object\n        %\n        % Parameters\n        % ----------\n        % Model: StateSpaceModelX object\n        %   A state-space model that should define the following models:    \n        %       + Measurement - Object handle to MeasurementModelX SubClass \n        %       + Clutter - Object handle to ClutterModelX SubClass \n        %       + Detection - Object handle to DetectionModelX SubClass\n            \n            % Call super-class\n            this@MeasurementSimulatorX(varargin{:});\n            \n        end\n        \n        function MeasurementScans = simulate(this, Track, varargin)\n        % simulate Simulate measurements given a set of ground truth data\n        %\n        % Parameters\n        % ----------\n        % Track: GroundTruthTrackX\n        %   An object containing ground-truth information for a single-target. \n        %   Detections will be generated on the basis of the Trajectory \n        %   property for each track.\n        % \n        % Returns\n        % -------\n        % MeasurementScans: (1 x NumScans) MeasurementListX array\n        %   An object array, whose elements contain the simulated measurement\n        %   scan at each timestep.\n            \n            % Dummy Detection probability\n            MeasurementScans = MeasurementListX.empty();\n            \n            % Initialise storage\n            numTimesteps = numel(Track.Trajectory);\n            \n            for k = 1:numTimesteps\n                \n                targetState = Track.Trajectory(k);\n                timestamp = targetState.Timestamp;\n                \n                % Compute number of tracks and clutter measurements\n                detectionProbability = 1;\n                if ~isempty(this.Model.Clutter)\n                    detectionProbability = this.Model.Detection.pdf(targetState.Vector);\n                end\n                    \n                targetDetected = binornd(1,detectionProbability);\n                numClutter = 0;\n                if ~isempty(this.Model.Clutter)\n                    numClutter = this.Model.Clutter.random('cardinality');\n                end\n                numMeasurements = targetDetected + numClutter;\n                \n                % Empty MeasurementX array\n                measurements = MeasurementX.empty(0, numMeasurements);\n\n                % Generate true measurement\n                if targetDetected\n                    measurementVector = this.Model.Measurement.feval(targetState.Vector,true);\n                    measurements(end+1) = MeasurementX(measurementVector, timestamp, this.Model);\n                end\n\n                % Generate clutter measurements\n                if(numClutter>0)\n                    clutterVectors = this.Model.Clutter.random(numClutter);\n                    for clutterVector = clutterVectors\n                        measurements(end+1) = MeasurementX(clutterVector, timestamp, this.Model);\n                    end\n                end\n                \n                MeasurementScans(k) = MeasurementListX(measurements);\n            end\n\n        end\n    end\nend\n", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Simulators/Measurement/SingleTargetMeasurementSimulatorX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21393010790330644}}
{"text": "function [fname] = gtopo30s(latlim,lonlim)\n\n    %GTOPO30S (30-arc-sec resolution) DEM file names\n    %\n    % fname = GTOPO30S(LATLIM,LONLIM) returns a cellarray of the file\n    % names covering the geographic region for GTOPO30 digital elevation maps\n    % (also referred to as \"30-arc second\" DEMs).  The region is specified by\n    % scalar latitude and longitude points, or two element vectors of latitude\n    % and longitude limits in units of degrees.\n    %\n    % The data is available over the Internet via anonymous ftp from\n    % <ftp://edcftp.cr.usgs.gov/pub/data/gtopo30/global>. The data and\n    % some documentation is also available over the World-Wide-Web from\n    % <http://edcwww.cr.usgs.gov/landdaac/gtopo30/gtopo30.html> and\n    % <http://edcwww.cr.usgs.gov/landdaac/gtopo30/README.html>.\n    %\n    % See also: GTOPO30\n\n    %  Written by:  A. Kim, W. Stumpf, L. Job\n    %  Copyright 1996-2000 Systems Planning and Analysis, Inc. and The MathWorks, Inc.\n    %  $Revision: 1399 $ $Date: 2006-08-11 11:19:27 +0200 (Fr, 11 Aug 2006) $\n\n    % ensure row vectors\n    latlim = latlim(:)';\n    lonlim = lonlim(:)';\n\n    if nargin~=2\n        error('Incorrect number of arguments')\n    end\n\n    if  isequal(size(latlim),[1 1])\n        latlim = latlim*[1 1];\n    elseif ~isequal(size(latlim),[1 2])\n        error('Latitude limit input must be a scalar or 2 element vector')\n    end\n\n    if isequal(sort(size(lonlim)),[1 1])\n        lonlim = lonlim*[1 1];\n    elseif ~isequal(sort(size(lonlim)),[1 2])\n        error('Longitude limit input must be a scalar or 2 element vector')\n    end\n\n    fid = fopen('gtopo30s.dat','r');\n    if fid==-1\n        error('Couldn''t open gtopo30s.dat')\n    end\n\n    % preallocate bounding rectangle data for speed\n\n    YMIN = zeros(1,33); YMAX = YMIN;\n    XMIN = YMIN; XMAX = YMIN;\n\n    % read names and bounding rectangle limits\n\n    for n=1:33\n        fnames{n,1} = fscanf(fid,'%s',1);\n        YMIN(n) = fscanf(fid,'%d',1);\n        YMAX(n) = fscanf(fid,'%d',1);\n        XMIN(n) = fscanf(fid,'%d',1);\n        XMAX(n) = fscanf(fid,'%d',1);\n    end\n    fclose(fid);\n\n    % case where dateline is not crossed\n    if lonlim(1) <= lonlim(2)\n        do = ...\n            find( ...\n            (...\n            (latlim(1) <= YMIN & latlim(2) >= YMAX) | ... % tile is completely within region\n            (latlim(1) >= YMIN & latlim(2) <= YMAX) | ... % region is completely within tile\n            (latlim(1) >  YMIN & latlim(1) <  YMAX) | ... % min of region is on tile\n            (latlim(2) >  YMIN & latlim(2) <  YMAX)   ... % max of region is on tile\n            ) ...\n            &...\n            (...\n            (lonlim(1) <= XMIN & lonlim(2) >= XMAX) | ... % tile is completely within region\n            (lonlim(1) >= XMIN & lonlim(2) <= XMAX) | ... % region is completely within tile\n            (lonlim(1) >  XMIN & lonlim(1) <  XMAX) | ... % min of region is on tile\n            (lonlim(2) >  XMIN & lonlim(2) <  XMAX)   ... % max of region is on tile\n            )...\n            );\n    end\n\n    % case where the dateline is crossed\n    if lonlim(1) > lonlim(2)\n        lmin = lonlim(1); lmax = lonlim(2);\n        lonlim(2) = 180;\n        % do eastern side of the dateline first\n        doEAST = ...\n            find( ...\n            (...\n            (latlim(1) <= YMIN & latlim(2) >= YMAX) | ... % tile is completely within region\n            (latlim(1) >= YMIN & latlim(2) <= YMAX) | ... % region is completely within tile\n            (latlim(1) >  YMIN & latlim(1) <  YMAX) | ... % min of region is on tile\n            (latlim(2) >  YMIN & latlim(2) <  YMAX)   ... % max of region is on tile\n            ) ...\n            &...\n            (...\n            (lonlim(1) <= XMIN & lonlim(2) >= XMAX) | ... % tile is completely within region\n            (lonlim(1) >= XMIN & lonlim(2) <= XMAX) | ... % region is completely within tile\n            (lonlim(1) >  XMIN & lonlim(1) <  XMAX) | ... % min of region is on tile\n            (lonlim(2) >  XMIN & lonlim(2) <  XMAX)   ... % max of region is on tile\n            )...\n            );\n        % do western side of the dateline second\n        lonlim(1) = -180; lonlim(2) = lmax;\n        doWEST = ...\n            find( ...\n            (...\n            (latlim(1) <= YMIN & latlim(2) >= YMAX) | ... % tile is completely within region\n            (latlim(1) >= YMIN & latlim(2) <= YMAX) | ... % region is completely within tile\n            (latlim(1) >  YMIN & latlim(1) <  YMAX) | ... % min of region is on tile\n            (latlim(2) >  YMIN & latlim(2) <  YMAX)   ... % max of region is on tile\n            ) ...\n            &...\n            (...\n            (lonlim(1) <= XMIN & lonlim(2) >= XMAX) | ... % tile is completely within region\n            (lonlim(1) >= XMIN & lonlim(2) <= XMAX) | ... % region is completely within tile\n            (lonlim(1) >  XMIN & lonlim(1) <  XMAX) | ... % min of region is on tile\n            (lonlim(2) >  XMIN & lonlim(2) <  XMAX)   ... % max of region is on tile\n            )...\n            );\n        % concatenate indices\n        do = [doEAST doWEST];\n    end\n\n    if ~isempty(do)\n        fname = fnames(do);\n    else\n        fname = [];\n    end\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/gtopo30s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21393010790330638}}
{"text": "% std_selsubject() - Helper function for std_erpplot(), std_specplot() \n%                    and std_erspplot() to select specific subject when\n%                    plotting channel data.\n% Usage:\n%  >> data = std_selsubject( data, subject, setinds, allsubjects);\n%\n% Inputs:\n%  data  -  [cell array] mean data for each subject group and/or data\n%           condition. For example, to compute mean ERPs statistics from a  \n%           STUDY for epochs of 800 frames in two conditions from three  \n%           groups of 12 subjects,\n%           >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n%                       [800x12] [800x12] [800x12] };  % 3 groups, cond 2\n% subject - [string] subject name\n% setinds - [cell array] set indices for each of the last dimension of the\n%           data cell array.\n%           >> setinds = { [12] [12] [12];... % 3 groups, cond 1\n%                          [12] [12] [12] };  % 3 groups, cond 2\n% allsubject - [cell array] all subjects (same order as in\n%              STUDY.datasetinfo)\n%\n% Output:\n%  data       - [cell array] data array with the subject or component selected\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n% \n% See also: std_erpplot(), std_specplot() and std_erspplot()\n\nfunction [data] = std_selsubject(data, subject, setinds, allsubjects, optndims);\n\nif nargin < 2\n    help std_selsubject;\n    return;\nend;\n\noptndims = max(optndims, ndims(data{1}));\nif isempty(strmatch(lower(subject), lower(allsubjects)))\n    error(sprintf('Cannot select subject %s in list %s', subject, vararg2str({ allsubjects })));\nend;\n\n% plot specific subject\n% ---------------------\nif size(setinds{1},1) > 1 && size(setinds{1},2) > 1 % single trials\n    % possible subject indices\n    selectInds = strmatch(lower(subject), lower(allsubjects));\n    for c = 1:size(data,1)\n        for g = 1:size(data,2)\n            selectCol = [];\n            for ind = 1:length(selectInds)\n                selectCol = [ selectCol find(setinds{c,g}  == selectInds') ];\n            end;\n            if optndims == 2\n                data{c,g} = data{c,g}(:,selectCol); %2-D\n            elseif optndims == 3\n                data{c,g} = data{c,g}(:,:,selectCol); %3-D\n            else\n                data{c,g} = data{c,g}(:,:,:,selectCol); %4-D\n            end;\n        end;\n    end;\nelse\n    for c = 1:size(data,1)\n        for g = 1:size(data,2)\n            subjectind = strmatch(lower(subject), lower(allsubjects));\n            l = zeros(size(setinds{c,g}));\n            for iSubj = 1:length(subjectind), l = l | setinds{c,g} == subjectind(iSubj); end;\n            if optndims == 2\n                data{c,g}(:,~l) = []; %2-D\n            elseif optndims == 3\n                data{c,g}(:,:,~l) = []; %3-D\n            else\n                data{c,g}(:,:,:,~l) = []; %4-D\n            end;\n        end;\n    end;\nend;", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/studyfunc/std_selsubject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.2138730614164036}}
{"text": "function [headmodel] = ft_datatype_headmodel(headmodel, varargin)\n\n% FT_DATATYPE_HEADMODEL describes the FieldTrip MATLAB structure for a volume\n% conduction model of the head that can be used for forward computations of\n% the EEG potentials or the MEG fields. The volume conduction model represents\n% the geometrical and the conductive properties of the head. These determine\n% how the secondary (or impressed) currents flow and how these contribute to\n% the model potential or field.\n%\n% A large number of forward solutions for the EEG and MEG are supported\n% in FieldTrip, each with its own specification of the MATLAB structure that\n% describes the volume conduction model of th ehead. It would be difficult to\n% list all the possibilities here. One common feature is that the volume\n% conduction model should specify its type, and that preferably it should\n% specify the geometrical units in which it is expressed (e.g. mm, cm or m).\n%\n% An example of an EEG volume conduction model with 4 concentric spheres is:\n%\n% headmodel =\n%        r: [86 88 94 100]\n%        c: [0.33 1.00 0.042 0.33]\n%        o: [0 0 0]\n%     type: 'concentricspheres'\n%     unit: 'mm'\n%\n% An example of an MEG volume conduction model with a single sphere fitted to\n% the scalp with its center 4 cm above the line connecting the ears is:\n%\n% headmodel =\n%        r: [12]\n%        o: [0 0 4]\n%     type: 'singlesphere'\n%     unit: 'cm'\n%\n% For each of the methods XXX for the volume conduction model, a corresponding\n% function FT_HEADMODEL_XXX exists that contains all specific details and\n% references to literature that describes the implementation.\n%\n% Required fields:\n%   - type\n%\n% Optional fields:\n%   - unit\n%\n% Deprecated fields:\n%   - inner_skull_surface, source_surface, skin_surface, source, skin\n%\n% Obsoleted fields:\n%   - <none specified>\n%\n% Revision history:\n%\n% (2015/latest) Use the field name \"pos\" instead of \"pnt\" for vertex positions.\n%\n% (2014) All numeric values are represented in double precision.\n%\n% (2013) Always use the field \"cond\" for conductivity.\n%\n% (2012) Use consistent names for the volume conductor type in the structure, the\n% documentation and for the actual implementation, e.g. bem_openmeeg -> openmeeg,\n% fem_simbio -> simbio, concentric -> concentricspheres. Deprecated the fields\n% that indicate the index of the innermost and outermost surfaces.\n%\n% See also FT_PREPARE_HEADMODEL, FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP,\n% FT_DATATYPE_FREQ, FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, \n% FT_DATATYPE_SPIKE, FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME\n\n% Copyright (C) 2011-2012, Cristiano Micheli, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% get the optional input arguments, which should be specified as key-value pairs\nversion = ft_getopt(varargin, 'version', 'latest');\n\nif strcmp(version, 'latest')\n  version = '2015';\nend\n\nif isempty(headmodel)\n  return;\nend\n\nif iscell(headmodel)\n  % this might represent combined EEG, ECoG and/or MEG\n  for i=1:numel(headmodel)\n    % call recursively\n    headmodel{i} = ft_datatype_headmodel(headmodel{i}, varargin{:});\n  end\n  return\nend\n\nswitch version\n\n  case '2015'\n    % first make it consistent with the 2014 version\n    headmodel = ft_datatype_headmodel(headmodel, 'version', '2013');\n\n    % rename pnt into pos\n    headmodel = fixpos(headmodel);\n\n  case '2014'\n    % first make it consistent with the 2013 version\n    headmodel = ft_datatype_headmodel(headmodel, 'version', '2013');\n\n    % ensure that all numbers are represented in double precision\n    headmodel = ft_struct2double(headmodel);\n\n  case '2013'\n    % first make it consistent with the 2012 version\n    headmodel = ft_datatype_headmodel(headmodel, 'version', '2012');\n\n    % then rename (if necessary the c into cond\n    if isfield(headmodel, 'c') && ~isfield(headmodel, 'cond')\n      headmodel.cond = headmodel.c;\n      headmodel = rmfield(headmodel, 'c');\n    elseif isfield(headmodel, 'cond') && isfield(headmodel, 'c') && isequal(headmodel.cond, headmodel.c)\n      headmodel = rmfield(headmodel, 'c');\n    elseif isfield(headmodel, 'cond') && isfield(headmodel, 'c') && ~isequal(headmodel.cond, headmodel.c)\n      ft_error('inconsistent specification of conductive properties for %s model', headmodel.type);\n    end\n\n  case '2012'\n    % the following will be determined on the fly in ft_prepare_vol_sens\n    if isfield(headmodel, 'skin_surface'),        headmodel = rmfield(headmodel, 'skin_surface');        end\n    if isfield(headmodel, 'source_surface'),      headmodel = rmfield(headmodel, 'source_surface');      end\n    if isfield(headmodel, 'inner_skull_surface'), headmodel = rmfield(headmodel, 'inner_skull_surface'); end\n    if isfield(headmodel, 'skin'),                headmodel = rmfield(headmodel, 'skin');                end\n    if isfield(headmodel, 'source'),              headmodel = rmfield(headmodel, 'source');              end\n\n    % ensure a consistent naming of the volume conduction model types\n    % these should match with the FT_HEADMODEL_XXX functions\n    if isfield(headmodel, 'type')\n      if strcmp(headmodel.type, 'concentric')\n        headmodel.type = 'concentricspheres';\n      elseif strcmp(headmodel.type, 'nolte')\n        headmodel.type = 'singleshell';\n      elseif strcmp(headmodel.type, 'multisphere')\n        headmodel.type = 'localspheres';\n      elseif strcmp(headmodel.type, 'bem_cp')\n        headmodel.type = 'bemcp';\n      elseif strcmp(headmodel.type, 'bem_dipoli')\n        headmodel.type = 'dipoli';\n      elseif strcmp(headmodel.type, 'bem_asa')\n        headmodel.type = 'asa';\n      elseif strcmp(headmodel.type, 'bem_openmeeg')\n        headmodel.type = 'openmeeg';\n      elseif strcmp(headmodel.type, 'fem_simbio')\n        headmodel.type = 'simbio';\n      elseif strcmp(headmodel.type, 'fdm_fns')\n        headmodel.type = 'fns';\n      elseif strcmp(headmodel.type, 'bem')\n        ft_error('not able to convert the original ''bem'' volume type, try using headmodel.type=''dipoli''');\n      elseif strcmp(headmodel.type, 'avo')\n        ft_error('this format is not supported anymore');\n      end\n    end\n\n    if isfield(headmodel, 'sens')\n      % this applies to type=interpolate, ensure that the sensor description is up to date\n      headmodel.sens = ft_datatype_sens(headmodel.sens);\n    end\n\n    if isfield(headmodel, 'type') && any(strcmp(headmodel.type, {'concentricspheres', 'singlesphere'}))\n      if isfield(headmodel, 'cond') && ~isfield(headmodel, 'c')\n        headmodel.c = headmodel.cond;\n        headmodel = rmfield(headmodel, 'cond');\n      elseif isfield(headmodel, 'cond') && isfield(headmodel, 'c') && isequal(headmodel.cond, headmodel.c)\n        headmodel = rmfield(headmodel, 'cond');\n      elseif isfield(headmodel, 'cond') && isfield(headmodel, 'c') && ~isequal(headmodel.cond, headmodel.c)\n        ft_error('inconsistent specification of conductive properties for %s model', headmodel.type);\n      end\n    end\n\n    % ensure that the geometrical units are specified\n    headmodel = ft_determine_units(headmodel);\n\n  otherwise\n    ft_error('converting to version \"%s\" is not supported', version);\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/utilities/ft_datatype_headmodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.21380345632369407}}
{"text": "\n% Author: Guosheng Lin (guosheng.lin@gmail.com)\n\n% this is a simpler demo file for testing on your own images.\n\nfunction demo_test_simple_voc()\n\nrng('shuffle');\naddpath('./my_utils');\ndir_matConvNet='../libs/matconvnet/matlab';\nrun(fullfile(dir_matConvNet, 'vl_setupnn.m'));\n\n\nrun_config=[];\n\nrun_config.use_gpu=true;\n% run_config.use_gpu=false;\nrun_config.gpu_idx=1;\n\n\n% result dir:\nresult_name=['runner_result_dir' datestr(now, 'YYYYmmDDHHMMSS')];\nresult_dir=fullfile('../cache_data', 'test_examples_voc', result_name);\nmkdir_notexist(result_dir);\n\n\n% the folder that contains testing images:\nimg_data_dir='../datasets/example_imgs_voc';\n\n\n% using a trained model which is trained on VOC 2012\nrun_config.trained_model_path='../model_trained/refinenet_res101_voc2012.mat';\nrun_config.class_info=gen_class_info_voc();\n\n\n% for trained model, control the size of input images\nrun_config.input_img_short_edge_min=450;\nrun_config.input_img_short_edge_max=600;\n\nrunner_info=prepare_runner_test_simple(run_config);\n\nimg_filenames=my_list_file(img_data_dir);\nimg_num=length(img_filenames);\nfor img_idx=1:img_num\n    task_info=[];\n    task_info.img_dir=img_data_dir;\n    task_info.img_filename=img_filenames{img_idx};\n    task_result=runner_info.run_task_fn(runner_info, task_info);\n    \n    [~, img_name]=fileparts(task_info.img_filename);\n    one_cache_file=fullfile(result_dir, [img_name '.png']);\n    fprintf('save predict mask:%s\\n', one_cache_file);\n    imwrite(task_result.mask_data, run_config.class_info.mask_cmap, one_cache_file);\nend\n\n\nend\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/demo_test_simple_voc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.21380344027240372}}
{"text": "function [iSourceRows, iRegionScouts, iVertices] = bst_convert_indices(iVertices, nComponents, GridAtlas, isSurfaceInd)\n% BST_CONVERT_INDICES: Convert scout indices (in GridLoc or Vertices matrix) to indices in ImageGridAmp/ImagingKernel\n%\n% USAGE:  [iSourceRows, iRegionScouts, iVertices] = bst_convert_indices(iVertices, nComponents, GridAtlas, isSurfaceInd)\n%\n% INPUT: \n%    - iVertices    : Array of vertex indices of the source space, to reference to rows in Results.GridLoc (volume) or Surface.Vertices (surface)\n%                     If empty, use all the vertices\n%    - nComponents  : Number of entries per vertex in SourceValues (1,2,3)\n%                     If 0, the number varies, the properties of each region are defined in input GridAtlas\n%    - GridAtlas    : Set of scouts that defines the properties of the source space regions, when nComponents=0\n%                     GridAtlas.Scouts(i).Region(2) is the source type (V=volume, S=surface, D=dba, X=exclude)\n%                     GridAtlas.Scouts(i).Region(3) is the orientation constrain (U=unconstrained, C=contrained, L=loose)\n%    - isSurfaceInd : If 1, the indices iVertices are referring to Surface.Vertices, and require a conversion in the case of mixed models\n%                     If 0, the indices iVertices are referring to Results.GridLoc\n%\n% OUTPUT: \n%    - iSourceRows   : Array of vertex indices of the source space, to reference to rows in Results.GridLoc (volume)\n%    - iRegionScouts : List of the scout indices in GridAtlas that are involved in the list of vertices iGridLoc\n%    - iVertices     : Modified list of vertices (when some are removed, compared with the initial iVertices)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2014\n\n% Check inputs\nif (nargin ~= 4) || isempty(iVertices) || isempty(nComponents) || ((nComponents == 0) && isempty(GridAtlas))\n\terror('Invalid call');\nend\niRegionScouts = [];\n\n% Make sure iVertices is a row vector\niVertices = iVertices(:)';\n% Get row numbers corresponding to the selected vertices\nswitch (nComponents)\n    case 0\n        % Convert indices from Surface.Vertices to Results.GridLoc\n        if isSurfaceInd\n            % Remove the vertices that are outside the list of vertices in Vert2Grid\n            iVertices(iVertices > size(GridAtlas.Vert2Grid,2)) = [];\n            % Surface.Vertices => Results.GridLoc\n            iVertices = find(any(GridAtlas.Vert2Grid(:,iVertices), 2))';\n        end\n        % Get indices in the ImageGridAmp/ImagingKernel matrix\n        iSourceRows = find(any(GridAtlas.Grid2Source(:,iVertices), 2))';\n        % Find over which regions this vertex selection spans\n        if (nargout >= 2)\n            iRegionScouts = find(~cellfun(@(c)isempty(intersect(c,iVertices)), {GridAtlas.Scouts.GridRows}));\n        end\n    case 1\n        iSourceRows = sort(iVertices);\n    case 2\n        iSourceRows = sort([2*iVertices-1, 2*iVertices]);\n    case 3\n        iSourceRows = sort([3*iVertices-2, 3*iVertices-1, 3*iVertices]);\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/inverse/bst_convert_indices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.21369502029428206}}
{"text": "function pascal_car_grammar(dotrainval, testyear)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% Set configuration override\nglobal VOC_CONFIG_OVERRIDE;\nif isempty(VOC_CONFIG_OVERRIDE)\n  VOC_CONFIG_OVERRIDE = @voc_config_car_grammar;\nend\n\ncls = 'car';\nconf = voc_config();\ncachedir = conf.paths.model_dir;\ntestset = conf.eval.test_set;\n\nif nargin < 1\n  dotrainval = false;\nend\n\nif nargin < 2\n  % which year to test on -- a string, e.g., '2007'.\n  testyear = conf.pascal.year;\nend\n\ntimestamp = datestr(datevec(now()), 'dd.mmm.yyyy:HH.MM.SS');\n\n% set the note to the training time if none is given\nif nargin < 3\n  note = timestamp;\nend\n\n% record a log of the training and test procedure\ndiary(conf.training.log([cls '-' timestamp]));\n\nth = tic;\nmodel = pascal_train_car_grammar(note);\ntoc(th);\n% Free feature vector cache memory\nfv_cache('free');\n\n% lower threshold to get high recall\nmodel.thresh = min(conf.eval.max_thresh, model.thresh);\nmodel.interval = conf.eval.interval;\n\nds = pascal_test(model, testset, testyear, testyear);\nap1 = pascal_eval(cls, ds, testset, testyear, testyear);\n%[ap1, ap2] = bboxpred_rescore(cls, testset, testyear);\n\nfprintf('AP = %.4f (without bounding box prediction)\\n', ap1)\n%fprintf('AP = %.4f (with bounding box prediction)\\n', ap2)\n\n% Clear the override\nclearvars -global VOC_CONFIG_OVERRIDE;\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/car_grammar/pascal_car_grammar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21358086225236989}}
{"text": "%\n% Work in progress.  Needs to be written to pay heed to sparsity.\n%\nfunction [x] = Back_Solve(A,b)\nx = A\\b;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21472-2d-fast-poisson-solver/Back_Solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.21354438925060118}}
{"text": "%  Copyright (c) 2014, Karen Simonyan\n%  All rights reserved.\n%  This code is made available under the terms of the BSD license (see COPYING file).\n\nfunction result = evaluate(config, scores, gt)\n\n    scores = reshape(scores, 1, []);\n\n    switch config     \n        case 'ap' \n            [res, extra] = evaluation.ap.eval(config, scores, gt);\n        case 'roc'   \n            [res, extra] = evaluation.roc.eval(config, scores, gt);\n        case 'accuracy'    \n            [res, extra] = evaluation.accuracy.eval(config, scores, gt); \n    end\n        \n        % measure name\n        result.meas_name = config;\n        \n        % measure value (a scalar)\n        result.measure = res;\n        \n        % extra data in a struct (e.g. optimal thresh), or empty\n        result.extra = extra;\n\nend\n", "meta": {"author": "AlfredXiangWu", "repo": "face_verification_experiment", "sha": "9e5031c9ee45dd2cd9a54c91c099abb34bfbdb56", "save_path": "github-repos/MATLAB/AlfredXiangWu-face_verification_experiment", "path": "github-repos/MATLAB/AlfredXiangWu-face_verification_experiment/face_verification_experiment-9e5031c9ee45dd2cd9a54c91c099abb34bfbdb56/code/+evaluation/evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21347409587024818}}
{"text": "function [ meta ] = read_ceos_img_meta( filename )\n%READ_CEOS_IMG_META Read CEOS SAR image file\n%\n% Written by: Wade Schwartzkopf, NGA/R\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n% Open file\nfid=fopen(filename,'r','b');\n\n% Read volume descriptor records\nmeta.rec_num=fread(fid,1,'uint32'); % Record sequence number\nmeta.rec_subtype1=fread(fid,1,'uint8'); % Record subtype code\nmeta.rec_type=fread(fid,1,'uint8'); % Record type\nmeta.rec_subtype2=fread(fid,1,'uint8'); % Record subtype code\nmeta.rec_subtype3=fread(fid,1,'uint8'); % Record subtype code\nmeta.rec_length=fread(fid,1,'uint32'); % Record length\nmeta.ascii_ebcdic=fread(fid,2,'uint8=>char').'; % Record length\nfseek(fid,2,'cof'); % Blanks\nmeta.doc_id=fread(fid,12,'uint8=>char').'; % Superstructure format control document ID\nmeta.doc_rev=fread(fid,2,'uint8=>char').'; % Superstructure format control document revision level\nmeta.rec_rev=fread(fid,2,'uint8=>char').'; % Superstructure record format revision level\nmeta.soft_rel_rev=fread(fid,12,'uint8=>char').'; % Software release and revision level\nmeta.file_num=fread(fid,4,'uint8=>char').'; % File number\nmeta.file_id=fread(fid,16,'uint8=>char').'; % File ID\nmeta.rec_seq_loc_type_flag=fread(fid,4,'uint8=>char').'; % Record sequency and location type flag\nmeta.seq_num_loc=fread(fid,8,'uint8=>char').'; % Sequence number of location\nmeta.fld_len_seq=fread(fid,4,'uint8=>char').'; % Field length of sequence number\nmeta.rec_code_loc_type_flag=fread(fid,4,'uint8=>char').'; % Records code and location type flag\nmeta.loc_rec_code=fread(fid,8,'uint8=>char').'; % Location of record code\nmeta.fld_len_code=fread(fid,4,'uint8=>char').'; % Field length of record code\nmeta.rec_len_loc_type_flag=fread(fid,4,'uint8=>char').'; % Record length and location type flag\nmeta.loc_rec_len=fread(fid,8,'uint8=>char').'; % Location of record length\nmeta.len_rec_len=fread(fid,4,'uint8=>char').'; % Location of record length\nfseek(fid,68,'cof'); % Blanks\nmeta.num_data_rec=str2double(fread(fid,6,'uint8=>char')); % Number of data set records\nmeta.data_len=str2double(fread(fid,6,'uint8=>char')); % Data set summary record length\nfseek(fid,24,'cof'); % Blanks\n% Sample group data\nmeta.sample_len=str2double(fread(fid,4,'uint8=>char')); % Bit length per sample\nmeta.num_samples=str2double(fread(fid,4,'uint8=>char')); % Number of samples per data group\nmeta.num_bytes=str2double(fread(fid,4,'uint8=>char')); % Number of bytes per data group\nmeta.just_order=fread(fid,4,'uint8=>char').'; % Justification and order of samples\n% SAR related data\nmeta.num_chan=str2double(fread(fid,4,'uint8=>char')); % Number of SAR channels\nmeta.num_lines=str2double(fread(fid,8,'uint8=>char')); % Number of lines per data set\nmeta.num_left=str2double(fread(fid,4,'uint8=>char')); % Number of left border pixels per line\nmeta.num_pixels=str2double(fread(fid,8,'uint8=>char')); % Number of data groups (or pixels) per line\nmeta.num_right=str2double(fread(fid,4,'uint8=>char')); % Number of right border pixels per line\nmeta.num_top=str2double(fread(fid,4,'uint8=>char')); % Number of top border lines\nmeta.num_bottom=str2double(fread(fid,4,'uint8=>char')); % Number of bottom border lines\nmeta.interleave=fread(fid,4,'uint8=>char').'; % Interleaving ID\n% Record data\nmeta.phys_rec_line=str2double(fread(fid,2,'uint8=>char')); % Number of physical records per line\nmeta.phys_rec_multi_chan=str2double(fread(fid,2,'uint8=>char')); % Number of physical records per multi-channel line\nmeta.prefix_bytes=str2double(fread(fid,4,'uint8=>char')); % Number of bytes of prefix per record\nmeta.sar_data_bytes=str2double(fread(fid,8,'uint8=>char')); % Number of bytes of SAR data per record\nmeta.suffix_bytes=str2double(fread(fid,4,'uint8=>char')); % Number of bytes of suffix data per record\nmeta.pre_suf_rpt_flg=fread(fid,4,'uint8=>char').'; % Prefix/suffix repeat flag\n% Prefix/suffix data locations\nmeta.loc_sar_data=fread(fid,8,'uint8=>char').'; % Sample data line number locator\nmeta.loc_sar_chan_num=fread(fid,8,'uint8=>char').'; % SAR channel number locator\nmeta.loc_time=fread(fid,8,'uint8=>char').'; % Time of SAR data line locator\nmeta.loc_leftfill=fread(fid,8,'uint8=>char').'; % Left-fill count locator\nmeta.loc_rightfill=fread(fid,8,'uint8=>char').'; % Right-fill count locator\nmeta.pad_pixels=fread(fid,4,'uint8=>char').'; % Pad pixels present indictor\nfseek(fid,28,'cof'); % Blanks\nmeta.loc_data_qual=fread(fid,8,'uint8=>char').'; % SAR data line quality code locator\nmeta.loc_cal_info=fread(fid,8,'uint8=>char').'; % Calibration information field locator\nmeta.loc_gain=fread(fid,8,'uint8=>char').'; % Gain values field locator\nmeta.loc_bias=fread(fid,8,'uint8=>char').'; % Bias values field lcoator\nmeta.sar_datatype=fread(fid,28,'uint8=>char').'; % SAR data format type indicator\nmeta.sar_datatype_code=fread(fid,4,'uint8=>char').'; % SAR data format type code\nmeta.num_leftfill=fread(fid,4,'uint8=>char').'; % Number of left fill bits within pixel\nmeta.num_rightfill=fread(fid,4,'uint8=>char').'; % Number of right fill bits within pixel\nmeta.max_data_range=fread(fid,8,'uint8=>char').'; % Maximum data range of pixel\nmeta.scansar_num_bursts=fread(fid,4,'uint8=>char').'; % ScanSAR, number of burst data in this file\nmeta.scansar_num_lines=fread(fid,4,'uint8=>char').'; % ScanSAR, number of lines per one burst\nmeta.scansar_num_overlap=fread(fid,4,'uint8=>char').'; % ScanSAR, number of overlap lines with adjacent bursts\nfseek(fid,260,'cof'); % Blanks\nsig_start = ftell(fid);\n\n% Pixel data\nswitch meta.file_id(8)\n    case 'B'\n        % Signal data records\n        % recs = 1:meta.num_data_rec;\n        % Only need the first (and maybe last) record, since these\n        % per-record fields are mostly all identical except for a few\n        % fields we don't need.\n        recs = [1, meta.num_data_rec];\n        for i = 1:numel(recs)\n            fseek(fid, sig_start + (meta.prefix_bytes + ...\n                (meta.num_pixels*meta.num_bytes)) * (recs(i)-1), 'bof');\n            meta.signal(i).rec_num=fread(fid,1,'uint32'); % Record sequence number\n            meta.signal(i).rec_subtype1=fread(fid,1,'uint8'); % Record subtype code\n            meta.signal(i).rec_type=fread(fid,1,'uint8'); % Record type\n            meta.signal(i).rec_subtype2=fread(fid,1,'uint8'); % Record subtype code\n            meta.signal(i).rec_subtype3=fread(fid,1,'uint8'); % Record subtype code\n            meta.signal(i).rec_length=fread(fid,1,'uint32'); % Record length\n            % Prefix data-general information\n            meta.signal(i).line_num=fread(fid,1,'uint32'); % SAR image data line number\n            meta.signal(i).sar_rec_ind=fread(fid,1,'uint32'); % SAR image data record index\n            meta.signal(i).left_fill=fread(fid,1,'uint32'); % Actual count of left-fill pixels\n            meta.signal(i).num_pixels=fread(fid,1,'uint32'); % Actual count of data pixels\n            meta.signal(i).right_fill=fread(fid,1,'uint32'); % Actual count of right-fill pixels\n            % Prefix data-sensor parameters\n            meta.signal(i).update_flg=fread(fid,1,'uint32'); % Sensor parameters update flag\n            meta.signal(i).year=fread(fid,1,'uint32'); % Sensor acquisition year\n            meta.signal(i).day=fread(fid,1,'uint32'); % Sensor acquisition day of year\n            meta.signal(i).msec=fread(fid,1,'uint32'); % Sensor acquisition milli-seconds of day\n            meta.signal(i).chan_id=fread(fid,1,'uint16'); % SAR channel ID\n            meta.signal(i).chan_code=fread(fid,1,'uint16'); % SAR channel code\n            meta.signal(i).tx_pol=fread(fid,1,'uint16'); % Transmitted polarization\n            meta.signal(i).rcv_pol=fread(fid,1,'uint16'); % Received polarization\n            meta.signal(i).prf=fread(fid,1,'uint32'); % PRF [mHz]\n            meta.signal(i).scan_id=fread(fid,1,'uint32'); % Scan ID\n            meta.signal(i).rng_comp_flg=fread(fid,1,'uint16'); % Onboard range compressed flag\n            meta.signal(i).chirp_type=fread(fid,1,'uint16'); % Chirp type designator\n            meta.signal(i).chirp_length=fread(fid,1,'uint32'); % Chirp length (pulse width) [nsec]\n            meta.signal(i).chirp_const=fread(fid,1,'int32'); % Chirp constant coefficient [Hz]\n            meta.signal(i).chirp_lin=fread(fid,1,'int32'); % Chirp linear coefficient [Hz/usec]\n            meta.signal(i).chirp_quad=fread(fid,1,'int32'); % Chirp quadratic coefficient [Hz/usec^2]\n            meta.signal(i).usec=fread(fid,1,'uint64'); % Sensor acquisition micro-second of day (rounded or floored)\n            meta.signal(i).gain=fread(fid,1,'uint32'); % Receiver gain [dB]\n            meta.signal(i).invalid_flg=fread(fid,1,'uint32'); % Invalid line flag\n            meta.signal(i).elec_ele=fread(fid,1,'int32'); % Electronic elevation angle at nadir of antenna [deg]\n            meta.signal(i).mech_ele=fread(fid,1,'int32'); % Mechanical elevation angle at nadir of antenna [deg]\n            meta.signal(i).elec_squint=fread(fid,1,'int32'); % Electronic antenna squint angle [deg]\n            meta.signal(i).mech_squint=fread(fid,1,'int32'); % Mechanical antenna squint angle [deg]\n            meta.signal(i).slant_rng=fread(fid,1,'uint32'); % Slant range to 1st data sample [m]\n            meta.signal(i).wind_pos=fread(fid,1,'uint32'); % Data record window position (SAMPLE DELAY [nsec])\n            fseek(fid,4,'cof'); % Blanks\n            % Prefix data-platform reference information\n            meta.signal(i).pos_update_flg=fread(fid,1,'uint32'); % Platform position parameters update flag\n            meta.signal(i).plat_lat=fread(fid,1,'int32'); % Platform latitude [1/1,000,000 deg]\n            meta.signal(i).plat_lon=fread(fid,1,'int32'); % Platform longitude [1/1,000,000 deg]\n            meta.signal(i).plat_alt=fread(fid,1,'int32'); % Platform altitude [m]\n            meta.signal(i).grnd_spd=fread(fid,1,'int32'); % Platform ground speed [cm/sec]\n            meta.signal(i).vel_x=fread(fid,1,'int32'); % Platform velocity X [cm/sec]\n            meta.signal(i).vel_y=fread(fid,1,'int32'); % Platform velocity Y [cm/sec]\n            meta.signal(i).vel_z=fread(fid,1,'int32'); % Platform velocity Z [cm/sec]\n            meta.signal(i).acc_x=fread(fid,1,'int32'); % Platform acceleration X [cm/sec^2]\n            meta.signal(i).acc_y=fread(fid,1,'int32'); % Platform acceleration X [cm/sec^2]\n            meta.signal(i).acc_z=fread(fid,1,'int32'); % Platform acceleration X [cm/sec^2]\n            meta.signal(i).track=fread(fid,1,'int32'); % Platform track angle [1/1,000,000 deg]\n            meta.signal(i).true_track=fread(fid,1,'int32'); % Platform rue track angle [1/1,000,000 deg]\n            meta.signal(i).pitch=fread(fid,1,'int32'); % Platform pitch angle [1/1,000,000 deg]\n            meta.signal(i).roll=fread(fid,1,'int32'); % Platform roll angle [1/1,000,000 deg]\n            meta.signal(i).yaw=fread(fid,1,'int32'); % Platform yaw angle [1/1,000,000 deg]\n            % Prefix data-sensor/facility specific auxiliary data\n            meta.signal(i).lat_first=fread(fid,1,'int32'); % Latitude of 1st pixel [1/1,000,000 deg]\n            meta.signal(i).lat_center=fread(fid,1,'int32'); % Latitude of center pixel [1/1,000,000 deg]\n            meta.signal(i).lat_last=fread(fid,1,'int32'); % Latitude of last pixel [1/1,000,000 deg]\n            meta.signal(i).lon_first=fread(fid,1,'int32'); % Longitude of 1st pixel [1/1,000,000 deg]\n            meta.signal(i).lon_center=fread(fid,1,'int32'); % Longitude of center pixel [1/1,000,000 deg]\n            meta.signal(i).lon_last=fread(fid,1,'int32'); % Longitude of last pixel [1/1,000,000 deg]\n            % ScanSAR burst data parameters\n            meta.signal(i).burst_num=fread(fid,1,'uint32'); % ScanSAR, burst number\n            meta.signal(i).line_num=fread(fid,1,'uint32'); % ScanSAR, line number in this burst\n            fseek(fid,60,'cof'); % Blanks\n            meta.signal(i).frame_num=fread(fid,1,'uint32'); % ALOS2 frame number\n            % fseek(fid,256,'cof'); % PALSAR auxiliary data\n            % fseek(fid,meta.num_pixels*meta.num_bytes,'cof'); % SAR data\n        end\n    case {'C','D'}\n        % Processed data records\n        disp('Processed data');\nend\n\n% Close file\nfclose(fid);\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/IO/complex/palsar2/read_ceos_img_meta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21347409587024818}}
{"text": "%Camera  Camera superclass\n%\n% An abstract superclass for Toolbox camera classes.\n%\n% Methods::\n%\n% plot           plot projection of world point to image plane\n% hold           control figure hold for image plane window\n% ishold         test figure hold for image plane\n% clf            clear image plane\n% figure         figure holding the image plane\n% mesh           draw shape represented as a mesh\n% point          draw homogeneous points on image plane\n% homline        draw homogeneous lines on image plane\n% lineseg        draw line segment defined by points\n% plot_camera    draw camera in world view\n%-\n% rpy            set camera attitude\n% move           clone Camera after motion\n% centre         get world coordinate of camera centre\n%-\n% delete         object destructor\n% char           convert camera parameters to string\n% display        display camera parameters\n%-\n% Properties (read/write)::\n% npix    image dimensions (2x1)\n% pp      principal point (2x1)\n% rho     pixel dimensions (2x1) in metres\n% T       camera pose as homogeneous transformation\n%\n% Properties (read only)::\n% nu    number of pixels in u-direction\n% nv    number of pixels in v-direction\n% u0    principal point u-coordinate\n% v0    principal point v-coordinate\n%\n% Notes::\n%  - Camera is a reference object.\n%  - Camera objects can be used in vectors and arrays\n%  - This is an abstract class and must be subclassed and a project()\n%    method defined.\n%  - The object can create a window to display the Camera image plane, this\n%    window is protected and can only be accessed by the plot methods of\n%    this object.\n%  - The project method is implemented by the concrete subclass.\n%\n% See also CentralCamera, SphericalCamera, FishEyeCamera, CatadiptricCamera.\n\n\n% Copyright (C) 1995-2009, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n%\n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.\n\n% TODO:\n%   make a parent imaging class and subclass perspective, fisheye, panocam\n%   test for points in front of camera and set to NaN if not\n%   test for points off the image plane and set to NaN if not\n%     make clipping/test flags\nclassdef Camera < handle\n    \n    properties\n        name    % camera name\n        type\n        rho     % pixel dimensions 1x2\n        pp      % principal point 1x2\n        npix    % number of pixel 1x2\n        T       % camera pose SE3 object\n        noise   % pixel noise 1x2\n        image\n    end\n    \n    properties (SetAccess = protected)\n        limits\n        perspective\n        h_imageplane     % handle for image plane\n        h_3dview % handle for camera 3D view\n        P           % world points (last plotted)\n        holdon\n        color\n    end\n    \n    properties (Dependent = true, SetAccess = protected)\n        u0\n        v0\n        nu\n        nv\n    end\n    \n    methods (Abstract)\n        p = project(c, P, varargin);\n    end\n    \n    methods\n        \n        function c = Camera(varargin)\n            %Camera.Camera Create camera object\n            %\n            % Constructor for abstact Camera class, used by all subclasses.\n            %\n            % C = Camera(OPTIONS) creates a default (abstract) camera with null parameters.\n            %\n            % Options::\n            % 'name',N          Name of camera\n            % 'image',IM        Load image IM to image plane\n            % 'resolution',N    Image plane resolution: NxN or N=[W H]\n            % 'sensor',S        Image sensor size in metres (2x1) [metres]\n            % 'centre',P        Principal point (2x1)\n            % 'pixel',S         Pixel size: SxS or S=[W H]\n            % 'noise',SIGMA     Standard deviation of additive Gaussian noise added to\n            %                   returned image projections\n            % 'pose',T          Pose of the camera as a homogeneous transformation\n            % 'color',C         Color of image plane background (default [1 1 0.8])\n            %\n            % Notes::\n            % - Normally the class plots points and lines into a set of axes that represent\n            %   the image plane.  The 'image' option paints the specified image onto the\n            %   image plane and allows points and lines to be overlaid.\n            %\n            % See also CentralCamera, FisheyeCamera, CatadioptricCamera, SphericalCamera.\n            \n            % default values\n            c.type = '**abstract**';\n            c.T = eye(4,4);\n            c.pp = [];\n            c.limits = [-1 1 -1 1];\n            c.perspective = false;\n            c.h_imageplane = [];\n            c.h_3dview = [];\n            c.holdon = false;\n            c.color = [1 1 0.8];\n            \n            if nargin == 1 && isa(varargin{1}, 'Camera')\n                return;\n            else\n                opt.name = 'noname';\n                opt.image = [];\n                opt.resolution = [];\n                opt.centre = [];\n                opt.sensor = [];\n                opt.pixel = [1 1];\n                opt.noise = [];\n                opt.pose = [];\n                opt.color = [];\n                c.pp = [0 0];\n                \n                \n                [opt,args] = tb_optparse(opt, varargin);\n                \n                c.name = opt.name;\n                if ~isempty(opt.image)\n                    c.image = opt.image;\n                    c.npix = [size(c.image,2) size(c.image,1)];\n                end\n                if ~isempty(opt.resolution)\n                    if length(opt.resolution) == 1\n                        c.npix = [opt.resolution opt.resolution];\n                    elseif length(opt.resolution) == 2\n                        c.npix = opt.resolution;\n                    else\n                        error('resolution must be a 1- or 2-vector');\n                    end\n                end\n                \n                c.pp = opt.centre;\n                c.rho = opt.pixel;\n                if ~isempty(opt.color)\n                    c.color = opt.color;\n                end\n                if ~isempty(opt.noise)\n                    if length(opt.noise) == 1\n                        c.noise = [opt.noise opt.noise];\n                    elseif length(opt.noise) == 2\n                        c.noise = opt.noise;\n                    else\n                        error('noise must be a 1- or 2-vector');\n                    end\n                end\n                if ~isempty(opt.pose)\n                    c.T = SE3(opt.pose);\n                end\n                if ~isempty(opt.sensor)\n                    c.rho = opt.sensor ./ c.npix;\n                end\n            end\n            \n            if length(c.rho) == 1\n                c.rho = ones(1,2) * c.rho;\n            end\n            if isempty(c.pp)\n                fprintf('principal point not specified, setting it to centre of image plane\\n');\n                c.pp = c.npix / 2;\n            end\n        end\n        \n        function delete(c)\n            %Camera.delete Camera object destructor\n            %\n            % C.delete() destroys all figures associated with the Camera object and\n            % removes the object.\n            %disp('delete camera object');\n            if ~isempty(c.h_imageplane) && isgraphics(c.h_imageplane)\n                delete(get(c.h_imageplane, 'Parent'));\n            end\n            if ~isempty(c.h_3dview) && isgraphics(c.h_3dview)\n                delete(get(c.h_3dview, 'Parent'));\n            end\n        end\n        \n        function display(c)\n            %Camera.display Display value\n            %\n            % C.display() displays a compact human-readable representation of the camera\n            % parameters.\n            %\n            % Notes::\n            % - This method is invoked implicitly at the command line when the result\n            %   of an expression is a Camera object and the command has no trailing\n            %   semicolon.\n            %\n            % See also Camera.char.\n            loose = strcmp( get(0, 'FormatSpacing'), 'loose');\n            if loose\n                disp(' ');\n            end\n            disp([inputname(1), ' = '])\n            if loose\n                disp(' ');\n            end\n            disp(char(c))\n            if loose\n                disp(' ');\n            end\n        end\n        \n        function s = char(c, s)\n            %Camera.char Convert to string\n            %\n            % S = C.char() is a compact string representation of the camera parameters.\n            \n            s = '';\n            if ~isempty(c.rho)\n                s = strvcat(s, sprintf('  pixel size:     (%.4g, %.4g)', c.rho(1), c.rho(2)));\n            end\n            if ~isempty(c.pp)\n                s = strvcat(s, sprintf('  principal pt:   (%.4g, %.4g)', c.u0, c.v0));\n            end\n            if ~isempty(c.npix)\n                s = strvcat(s, sprintf('  number pixels:  %d x %d', c.nu, c.nv));\n            end\n            if ~isempty(c.noise)\n                s = strvcat(s, sprintf('  noise:          %.4g,%.4g pix', c.noise));\n            end\n            s = strvcat(s,     sprintf('  pose:           %s', print(c.T, 'camera')));\n            % = strvcat(s, [repmat('      ', 4,1) num2str(c.T)]);\n        end\n        \n        function rpy(c, roll, pitch, yaw)\n            %Camera.rpy Set camera attitude\n            %\n            % C.rpy(R, P, Y) sets the camera attitude to the specified roll-pitch-yaw angles.\n            %\n            % C.rpy(RPY) as above but RPY=[R,P,Y].\n            if nargin == 2,\n                pitch = roll(2);\n                yaw = roll(3);\n                roll = roll(1);\n            end\n            c.T = SE3.Ry(yaw) * SE3.Rx(pitch) * SE3.Rz(roll);\n        end\n        \n        function c = centre(c)\n            %Camera.centre Get camera position\n            %\n            % P = C.centre() is the 3-dimensional position of the camera centre (3x1).\n            \n            c = c.T.t;\n        end\n        \n        function ishold = hold(c, flag)\n            %Camera.hold Control hold on image plane graphics\n            %\n            % C.hold() sets \"hold on\" for the camera's image plane.\n            %\n            % C.hold(H) hold mode is set on if H is true (or > 0), and off if\n            % H is false (or 0).\n            \n            % cam.ishold(); set hold\n            % cam.ishold(flag); set hold\n            if nargin < 2\n                flag = true;\n            end\n            c.holdon = flag;\n            if flag\n                set(c.h_imageplane, 'NextPlot', 'add');\n            else\n                set(c.h_imageplane, 'NextPlot', 'replacechildren');\n            end\n            if nargout > 0\n                % i = cam.ishold(); test hold condition\n                ishold = c.holdon;\n                \n            end\n        end\n        \n        function v = ishold(c)\n            %Camera.ishold Return image plane hold status\n            %\n            % H = C.ishold() returns true (1) if the camera's image plane is in hold mode,\n            % otherwise false (0).\n            v = c.holdon();\n        end\n        \n        function clf(c, flag)\n            %Camera.clf Clear the image plane\n            %\n            % C.clf() removes all graphics from the camera's image plane.\n            h = c.h_imageplane;\n            if ~isempty(h) && isgraphics(h)\n                % remove all children of the figure\n                children = get(h, 'Children');\n                for child=children\n                    delete(child)\n                end\n                \n                % if the camera is displaying an image\n                if ~isempty(c.image)\n                    c.figure\n                    idisp(c.image, 'nogui');\n                    hold on\n                end\n            end\n        end\n        \n        function h = figure(c)\n            %Camera.figure Return figure handle\n            %\n            % H = C.figure() is the handle of the figure that contains the camera's\n            % image plane graphics.\n            fig  = get(c.h_imageplane, 'Parent');\n            figure( fig );\n            if nargout > 0\n                h = fig;\n            end\n        end\n        \n        % Return the graphics handle for this camera's image plane\n        % and create the graphics if it doesnt exist\n        %\n        function h = plot_create(c, hin)\n            \n            if ~isempty(c.image)\n                % if this camera is created from an image, then display that image\n\n                if isempty(c.h_imageplane) || ~isgraphics(c.h_imageplane)\n                    idisp(c.image, 'nogui');\n                    set(gcf, 'name', sprintf('%s(%s) - image plane', class(c), c.name));\n                    set(gcf, 'MenuBar', 'none');\n                    hold on\n                    h = gca;\n                    %title(h, ['CentralCamera image plane:' c.name);\n                    c.h_imageplane = h;\n                    set(gcf, 'HandleVisibility', 'off');\n                    set(h, 'HandleVisibility', 'off');\n                else\n                    h = c.h_imageplane;\n                end\n                return;\n            end\n            \n            if isgraphics(c.h_imageplane)\n                % it already exists, just return the handle\n                h = c.h_imageplane;\n                return;\n            end\n            c.h_imageplane = [];  % handle is invalid\n            \n            if (nargin == 2) && isgraphics(hin)\n                % draw camera in an existing axes\n                disp('draw image plane in existing axes')\n                h = hin;\n                h.HandleVisibility = 'Off';\n            else\n                disp('creating new figure for camera')\n                \n                figure\n                h = axes\n                fig = get(h, 'Parent');\n                disp('make axes');\n                axis square\n                set(fig, 'MenuBar', 'none');\n                set(fig, 'Tag', 'camera');\n                set(h, 'Color', c.color);\n                set(fig, 'HandleVisibility', 'off');\n                set(fig, 'name', sprintf('%s(%s) - image plane', class(c), c.name));\n            end\n            % create an axis for camera view\n            set(h, 'XLim', c.limits(1:2), 'YLim', c.limits(3:4), ...\n                'DataAspectRatio', [1 1 1], ...\n                'Xgrid', 'on', 'Ygrid', 'on', ...\n                'Ydir' , 'reverse', ...\n                'NextPlot', 'add', ...\n                'Tag', c.name ...\n                );\n            c.h_imageplane = h;       % keep this around\n            c.labelaxes();\n            \n            title(h, c.name);\n            %figure( fig );   % raise the camera view\n            set(h, 'NextPlot', 'replacechildren');      \n        end\n           \n        function labelaxes(c)\n            h = c.h_imageplane;\n            \n            if ~isempty(c.npix)\n                xlabel(h, 'u (pixels)');\n                ylabel(h, 'v (pixels)');\n            else\n                xlabel(h, 'x (m)');\n                ylabel(h, 'y (m)');\n            end\n        end\n        \n        function v =  plot(c, points, varargin)\n            %Camera.plot Plot points on image plane\n            %\n            % C.plot(P, OPTIONS) projects world points P (3xN) to the image plane and plots them.  If P is 2xN\n            % the points are assumed to be image plane coordinates and are plotted directly.\n            %\n            % UV = C.plot(P) as above but returns the image plane coordinates UV (2xN).\n            %\n            % - If P has 3 dimensions (3xNxS) then it is considered a sequence of point sets and is\n            %   displayed as an animation.\n            %\n            % C.plot(L, OPTIONS) projects the world lines represented by the\n            % array of Plucker objects (1xN) to the image plane and plots them.\n            %\n            % LI = C.plot(L, OPTIONS) as above but returns an array (3xN) of\n            % image plane lines in homogeneous form.\n            %\n            % Options::\n            % 'objpose',T     Transform all points by the homogeneous transformation T before\n            %                  projecting them to the camera image plane.\n            % 'pose',T         Set the camera pose to the homogeneous transformation T before\n            %                  projecting points to the camera image plane.  Overrides the current\n            %                  camera pose C.T.\n            % 'fps',N          Number of frames per second for point sequence display\n            % 'sequence'       Annotate the points with their index\n            % 'textcolor',C    Text color for annotation (default black)\n            % 'textsize',S     Text size for annotation (default 12)\n            % 'drawnow'        Execute MATLAB drawnow function\n            %\n            % Additional options are considered MATLAB line or marker style parameters and are passed\n            % directly to plot.\n            %\n            % See also Camera.mesh, Camera.hold, Camera.clf, Plucker.\n            \n            opt.fps = 5;\n            opt.sequence = false;\n            opt.textcolor = 'k';\n            opt.textsize = 12;\n            opt.drawnow = false;\n            \n            [opt,arglist,ls] = tb_optparse(opt, varargin);\n            \n            % get handle for this camera image plane\n            h = c.plot_create();\n            \n            if isa(points, 'Plucker')\n                % plot lines\n                \n                % project 3D world lines using the class project() method\n                uv = c.project(points, arglist{:});\n                c.hold(true);\n                for line=uv\n                    c.homline(line);\n                end\n                c.hold(false)\n            else\n                % plot points\n                nr = numrows(points);\n                \n                if nr == 3\n                    % project 3D world points using the class project() method\n                    uv = c.project(points, arglist{:});\n                else\n                    uv = points;\n                end\n                \n                if isempty(ls) || ~any(cellfun(@(x) ischar(x)&&contains(x, 'Marker'), arglist))\n                    % set default style if none given\n                    ls = {'Marker', 'o', 'MarkerFaceColor', 'k', 'MarkerEdgeColor', 'k', 'LineStyle', 'none'};\n                else\n                    ls = {ls};\n                end\n                \n                for i=1:size(uv,3)\n                    % for every frame in the animation sequence\n                    plot(uv(1,:,i), uv(2,:,i), ls{:}, 'Parent', h);\n                    if opt.sequence\n                        for j=1:size(uv,2)\n                            text(uv(1,j,i), uv(2,j,i), sprintf('  %d', j), ...\n                                'HorizontalAlignment', 'left', ...\n                                'VerticalAlignment', 'middle', ...\n                                'FontUnits', 'pixels', ...\n                                'FontSize', opt.textsize, ...\n                                'Color', opt.textcolor, ...\n                                'Parent', h);\n                        end\n                    end\n                    \n                    if size(uv,3) > 1\n                        pause(1/opt.fps);\n                    end\n                end\n            end\n            \n            if opt.drawnow\n                drawnow\n            end\n            \n            if nargout > 0,\n                v = uv;\n            end\n        end % plot\n        \n        function mesh(c, X, Y, Z, varargin)\n            %Camera.mesh Plot mesh object on image plane\n            %\n            % C.mesh(X, Y, Z, OPTIONS) projects a 3D shape defined by the matrices X, Y, Z\n            % to the image plane and plots them.  The matrices X, Y, Z are of the same size\n            % and the corresponding elements of the matrices define 3D points.\n            %\n            % Options::\n            % 'objpose',T   Transform all points by the homogeneous transformation T before\n            %               projecting them to the camera image plane.\n            % 'pose',T      Set the camera pose to the homogeneous transformation T before\n            %               projecting points to the camera image plane.  Temporarily overrides\n            %               the current camera pose C.T.\n            %\n            % Additional arguments are passed to plot as line style parameters.\n            %\n            % See also MESH, CYLINDER, SPHERE, MKCUBE, Camera.plot, Camera.hold, Camera.clf.\n            \n            % check that mesh matrices conform\n            assert( all(size(X) == size(Y)) && all(size(X) == size(Z)), 'matrices must be the same size');\n            \n            opt.objpose = [];\n            opt.pose = [];\n            \n            [opt,arglist,ls] = tb_optparse(opt, varargin);\n            if isempty(opt.pose)\n                opt.pose = c.T;\n            end\n            \n            if isempty(ls)\n                ls = {'k'};\n            end\n            \n            % get handle for this camera image plane\n            h = c.plot_create();\n            \n            % draw 3D line segments\n            nsteps = 21;\n            \n            c.clf\n            holdon = c.hold(1);\n            s = linspace(0, 1, nsteps);\n            \n            for i=1:numrows(X)-1\n                for j=1:numcols(X)-1\n                    P0 = [X(i,j), Y(i,j), Z(i,j)]';\n                    P1 = [X(i+1,j), Y(i+1,j), Z(i+1,j)]';\n                    P2 = [X(i,j+1), Y(i,j+1), Z(i,j+1)]';\n                    \n                    if c.perspective\n                        % straight world lines are straight on the image plane\n                        uv = c.project([P0 P1], 'setopt', opt);\n                    else\n                        % straight world lines are not straight, plot them piecewise\n                        P = bsxfun(@times, (1-s), P0) + bsxfun(@times, s, P1);\n                        uv = c.project(P, 'setopt', opt);\n                    end\n                    plot(uv(1,:)', uv(2,:)', ls{:}, arglist{:}, 'Parent', c.h_imageplane);\n                    \n                    if c.perspective\n                        % straight world lines are straight on the image plane\n                        uv = c.project([P0 P2], 'setopt', opt);\n                    else\n                        % straight world lines are not straight, plot them piecewise\n                        P = bsxfun(@times, (1-s), P0) + bsxfun(@times, s, P2);\n                        uv = c.project(P, 'setopt', opt);\n                    end\n                    plot(uv(1,:)', uv(2,:)', ls{:}, arglist{:}, 'Parent', c.h_imageplane);\n                end\n            end\n            \n            for j=1:numcols(X)-1\n                P0 = [X(end,j), Y(end,j), Z(end,j)]';\n                P1 = [X(end,j+1), Y(end,j+1), Z(end,j+1)]';\n                \n                if c.perspective\n                    % straight world lines are straight on the image plane\n                    uv = c.project([P0 P1], 'setopt', opt);\n                else\n                    % straight world lines are not straight, plot them piecewise\n                    P = bsxfun(@times, (1-s), P0) + bsxfun(@times, s, P1);\n                    uv = c.project(P, 'setopt', opt);\n                end\n                plot(uv(1,:)', uv(2,:)', ls{:}, arglist{:}, 'Parent', c.h_imageplane);\n            end\n            c.hold(holdon); % turn hold off if it was initially off\n            \n        end % mesh\n        \n        function h =  point(c, p, varargin)\n            %Camera.point Plot homogeneous points on image plane\n            %\n            % C.point(P) plots points on the camera image plane which are defined by columns\n            % of P (3xN) considered as points in homogeneous form.\n            \n            % get handle for this camera image plane\n            h = c.create\n            \n            uv = e2h(p);\n            h = plot(uv(1,:), uv(2,:), varargin{:});\n        end % point\n        \n        function h =  homline(c, lines, varargin)\n            %Camera.homline Plot homogeneous lines on image plane\n            %\n            % C.homline(L) plots lines on the camera image plane which are defined by columns\n            % of L (3xN) considered as lines in homogeneous form: a.u + b.v + c = 0.\n            \n            % get handle for this camera image plane\n            h = c.plot_create;\n            xlim = get(h, 'XLim');\n            ylim = get(h, 'YLim');\n            \n            if numel(lines) == 3\n                lines = lines(:);\n            end\n            \n            for l=lines\n                if abs(l(1)/l(2)) > 1\n                    % steeper than 45deg\n                    x = (-l(3) - l(2)*ylim) / l(1);\n                    h = plot(x, ylim, varargin{:}, 'Parent', c.h_imageplane);\n                else\n                    % less than 45deg\n                    y = (-l(3) - l(1)*xlim) / l(2);\n                    \n                    h = plot(xlim, y, varargin{:}, 'Parent', c.h_imageplane);\n                end\n            end\n        end % line\n        \n        function h = lineseg(c, p0, p1, varargin)\n            % get handle for this camera image plane\n            h = c.plot_create\n            c.hold(1)\n            for i=1:numcols(p0)\n                plot([p0(1,i) p1(1,i)], [p0(2,i) p1(2,i)], varargin{:}, 'Parent', c.h_imageplane);\n            end\n        end\n        \n        function newcam = move(cam, T)\n            %Camera.move Instantiate displaced camera\n            %\n            % C2 = C.move(T) is a new camera object that is a clone of C but its pose\n            % is displaced by the homogeneous transformation T with respect to the\n            % current pose of C.\n            newcam = CentralCamera(cam);\n            newcam.T = newcam.T * SE3.convert(T);\n        end\n        \n        function movedby(c, robot)\n            robot.addlistener('Moved', @(src,data)cameramove_callback(src,data,c));\n            \n            function cameramove_callback(robot, event, camera)\n                camera.T = robot.fkine(robot.q);\n            end\n        end\n        \n        % return components of principal point and image size\n        function v = get.u0(c)\n            v = c.pp(1);\n        end\n        \n        function v = get.v0(c)\n            v = c.pp(2);\n        end\n        \n        function v = get.rho(c)\n            v = c.rho;\n        end\n        \n        function v = get.nu(c)\n            v = c.npix(1);\n        end\n        \n        function v = get.nv(c)\n            v = c.npix(2);\n        end\n        \n        function c = set.T(c, Tc)\n            c.T = SE3(Tc);\n            \n            \n            if ~isempty(c.h_3dview) && isgraphics(c.h_3dview)\n                set(c.h_3dview, 'Matrix', c.T.T);\n            end\n        end\n        \n        \n        function c = set.rho(c, sxy)\n            if isempty(sxy)\n                c.rho = sxy;\n            elseif length(sxy) == 1\n                c.rho = [sxy sxy];\n            elseif length(sxy) == 2\n                c.rho = sxy(:)';\n            else\n                error('need 1 or 2 scale elements');\n            end\n        end\n        \n        function c = set.pp(c, pp)\n            if isempty(pp)\n                c.pp = [];\n            elseif length(pp) == 1\n                c.pp = [pp pp];\n            elseif length(pp) == 2\n                c.pp = pp(:)';\n            else\n                error('need 1 or 2 pp elements');\n            end\n        end\n        \n        function c = set.npix(c, npix)\n            if ~isempty(npix)\n                if length(npix) == 1,\n                    c.npix = [npix npix];\n                elseif length(npix) == 2,\n                    c.npix = npix(:)';\n                else\n                    error('need 1 or 2 npix elements');\n                end\n                c.limits = [0 c.npix(1) 0 c.npix(2)];\n            end\n        end\n        \n        function help(c)\n            disp(' C.plot(P)     return image coordinates for world points  P');\n            disp(' C.point(P)     return image coordinates for world points  P');\n            disp(' C.line(P)     return image coordinates for world points  P');\n            disp(' C.clf     return image coordinates for world points  P');\n            disp(' C.hold     return image coordinates for world points  P');\n            disp(' C.project(P)     return image coordinates for world points  P');\n            disp(' C.project(P, Tobj)  return image coordinates for world points P ');\n            disp(' C.project(P, To, Tcm)  return image coordinates for world points P ');\n            disp(' transformed by T prior to projection');\n        end\n    end % methods\n    \nend % class\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/@Camera/Camera.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21342241572092177}}
{"text": "function dummyObject = fixDummyObjectSize(dummyObject,originalObject);\n\nframeUpdateInterval = dummyObject.frameUpdateInterval;\nendMargin = size(originalObject.spectrogram,2)*frameUpdateInterval-max(originalObject.anchorTimeLocation);\nif size(dummyObject.spectrogram,2)*frameUpdateInterval < max(dummyObject.anchorTimeLocation)+endMargin\n    dummyFrameSize = max(dummyObject.anchorTimeLocation)+endMargin;\n    dimmyFrequencySize = size(originalObject.spectrogram,1);\n    dummyObject.spectrogram = ones(dimmyFrequencySize,dummyFrameSize);\n    dummyObject.aperiodicityIndex = ones(dimmyFrequencySize,dummyFrameSize);\n    dummyObject.F0 = ones(1,dummyFrameSize);\n    dummyObject.vuv = ones(1,dummyFrameSize);\nend;\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/morphing_src/fixDummyObjectSize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21342241572092174}}
{"text": "% test find root node\nclear;clc;close all;\npath(path,'toolbox') ;\nt3 = 6; % for small cycles;\n% sk_filename='../result/cylinder1_contract_t(2)_nn(14)_WL(10.633697)_WH(1.000000)_sl(3.000000)_skeleton.mat';\n% sk_filename='../result/simplejoint_v4770_contract_t(3)_nn(30)_WL(15.378798)_WH(1.000000)_sl(3.000000)_skeleton.mat';\nsk_filename='../result/horse_v1987_contract_t(3)_nn(24)_WL(7.786614)_WH(1.000000)_sl(3.000000)_skeleton.mat';\n\nload(sk_filename,'M');\n\n%%\n[joints, segments] = find_joints(M,false);\n[joints, segments] = remove_small_cycles(M, joints, segments,t3, true);", "meta": {"author": "taiya", "repo": "cloudcontr", "sha": "9c27e747136c5286c9a6e9f9c6b278f63cd5312f", "save_path": "github-repos/MATLAB/taiya-cloudcontr", "path": "github-repos/MATLAB/taiya-cloudcontr/cloudcontr-9c27e747136c5286c9a6e9f9c6b278f63cd5312f/matlab/test_remove_small_cycles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21342241572092174}}
{"text": "function kern = gaussianwhiteKernExpandParam(kern, params)\n\n% GAUSSIANWHITEKERNEXPANDPARAM Create kernel structure from gaussian white \n%                              kernel's parameters.\n% FORMAT\n% DESC returns a gaussian white kernel structure filled with the parameters in the given\n%\tvector. This is used as a helper function to enable parameters to be\n%\toptimised in, for example, the NETLAB optimisation functions.\n% RETURN kern : kernel structure with the given parameters in the relevant\n%\t   locations.\n% ARG kern : the kernel structure in which the parameters are to be\n% ARG param : vector of parameters which are to be placed in the kernel\n%\t   structure.\n%\t\n% SEEALSO : gaussianwhiteKernParamInit, gaussianwhiteKernExtractParam, kernExpandParam\n%\n% COPYRIGHT : Mauricio Alvarez and Neil D. Lawrence, 2008\n%\n% MODIFICATIONS : Mauricio A. Alvarez, 2009\n\n% KERN\n\nif kern.isArd\n    if kern.nIndFunct == 1,\n        kern.precisionT =  params(1:end-1)';\n    else\n        kern.precisionT = reshape(params(1:end-1), size(kern.precisionT));\n    end\nelse\n    kern.precisionT =  params(1:end-1);\nend\nkern.sigma2Noise = params(end);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/gaussianwhiteKernExpandParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2132065903854601}}
{"text": "function [cl,cu] = matRad_getConstraintBounds(optiProb,cst)\n% matRad IPOPT get constraint bounds function for direct aperture optimization\n% \n% call\n%   [cl,cu] = matRad_daoGetConstBounds(optiProb,cst)\n%\n% input\n%   optiProb:   option struct defining the type of optimization\n%   cst:        matRad cst struct\n%\n% output\n%   cl:         lower bounds on constraints\n%   cu:         lower bounds on constraints\n%\n% References\n%\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\napertureInfo = optiProb.apertureInfo;\n\n% Initialize bounds\ncl_dao = zeros(apertureInfo.totalNumOfLeafPairs,1);\ncu_dao = inf*ones(apertureInfo.totalNumOfLeafPairs,1);\n\n% get dosimetric bounds from cst (just like for conv opt) by call to\n% superclass method\n[cl_dos,cu_dos] = matRad_getConstraintBounds@matRad_OptimizationProblem(optiProb,cst);\n\n% concatenate\ncl = [cl_dao; cl_dos];\ncu = [cu_dao; cu_dos];\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/@matRad_OptimizationProblemDAO/matRad_getConstraintBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21320659038546003}}
{"text": "function diri = sb_find_elec(vol,sens)\n\n% SB_FIND_ELEC\n%\n% $Id$\n\ndiri = zeros(size(sens.elecpos,1),1);\ndist = zeros(size(sens.elecpos,1),1);\nfor i=1:size(sens.elecpos,1)\n    [dist(i), diri(i)] = min(sum(bsxfun(@minus,vol.pos,sens.elecpos(i,:)).^2,2));\nend\nif ~all(dist < 1e-8)\n    error('Electrode positions are not located on mesh nodes! This should not happen, please contact support.');\nend\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/simbio/sb_find_elec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.21314377297497336}}
{"text": "function obj = runICPTransformFinal(obj, p, g)\n\nmsg('S', {g.proc{:} 'TRANSFORMATION'}, 'LogLevel', 'basic');\n\nfor i = 1:g.nPC\n    \n    % Find new path\n    [~, file] = fileparts(obj.PC{i});\n    p2mat = fullfile(obj.OutputFolder, [file '_POSTICP.mat']);\n    \n    if ~ismember(i, p.IdxFixedPointClouds) % trafo only if point cloud is not fixed, i.e. loose\n\n        % Load point cloud\n        PC = obj.loadPC(i);\n\n        % Trafo\n        PC.transform(1, obj.D.H{1,i}(1:3,1:3), obj.D.H{1,i}(1:3,4));\n\n        % Update mat file\n        PC.save(p2mat);\n        \n    else\n        \n        % Copy original mat file\n        copyfile(obj.PC{i}, p2mat);\n        \n    end\n\n    % Set new path\n    obj.PC{i} = p2mat;\n    \nend\n\nmsg('E', {g.proc{:} 'TRANSFORMATION'}, 'LogLevel', 'basic');\n    \nend", "meta": {"author": "pglira", "repo": "Point_cloud_tools_for_Matlab", "sha": "4768f45e7d3527c52e911eb0450c31ca19b58f72", "save_path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab", "path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab/Point_cloud_tools_for_Matlab-4768f45e7d3527c52e911eb0450c31ca19b58f72/classes/@globalICP/private/runICPTransformFinal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21305412890610081}}
{"text": "% -*- INTERNAL UNDOCUMENTED FUNCTION -*-\nfunction [geometry, msh, spv, vel, gnum, spp, press, gnump] = ...\n              mp_solve_stokes_3d (problem_data, method_data)\n\nwarning ('geopdes:obsolete','Function MP_SOLVE_STOKES_3D is obsolete. Using MP_SOLVE_STOKES instead')\n\nfunction [geometry, msh, spv, vel, gnum, spp, press, gnump] = ...\n              mp_solve_stokes (problem_data, method_data)\n\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/obsolete/mp_solve_stokes_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.21305412741923316}}
{"text": "% -*- INTERNAL UNDOCUMENTED FUNCTION -*-\nfunction [geometry, msh, space, eigv, eigf, gnum, dofs_ornt] = ...\n              mp_solve_maxwell_eig_2d (problem_data, method_data)\n\nwarning ('geopdes:obsolete','Function MP_SOLVE_MAXWELL_EIG_2D is obsolete. Using SOLVE_MAXWELL_EIG instead')\n\n[geometry, msh, space, eigv, eigf, gnum, dofs_ornt] = mp_solve_maxwell_eig (problem_data, method_data);\n\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/obsolete/mp_solve_maxwell_eig_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21298525973401006}}
{"text": "% ------------------------------------------------------------------------\n%      Analyze non-linear ROIs that were clicked as 'object points'\n% ------------------------------------------------------------------------\n\n\n%% ENTER PARAMETERS AND FILE LOCATION\n\n% file location of object points\nsave_folder = 'C:\\Drive\\Histology\\brainX\\processed';\n\n% directory of reference atlas files\nannotation_volume_location = 'C:\\Drive\\Histology\\for tutorial\\annotation_volume_10um_by_index.npy';\nstructure_tree_location = 'C:\\Drive\\Histology\\for tutorial\\structure_tree_safe_2017.csv';\n\n% name of the saved object points\nobject_save_name_suffix = '';\n\n% either set to 'all' or a list of indices from the clicked objects in this file, e.g. [2,3]\nobjects_to_analyze = 'all';\n\n% plane used to view when points were clicked ('coronal' -- most common, 'sagittal', 'transverse')\nplane = 'coronal';\n\n% brain figure black or white\nblack_brain = true;\n\n\n%% LOAD THE REFERENCE ANNOTATIONS AND PROBE POINTS\n\n% load the reference brain annotations\nif ~exist('av','var') || ~exist('st','var')\n    disp('loading reference atlas...')\n    av = readNPY(annotation_volume_location);\n    st = loadStructureTree(structure_tree_location);\nend\n\n\n% load object points\nobjectPoints = load(fullfile(save_folder, ['probe_points' object_save_name_suffix]));\n\n% determine which objects to analyze\nif strcmp(objects_to_analyze,'all')\n    objects = 1:size(objectPoints.pointList.pointList,1);\nelse\n    objects = objects_to_analyze;\nend \n\n\n%% BRING UP THE RELEVANT DATA FOR EACH PROBE POINTS, FOR FURTHER ANALYSIS\n\n% initialize cell array containing info on each clicked point\nif length(objects) > 1\n    roi_annotation = cell(length(objects),1);\n    roi_location = cell(length(objects),1);\nend\n\n% generate needed values\nbregma = allenCCFbregma(); % bregma position in reference data space\natlas_resolution = 0.010; % mm\n\n% plot brain grid\nProbeColors = [1 1 1; 1 .75 0;  .3 1 1; .4 .6 .2; 1 .35 .65; .7 .7 1; .65 .4 .25; .7 .95 .3; .7 0 0; .6 0 .7; 1 .6 0]; \n% order of colors: {'white','gold','turquoise','fern','bubble gum','overcast sky','rawhide', 'green apple','purple','orange','red'};\nfwireframe = plotBrainGrid([], [], [], black_brain); hold on; \nfwireframe.InvertHardcopy = 'off';\n\n\n\nfor object_num = objects\n    \n    selected_object = objects(object_num);\n        \n    % get the object points for the currently analyzed object    \n    if strcmp(plane,'coronal')\n        curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [3 2 1]);\n    elseif strcmp(plane,'sagittal')\n        curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [1 2 3]);\n    elseif strcmp(plane,'transverse')\n        curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [1 3 2]);\n    end\n\n    % plot points on the wire frame brain\n    figure(fwireframe); hold on\n    hp = plot3(curr_objectPoints(:,1), curr_objectPoints(:,3), curr_objectPoints(:,2), '.','linewidth',2, 'color',[ProbeColors(object_num,:) .2],'markers',10);   \n\n    % use the point's position in the atlas to get the AP, DV, and ML coordinates\n    ap = -(curr_objectPoints(:,1)-bregma(1))*atlas_resolution;\n    dv = (curr_objectPoints(:,2)-bregma(2))*atlas_resolution;\n    ml = (curr_objectPoints(:,3)-bregma(3))*atlas_resolution;\n\n    roi_location_curr = [ap dv ml];\n    \n    % initialize array of region annotations\n    roi_annotation_curr = cell(size(curr_objectPoints,1),3);    \n    \n    % loop through every point to get ROI locations and region annotations\n    for point = 1:size(curr_objectPoints,1)\n\n        % find the annotation, name, and acronym of the current ROI pixel\n        ann = av(curr_objectPoints(point,1),curr_objectPoints(point,2),curr_objectPoints(point,3));\n        name = st.safe_name{ann};\n        acr = st.acronym{ann};\n\n        roi_annotation_curr{point,1} = ann;\n        roi_annotation_curr{point,2} = name;\n        roi_annotation_curr{point,3} = acr;\n\n    end\n    \n    % save results in cell array\n    if length(objects) > 1\n        roi_annotation{object_num} = roi_annotation_curr;\n        roi_location{object_num} = roi_location_curr;\n    else\n        roi_annotation = roi_annotation_curr;\n        roi_location = roi_location_curr;\n    end\n \n    % display results in a table\n    disp(['Clicked points for object ' num2str(selected_object)])\n    roi_table = table(roi_annotation_curr(:,2),roi_annotation_curr(:,3), ...\n                        roi_location_curr(:,1),roi_location_curr(:,2),roi_location_curr(:,3), roi_annotation_curr(:,1), ...\n         'VariableNames', {'name', 'acronym', 'AP_location', 'DV_location', 'ML_location', 'avIndex'});\n     disp(roi_table)\n    \nend\n\n\n% now, use roi_location and roi_annotation for your further analyses\n\n\n", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/SHARP-Track/Analyze_Clicked_Points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.21298313012380518}}
{"text": "function varargout = processingLLCs(process, varargin)\n% This function contains two different processes for manipulating the\n% localized loop constraints (LLCs) to formulate a model-specific and\n% objective-function-specific MILP for finding loopless flux distributions\n% with a minimal number of binary variables\n%\n% USAGE:\n%    1. Preprocess loop information after calling `addLoopLawConstraints`:\n%       [solveLP, MILPproblem, loopInfo] = processingLLCs('preprocess', loopInfo, LPproblem, model, nRxns, osenseStr, MILPproblem)\n%\n%    2. Update the loop constraints for a specific objective vector\n%       [solveLP, MILPproblem] = processingLLCs('update', loopInfo, osenseStr, MILPproblem, objVector)\n%\n% INPUTS:\n%    loopInfo:      structure containing info about the loops, initially outputed\n%                   from `addLoopLawConstraints` and updated by the current function\n%    LPproblem:     original COBRA LP problem structure \n%    model:         the COBRA model from which LPproblem is constructed\n%    nRxns:         number of reactions in the model (default size(model.S, 2))\n%    osenseStr:     optimization sense of the current problem (e.g., FBA max v_biomass, or FVA min v_PYK)\n%                   'max' (defaulted) or 'min'\n%    MILPproblem:   COBRA MILP problem generated from LPproblem using `addLoopLawConstraints`\n%                   (default generated from LPproblem if not given in the preprocessing call)\n%    objVector:     nRxns-by-1 objective vector for the current optimization problem \n%                   for updating LLCs (e.g., FVA min v_PYK given fixed v_biomass)\n%\n% OUTPUTS:\n%    solveLP:       true if solving LP is sufficient to gaurantee the objective function value \n%                   is the same as solving MILP with loop constraints\n%    MILPproblem:   updated MILP problem with LLCs\n%    loopInfo:      updated loopInfo with info about the loops (outputed only for the preprocess call)\n\nsolveLP = true;\nswitch process\n    case 'preprocess'\n        loopInfo = preprocessLLCs(varargin{1:5});\n        MILPproblem = varargin{6};\n        % initial update for MILP. No specific objective reactions\n        if loopInfo.alwaysLLC\n            % need to solve MILP if the problem constraints or original objective function necessitate the need\n            solveLP = false;\n            % update bounds and rhs\n            MILPproblem = updateLLCs(MILPproblem, loopInfo, []);\n        end\n        varargout = {solveLP, MILPproblem, loopInfo};\n    case 'update'\n        loopInfo = varargin{1};\n        osenseStr = varargin{2};\n        if isempty(osenseStr)\n            osenseStr = 'max';\n        end\n        MILPproblem = varargin{3};\n        if numel(varargin) < 4\n            objVector = [];\n        else\n            objVector = varargin{4};\n        end\n        \n        if isempty(objVector)\n            % if updating but no object vector is given, just restore the original bounds\n            MILPproblem = restoreOriginalBounds(MILPproblem, loopInfo.rhs0, loopInfo.var, loopInfo.BDg);\n        else\n            % update with a specific objective function\n            [rxnID, ~, cCoeff] = find(objVector(:));\n            osense = strcmp(osenseStr, 'min') - strcmp(osenseStr, 'max');\n            % need to solve MILP if the problem constraints or original objective function necessitate the need or \n            % the reactions being minimized has their reverse direction in loops or \n            % the reactions being maximized has their forward direction in loops\n            if loopInfo.alwaysLLC || any(loopInfo.rxnInLoops(rxnID(cCoeff * osense > 0), 1)) || any(loopInfo.rxnInLoops(rxnID(cCoeff * osense < 0), 2))\n                solveLP = false;\n                % restore the original bounds\n                MILPproblem = restoreOriginalBounds(MILPproblem, loopInfo.rhs0, loopInfo.var, loopInfo.BDg);\n                % find the reactions in the objective function which are being minimized and has their reverse \n                % direction in loops or the reactions being maximized has their forward direction in loops\n                rxnIdLLC = false(numel(rxnID));\n                for j = 1:numel(rxnID)\n                    if (loopInfo.rxnInLoops(rxnID(j), 1) && cCoeff(j) * osense > 0) ...\n                            || (loopInfo.rxnInLoops(rxnID(j), 2) && cCoeff(j) * osense < 0)\n                        rxnIdLLC(j) = true;\n                    end\n                end\n                rxnIdLLC = rxnID(rxnIdLLC);\n                % update bounds and rhs\n                MILPproblem = updateLLCs(MILPproblem, loopInfo, rxnIdLLC);\n            end\n            \n        end\n        varargout = {solveLP, MILPproblem};\nend\n\nend\n\nfunction loopInfo = preprocessLLCs(loopInfo, LPproblem, model, nRxns, osenseStr)\nif nargin < 4 || isempty(nRxns)\n    nRxns = size(model.S, 2);\nend\nif nargin < 5 || isempty(osenseStr)\n    osenseStr = 'max';\nend\nif strcmp(osenseStr, 'min')\n    model.c = -model.c;\nend\nrxnInLoops = loopInfo.rxnInLoops;\nconComp  = loopInfo.conComp;\n\n% determine the set of reactions for which LLCs are always required\n% condition I in Prop. 2 in Chan et al., 2017\ncond1 = rxnInLoops(:, 2) & model.c > 0;\n% condition II in the paper in Prop. 2 in Chan et al., 2017 \ncond2 = rxnInLoops(:, 1) & model.c < 0;\n% condition III in the paper in Prop. 2 in Chan et al., 2017\n[cond3A1, cond3A2, cond3B] = deal(false(nRxns, 1));\nfor i = (size(model.S, 1) + 1):size(LPproblem.A, 1)\n    % for constraint p with sum(a_pj * v_j) <= b_p\n    if ~strcmp(LPproblem.csense(i), 'G')  % '<=' or '=' constraint\n        % if reaction j has its forward direction in cycles and a_pj < 0\n        cond3A1 = cond3A1 | (rxnInLoops(:, 2) & LPproblem.A(i, 1:nRxns)' < 0);\n        % if reaction j has its reverse direction in cycles and a_pj > 0\n        cond3A2 = cond3A2 | (rxnInLoops(:, 1) & LPproblem.A(i, 1:nRxns)' > 0);\n        % if the constraint involves 2 or more reactinos or RHS < 0\n        cond3B = cond3B | (nnz(LPproblem.A(i, 1:nRxns)) > 1 | LPproblem.b(i) < 0);\n    end\n    if ~strcmp(LPproblem.csense(i), 'L')  % '>=' or '=' constraint\n        cond3A1 = cond3A1 | (rxnInLoops(:, 2) & LPproblem.A(i, 1:nRxns)' > 0);\n        cond3A2 = con3A2 | (rxnInLoops(:, 1) & LPproblem.A(i, 1:nRxns)' < 0);\n        cond3B = cond3B | (nnz(LPproblem.A(i, 1:nRxns)) > 1 | LPproblem.b(i) > 0);\n    end\nend\n% reactions satisfying (3A1 or 3A2) and 3B\ncond3 = (cond3A1 | cond3A2) & cond3B;\n% condition III for bound constraints can be simplified as follows:\ncond3 = cond3 | (model.lb > 0 & rxnInLoops(:, 2)) | (model.ub < 0 & rxnInLoops(:, 1));\n% reactions that are required to be constrained by loopless constraints all the time\nrxnInLoopsAlwaysOn = cond1 | cond2 | cond3;\n% LLCs are always required if the set is non-empty\nalwaysLLC = any(rxnInLoopsAlwaysOn);\n% the corresponding set of reactions in the same connected components as\n% the always-on reactions\nconCompAlwaysOn = false(max(conComp), 1);\nconCompAlwaysOn(conComp(rxnInLoopsAlwaysOn)) = true;\nif loopInfo.printLevel \n    fprintf('Reactions in internal nullspace can be divided into %d connected components.\\n', max(conComp))\nend\n\n% get an initial feasible and loopless solution in case MipStart is needed\nmodel2 = model;\nmodel2.lb = model2.lb(1:size(model2.S, 2));\nmodel2.ub = model2.ub(1:size(model2.S, 2));\nmodel2.c = zeros(size(model2.S, 2), 1);\nmodel2.b = zeros(size(model2.S, 1), 1);\nsFeas = optimizeCbModel(model2, 'max', 'one');\nx0 = sFeas.x;\n[loopInfo.alwaysLLC, loopInfo.rxnInLoopsAlwaysOn, loopInfo.conCompAlwaysOn, loopInfo.x0] ...\n    = deal(alwaysLLC, rxnInLoopsAlwaysOn, conCompAlwaysOn, x0);\nend\n\nfunction MILPproblemLLC = updateLLCs(MILPproblemLLC, loopInfo, rxnID)\n% apply LLCs by relaxing constraints and pre-assign values to variables\nif nargin < 3\n    rxnID = [];\nend\nconCompOn = loopInfo.conCompAlwaysOn;\nconCompOn(loopInfo.conComp(rxnID)) = true;\n\nbigM = inf;\nif ~loopInfo.useRxnLink\n    % use connections from nullspace\n    for jCon = 1:numel(loopInfo.conCompAlwaysOn)\n        if ~conCompOn(jCon)\n            % relax constraints not affecting optimality and feasibility\n            MILPproblemLLC.b(loopInfo.con.vU(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = bigM;\n            MILPproblemLLC.b(loopInfo.con.gU(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = bigM;\n            MILPproblemLLC.b(loopInfo.con.vL(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = -bigM;\n            MILPproblemLLC.b(loopInfo.con.gL(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = -bigM;\n            % fix variables not affecting optimality and feasibility\n            MILPproblemLLC.lb(loopInfo.var.g(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = 0;\n            MILPproblemLLC.ub(loopInfo.var.g(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = 0;\n            MILPproblemLLC.ub(loopInfo.var.z(loopInfo.rxnInLoopIds(loopInfo.conComp == jCon))) = 0;\n        end\n    end\nelse\n    % use connections from EFMs\n    rxnOn = loopInfo.rxnInLoopsAlwaysOn;\n    rxnOn(rxnID) = true;\n    \n    % reactions in cycles not sharing EFMs with the current rxns and\n    % not being one of the reactions required to have no flux through cycles\n    id = ~any(loopInfo.rxnLink(rxnOn, :), 1)' & any(loopInfo.rxnInLoops, 2);\n    % the loop constraints on them are relaxed\n    MILPproblemLLC.b(loopInfo.con.vU(loopInfo.rxnInLoopIds(id))) = bigM;\n    MILPproblemLLC.b(loopInfo.con.gU(loopInfo.rxnInLoopIds(id))) = bigM;\n    MILPproblemLLC.b(loopInfo.con.vL(loopInfo.rxnInLoopIds(id))) = -bigM;\n    MILPproblemLLC.b(loopInfo.con.gL(loopInfo.rxnInLoopIds(id))) = -bigM;\n\n    % pre-determine variables not connected to the reaction for FVA\n    % except reactions required to be always constrained\n    rxnKeep = loopInfo.conComp == 0;\n    for jCon = 1:numel(conCompOn)\n        if conCompOn(jCon)\n            rxnKeep(loopInfo.conComp == jCon) = true;\n        end\n    end\n    MILPproblemLLC.lb(loopInfo.var.g(loopInfo.rxnInLoopIds(~rxnKeep))) = 0;\n    MILPproblemLLC.ub(loopInfo.var.g(loopInfo.rxnInLoopIds(~rxnKeep))) = 0;\n    MILPproblemLLC.ub(loopInfo.var.z(loopInfo.rxnInLoopIds(~rxnKeep))) = 0;\nend\nend\n\nfunction MILPproblemLLC = restoreOriginalBounds(MILPproblemLLC, rhs0, varInd, BDg)\n    MILPproblemLLC.b = rhs0;\n    MILPproblemLLC.ub(varInd.z) = 1;\n    MILPproblemLLC.ub(varInd.g) = BDg;\n    MILPproblemLLC.lb(varInd.g) = -BDg;\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/thermoFBA/processingLLCs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.21298313012380513}}
{"text": "classdef LvdDataPoint < AbstractGeometricPoint\n    %LvdDataPoint Summary of this class goes here\n    %   Detailed explanation goes here\n\n    properties\n        allTimes cell = {};\n        allRVVect cell = {};\n        allFrames(1,:) AbstractReferenceFrame\n        allGIs cell = {};\n\n        name(1,:) char = 'New Point';\n\n        inputLvdData LvdData\n        lvdData LvdData\n\n        %marker\n        markerColor(1,1) ColorSpecEnum = ColorSpecEnum.Red;\n        markerShape(1,1) MarkerStyleEnum = MarkerStyleEnum.RightTriangle;\n        \n        %track line\n        plotTrkLine(1,1) logical = true;\n        trkLineColor(1,1) ColorSpecEnum = ColorSpecEnum.Black;\n        trkLineSpec(1,1) LineSpecEnum = LineSpecEnum.DottedLine;\n    end\n\n    methods\n        function obj = LvdDataPoint(inputLvdData, lvdData, name)\n            arguments\n                inputLvdData(1,1) LvdData %the lvd data that contains the trajectory to be loaded\n                lvdData(1,1) LvdData %the lvd data for the current case/scenario/mission\n                name(1,:) char %the name of the point\n            end\n\n            obj.name = name;\n            obj.lvdData = lvdData;\n\n            obj.loadLvdData(inputLvdData, lvdData);\n        end\n\n        function tf = hasValidLvdData(obj)\n            tf = true;\n\n            if(isempty(obj.inputLvdData) || ...\n               obj.inputLvdData == obj.lvdData)\n                tf = false;\n\n                return;\n            end\n        end\n\n        function cartElems = getPositionAtTime(obj, inputTimes, ~, inFrame)\n            cartElems = obj.getCartElemForTime(inputTimes, inFrame);\n        end\n\n        function loadLvdData(obj, inputLvdData, lvdData)\n            obj.inputLvdData = inputLvdData;\n\n            stateLog = inputLvdData.script.executeScript(false, inputLvdData.script.getEventForInd(1), true, false, false, false);\n            \n            obj.allTimes = {};\n            obj.allRVVect = {};\n            obj.allFrames = AbstractReferenceFrame.empty(1,0);\n            obj.allGIs = {};\n\n            for(i=1:inputLvdData.script.getTotalNumOfEvents()) %#ok<*NO4LP> \n                evt = inputLvdData.script.getEventForInd(i);\n                entries = stateLog.getAllStateLogEntriesForEvent(evt);\n\n                [~,ia,~] = unique([entries.time], 'sorted');\n                entries = entries(ia);\n\n                if(numel(entries) > 2)\n                    useFrame = entries(1).centralBody.getBodyCenteredInertialFrame();\n\n                    times = [];\n                    rvVects = [];\n                    for(j=1:length(entries))\n                        entry = entries(j);\n                        maEntry = entry.getMAFormattedStateLogMatrix(true);\n    \n                        time = maEntry(1);\n                        rVect = maEntry(2:4)';\n                        vVect = maEntry(5:7)';   \n                        \n                        bodyInfo = lvdData.celBodyData.getBodyInfoById(maEntry(8));\n                        frame = bodyInfo.getBodyCenteredInertialFrame();\n    \n                        ce = CartesianElementSet(time, rVect(:), vVect(:), frame);\n                        ce = ce.convertToFrame(useFrame, true);\n    \n                        rvVect = [ce.rVect; ce.vVect];\n\n                        times(j) = time; %#ok<AGROW> \n                        rvVects(:,j) = rvVect; %#ok<AGROW> \n                    end\n\n                    obj.allTimes{end+1} = times;\n                    obj.allRVVect{end+1} = rvVects;\n                    obj.allFrames(end+1) = useFrame;\n                    obj.allGIs{end+1} = griddedInterpolant(times,[rvVects;times]', \"makima\", \"nearest\");\n                end\n            end\n        end\n        \n        function name = getName(obj)\n            name = obj.name;\n        end\n        \n        function setName(obj, name)\n            obj.name = name;\n        end\n        \n        function listboxStr = getListboxStr(obj)\n            listboxStr = sprintf('%s (LVD Trajectory)', obj.getName());\n        end\n        \n        function useTf = openEditDialog(obj, ~)            \n            output = AppDesignerGUIOutput({false});\n            lvd_EditLvdTrajectoryPointGUI_App(obj, output, obj.lvdData);\n            useTf = output.output{1};\n        end\n        \n        function tf = isVehDependent(obj) %#ok<MANU> \n            tf = false;\n        end\n        \n        function tf = canBePlotted(obj) %#ok<MANU> \n            tf = true;\n        end\n        \n        function bodyInfo = getOriginBody(obj)\n            bodyInfo = obj.bodyInfo;\n        end\n        \n        function tf = usesGroundObj(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricPoint(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricVector(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricCoordSys(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricRefFrame(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricAngle(~, ~)\n            tf = false;\n        end\n        \n        function tf = usesGeometricPlane(~, ~)\n            tf = false;\n        end \n        \n        function tf = isInUse(obj, lvdData)\n            tf = lvdData.usesGeometricPoint(obj);\n        end\n    end\n\n    methods(Access=private)\n        function cartElem = getCartElemForTime(obj, qTimes, inFrame)\n            fillerCe = CartesianElementSet(0, [0;0;0], [0;0;0], inFrame);\n            cartElem = repmat(fillerCe, [1, numel(qTimes)]);\n\n            for(i=1:length(obj.allTimes))\n                times = obj.allTimes{i};\n                minTime = min(times);\n                maxTime = max(times);\n\n                bool = qTimes >= minTime & qTimes <= maxTime;\n                if(any(bool))\n                    subQTimes = qTimes(bool);\n                    gi = obj.allGIs{i};\n                    frame = obj.allFrames(i);\n\n                    rvVects = gi(subQTimes)';\n                    subCe = CartesianElementSet(subQTimes, rvVects(1:3,:), rvVects(4:6,:), frame);\n                    subCe = convertToFrame(subCe, inFrame, true);\n                    cartElem(bool) = subCe;\n                end\n            end\n\n            bool = cartElem == fillerCe;\n            if(any(bool))\n                outQTimes = qTimes(bool);\n\n                for(i=1:length(obj.allTimes))\n                    times = obj.allTimes{i};\n                    minTime = min(times);\n                    maxTime = max(times);\n\n                    distToLb = abs(outQTimes - minTime);\n                    distToUb = abs(outQTimes - maxTime);\n                    distToBnd(:,i) = min([distToLb(:), distToUb(:)], [], 2); %#ok<AGROW> \n                end\n\n                boolInds = find(bool);\n\n                [~,I] = min(distToBnd, [], 2);\n                for(i=1:length(I))\n                    qTime = outQTimes(i);\n                    Ii = I(i);\n                    \n                    gi = obj.allGIs{Ii};\n                    frame = obj.allFrames(Ii);\n\n                    rvVects = gi(qTime)';\n                    rVects = rvVects(1:3,:);\n                    vVects = rvVects(4:6,:);\n                    nearestTimes = rvVects(7,:);\n                    subCe = CartesianElementSet(nearestTimes, rVects, vVects, frame);\n                    subCe = convertToFrame(subCe, inFrame, true);\n                    cartElem(boolInds(i)) = subCe;\n                end\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Geometry/Points/@LvdDataPoint/LvdDataPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21290269256000524}}
{"text": "function e2s2_loadAndEvaluate(varargin)\n% e2s2_loadAndEvaluate(varargin)\n%\n% Evaluate a network snapshot on a given dataset.\n%\n% Copyright by Holger Caesar, 2016\n\n% Initial settings\np = inputParser;\naddParameter(p, 'dataset', SiftFlowDatasetMC());\naddParameter(p, 'weaklySupervised', false);\naddParameter(p, 'run', 28);\naddParameter(p, 'exp', 25);\naddParameter(p, 'epochs', [1, 5:5:30]);\naddParameter(p, 'gpus', 1);\naddParameter(p, 'subset', 'test');\naddParameter(p, 'plotStats', true);\naddParameter(p, 'minSize', []); % typically 100\naddParameter(p, 'maxSizeRel', []);\naddParameter(p, 'doCache', true);\naddParameter(p, 'storeOutputMaps', false);\naddParameter(p, 'limitImageCount', Inf);\naddParameter(p, 'subsamplePosRange', []);\naddParameter(p, 'testColorSpace', []);\nparse(p, varargin{:});\n\ndataset = p.Results.dataset;\nweaklySupervised = p.Results.weaklySupervised;\nrun = p.Results.run;\nexp = p.Results.exp;\nepochs = p.Results.epochs;\ngpus = p.Results.gpus;\nsubset = p.Results.subset;\nplotStats = p.Results.plotStats;\nminSize = p.Results.minSize;\nmaxSizeRel = p.Results.maxSizeRel;\ndoCache = p.Results.doCache;\nstoreOutputMaps = p.Results.storeOutputMaps;\nlimitImageCount = p.Results.limitImageCount;\nsubsamplePosRange = p.Results.subsamplePosRange;\ntestColorSpace = p.Results.testColorSpace;\n\n% Settings\nplotStats = plotStats && strcmp(subset, 'test') && numel(epochs) > 1;\nstats = cell(numel(epochs), 1);\nif ~isempty(minSize) || ~isempty(maxSizeRel) || ~isinf(limitImageCount),\n    fprintf('Warning: Cannot cache results due to custom (blob size or limitImageCount) settings!\\n');\n    doCache = false;\nend\n\n% Create paths\nglobal glFeaturesFolder;\nif weaklySupervised,\n    wsStr = 'ws';\nelse\n    wsStr = '';\nend\noutputName = sprintf('%s_e2s2%s_run%d_exp%d', dataset.name, wsStr, run, exp);\nnetFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'E2S2', dataset.name, sprintf('Run%d', run), outputName);\n\n%%% Load and set netOpts\nnetOptsPath = fullfile(netFolder, 'net-opts.mat');\nnetOptsStruct = load(netOptsPath, 'imdb', 'nnOpts');\nnetOptsStruct.nnOpts.gpus = gpus;\nnetOptsStruct.nnOpts.expDir = netFolder;\n\n% Disable conversion from test to train\nnetOptsStruct.nnOpts.convertToTrain = false;\n\n% Update the dataset in the imdb to avoid a nasty bug due to changed dataset classes\nnetOptsStruct.imdb.dataset = dataset;\n\n% Set testing options to restrict regions by size\nif ~isempty(maxSizeRel),\n    netOptsStruct.nnOpts.misc.testOpts.maxSizeRel = maxSizeRel;\nend\nif ~isempty(minSize),\n    netOptsStruct.nnOpts.misc.testOpts.minSize = minSize;\nend\nif ~isempty(subsamplePosRange),\n    netOptsStruct.nnOpts.misc.testOpts.subsamplePosRange = subsamplePosRange;\nend\nif ~isempty(testColorSpace)\n    netOptsStruct.nnOpts.misc.testOpts.testColorSpace = testColorSpace;\nend\n\nfor epochIdx = 1 : numel(epochs),\n    epoch = epochs(epochIdx);\n    netPath = fullfile(netFolder, sprintf('net-epoch-%d.mat', epoch));\n    \n    % Load net\n    netIn = load(netPath, 'net', 'stats');\n    \n    % Create network\n    nnClass = E2S2NN(netIn, netOptsStruct.imdb, netOptsStruct.nnOpts);\n    \n    % Test network\n    stats{epochIdx} = nnClass.testOnSet('subset', subset, 'doCache', doCache, 'limitImageCount', limitImageCount, 'storeOutputMaps', storeOutputMaps);\n    fprintf('Displaying stats for epoch %d of exp %s...\\n', epoch, outputName);\n    disp(stats{epochIdx});\nend\n\n% Create a plot of the above stats\nif plotStats,\n    trainLoss = cell2mat({nnClass.stats.train.objective});\n    valLoss   = cell2mat({nnClass.stats.val.objective});\n    paccs = cellfun(@(s) s.pacc, stats);\n    maccs = cellfun(@(s) s.macc, stats);\n    mius  = cellfun(@(s) s.miu, stats);\n    \n    figure(1); clf;\n    \n    subplot(2, 1, 1);\n    hold on;\n    plot(1:numel(trainLoss), trainLoss);\n    plot(1:numel(valLoss),     valLoss);\n    legend({'train', 'val'});\n    xlabel('epoch');\n    ylabel('loss');\n    ax = gca;\n    axis([0, numel(trainLoss), ax.YLim]);\n    grid on;\n    \n    subplot(2, 1, 2);\n    hold on;\n    plot(epochs, paccs);\n    plot(epochs, maccs);\n    plot(epochs, mius);\n    legend({'Pix. Acc. test', 'Class Acc. test', 'Mean IU test'}, 'Location', 'SouthEast');\n    xlabel('epoch');\n    ylabel('accuracy');\n    ax = gca;\n    axis([0, numel(trainLoss), ax.YLim]);\n    grid on;\n    \n    plotPath = fullfile(netFolder, 'net-test.pdf');\n    if exist(plotPath, 'file'),\n        error('Error: plotPath already exists: %s', plotPath);\n    end\n    print(1, plotPath, '-dpdf'); %#ok<MCPRT>\nend\n", "meta": {"author": "nightrome", "repo": "matconvnet-calvin", "sha": "42d7e80bac56741d39404b6646a0866c10aad021", "save_path": "github-repos/MATLAB/nightrome-matconvnet-calvin", "path": "github-repos/MATLAB/nightrome-matconvnet-calvin/matconvnet-calvin-42d7e80bac56741d39404b6646a0866c10aad021/matconvnet-calvin/examples/e2s2/e2s2_loadAndEvaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21290269256000524}}
{"text": "% ----------------------------------------------------------------------------\n% function hfssCreateRelativeCS(fid, Name, Origin, Units)\n% \n% Description :\n% -------------\n% Create a relative Coordinate System at \"origin\" point relative to the\n% Global Coordinate System.\n%\n% Parameters :\n% ------------\n% fid     - file identifier of the HFSS script file.\n% Name    -\n% Origin  - point relative to the Global Coordinate System where the\n%           Relative Coordinate System will be created.\n% Units   - units of the points (specify using either 'in', 'mm', 'meter'\n%           or anything else defined in HFSS).\n% \n% Note :\n% ------\n% Use this function to facilitate drawing stuff. To return to use\n% another CS (i.e. the Global CS), you can use the function hfssSetWCS\n%\n% Example :\n% ---------\n% fid = fopen('myantenna.vbs', 'wt');\n% ...\n% hfssInsertDesign(fid, 'Dipole_SingleElement');\n% ----------------------------------------------------------------------------\n\n% ----------------------------------------------------------------------------\n% Written by Daniel R. Prado\n% danysan@gmail.com / drprado@tsc.uniovi.es\n% 20 September 2012\n% ----------------------------------------------------------------------------\n\nfunction hfssCreateRelativeCS(fid, Name, Origin, Units)\n\n% arguments processor.\nif (nargin < 4)\n\terror('Insufficient number of arguments !');\nend\n\n% Preamble.\nfprintf(fid, '\\n');\nfprintf(fid, 'oEditor.CreateRelativeCS _\\n');\n\n% CS Parameters\nfprintf(fid, 'Array(\"NAME:RelativeCSParameters\", _\\n');\nfprintf(fid, '\"OriginX:=\", \"%.4f%s\", _\\n', Origin(1), Units);\nfprintf(fid, '\"OriginY:=\", \"%.4f%s\", _\\n', Origin(2), Units);\nfprintf(fid, '\"OriginZ:=\", \"%.4f%s\", _\\n', Origin(3), Units);\nfprintf(fid, '\"XAxisXvec:=\", \"1%s\", _\\n', Units);\nfprintf(fid, '\"XAxisYvec:=\", \"0%s\", _\\n', Units);\nfprintf(fid, '\"XAxisZvec:=\", \"0%s\", _\\n', Units);\nfprintf(fid, '\"YAxisXvec:=\", \"0%s\", _\\n', Units);\nfprintf(fid, '\"YAxisYvec:=\", \"1%s\", _\\n', Units);\nfprintf(fid, '\"YAxisZvec:=\", \"0%s\"), _\\n', Units);\n\n% CS Attributes\nfprintf(fid, 'Array(\"NAME:Attributes\", _\\n');\nfprintf(fid, '\"Name:=\", \"%s\")\\n', Name);", "meta": {"author": "yuip", "repo": "hfss-api", "sha": "93ac0700830f473f1438f335a7fa964383b07abb", "save_path": "github-repos/MATLAB/yuip-hfss-api", "path": "github-repos/MATLAB/yuip-hfss-api/hfss-api-93ac0700830f473f1438f335a7fa964383b07abb/3dmodeler/hfssCreateRelativeCS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21290269256000519}}
{"text": "hydro = struct();\n\nhydro = readNEMOH(hydro,'../Coer_Comp/');\n% hydro = readWAMIT(hydro,'../../WAMIT/Coer_Comp/coer_comp.out',[]);\n% hydro = combineBEM(hydro); % Compare to WAMIT\nhydro = radiationIRF(hydro,10,[],[],[],[]);\nhydro = radiationIRFSS(hydro,[],[]);\nhydro = excitationIRF(hydro,10,[],[],[],[]);\nwriteBEMIOH5(hydro)\nplotBEMIO(hydro)", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/examples/BEMIO/NEMOH/Coer_Comp/bemio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.212807470262968}}
{"text": "function [region_obj, results_table, varargout] = table(w, varargin)\n% Print a table of all regions in a thresholded image. Return a Matlab table object\n% and labeled region object. Used with fmri_data, statistic_image, and\n% image_vector objects.\n%\n% This function has two \"modes\":\n% - Without an optional atlas object input, it uses region.table to generate a table based\n% on contiguous clusters (separated by those with positive and negative peak values) \n%\n% - With an optional atlas object input, it uses image_vector.subdivide_by_atlas to \n% generate a table based on atlas regions covered by the input image. The table has\n% one row per atlas region. The region object is also divided by the atlas,\n% so one large contiguous blob in the image may cover multiple rows with\n% different labeled regions.\n%\n% :Usage:\n% ::\n%\n%    [poscl, negcl] = table(cl, [optional inputs])\n%\n% - By default, region.table() separates clusters into subregions with positive\n%   and negative values. Thus, the number of rows may not match the original number of regions. \n%   To turn this feature off, use 'nosep'.\n% - By default, region.table() re-sorts the regions to group the table rows by macro-scale brain\n%   structures (cortex, basal ganglia, etc.). So the ordering in the table may not match\n%   the original region object. To turn this feature off, use 'nosort'.\n%\n% :Optional inputs:\n%\n%   **atlas_obj**\n%       Any atlas-class object, e.g., loaded by load_atlas().\n%\n%   **k:**\n%        Print only regions with k or more contiguous voxels\n%\n%   **nosep:**\n%        do not separate cl with pos and neg effects based on peak in .val\n%\n%   **names:**\n%        name clusters manually before printing to table and output; saves in .shorttitle field\n%\n%   **forcenames:**\n%        force manual naming of cl by removing existing names in .shorttitle field\n%\n%   **nosort:**\n%        Do not sort rows by network/brain lobe [default is to sort]\n%\n%   **legacy:**\n%        force manual naming of cl by removing existing names in .shorttitle field\n%\n%   **nolegend:**\n%        omit table legend\n%\n% :Outputs:\n%\n%   Returns region objects for cl with pos and neg effects\n%   - autolabeled if Neuroimaging_Pattern_Masks and atlas tools are available on Matlab path\n%   - limited by size if entered\n%   - manually named if requested (see optional inputs)\n%\n% ..\n%     Author and copyright information:\n%\n%     Copyright (C) 2011  Tor Wager\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n% :Examples:\n% -------------------------------------------------------------------------\n% ::\n% Example 1:\n% % Complete group analysis of a standard dataset\n% % Do analysis and prep results region object:\n%\n%   img_obj = load_image_set('emotionreg');         % Load a dataset\n%   t = ttest(img_obj, .005, 'unc');                % Do a group t-test\n%   t = threshold(t, .005, 'unc', 'k', 10);         % Re-threshold with extent threshold of 10 contiguous voxels\n%   r = region(t);                                  % Turn t-map into a region object with one element per contig region\n%\n%   Label regions and print a table:\n%   [r, region_table, table_legend_text] = autolabel_regions_using_atlas(r);  \n%                                                   % Label regions. Can be skipped because 'table' below attempts to do this automatically\n%   table(r);                                       % Print a table of results using new region names\n%\n%   [rpos, rneg] = table(r);                        % Print and table and return region object separated into regions with positive vs. negative statistic values (from .Z field)\n\n% ..\n%    Programmers' notes:\n%    List dates and changes here, and author of changes\n% ..\n%    July 2018:  Autolabel update and \"new 2018 version\", Tor Wager. Also added legend text.\n\nn_cols = 140;                       % 140 good for HTML reports\nsep_str = repmat('_', 1, n_cols);   % see textwrap\n\nk = 0;\ndosep = true;\ndonames = false;        % name clusters before printing to table and output; saves in .shorttitle field (legacy only)\nforcenames = false;     % force naming of cl by removing existing names in .shorttitle field (legacy only)\ndolegacy = false;\ndosortrows = true;          % sort rows by area\ndolegend = true;\n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n            \n            % functional commands\n            case {'k', 'maxsize'}, k = varargin{i+1};\n            case 'nosep', dosep = 0;\n            case {'names', 'name', 'donames'}, donames = true;\n            case 'forcenames', forcenames = true;\n                \n            case {'nosort', 'nosortrows'}, dosortrows = false;\n                \n            case {'legacy', 'dolegacy'}, dolegacy = true;\n                \n            case 'nolegend', dolegend = false;\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n\n \n[poscl, negcl, results_table] = table(cl, varargin)\n\n\n[w_atlas, w_region_obj] = subdivide_by_atlas(w, atl);\n\n% Make a table of labeled regions with significant voxels in the weight map\n\n[region_obj, region_table] = autolabel_regions_using_atlas(w_region_obj, atl);\nregion_table = region_table(:, 1:3);\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@image_vector/table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21261925810785232}}
{"text": "function obj2 = fft( obj1, varargin )\n\nobj2 = unitaryopp(@fft, obj1, varargin{:});\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/@mmo/fft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21247230174906312}}
{"text": "function [x,fval,exitflag,info] = opti_filtersd(fun,grad,x0,lb,ub,nlcon,nljac,nljacstr,cl,cu,opts)\n%OPTI_FILTERSD Solve a NLP using FILTERSD \n%\n%   min f(x)       subject to:    cl <= nlcon(x) <= cu\n%    x                            lb <= x <= ub\n%\n%   x = opti_filtersd(fun,grad,x0) solves a NLP where fun is the objective \n%   function, grad is the gradient of the objective and x0 is a starting \n%   guess.\n%\n%   x = opti_filtersd(fun,grad,x0,lb,ub) solves subject to decision \n%   variable bounds lb <= x <= ub. Infinite bounds are OK.\n%\n%   x = opti_filtersd(fun,x0,lb,ub,nlcon,nljac,[],cl,cu) solves subject to \n%   the nonlinear inequality constraints cl <= nlcon(x) <= cu, and nljac\n%   returns a DENSE Jacobian of the constraints.\n%\n%   x = opti_filtersd(fun,x0,lb,ub,nlcon,nljac,nljacstr,cl,cu) solves as\n%   above, except nljac returns a SPARSE Jacobian of the constraints, and\n%   nljacstr supplies a sparse matrix of ALL possible non-zero locations\n%   within the Jacobian.\n%\n%   x = opti_filtersd(fun,...,cu,opts) uses opts to pass optiset options to \n%   the solver. \n%\n%   [x,fval,exitflag,info] = opti_filtersd(...) returns the objective value \n%   at the solution, together with the solver exitflag, and an information\n%   structure.\n%\n%   THIS IS A WRAPPER FOR FILTERSD\n%   See supplied Eclipse Public License\n\n%   Copyright (C) 2013 Jonathan Currie (IPL)\n\nif(nargin < 11), opts = optiset; else opts = optiset(opts); end\nif(nargin < 10), cu = []; end\nif(nargin < 9),  cl = []; end\nif(nargin < 8),  nljacstr = []; end\nif(nargin < 7),  nljac = []; end\nif(nargin < 6),  nlcon = []; end\nif(nargin < 5),  ub = []; end\nif(nargin < 4),  lb = []; end\nif(nargin < 3),  error('FILTERSD requires at least 3 arguments'); end\n\n%Default is not sparse\nsp = false;\n\n%Determine we have a sparse problem\nif(~isempty(nljacstr))\n    sp = true; %must be sparse if we passed an arg here\n    if(~isa(nljacstr,'function_handle'))\n        error('Jacobian Structure must be a function handle');\n    end\nend\n\n%Check we have a valid x0\nif(isempty(x0) || any(isnan(x0)))\n    error('FILTERSD requires an initial guess, x0!');\nend\n\n%Setup display level\nopts.display = dispLevel(opts.display);\nopts.optiver = optiver;\n\nt = tic;\nif(sp)\n    % Run FILTERSD [Sparse]\n    jacstr = nljacstr(); %filtersd just requires the matrix\n    [x, fval, exitflag, stats, lambda] = filtersdsp(fun,grad,x0,lb,ub,nlcon,nljac,jacstr,cl,cu,opts);\nelse\n    % Run FILTERSD [Dense]\n    [x, fval, exitflag, stats, lambda] = filtersd(fun,grad,x0,lb,ub,nlcon,nljac,cl,cu,opts);\nend\n\n%Collect Results\ninfo.Iterations = stats.niter;\ninfo.FuncEvals = stats.nfval;\ninfo.GradEvals = stats.ngval;\ninfo.Time = toc(t);\nif(sp)\n    info.Algorithm = 'FILTERSD: Nonlinear Optimization using the Filter Search & Trust Region [Sparse]';\nelse\n    info.Algorithm = 'FILTERSD: Nonlinear Optimization using the Filter Search & Trust Region [Dense]';\nend\n\nswitch(exitflag)\n    case 0\n        info.Status = 'Locally Optimal';\n        exitflag = 1;\n    case {5,101,102}\n        info.Status = 'Exceeded Iterations / Function Evaluations / Time';\n        exitflag = 0;\n    case {1,2,4,7,8}\n        info.Status = 'Initialization Error';\n        exitflag = -2;\n    case {3,6}\n        info.Status = 'Infeasible / Inconsistent Constraints';\n        exitflag = -1;\n    case {9,10}\n        info.Status = 'LCP Solver Error';\n        exitflag = -3;\n    case 105\n        info.Status = 'User Exited';\n        exitflag = -5;\n    otherwise        \n        info.Status = 'FILTERSD Error';\nend\n\ninfo.Lambda = lambda;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Solvers/opti_filtersd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21247229600880277}}
{"text": "function [im, scale] = readImage(imagePath)\n% READIMAGE   Read and standardize image\n%    [IM, SCALE] = READIMAGE(IMAGEPATH) reads the specified image file,\n%    converts the result to SINGLE class, and rescales the image\n%    to have a maximum height of 480 pixels, returing the corresponding\n%    scaling factor SCALE.\n%\n%    READIMAGE(IM) where IM is already an image applies only the\n%    standardization to it.\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif ischar(imagePath)\n  try\n    im = imread(imagePath) ;\n  catch\n    error('Corrupted image %s', imagePath) ;\n  end\nelse\n  im = imagePath ;\nend\n\nim = im2single(im) ;\n\nscale = 1 ;\nif (size(im,1) > 480)\n  scale = 480 / size(im,1) ;\n  im = imresize(im, scale) ;\n  im = min(max(im,0),1) ;\nend\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/align2RGBD/align2RGBD/lib/vlfeat/apps/recognition/readImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21238369114491984}}
{"text": "function out_fwrite_edf(sFile, sfid, SamplesBounds, ChannelsRange, F)\n% OUT_FWRITE_EDF: Write a block of recordings from a EDF file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Martin Cousineau, 2017\n%          Francois Tadel, 2019\n\n% ===== PARSE INPUTS =====\n[nSignals, nSamples] = size(F);\nif isempty(SamplesBounds)\n    SamplesBounds = [0, nSamples];\nend\nif isempty(ChannelsRange)\n    ChannelsRange = [1, nSignals];\nend\n\nfseek(sfid, 0, 'eof');\n\n% Get the gains of the channels for all the non-Annotation channels\niChanGain = setdiff(1:length(sFile.header.signal), sFile.header.annotchan);\n% Apply channel gains before converting to integer\nchgain = [sFile.header.signal(iChanGain).unit_gain] ./ ...\n            ([sFile.header.signal(iChanGain).physical_max] - [sFile.header.signal(iChanGain).physical_min]) .* ...\n            ([sFile.header.signal(iChanGain).digital_max]  - [sFile.header.signal(iChanGain).digital_min]);\nF = bst_bsxfun(@times, F, chgain');\n\n% Convert to 2-byte integer in 2's complement\nF = int16(F);\nnegF = F < 0;\nF(negF) = bitcmp(abs(F(negF))) + 1;\n\n% Prepare annotations if any.\nif sFile.header.annotchan >= 0\n    annotations    = 1;\n    nAnnots        = numel(sFile.header.annotations);\n    nSamplesReal   = round((sFile.prop.times(2) - sFile.prop.times(1)) .* sFile.prop.sfreq);\n    nSamplesAnnots = sFile.header.signal(sFile.header.annotchan).nsamples;\n    annotThreshold = floor((1:nAnnots) / nAnnots * nSamplesReal);\n    annotBounds    = [0, 0];\n    \n    % Insert annotation in this record only if it contains the required\n    % cutoff sample threshold\n    for iThr = 1:nAnnots\n        if annotThreshold(iThr) >= SamplesBounds(1) && annotThreshold(iThr) <= SamplesBounds(2)\n            if annotBounds(1) < 1\n                annotBounds(1) = iThr;\n            end\n            annotBounds(2) = iThr;\n        end\n    end\n    \n    if annotBounds(2) < 1\n        annotsList = [];\n    else\n        annotsList = sFile.header.annotations(annotBounds(1) : annotBounds(2));\n    end\n    \n    nAnnots     = numel(annotsList);\n    nextAnnot   = 1;\nelse\n    annotations = 0;\nend\n\n% Write to file record per record\nnSamplesPerRecord = sFile.prop.sfreq * sFile.header.reclen;\nnRecords          = ceil((SamplesBounds(2) - SamplesBounds(1)) / nSamplesPerRecord);\nncount            = 0;\nbounds            = [1, nSamplesPerRecord];\ntimeOffset        = SamplesBounds(1) / sFile.prop.sfreq;\n\nfor iRec = 1:nRecords\n    % Special case when we don't have enough data to fill the last record\n    if bounds(2) > nSamples\n        if iRec ~= nRecords\n            error('Ran out of data before last record.');\n        end\n        writeZeros = bounds(2) - nSamples;\n        bounds(2)  = nSamples;\n    else\n        writeZeros = 0;\n    end\n\n    % Write data\n    for iSig = ChannelsRange(1):ChannelsRange(2)\n        ncount = ncount + fwrite(sfid, F(iSig, floor(bounds(1)):floor(bounds(2))), 'int16');\n        \n        % Fill rest of the record with 0s if required\n        if writeZeros\n            fwrite(sfid, zeros(writeZeros, 1), 'int16');\n        end\n    end\n    \n    % Write annotations if any, split by records\n    if annotations\n        bytesLeft = nSamplesAnnots * 2;\n        \n        % The first annotation specifies the time offset\n        bytesLeft = bytesLeft - fprintf(sfid, '+%f%c%c%c', timeOffset, char(20), char(20), char(0));\n        \n        % Write as many annotations as possible in current record\n        while nextAnnot <= nAnnots && bytesLeft >= length(annotsList{nextAnnot})\n            bytesLeft = bytesLeft - fprintf(sfid, '%s', annotsList{nextAnnot});\n            nextAnnot = nextAnnot + 1;\n        end\n        \n        % Fill remaining of record with 0-bytes.\n        fprintf(sfid, '%s', repmat(char(0), 1, bytesLeft));\n    end\n    \n    % Get ready for next record\n    bounds     = bounds + nSamplesPerRecord;\n    timeOffset = timeOffset + sFile.header.reclen;\nend\n\n% Check number of values written\nif (ncount ~= numel(F))\n    error('Error writing data to file.');\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_fwrite_edf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.21237368777394963}}
{"text": "function ExportAedat2Frames(aedat)\n\n%{\nThis function exports data to a .aedat file. \nThe .aedat file format is documented here:\n\nhttp://inilabs.com/support/software/fileformat/\n%}\n\ndbstop if error\n\nif ~exist('aedat', 'var')\n\terror('Missing input')\nend\n\nif ~isfield(aedat, 'data')\n\tdisp('No data to export')\n    return\nend\n\n% Create the file\nif ~isfield(aedat.exportParams, 'filePath')\n    error('Missing file path and name')\nend\n\nf = fopen(aedat.exportParams.filePath, 'w', 'b');\n\n% Simple - events only - assume DAVIS\n\n% CRLF \\r\\n is needed to not break header parsing in jAER\nfprintf(f,'#!AER-DAT2.0\\r\\n');\nfprintf(f,'# This is a raw AE data file created by an export function in the AedatTools library\\r\\n');\nfprintf(f,'# Data format is int32 address, int32 timestamp (8 bytes total), repeated for each event\\r\\n');\nfprintf(f,'# Timestamps tick is 1 us\\r\\n');\n% Put the source in - use an override if it has been given\nif isfield(aedat.exportParams, 'source')\n    fprintf(f,['# AEChip: ' aedat.exportParams.source '\\r\\n']);\nelse \n    fprintf(f,['# AEChip: ' aedat.info.source '\\r\\n']);\nend\nfprintf(f,'# End of ASCII Header\\r\\n');\n\n% DAVIS\n% In the 32-bit address (1-based):\n% Bit-32   Bit-11   Meaning\n% 1        0        APS sample \n% 1        1        IMU sample\n% 0        1        Special event \n% 0        0        Polarity event\n\nyShiftBits = 22;\nxShiftBits = 12;\n% frameShiftBits = 0;\nframeFlagShiftBits = 31;\nsignalShiftBits = 9;\n\nframeData = aedat.data.frame;\n\nnumFrames = frameData.numEvents;\nxDim = aedat.info.deviceAddressSpace(1);\nyDim = aedat.info.deviceAddressSpace(2);\nnumPixels = xDim * yDim;\n\n% Allocate horizontal vectors to hold output data.\n% Why are the vectors that big? The factor of 2 is because \n% we insert dummy 'reset' frames prior to each frame. \nsamples = uint32(zeros(1, 2 * numFrames * numPixels)); \ntimeStamps = uint32(zeros(1, 2 * numFrames * numPixels)); \n\n% The output vector is twice as big again because samples and timeStamps \n% will be interspersed in the 'output' vector.\noutput = uint32(zeros(1, 2 * 2 * numFrames * numPixels)); \ny = repmat(uint32(yDim - 1 : -1 : 0), 1, xDim * numFrames * 2);\nx = repmat(uint32(xDim - 1 : -1 : 0), yDim, numFrames * 2);\nx = x(:);\nx = x';\n% in bit 11 (1-based) 1 means signal read and 0 means reset read.\nsignalFlag = repmat([zeros(1, numPixels, 'uint32')  ones(1, numPixels, 'uint32') * 2^10], 1, numFrames);\n% The last event mask is synonymous with the sample from x=0 y=0; data is\n% therefore ordered backwards.\nfor frameIndex = 1 : numFrames\n    samplesTemp = frameData.samples{frameIndex}(:);\n    samplesTemp = samplesTemp(end : -1 : 1);\n    samples((frameIndex * 2 - 1) * numPixels + 1 : frameIndex * 2 * numPixels) ...\n        = samplesTemp ;\n    timeStamps((frameIndex - 1) * 2 * numPixels + 1 : frameIndex * 2 * numPixels) ...\n        = frameData.timeStampStart(frameIndex); \nend\nframeFlag = uint32(ones(1, numFrames * 2 * numPixels) * 2 ^ frameFlagShiftBits);\ny = y * uint32(2 ^ yShiftBits);\nx = x * uint32(2 ^ xShiftBits);\n% samples should now be in the range 0-1023 (10-bit). \n% subtract samples from 1023. This has the effect of leaving all the reset\n% frame samples at 1023 - the highest value, against which the signal frames\n% will later be subtracted. \nsamples = 1023 - samples;\n\noutput(1:2:end) = frameFlag + y + x + signalFlag + samples;\noutput(2:2:end) = timeStamps; % set even elements to timestamps\n\n% write addresses and timestamps\ncount=fwrite(f, output, 'uint32', 0, 'b')/2; % write 4 byte data\nfclose(f);\nfprintf('wrote %d events to %s\\n', count, aedat.exportParams.filePath);\n\n\n", "meta": {"author": "panpanfei", "repo": "Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "sha": "aabdd6ae323726132b0e0592ce151461e3ad7c5a", "save_path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera/Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera-aabdd6ae323726132b0e0592ce151461e3ad7c5a/event_cvpr_github/read_data/code/AedatTools-master/Matlab/ExportAedat2Frames.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.21219594317433224}}
{"text": "run('matconvnet/matlab/vl_setupnn.m');\naddpath('util/');\n\noutDir = 'result'; % output directory\ndata = 'Set5';     % test data (directory) which is in data folder \nSF = 2;            % test scale factors. can be 2, 3 or 4\noutRoute = fullfile(outDir, data, ['VDSR_x',num2str(SF)]);\n\nif ~exist(outRoute, 'dir')\n    mkdir(outRoute);\nend\n\n%VDSR(data, SF, 'VDSR.mat', outRoute);\nVDSR(data, SF, 'VDSR_CPUonly_SupER.mat', outRoute); % MAGI-ADAPT\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/VDSR/testVDSR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.21197695174630618}}
{"text": "function a = subsasgn( a,s,b )\n%SUBSASGN for nested cells\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\nif(length(s) > 1)\n    posCell = size(s(1).subs,2);\n    posCell = s(1).subs{1,posCell};\n    posMat = cell2mat(s(2).subs);\n    [out,idx] = flattenCellMatrix(a.data);\n    out{posCell}(sub2ind(size(out{posCell}),posMat(1),posMat(2),posMat(3))) = b;\n    a.data = reconFlatCellMatrix(out,idx);\n    \nelse\n    if(strcmp(s.type,'{}'))\n        pos = size(s.subs,2);\n        pos = s.subs{1,pos};\n        [out,idx] = flattenCellMatrix(a.data);\n        out{pos} = b;\n        a.data = reconFlatCellMatrix(out,idx);\n        \n    else\n        pos = size(s.subs,2);\n        pos = s.subs{1,pos};\n        % a = a.data;\n        % meta = a.meta;\n        if(isa(b,'TRAFO'))\n            if(size(s.subs,2) == 5)\n                a.data(pos,:) = b.data; % for kernelImg (due to 5D dataset => cha-cha)\n                if iscell(b.meta) ~= 1\n                    a.meta = b.meta; %changed for curvelab!\n                else\n                    a.meta(pos,:) = b.meta;\n                end\n            else\n                a.data(1,pos) = b.data;\n                if(~iscell(b.meta) || length(b.meta) > 1)\n                    a.meta = b.meta; %changed for curvelab!\n                else\n                    a.meta(1,pos) = b.meta;\n                end\n            end\n        % a = TRAFO(a,meta);\n        else\n            [out,idx] = flattenCellMatrix(a.data(1,pos));\n            for i=1:length(out)\n                out{i}(:) = b;\n            end\n            a.data(1,pos) = reconFlatCellMatrix(out,idx);\n        end\n    end\nend\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@TRAFO/subsasgn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630615}}
{"text": "function outputImage = plus(this, otherImage)\n% Adds data of other image to this one and writes output in new image\n%\n% NOTE: If voxel dimensions of 2nd image do not match - or a scalar is\n% given as 2nd argument - data in the 2nd argument is automatically\n% replicated to match this image geometry.\n%\n%\n%   Y = MrImage()\n%   outputImage = plus(Y, otherImage, ...\n%   functionHandle)\n%\n% This is a method of class MrImage.\n%\n%\n% IN\n%   otherImage              image that will be added to this one\n%\n% OUT\n%   outputImage             new MrImage, sum of this and otherImage\n%\n% EXAMPLE\n%\n%   % Compute sum of 2 images\n%\t\tY = MrImage();\n%\t\tZ = MrImage();\n%\t\tX = Y.plus(Z);\n%\n%   % OR (cool overload!):\n%       X = Y+Z\n%\n%   See also MrImage perform_binary_operation\n\n% Author:   Saskia Bollmann & Lars Kasper\n% Created:  2014-11-13\n% Copyright (C) 2014 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\n\noutputImage = this.perform_binary_operation(otherImage, @plus);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDataNd/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.21193545340226322}}
{"text": "function []= sounding_powerlaw_sens(hydro,wet)\n% function that computes the power law coefficents and performs a\n% sensitivity analysis.\n%\n%     Copyright (C) 2015  Bekaert David - University of Leeds\n%     Email: eedpsb@leeds.ac.uk or davidbekaert.com\n% \n%     This program is free software; you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation; either version 2 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License along\n%     with this program; if not, write to the Free Software Foundation, Inc.,\n%     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% By David Bekaert -- University of Leeds 2013\n% modifications\n% 05/2013   DB:     Compute the power law coefficients for dedicated days.\n% 08/2013   DB:     Fix the case when a netdelay cannot be computed.\n% 02/2014   DB:     Add non-stamps file support of ifgs-based estimation.\n% 03/2014   DB:     Fix the computation of the sensitivity analysis in\n%                   absence of soundign for specific SAR dates. \n% 08/2014   DB:     Expand for PS network and SB network for SAR date estimation\n% 03/2016   DB:     remove warning on ifgday for non-stamps processing\n\nif nargin<1\n    hydro=1;\n    wet=1;\nend\n\n% getting the data from the parms_aps file\nn_months = getparm_aps('sounding_months');\nsounding_start_date = getparm_aps('sounding_start_date');\nsounding_end_date = getparm_aps('sounding_end_date');\nsounding_dir=getparm_aps('sounding_dir');\ntime_stamp = getparm_aps('sounding_time_stamp');\nsounding_ifg_dates = getparm_aps('sounding_ifg_dates');\ntime_stamp_str = [];\nfor k=1:size(time_stamp,1)\n    if k>1\n        time_stamp_str = [time_stamp_str '_' time_stamp(k,:)];\n    else\n        time_stamp_str = [time_stamp(k,:)];\n    end\nend\n    \n% checking if the directory exists\nif exist([sounding_dir filesep],'dir')~=7\n        error('myApp:argChk', ['The specified filepath of the sounding data does not exist,...  \\nAbort,... \\n'])\nend     \n% current directry\ncurdir = pwd;\n\n% getting the interferogram data information\n% loading the data\nstamps_processed = getparm_aps('stamps_processed');\nif strcmp(stamps_processed,'y')   \n   fprintf('Stamps processed structure \\n')\n   ll_matfile = getparm_aps('ll_matfile');\n   ps = load(ll_matfile);\n   dates = ps.day;\n   lonlat = ps.lonlat;\n   \n    % getting the parms file list from stamps to see the final ifg list   \n    \n    % constructing the matrix with master and slave dates\n    if strcmp(getparm('small_baseline_flag'),'y')\n        % for SB\n        ifgs_ix = ps.ifgday_ix;\n    \n    else\n        n_ifg = ps.n_ifg;\n        % slightly different for PS.\n        date_slave_ix = [1:n_ifg]';\n        % the master dates\n        date_master_ix = repmat(ps.master_ix,size(date_slave_ix,1),1);\n        % ix interferograms\n        ifgs_ix = [date_master_ix date_slave_ix];\n    end\nelse\n    % getting the dates in jullian format\n    ifgday_matfile = getparm_aps('ifgday_matfile');\n    ifgs_dates = load(ifgday_matfile);\n    ifgs_dates = ifgs_dates.ifgday;\n    dates = reshape(ifgs_dates,[],1);\n    dates = unique(dates);\n    dates = datenum(num2str(dates),'yyyymmdd');\n    dates = sort(dates);        % dates increasing with time\n    \n    % getting the ix position for the master and slave dates with respect\n    % to the times\n    date_master = datenum(num2str(ifgs_dates(:,1)),'yyyymmdd');\n    date_slave = datenum(num2str(ifgs_dates(:,2)),'yyyymmdd');\n    \n    for k=1:size(date_master,1)\n        [date_master_ix(k,1)] = find(date_master(k,1)==dates);\n        [date_slave_ix(k,1)] = find(date_slave(k,1)==dates);\n    end\n    \n    % ix interferograms\n    ifgs_ix = [date_master_ix date_slave_ix];\n    clear date_master_ix date_slave_ix\nend\n\n\n\n\nif strcmp(sounding_ifg_dates,'y')\n    % estimate for interferogram dates\n    stamps_processed = getparm_aps('stamps_processed');\n    if strcmp(stamps_processed,'y')\n        ps = load(ll_matfile);\n        date_start_vector = datestr(ps.day-15,'yyyymmdd');\n        date_end_vector = datestr(ps.day+15,'yyyymmdd');\n        \n    else\n\n        ifgday_matfile = getparm_aps('ifgday_matfile');\n        ifgs_dates = load(ifgday_matfile);\n        ifgs_dates = ifgs_dates.ifgday;\n        dates = reshape(ifgs_dates,[],1);\n        dates = unique(dates);\n        dates = datenum(num2str(dates),'yyyymmdd');\n        dates = sort(dates);        % dates increasing with time\n    \n          \n        date_start_vector =  datestr(dates-15,'yyyymmdd');\n        date_end_vector =  datestr(dates+15,'yyyymmdd');\n    end\n    \n    % save name of the output data\n    if hydro==1 && wet==0\n        save_name = ['Powerlaw_sensitivity_hydro_SAR_dates_1month_' time_stamp_str 'Hr.mat'  ];\n    elseif hydro==0 && wet==1\n        save_name = ['Powerlaw_sensitivity_wet_SAR_dates_1month_' time_stamp_str 'Hr.mat'  ];\n    else\n        save_name = ['Powerlaw_sensitivity_SAR_dates_1month_' time_stamp_str 'Hr.mat'  ];\n    end\n    if exist([sounding_dir filesep 'Powerlaw'],'dir')~=7\n        mkdir([sounding_dir filesep 'Powerlaw']);\n    end \n    \n    \nelse\n    % estimate is on fixed intervals\n    % in case no start or end time is given, get it from the data files\n    if isempty(sounding_start_date) || isempty(sounding_end_date)\n        \n        if exist('sounding.list','file')~=2\n            % making a list of all the sounding files\n            [dummy dummy2] = system('echo sounding_list > sounding.list');\n            clear dummy dummy2\n            for k=1:size(time_stamp,1)\n                command_str = ['ls [0-9]???????_' time_stamp(k,:) '.mat >> sounding.list']; \n                [dummy dummy2] = system(command_str);\n                clear dummy dummy2\n            end\n        end\n        temp = tdfread('sounding.list');\n        [dummy dummy2] = system('rm sounding.list');\n        clear dummy dummy2\n        date_list_temp = temp.sounding_list(:,[1:8]);\n\n        % selecting a date range when requested\n        clear ix\n\n        if isempty(start_date)\n            sounding_start_date = date_list_temp(1,:);\n        end\n        if isempty(end_date)\n            sounding_end_date = date_list_temp(end,:);    \n        end\n        clear date_list_temp\n    end\n\n    % putting the variables in the right set-up\n    start_year = str2num(sounding_start_date(1:4));\n    end_year = str2num(sounding_end_date(1:4));\n    start_str = sounding_start_date(5:6);\n    end_str = sounding_end_date(5:6);\n    start_month = str2num(start_str);\n    end_month = str2num(end_str);\n\n    % save name of the output data\n   if hydro==1 && wet==0\n        save_name = ['Powerlaw_sensitivity_hydro_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat'  ];\n    elseif hydro==0 && wet==1\n        save_name = ['Powerlaw_sensitivity_wet_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat'  ];\n   else\n        save_name = ['Powerlaw_sensitivity_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat'  ];\n    end\n    if exist([sounding_dir filesep 'Powerlaw'],'dir')~=7\n        mkdir([sounding_dir filesep 'Powerlaw']);\n    end \n    \n    \n    \n    if exist([sounding_dir filesep 'Powerlaw'],'dir')~=7\n        mkdir([sounding_dir filesep 'Powerlaw']);\n    end\n    \n    % generating the periods\n    month_str = ['01';'02';'03';'04';'05';'06';'07';'08';'09';'10';'11';'12'];\n    counter = 1;\n    % runnign the computation of the powerlaw in batches\n    for k=1:end_year-start_year+1\n        if k==end_year-start_year+1 & k>1\n            for l=1:end_month\n                date_start_temp = datenum([num2str(start_year+k-1)  month_str(l,:) '01'],'yyyymmdd');\n                date_start_month_vector(counter,:) = datestr(date_start_temp,'yyyymmdd');\n                counter = counter+1;\n            end\n        elseif k==end_year-start_year+1 & k==1\n            for l=start_month:end_month\n                date_start_temp = datenum([num2str(start_year+k-1)  month_str(l,:) '01'],'yyyymmdd');\n                date_start_month_vector(counter,:) = datestr(date_start_temp,'yyyymmdd');\n                counter = counter+1;\n            end\n        else\n            for l=1:12\n                date_start_temp = datenum([num2str(start_year+k-1)  month_str(l,:) '01'],'yyyymmdd');\n                date_start_month_vector(counter,:) = datestr(date_start_temp,'yyyymmdd');\n                counter = counter+1;\n            end\n        end\n    end\n\n    n_months_total = size(date_start_month_vector,1);\n    for k=1:ceil(n_months_total/n_months)\n        k_lower = n_months*(k-1)+1;\n        k_upper = n_months*(k)+1;\n\n        if k_upper>n_months_total\n            k_upper = n_months_total;\n        end\n        date_start_vector(k,:)=date_start_month_vector(k_lower,:);\n        date_end_vector(k,:) = datestr(datenum(date_start_month_vector(k_upper,:),'yyyymmdd')-1,'yyyymmdd');\n    end\n\nend\n\n% Remove those months outside the users request\nif ~isempty(sounding_start_date)\n    ix_drop = find(datenum(date_start_vector,'yyyymmdd')<datenum(sounding_start_date,'yyyymmdd'));\nelse\n    ix_drop = [];\nend\nif ~isempty(sounding_end_date)\n    ix_drop = [ix_drop ; find(datenum(date_end_vector,'yyyymmdd')>datenum(sounding_end_date,'yyyymmdd'))];\nend\nix_drop = unique(ix_drop);\ndate_end_vector(ix_drop,:)=[];\ndate_start_vector(ix_drop,:)=[];\n    \n% Computing the power law coefficients\nfor k=1:size(date_start_vector,1)\n    fprintf(['\\n' num2str(k) '/' num2str(size(date_start_vector,1)) ' completed \\n']);\n\t% When having sounding data estimate the powerlaw and b coefficients\n    \n    [alpha_all,alpha_hc,h_0_threshold,n_soundings] = sounding(date_start_vector(k,:),date_end_vector(k,:),[],hydro,wet);\t\n\talpha_vector_all(k,1) = alpha_all;               \n    alpha_vector(k,1) = alpha_hc;\n\tn_soundings_vector(k,1)=n_soundings;\n\th0_vector(k,1)=h_0_threshold;\n\nend\nsave([sounding_dir filesep 'Powerlaw' filesep save_name],'alpha_vector_all','alpha_vector','n_soundings_vector','h0_vector','date_start_vector','date_end_vector')\n\ncd(curdir)\nif strcmp(sounding_ifg_dates,'y')\n    % estimate for interferogram dates\n    stamps_processed = getparm_aps('stamps_processed');\n    if strcmp(stamps_processed,'y')      \n        fprintf('Updating powerlaw parameters with new values. \\n')\n\n        % removing NaN by replacing them with the other SAR date estimates\n        ix_alpha_fix = find(isnan(alpha_vector(:,1)));\n        if ~isempty(ix_alpha_fix)\n           if length(ix_alpha_fix)~=length(alpha_vector)\n                fprintf([num2str(length(ix_alpha_fix)) ' out of ' num2str(length(alpha_vector)) ' SAR dates where set to the mean alpha due to lack of sounding data. \\n']) \n                alpha_vector(isnan(alpha_vector))=nanmean(alpha_vector);\n                alpha_vector_fix = alpha_vector;\n                save([sounding_dir filesep 'Powerlaw' filesep save_name],'-append','alpha_vector_fix','ix_alpha_fix')\n\n           else\n              fprintf('None of the SAR dates where estimate using sounding data \\n') \n           end\n\n        end\n        \n        ix_height_fix = find(isnan(h0_vector(:,1)));\n        if ~isempty(ix_height_fix)\n           if length(ix_height_fix)~=length(h0_vector)\n                fprintf([num2str(length(ix_height_fix)) ' out of ' num2str(length(alpha_vector)) ' SAR dates where set to the mean h0 due to lack of sounding data. \\n']) \n                h0_vector(isnan(h0_vector))=nanmean(h0_vector);\n                h0_vector_fix = h0_vector;\n                save([sounding_dir filesep 'Powerlaw' filesep save_name],'-append','h0_vector_fix','ix_height_fix')\n           else\n              fprintf('None of the SAR dates where estimate using sounding data \\n') \n           end\n        end      \n        \n        \n        alpha_SAR = [alpha_vector(ifgs_ix(:,1)) alpha_vector(ifgs_ix(:,2))];\n        h0_SAR = [h0_vector(ifgs_ix(:,1)) h0_vector(ifgs_ix(:,2))];\n               \n        \n        % computing the mean between two SAR dates \n        h0_InSAR = mean(h0_SAR,2);\n        alpha_InSAR = mean(alpha_SAR,2);\n        \n        setparm_aps('powerlaw_h0',h0_InSAR');\n        setparm_aps('powerlaw_alpha',alpha_InSAR');\n    end    \nelse\n\n    % computing the mean between two SAR dates \n    ix = isnan(h0_vector);\n    powerlaw_h0 = mean(h0_vector(~ix));\n    powerlaw_alpha = mean(alpha_vector(~ix));\n\n    setparm_aps('powerlaw_h0',powerlaw_h0');\n    setparm_aps('powerlaw_alpha',powerlaw_alpha');\nend\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/sounding_powerlaw_sens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2119354534022632}}
{"text": "function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, transcrData, metabolomicsData, INITSteps, removeGenes, useScoresForTasks, paramsFT, verbose)\n% ftINIT\n%   Main function for generates a model using the ftINIT algorithm, based \n%   on proteomics and/or transcriptomics and/or metabolomics and/or metabolic \n%   tasks. The algorithm is not designed for running with metabolomics only.\n%   The function prepINITModel needs to be run first for the template\n%   model (such as the generic Human-GEM), but only need to be run once. This\n%   function precalculates things independent of the omics to speed up the model\n%   generation process, and outputs the prepData, which is input to this function.\n%\n%   prepData            The prepdata for the model.\n%   tissue              tissue to score for. Should exist in either\n%                       hpaData.tissues or transcrData.tissues\n%   celltype            cell type to score for. Should exist in either\n%                       hpaData.celltypes or transcrData.celltypes for this\n%                       tissue (opt, default is to use the max values\n%                       among all the cell types for the tissue.\n%   hpaData             HPA data structure from parseHPA (opt if transcrData\n%                       is supplied, default [])\n%   transcrData         gene expression data structure (opt if hpaData is\n%                       supplied, default []). Used to be called arrayData.\n%       genes           cell array with the unique gene names\n%       tissues         cell array with the tissue names. The list may not\n%                       be unique, as there can be multiple cell types per\n%                       tissue.\n%       celltypes       cell array with the cell type names for each tissue\n%       levels          GENESxTISSUES array with the expression level for\n%                       each gene in each tissue/celltype. NaN should be\n%                       used when no measurement was performed\n%       threshold       a single value or a vector of gene expression \n%                       thresholds, above which genes are considered to be\n%                       \"expressed\". default = 1(opt, by default, the mean expression\n%                       levels of each gene across all tissues in transcrData\n%                       will be used as the threshold values)\n%       singleCells     binary value selecting whether to use the\n%                       single-cell algorithm to identify expressed genes.\n%                       If used, specify cell subpopulations in CELLTYPES\n%                       (opt, default [])\n%       plotResults     true if single cell probability distributions\n%                       should be plotted (opt, default = false)\n%   metabolomicsData    cell array with metabolite names that the model\n%                       should produce (opt, default [])\n%   INITSteps           Specifies the steps in the algorithm. For more info,\n%                       see INITStepDesc and getINITSteps. \n%                       (opt, default getINITSteps(), which is the standard ftINIT).\n%   removeGenes         if true, low-abundance genes will be removed from\n%                       grRules, unless they are the only gene associated \n%                       with a reaction, or a subunit of an enzyme complex\n%                       (see \"removeLowScoreGenes\" function for details).\n%                       If false, grRules will not be modified; however,\n%                       genes that were associated only with removed \n%                       reactions will not be present in the final model.\n%                       (opt, default true).\n%   useScoresForTasks   true if the calculated reaction scored should be \n%                       used as weights when fitting to tasks (opt, default\n%                       true)\n%   paramsFT            parameter structure as used by getMILPParams. This\n%                       is for the fitTasks step. For the INIT algorithm,\n%                       see params (opt, default [])\n%   verbose             if true, the MILP progression will be shown. \n%                       (opt, default true)\n%\n%   model                   the resulting model structure\n%   metProduction           array that indicates which of the\n%                           metabolites in metabolomicsData that could be\n%                           produced. Note that this is before the\n%                           gap-filling process to enable defined tasks. To\n%                           see which metabolites that can be produced in\n%                           the final model, use canProduce.\n%                           -2: metabolite name not found in model\n%                           -1: metabolite found, but it could not be produced\n%                           1: metabolite could be produced\n%   addedRxnsForTasks       cell array of the reactions which were added in\n%                           order to perform the tasks\n%   deletedRxnsInINIT       cell array of reactions deleted because they\n%                           could not carry flux (INIT requires a\n%                           functional input model)\n%   fullMipRes              The solver results from the last MILP step run\n%\n%   This is the main function for automatic reconstruction of models based\n%   on the ftINIT algorithm (). \n%\n%   NOTE: Exchange metabolites should normally not be removed from the model\n%   when using this approach, since checkTasks/fitTasks rely on putting specific\n%   constraints for each task. The INIT algorithm will remove exchange metabolites\n%   if any are present. Use importModel(file,false) to import a model with\n%   exchange metabolites remaining.\n%\n%   Usage: [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, ...\n%               fullMipRes] = ...\n%               ftINIT(prepData, tissue, celltype, hpaData, transcrData, ...\n%               metabolomicsData, INITSteps, removeGenes, useScoresForTasks, ...\n%               paramsFT);\n%\n\n\nif nargin < 5\n    transcrData = [];\nend\nif nargin < 6\n    metabolomicsData = [];\nend\nif nargin < 7 || isempty(INITSteps)\n    INITSteps = getINITSteps([],'1+1');\nend\nif nargin < 8 || isempty(removeGenes)\n    removeGenes = true;\nend\nif nargin < 9 || isempty(useScoresForTasks)\n    useScoresForTasks = true;\nend\nif nargin < 10\n    paramsFT = [];\nend\n\nif nargin < 11\n    verbose = true;\nend\n%Handle detected mets:\n%Previously, this was handled by giving a bonus for secreting those metabolites,\n%but that doesn't work since the metabolite secretion and uptake can be lost when \n%we merge linearly dependent reactions.\n%Instead, we need to figure out which reactions either produce or take up the mets.\n%We then give a bonus if any of them carry flux.\n%To simplify things, we focus on reactions that produce the metabolite (since there must be one such reaction). \n%It is still a bit complicated though. In this step, we focus on identifying\n%producer reactions. We further reason that the direction doesn't matter - \n%we can force one of these reactions in any direction - if it becomes a consumer, it will\n%automatically force another producer on as well (otherwise we'll have a net consumption).\n\nif (~isempty(metabolomicsData))\n    if length(unique(upper(metabolomicsData))) ~= length(metabolomicsData)\n        dispEM('Metabolomics contains the same metabolite multiple times');\n    end\n    metData = false(numel(metabolomicsData), length(prepData.minModel.rxns)); %one row per metabolite that is a boolean vector\n    for i=1:numel(metabolomicsData)\n        %Get the matching mets\n        metSel = ismember(upper(prepData.refModel.metNames),upper(metabolomicsData{i}));\n        prodRxnsSel = any(prepData.refModel.S(metSel,:) > 0,1) | ... %direct producers\n                     (any(prepData.refModel.S(metSel,:) < 0,1) & prepData.refModel.rev.'); %reversible reactions that are consumers\n        %convert the production rxns from refModel to minModel\n        prepData.groupIds;\n        [~,ia,ib] = intersect(prepData.minModel.rxns,prepData.refModel.rxns);\n        grpIdsMerged = nan(length(prepData.minModel.rxns),1);\n        grpIdsMerged(ia) = prepData.groupIds(ib);\n        \n        groupIdsPos = unique(prepData.groupIds(prodRxnsSel));%gets all group ids which includes a production rxn\n        groupIdsPos = groupIdsPos(groupIdsPos ~= 0);%remove the 0 id, it means there is no group\n        %the other option is that there is a direct match between the rxn id in minModel and refModel:\n        posRxns = prepData.refModel.rxns(prodRxnsSel);\n        directMatch = ismember(prepData.minModel.rxns, posRxns).';\n        \n        metData(i,:) = ismember(grpIdsMerged, groupIdsPos).' | directMatch;\n    end\n    metData = sparse(metData);\nelse\n    metData = [];\nend\n\n% Get rxn scores and adapt them to the minimized model\norigRxnScores = scoreComplexModel(prepData.refModel,hpaData,transcrData,tissue,celltype);\norigRxnScores(origRxnScores > -0.1 & origRxnScores <= 0) = -0.1;%we don't want reaction scores that are exactly 0 (or close), this causes problems in the milp\norigRxnScores(origRxnScores < 0.1 & origRxnScores > 0) = 0.1;\n\nrxnsTurnedOn = false(length(prepData.minModel.rxns),1);\nfluxes = zeros(length(prepData.minModel.rxns),1);\n\nrxnsToIgnoreLastStep = [1;1;1;1;1;1;1;1];\n\n%We assume that all essential rxns are irrev - this is taken care of in\n%prepINITModel. We then use an initial flux \"from last run\" of 0.1 for all \n%reactions. This is used for knowing what flux should be forced through an\n%essential rxn.\nfluxes = ones(length(prepData.minModel.rxns), 1).*0.1;\n\nfor initStep = 1:length(INITSteps)\n    disp(['ftINIT: Running step ' num2str(initStep)])\n    stp = INITSteps{initStep};\n    \n    if any ((rxnsToIgnoreLastStep - stp.RxnsToIgnoreMask) < 0)\n        dispEM('RxnsToIgnoreMask may not cover rxns not covered in previous steps, but the other way around is fine.');\n    end\n    rxnsToIgnoreLastStep = stp.RxnsToIgnoreMask;\n    \n    mm = prepData.minModel;\n    \n    if (~isempty(stp.MetsToIgnore))\n        if (~isempty(stp.MetsToIgnore.simpleMets))\n            %Here, we remove simple metabolites that will not really affect the milp but \n            %are very common in the S matrix. For example H2O, H+, etc.\n            %It is also possible to leave compartments untouched, for example the i compartment in the mitochondria (for H+).\n            metsToRem = ismember(mm.metNames,stp.MetsToIgnore.simpleMets.mets);\n            compsToKeep = find(ismember(mm.comps, stp.MetsToIgnore.simpleMets.compsToKeep));\n            metsToRem = metsToRem & ~ismember(mm.metComps, compsToKeep);\n            mm.S(metsToRem,:) = 0;\n        end    \n    end\n\n    %Set up the reaction scores and essential rxns\n    rxnsToIgnore = getRxnsFromPattern(stp.RxnsToIgnoreMask, prepData);\n    rxnScores = groupRxnScores(prepData.minModel, origRxnScores, prepData.refModel.rxns, prepData.groupIds, rxnsToIgnore);\n\n    essentialRxns = prepData.essentialRxns;\n    toRev = false(numel(mm.rxns),1);\n    %Handle the results from previous steps ('ignore', 'exclude', 'essential')\n    if strcmp(stp.HowToUsePrevResults, 'exclude')\n        rxnScores(rxnsTurnedOn) = 0; %This is not used anymore in any step setup.\n    elseif strcmp(stp.HowToUsePrevResults, 'essential')\n        %Make all reversible reactions turned on in previous steps reversible\n        %in the direction that they were previously carrying flux\n        \n        %first reverse the reactions that need to be reversed\n        rev = mm.rev == 1;\n        toRev = rxnsTurnedOn & rev & fluxes < 0;\n        mm = reverseRxns(mm, mm.rxns(toRev));\n        \n        %Then make them irreversible\n        mm.rev(rxnsTurnedOn) = 0;\n        mm.lb(rxnsTurnedOn) = 0;\n\n        essentialRxns = unique([prepData.essentialRxns;mm.rxns(rxnsTurnedOn)]);\n    end\n\n    \n    mipGap = 1;\n    first = true;\n    success = false;\n    fullMipRes = [];\n    for rn = 1:length(stp.MILPParams)\n        params = stp.MILPParams{rn};\n        if ~isfield(params, 'MIPGap')\n            params.MIPGap = 0.0004;\n        end\n        \n        if ~isfield(params, 'TimeLimit')\n            params.TimeLimit = 5000;\n        end\n        \n        if ~first \n            %There is sometimes a problem with that the objective function becomes close to zero,\n            %which leads to that a small percentage of that (which is the MIPGap sent in) is very small\n            %and the MILP hence takes a lot of time to finish. We also therefore use an absolute MIP gap, \n            %converted to a percentage using the last value of the objective function.\n            params.MIPGap = min(max(params.MIPGap, stp.AbsMIPGaps{rn}/abs(lastObjVal)),1);\n            params.seed = 1234;%use another seed, may work better\n\n            if mipGap <= params.MIPGap\n                success = true;\n                break; %we're done - this will not happen the first time\n            else\n                disp(['MipGap too high, trying with a different run. MipGap = ' num2str(mipGap) ' New MipGap Limit = ' num2str(params.MIPGap)])\n            end\n        end\n        \n        first = false;\n        \n        %now run the MILP\n        try\n            %The prodweight for metabolomics is currently set to 5 - 0.5 was default in the old version, which I deemed very small?\n            %There could be a need to specify this somewhere in the call at some point. \n            %This value has not been evaluated, but is assumed in the test cases - if changed, update the test case\n            startVals = [];\n            if ~isempty(fullMipRes)\n                startVals = fullMipRes.full;\n            end\n            [deletedRxnsInINIT1, metProduction,fullMipRes,rxnsTurnedOn1,fluxes1] = ftINITInternalAlg(mm,rxnScores,metData,essentialRxns,5,stp.AllowMetSecr,stp.PosRevOff,params, startVals, fluxes, verbose);\n            %This is a bit tricky - since we reversed some reactions, those fluxes also need to be reversed\n            fluxes1(toRev) = -fluxes1(toRev);\n            \n            mipGap = fullMipRes.mipgap;\n            lastObjVal = fullMipRes.obj;\n        catch e\n            mipGap = Inf;\n            lastObjVal = Inf; %we need to set something here, Inf leads to that this doesn't come into play\n        end\n        \n        success = mipGap <= params.MIPGap;\n    end\n    \n    if ~success\n        dispEM(['Failed to find good enough solution within the time frame. MIPGap: ' num2str(mipGap)]);\n    end\n    \n    %save the reactions turned on and their fluxes for the next step\n    rxnsTurnedOn = rxnsTurnedOn | rxnsTurnedOn1.';\n    %The fluxes are a bit tricky - what if they change direction between the steps?\n    %The fluxes are used to determine the direction in which reactions are forced on \n    %(to simplify the problem it is good if they are unidirectional).\n    %We use the following strategy:\n    %1. Use the fluxes from the most recent step.\n    %2. If any flux is very low there (i.e. basically zero), use the flux from the previous steps\n    %This could in theory cause problems, but seems to work well practically\n    fluxesOld = fluxes;\n    fluxes = fluxes1;\n    %make sure that all reactions that are on actually has a flux - otherwise\n    %things could go bad, since the flux will be set to essential in a random direction\n    %This sometimes happens for rxns with negative score - let's just accept that.\n    %if (sum(abs(fluxes1) < 10^-7 & rxnsTurnedOn))\n    %    dispEM('There are rxns turned on without flux - this might cause problems');\n    %end\n    %fluxes(abs(fluxes1) < 10^-7) = fluxesOld(abs(fluxes1) < 10^-9);\nend\n\n\n%get the essential rxns\nessential = ismember(prepData.minModel.rxns,prepData.essentialRxns);\n%So, we only add reactions where the linearly merged scores are zero for all linearly dependent reactions \n% (this cannot happen by chance, taken care of in the function groupRxnScores)\nrxnsToIgn = rxnScores == 0; \ndeletedRxnsInINITSel = ~(rxnsTurnedOn | rxnsToIgn | essential);\ndeletedRxnsInINIT = prepData.minModel.rxns(deletedRxnsInINITSel);\n\n%Here we need to figure out which original reactions (before the linear merge) \n%that were removed. These are all reactions with the same group ids as the removed reactions\ngroupIdsRemoved = prepData.groupIds(ismember(prepData.refModel.rxns, deletedRxnsInINIT)); %can improve this slightly, use sel above\ngroupIdsRemoved = groupIdsRemoved(groupIdsRemoved ~= 0);%zero means that the reaction was not grouped, all with zeros are not a group!\nrxnsToRem = union(prepData.refModel.rxns(ismember(prepData.groupIds,groupIdsRemoved)), deletedRxnsInINIT);%make a union here to include the ungrouped (unmerged) as well\n\ninitModel = removeReactions(prepData.refModel,rxnsToRem,false,true);\n\n% remove metabolites separately to avoid removing those needed for tasks\nunusedMets = initModel.mets(all(initModel.S == 0,2));\ninitModel = removeMets(initModel, setdiff(unusedMets, prepData.essentialMetsForTasks));\n\n%if printReport == true\n%    printScores(initModel,'INIT model statistics',hpaData,transcrData,tissue,celltype);\n%    printScores(removeReactions(cModel,setdiff(cModel.rxns,rxnsToRem),true,true),'Reactions deleted by INIT',hpaData,transcrData,tissue,celltype);\n%end\n\n%The full model has exchange reactions in it. ftINITFillGapsForAllTasks calls \n%ftINITFillGaps, which automatically removes exchange metabolites (because it \n%assumes that the reactions are constrained when appropriate). In this case the\n%uptakes/outputs are retrieved from the task sheet instead. To prevent\n%exchange reactions being used to fill gaps, they are deleted from the\n%reference model here.\ninitModel.id = 'INITModel';\n\n%If gaps in the model should be filled using a task list\nif ~isempty(prepData.taskStruct)\n    %Remove exchange reactions and reactions already included in the INIT\n    %model\n    %We changed strategy and instead include all rxns except the exchange rxns in the ref model\n    %But we do keep the exchange rxns that are essential.\n    %Let's test to remove all, that should work\n    \n    %At this stage the model is fully connected and most of the genes with\n    %good scores should have been included. The final gap-filling should\n    %take the scores of the genes into account, so that \"rather bad\"\n    %reactions are preferred to \"very bad\" reactions. However, reactions\n    %with positive scores will be included even if they are not connected\n    %in the current formulation. Therefore, such reactions will have to be\n    %assigned a small negative score instead.\n    exchRxns = getExchangeRxns(prepData.refModel);\n    refModelNoExc = removeReactions(prepData.refModelWithBM,exchRxns,true,true);\n    exchRxns = getExchangeRxns(initModel);\n    initModelNoExc = removeReactions(closeModel(initModel),exchRxns,true,true);\n    \n    if useScoresForTasks == true\n        %map the rxn scores to the model without exchange rxns\n        [~,ia,ib] = intersect(refModelNoExc.rxns,prepData.refModel.rxns);\n        rxnScores2nd = NaN(length(refModelNoExc.rxns),1);\n        rxnScores2nd(ia) = origRxnScores(ib);\n        %all(rxnScores2nd == refRxnScores);%should be the same, ok!\n        [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,min(rxnScores2nd,-0.1),prepData.taskStruct,paramsFT,verbose);\n    else\n        [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,[],prepData.taskStruct,paramsFT,verbose);\n    end\n    %if printReport == true\n    %    printScores(outModel,'Functional model statistics',hpaData,transcrData,tissue,celltype);\n    %    printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,transcrData,tissue,celltype);\n    %end\n    \n    addedRxnsForTasks = refModelNoExc.rxns(any(addedRxnMat,2));\nelse\n    outModel = initModel;\n    addedRxnMat = [];\n    addedRxnsForTasks = {};\nend\n\n% The model can now perform all the tasks defined in the task list.\nmodel = outModel;\n\n\n% At this stage the model will contain some exchange reactions but probably\n% not all (and maybe zero). This can be inconvenient, so all exchange\n% reactions from the reference model are added, except for those which\n% involve metabolites that are not in the model.\n\n%Start from the original model, and just remove the reactions that are no longer there (and keep exchange rxns). The model we got out\n%from the problem is not complete, it doesn't have GRPs etc.\n%The logic below is a bit complicated. We identify the reactions that should be removed from the full model as \n%reactions that have been removed in the init model except the ones that were added back. In addition, we make \n%sure that no exchange rxns are removed - they can be removed in the init model if they were linearly merged with other\n%reactions that were decided to be removed from the model. We want to keep all exchange rxns to make sure the tasks can\n%be performed also without manipulating the b vector in the model (which is what is done in the gap-filling).\nexchRxns = getExchangeRxns(prepData.refModel);\ndeletedRxnsInINIT = setdiff(prepData.refModel.rxns,union(union(initModel.rxns, addedRxnsForTasks), exchRxns));\noutModel = removeReactions(prepData.refModel, deletedRxnsInINIT, true); %we skip removing the genes for now, I'm not sure it is desirable\n\n% If requested, attempt to remove negative-score genes from the model, \n% depending on their role (isozyme or complex subunit) in each grRule.\n% See the \"removeLowScoreGenes\" function more more details, and to adjust\n% any default parameters therein.\nif ( removeGenes )\n    [~, geneScores] = scoreComplexModel(outModel,hpaData,transcrData,tissue,celltype);\n    outModel = removeLowScoreGenes(outModel,geneScores);\nend\n\n\nmodel = outModel;\n\nend\n\n%This is for printing a summary of a model\nfunction [rxnS, geneS] = printScores(model,name,hpaData,transcrData,tissue,celltype)\n    [a, b] = scoreComplexModel(model,hpaData,transcrData,tissue,celltype);\n    rxnS = mean(a);\n    geneS = mean(b,'omitnan');\n    fprintf([name ':\\n']);\n    fprintf(['\\t' num2str(numel(model.rxns)) ' reactions, ' num2str(numel(model.genes)) ' genes\\n']);\n    fprintf(['\\tMean reaction score: ' num2str(rxnS) '\\n']);\n    fprintf(['\\tMean gene score: ' num2str(geneS) '\\n']);\n    fprintf(['\\tReactions with positive scores: ' num2str(100*sum(a>0)/numel(a)) '%%\\n\\n']);\nend\n\nfunction rxnsToIgnore = getRxnsFromPattern(rxnsToIgnorePattern, prepData)\n    rxnsToIgnore = false(length(prepData.toIgnoreExch),1);\n    if rxnsToIgnorePattern(1) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreExch; end;\n    if rxnsToIgnorePattern(2) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreImportRxns; end;\n    if rxnsToIgnorePattern(3) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSimpleTransp; end;\n    if rxnsToIgnorePattern(4) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAdvTransp; end;\n    if rxnsToIgnorePattern(5) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSpont; end;\n    if rxnsToIgnorePattern(6) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreS; end;\n    if rxnsToIgnorePattern(7) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreCustomRxns; end;\n    if rxnsToIgnorePattern(8) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAllWithoutGPRs; end;\nend\n\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/INIT/ftINIT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.2117038749857707}}
{"text": "function [flat, allDist, sumDist, geodesicCoords, geodesicLayer] = measureCorticalDistance(flat, coords, verboseFlag, gray)\n% USAGE: measureCorticalDistance(flat, [coords], [verboseFlag], [gray])\n%   \n% AUTHOR:  Dougherty\n% DATE:    2002.01.15\n% PURPOSE:\n%   Compute the shortest cortical manifold distance between \n%   points. If coords is passed in, then the points are drawn\n%   from there. Otherwise, the points are obtained via ginput.\n%   (Note that coords must be a valid nx3 list of flat view coords,\n%   such as would be obtained by 'getCurROIcoords(flatView)'.)\n% \n% HISTORY\n%\n% 7/16/02 djh, replaced mrSESSION.vAnatomyPath with global vANATOMYPATH\n% 9/02/04 mms, inserted a warning not to use rotated flats.\n% 9/22/04 rfd, now returns the geodesic path (as coords) and the gray layer\n% of each point along the path.\n\nglobal vANATOMYPATH;\nmmPerPix = readVolAnatHeader(vANATOMYPATH);\n\n% Check some flat and volume stuff here when you\n% get a chance to fix this code up\n\n% Get a gray structure because we need the gray nodes.\nif notDefined('gray')\n    gray = getSelectedGray;\n    if isempty(gray)\n        gray=initHiddenGray;\n    end\nend\n\nif(~exist('coords','var') | isempty(coords))\n    % Select flat figure and get a single point from the user\n    figure(flat.ui.figNum)\n    disp('Click left to add points, right to quit');\n    button = 1;\n    count = 0;\n    w = 0.5;\n    coords = [];\n    z = viewGet(flat, 'Current Slice');\n    while(button~=3)\n        [x,y,button] = ginput(1);\n        if(button==3)\n            break;\n        end\n        count = count+1;\n        coords = [coords,round([y;x;z])];\n        h(count) = line([x-w,x-w,x+w,x+w,x-w],[y-w,y+w,y+w,y-w,y-w],'Color','w');\n        if flat.rotateImageDegrees(coords(3,1))>0  %detects if the Flat your are currently selecting the points ist rotated\n            errordlg('Flat must not be rotated','Warning!'); %Results would be wrong!\n        end\n    end\n    % Delete the temporarily drawn squares\n    for ii=1:length(h)\n        delete(h(ii));\n    end\n    clear h;\nend\nif(~exist('verboseFlag','var') || isempty(verboseFlag))\n    verboseFlag=1;\nend\n\n% the third coordinate is the 'slice', which, for flat views, means left or right hemisphere.\nslice = coords(3,1);\nif (slice==1)\n    nodes = gray.allLeftNodes;\n    edges = gray.allLeftEdges;\nelse\n    nodes = gray.allRightNodes;\n    edges = gray.allRightEdges;\nend\n\n% We loop for the number of line segements, which is the number of\n% coords - 1.\ngeodesic = [];\nfor(ii=1:size(coords,2)-1)\n    % get nearest flat coordinate (not all points on the flat correspond to flat coordinates)\n    flatDistances = (flat.coords{slice}(1,:) - coords(1,ii)).^2 + ...\n        (flat.coords{slice}(2,:) - coords(2,ii)).^2;\n    % There is a one-to-many mapping of flatCoords to grayCoords, but we ignore that\n    % here by using 'min', which will always reuturn one value, even if there are several\n    % identical minima. \n    % FIX THIS- we should always grab layer 1, or something more consistent\n    % than relying on min's arbitrary sort.\n    [val,startIndex] = min(flatDistances);\n    % Do it again, for ii+1, to find the end point of this line segment.\n    flatDistances = (flat.coords{slice}(1,:) - coords(1,ii+1)).^2 + ...\n        (flat.coords{slice}(2,:) - coords(2,ii+1)).^2;\n    [val,endIndex] = min(flatDistances);\n    \n    % Draw a line for each measured segment\n    % we use the actual gray node coords rather than the ROI coords, so the use can see if\n    % there is any non-trivial discrepancy.\n    h(ii) = line([flat.coords{slice}(2,startIndex),flat.coords{slice}(2,endIndex)], ...\n                 [flat.coords{slice}(1,startIndex),flat.coords{slice}(1,endIndex)], ...\n                 'Color', 'r', 'LineWidth', 2);\n    \n    % Extract the gray node corresponding to the start\n    startGrayNode = find(nodes(2,:) == flat.grayCoords{slice}(1,startIndex) & ...\n                         nodes(1,:) == flat.grayCoords{slice}(2,startIndex) & ...\n                         nodes(3,:) == flat.grayCoords{slice}(3,startIndex));\n    endGrayNode = find(nodes(2,:) == flat.grayCoords{slice}(1,endIndex) & ...\n                       nodes(1,:) == flat.grayCoords{slice}(2,endIndex) & ...\n                       nodes(3,:) == flat.grayCoords{slice}(3,endIndex));\n    \n    % Catch errors. If we give mrManDist an empty startPoint array, it barfs.\n    if(isempty(startGrayNode) | isempty(endGrayNode))\n        myErrorDlg('No gray nodes were found for these coords!');\n    end\n    \n    % Now, compute the manifold distance between these points.\n    % mrManDist returns the distance to all other points from the given 'start' point.\n    %allDist = mrManDist(nodes, edges, startGrayNode, mmPerPix, -1, 0);\n    [allDist,nPts,lastPoint] = mrManDist(nodes, edges, startGrayNode, ...\n                                      mmPerPix, -1,0);\n    nextPoint = endGrayNode;\n    while(nextPoint~=startGrayNode)\n      geodesic(end+1) = lastPoint(nextPoint);\n      nextPoint = lastPoint(nextPoint);\n    end\n\n    % We just want the distance from the start point to the end point, so we\n    % pull that out by providing the index of the end point.\n    dist(ii) = allDist(endGrayNode);\n    if(verboseFlag>=0)\n        disp(['Cortical distance of segment ',num2str(ii),': ',num2str(dist(ii)),' mm.']);  \n    end\nend\nsumDist=sum(dist);\nif(verboseFlag>=0)\n    disp(['Total cortical distance: ',num2str(sumDist),' mm.']);\nend\nif(verboseFlag>0)\n    uiwait(msgbox(['Total cortical distance: ',num2str(sumDist),' mm.'], ...\n        'Cortical Distance', 'modal'));\nend\n\nfor ii=1:length(h)\n    delete(h(ii))\nend\ngeodesicCoords = nodes([2,1,3],geodesic);\ngeodesicLayer =  nodes(6,geodesic);\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/SurfaceMeasurements/measureCorticalDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.21167826173958437}}
{"text": "function [At,b,c,K,prep,origcoeff] = pretransfo(At,b,c,K,pars)\n\n% [At,b,c,K,prep] = pretransfo(At,b,c,K)\n%\n% PRETRANSFO  Checks data and then transforms into internal SeDuMi format.\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% Nearly complete rewrite\n% Copyright (c) 2013 Michael C. Grant\n%\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\n% -------------------------------------------------------------------------\n% Make sure that all fields exist in K, and verify that they are valid\n% -------------------------------------------------------------------------\n\nif ~isfield(K,'f') || isempty(K.f)\n    K.f = 0;\nelseif numel(K.f) ~= 1 || K.f ~= floor(K.f) || K.f < 0 || ~isreal(K.f)\n    error('K.f should be nonnegative integer')\nend\nif ~isfield(K,'l') || isempty(K.l)\n    K.l = 0;\nelseif K.l ~= floor(K.l) || K.l < 0 || ~isreal(K.l)\n    error('K.l should be nonnegative integer')\nend\nif ~isfield(K,'q') || ~nnz(K.q)\n    K.q = zeros(1,0);\nelse\n    K.q = K.q(:)';\n    if any(K.q ~= floor(K.q)) || any(K.q<2) || ~isreal(K.q)\n        error('K.q should contain only integers bigger than 1')\n    end\nend\nif ~isfield(K,'r') || ~nnz(K.r)\n    K.r = zeros(1,0);\nelse\n    K.r = K.r(:)';\n    if any(K.r ~= floor(K.r)) || any(K.r<3) || ~isreal(K.r)\n        error('K.r should contain only integers bigger than 2')\n    end\nend\nif ~isfield(K,'s') || ~nnz(K.s)\n    K.s = zeros(1,0);\nelse\n    K.s = K.s(:)';\n    if any(K.s ~= floor(K.s)) || any(K.s<1) || ~isreal(K.s)\n        error('K.s should contain only positive integers')\n    end\nend\n% As an alternative to the 'scomplex' flag, I've added a 'z' parameter\n% containing a list of Hermitian semidefinite cone sizes. For now, this\n% is just translated to 'scomplex' for you. In the future, we may use\n% this internally *instead* of scomplex or rsdpN.\nif ~isfield(K,'z') || ~nnz(K.z)\n    K.z = zeros(1,0);\nelse\n    K.z = K.z(:)';\n    if any(K.z ~= floor(K.z)) || any(K.z<1) || ~isreal(K.z)\n        error('K.z should contain only positive integers')\n    end\nend\n\nN_f    = K.f;\nN_l    = K.l;\nN_fl   = N_f + N_l;\nL_q    = length(K.q);\nN_q    = sum(K.q);\nL_r    = length(K.r);\nN_r    = sum(K.r);\nN_qr   = N_q + N_r;\nL_qr   = L_q + L_r;\nL_s    = length(K.s);\nL_z    = length(K.z);\nL_sz   = L_s + L_z;\nN_s    = sum((K.s).^2);\nN_z    = sum((K.z).^2);\nN_sz   = N_s + N_z;\nL_qrsz = L_qr + L_sz;\nN_flqr = N_fl + N_qr;\nN      = N_flqr + N_sz;\n\nif ~isfield(K,'ycomplex') || isempty(K.ycomplex)\n    K.ycomplex = zeros(1,0);\nelse\n    K.ycomplex = sort(K.ycomplex(:))';\n    K.ycomplex(find(~diff(K.ycomplex))+1) = [];\n    if any(K.ycomplex ~= floor(K.ycomplex)) || any(K.ycomplex<1)\n        error('K.ycomplex should contain only positive integers');\n    elseif any(K.ycomplex > numel(b))\n        error('Elements of K.ycomplex are out of range');\n    end\nend\nif ~isfield(K,'xcomplex') || isempty(K.xcomplex)\n    K.xcomplex = zeros(1,0);\nelse\n    K.xcomplex = sort(K.xcomplex(:))';\n    K.xcomplex(find(~diff(K.xcomplex))+1) = [];\n    if any(K.xcomplex ~= floor(K.xcomplex)) || any(K.xcomplex<1)\n        error('K.xcomplex should contain only positive integers');\n    elseif any(K.xcomplex>N_flqr)\n        error('Elements of K.xcomplex are out of range');\n    end\nend\nif ~isfield(K,'scomplex') || isempty(K.scomplex)\n    K.scomplex = zeros(1,0);\nelse\n    K.scomplex = sort(K.scomplex(:))';\n    K.scomplex(find(~diff(K.scomplex))+1) = [];\n    if any(K.scomplex~=floor(K.scomplex)) || any(K.scomplex<1)\n        error('K.scomplex should contain only positive integers');\n    elseif any(K.scomplex>L_s)\n        error('Elements of K.xcomplex are out of range');\n    end\nend\nif L_z\n    K.s = [ K.s, K.z ];\n    K.scomplex = [ K.scomplex, L_s + 1 : L_sz ];\n    K.z = zeros(1,0);\n    L_s = L_s + L_z;\n    N_s = N_s + N_z;\n    L_z = 0; %#ok\n    N_z = 0; %#ok\nend\n\n% -------------------------------------------------------------------------\n% Verify the size and validity of At, b, and c\n% N = # variables\n% -------------------------------------------------------------------------\n\n% SeDuMi assumes that if At is not consistent with K but At' is, that the\n% user supplied the transpose of the coefficient matrix. This introduces a\n% rare ambiguity in the case where At happens to be square. Past versions \n% of SeDuMi would not have allowed this, instead rejecting the case where\n% m >= N; however, with complex variables, the situation is not quite as\n% clear, and there may technically be cases where m >= N is acceptable.\n\nif ndims(At) > 2 %#ok\n    error('A must be a matrix');\nelseif nnz(isnan(At)) || nnz(isinf(At))\n    error('A contains NaN or Inf');\nelseif size(At,1) == N\n    % nothing\nelseif size(At,2) == N\n    At = At';\nelse\n    error('(At,K) size mismatch');\nend\nif all(size(b)>1)\n    error('Parameter b must be a vector');\nelseif any(isnan(b)) || any(isinf(b))\n    error('b contains NaN or Inf');\nelseif length(b) ~= size(At,2)\n    error('(At,b) size mismatch');\nelse\n    b = b(:);\nend\nif all(size(c)>1)\n    error('Parameter c must be a vector');\nelseif any(isnan(c)) || any(isinf(c))\n    error('c contains NaN or Inf');\nelseif length(c) ~= N\n    error('(c,K) size mismatch');\nelse\n    c = c(:);\nend\n\n% -------------------------------------------------------------------------\n% Save the standardized data for further use if needed\n% -------------------------------------------------------------------------\n\nif isfield(pars,'errors') && pars.errors==1\n    origcoeff.At=At;\n    origcoeff.c=c;\n    origcoeff.b=b;\n    origcoeff.K=K;\nelse\n    origcoeff=[];\nend\n\n% -------------------------------------------------------------------------\n% Flag diagonal SDP blocks for removal\n% -------------------------------------------------------------------------\n\n% There is some serious MATLAB trickery here (if I do say so myself) that\n% merits explanation. \"spattern\" contains the indices of symbolically \n% nonzero elements of the dual variable z = c - At * y. This is a single\n% vector across all LMI constraints, so \"sblk\" tells us which indices \n% belong to which constraints. The \"rem\" statement is what determines if\n% a particular element is off-diagonal. If there is even one off-diagonal\n% element in an SDP, then its corresponding element of \"sdiag\" is false.\n%\n% This new version of the analysis replaces the old preprocessSDP(), and\n% seems inexpensive enough to apply to all LMIs regardless of size/count.\n% The previous version was applied more sparingly.\n%\n% In theory one could do a more complex analysis of the block structure of\n% an LMI, potentially breaking a larger into smaller ones. But this would\n% likely be significantly more expensive.\n\nif L_s && ( ~isfield(pars,'sdp') || pars.sdp )\n    ssiz        = (K.s).^2;\n    strt        = cumsum([1,ssiz(1:end-1)]);\n    sblk        = zeros(1,N_s);\n    sblk(strt)  = 1;\n    sblk        = cumsum(sblk);\n    spattern    = find(c(N_flqr+1:N)~=0|any(At(N_flqr+1:N,:),2))';\n    sblk        = sblk(spattern);\n    sblk        = sblk(rem(spattern-strt(sblk),K.s(sblk)+1)~=0);\n    sdiag       = true(1,L_s);\n    sdiag(sblk) = false;\nelse\n    % Even if we disable SDP processing, we're going to move 1x1 SDPs into\n    % the nonnegative variable block. It just doesn't make sense to deploy\n    % all of that SDP machinery for nonnegative variables.\n    sdiag = K.s == 1;\nend\n\n% -------------------------------------------------------------------------\n% Handle K.ycomplex by splitting apart the complex constraints into pairs\n% of real constraints\n% -------------------------------------------------------------------------\n\nif ~isempty(K.ycomplex)\n    b  = [ real(b) ; imag(b(K.ycomplex)) ];\n    At = [ At, 1j * At(:,K.ycomplex) ];\nelse\n    b  = real(b);\nend\n\n% -------------------------------------------------------------------------\n% Find the locations of the the complex data, so we can convert into\n% SeDuMi's internal format, which uses only MATLAB's real representation.\n% -------------------------------------------------------------------------\n% Strictly speaking, nonnegative variables, the first variable in a Lorentz \n% cone, and the first two variables in a rotated Lorentz cone are real. But\n% But SeDuMi has allowed them all to be specified as complex; the imaginary\n% portions are interpreted as free variables. We have kept that behavior.\n\n% This code replaces whichcpx.c in its entirety. It actually fixes a bug in\n% rotated Lorentz cone handling that was probably never exercised.\nif isempty(K.xcomplex) && isempty(K.scomplex)\n    K.fcplx = zeros(1,0);\n    K.qcplx = zeros(1,0);\n    K.rcplx = zeros(1,0);\n    scplx   = false(1,L_s);\n    sreal   = ~sdiag;\n    K.rsdpN = L_s;\n    N_fc = 0;\n    K.cdim = 0;\nelse\n    xc = K.xcomplex;\n    tt = xc <= N_fl;\n    K.fcplx = xc(tt);\n    xc = xc(~tt) -  N_fl;\n    tt = xc <= N_q;\n    K.qcplx = xc(tt);\n    xc = xc(~tt) - N_q;\n    tt = xc <= N_r;\n    K.rcplx = xc(tt);\n    if ~isempty(K.qcplx)\n        ndxs = cumsum([1,K.q(1:end-1)]);\n        t2 = any(bsxfun(@eq,K.qcplx,ndxs'),1);\n        K.fcplx = [ K.fcplx, K.qcplx(t2) + N_fl ];\n        K.qcplx(t2) = [];\n        t2 = sum(bsxfun(@gt,K.qcplx,ndxs'),1);\n        K.q = K.q + full(sparse(1,t2,1,1,L_q));\n        K.qcplx = K.qcplx + (1:length(K.qcplx));\n        N_q = N_q + length(K.qcplx);\n    end\n    if ~isempty(K.rcplx)\n        ndxs = cumsum([1,K.r(1:end-1)]);\n        t2 = any(bsxfun(@eq,K.rcplx,[ndxs,ndxs+1]'),1);\n        K.fcplx = [ K.fcplx, K.rcplx(t2) + N_fl + N_q ];\n        K.rcplx(t2) = [];\n        t2 = sum(bsxfun(@gt,K.rcplx,ndxs'),1);\n        K.r = K.r + full(sparse(1,t2,1,1,L_r));\n        % This 2*t2 offset is required because QR makes two accesses\n        % each of the first two elements of a rotated Lorentz cone.\n        K.rcplx = K.rcplx + (1:length(K.rcplx)) + 2 * t2;\n        N_r = N_r + length(K.rcplx);\n    end\n    N_fc = length(K.fcplx);\n    N_f  = N_f + N_fc;\n    scplx = false(1,L_s);\n    scplx(K.scomplex&~sdiag) = true;\n    sreal = ~scplx & ~sdiag;\n    K.rsdpN = nnz(sreal);\n    K.cdim = length(K.xcomplex) + sum(K.s(scplx).^2);\nend\n\n% -------------------------------------------------------------------------\n% We have significantly rewritten this section of the code. This section\n% constructs a sparse matrix that represents the following transformations:\n%   --- Free variables split into differences of nonnegative variables; OR\n%   --- Free variables placed in a Lorentz-cone\n%   --- Rotated lorentz cones translated to standard Lorentz cones\n%   --- Lorentz cones rearranged to trace block + norm-bound blocks\n%   --- Conversion of diagonal SDPs to nonnegative variables\n%   --- SDP coefficients moved to the lower triangle for increased sparsity\n% This code replaces the rotlorenz, qreshape, and vectril MEX files.\n% -------------------------------------------------------------------------\n\nnewL = 0;\nnewQ = zeros(1,0);\nii = {}; jj = {}; vv = {};\n\n% Split free variables into the difference of nonnegatives\nif ~isfield( pars, 'free' ) || pars.free == 2 && L_qrsz\n    pars.free = 1;\nend\nif N_f && ~pars.free\n    jt = [ 1 : K.f, K.fcplx ; 1 : K.f, K.fcplx ];\n    vt = [ ones(1,K.f), -1j*ones(1,N_fc) ; -ones(1,K.f), 1j*ones(1,N_fc) ];\n    ii{end+1} = 1 : 2 * N_f;\n    jj{end+1} = jt(:)';\n    vv{end+1} = vt(:)';\n    newL = 2 * N_f;\n    prep.freeL = N_f;\nend\n\n% Copy nonnegative variables without change\nif K.l\n    ii{end+1} = newL + 1 : newL + K.l;\n    jj{end+1} = K.f + 1 : K.f + K.l;\n    vv{end+1} = ones(1,K.l);\n    newL = newL + K.l;\nend\n\n% Convert diagonal SDPs to nonnegative variables\nif any(sdiag)\n    dsize = K.s(sdiag);\n    sdpL = sum(dsize);\n    prep.sdiag = dsize;\n    jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n    jstrt = jstrt(sdiag);\n    istrt = cumsum([1,dsize(1:end-1)]);\n    dsize = dsize + 1;\n    dblks = cumsum(full(sparse(1,istrt,1,1,sdpL)));\n    ii{end+1} = newL + 1 : newL + sdpL;\n    jj{end+1} = jstrt(dblks) + dsize(dblks) .* ( ( 1 : sdpL ) - istrt(dblks) );\n    vv{end+1} = ones(1,sdpL);\n    newL = newL + sdpL;\nend\n\n% Stuff free variables into a Lorentz cone\ntr_off = newL;\nnb_off = newL + L_qr;\nif N_f && pars.free\n    tr_off = tr_off + 1;\n    nb_off = nb_off + 1;\n    ii{end+1} = nb_off + 1 : nb_off + N_f;\n    jj{end+1} = [ 1 : K.f, K.fcplx ];\n    vv{end+1} = [ ones(1,K.f), -1j*ones(1,N_fc) ];\n    nb_off = nb_off + K.f;\n    newQ = N_f + 1;\nend\n\n% Rearrange Lorentz cones to trace block + norm-bound blocks\nif N_q\n    ndxs      = cumsum([1,K.q(1:end-1)]);\n    it        = zeros(1,N_q);\n    it(ndxs)  = tr_off + 1 : tr_off + L_q;\n    it(it==0) = nb_off + 1 : nb_off + ( N_q - L_q );\n    jt = K.f + K.l + 1 : K.f + K.l + N_q;\n    vt = ones(1,N_q);\n    if ~isempty(K.qcplx)\n        jt = jt - cumsum(full(sparse(1,K.qcplx,1,1,N_q)));\n        vt(K.qcplx) = -1j;\n    end\n    ii{end+1} = it(:)';\n    jj{end+1} = jt;\n    vv{end+1} = vt;\n    tr_off    = tr_off + L_q;\n    nb_off    = nb_off + N_q - L_q;\nend\n\n% Transform rotated Lorentz cones to standard Lorentz cones, and rearrange\n% to trace block + norm-bound blocks.\nif N_r\n    ndxr       = cumsum([1,K.r(1:end-1)]);\n    ndxp       = ndxr + 2*(0:L_r-1); \n    it         = zeros(1,N_r+2*L_r);\n    it(ndxp)   = tr_off + 1 : tr_off + L_r;\n    it(ndxp+1) = -1;\n    it(ndxp+2) = it(ndxp);\n    it(it==0)  = nb_off + 1 : nb_off + ( N_r - L_r );\n    it(ndxp+1) = it(ndxp+3);\n    jt = [ K.f + K.l + N_q + 1, ones(1,N_r+2*L_r-1) ];\n    jt([ndxp+1,ndxp+3]) = 0;\n    vt = ones(1,N_r+2*L_r);\n    vt([ndxp,ndxp+1,ndxp+2]) = sqrt(0.5);\n    vt(ndxp+3) = -sqrt(0.5);\n    if ~isempty(K.rcplx)\n        jt(K.rcplx) = 0;\n        vt(K.rcplx) = -1j;\n    end\n    ii{end+1} = it;\n    jj{end+1} = cumsum(jt);\n    vv{end+1} = vt;\n    nb_off = nb_off + N_r - L_r;\nend\n\n% Replace non-diagonal real SDP coefficients with tril(X) + tril(X',-1).\n% This cuts the number of nonzeros approximately in half.\nif K.rsdpN\n    dsize = K.s(sreal);\n    sdpL  = sum(dsize.^2);\n    jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n    jstrt = jstrt(sreal);\n    istrt = cumsum([1,dsize(1:end-1).^2]);\n    dblks = cumsum(full(sparse(1,istrt,1,1,sdpL)));\n    istrt = istrt + nb_off;\n    dsize = dsize(dblks);\n    istrt = istrt(dblks);\n    jndxs = ( nb_off + 1 : nb_off + sdpL ) - istrt;\n    cols  = floor(jndxs ./ dsize);\n    rows  = jndxs - dsize .* cols;\n    ii{end+1} = max(rows,cols) + min(rows,cols) .* dsize + istrt;\n    jj{end+1} = jndxs + jstrt(dblks);\n    vv{end+1} = ones(1,sdpL);\n    nb_off = nb_off + sdpL;\n    clear dsize jstrt istrt dblks jndxs rows cols\nend\n\n% Replace Hermitian SDP coefficients with tril(X) + tril(X',-1). This one's\n% a bit trickier because we have the real and complex values interleaved, \n% and the imaginary values along the diagonal are zero.\nif K.rsdpN < length(K.s)\n    dsize = K.s(scplx);\n    jsize = dsize .^ 2;\n    sdpL  = 2 * sum(jsize);\n    jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n    jstrt = jstrt(scplx);\n    bstrt = cumsum([1,2*jsize(1:end-1)]);\n    dblks = cumsum(full(sparse(1,bstrt,1,1,sdpL)));\n    istrt = bstrt + nb_off;\n    dsize = dsize(dblks);\n    istrt = istrt(dblks);\n    bndxs = ( nb_off + 1 : nb_off + sdpL ) - istrt;\n    cols  = floor( bndxs ./ dsize );\n    rows  = bndxs - dsize .* cols;\n    imgv  = cols >= dsize;\n    cols  = cols - imgv .* dsize;\n    indxs = max(rows,cols) + min(rows,cols) .* dsize + imgv .* jsize(dblks) + istrt;\n    vals  = ( 1 - 2 * ( cols > rows ) ) .* ( 1 - ( 1 + 1j ) .* imgv );\n    keep  = ~imgv | ( rows ~= cols );\n    jndxs = rows + cols .* dsize + jstrt(dblks);\n    ii{end+1} = indxs(keep);\n    jj{end+1} = jndxs(keep);\n    vv{end+1} = vals(keep);\n    clear dsize jsize jstrt bstrt istrt bndxs rows cols vals imgv keep\nend\n\n% Update free, nonnegative, and Lorentz variable counts\nK.f = 0;\nK.l = newL;\nK.q = [ newQ, K.q, K.r ];\nK.r = zeros(0,1);\nK.s = [ K.s(:,~scplx&~sdiag), K.s(scplx&~sdiag) ];\nK.rsdpN = nnz(~scplx&~sdiag);\nK.N = K.l + sum(K.q) + sum(K.s(1:K.rsdpN).^2)+2*sum(K.s(K.rsdpN+1:end).^2);\n\n% Create the artificial (x0,z0) variable for the self-dual model by\n% appending a zero row to At and c. This is accomplished in QR by adding\n% 1 to all of the row indices created above.\nK.N  = K.N + 1;\nK.l  = K.l + 1;\nK.m  = length(b);\n\n% Transform At, c\n% The transformation matrix QR does not satisfy QR'*QR=I. But it does, in \n% fact, serve as a reverse transformation:\n%    --- For Lorentz cones, QR applies a permutation; QR' reverses it.\n%    --- For rotated Lorentz cones, QR applies a unitary, self-adjoint\n%        rotation on the first two variables, so QR' reverses it.\n%    --- For split free variables, QR creates the positive and negative\n%        parts; QR' combines them back together.\n%    --- For free variables placed in a Lorentz cone, QR moves them to the\n%        Lorentz cone block, adding an extra epigraph variable. QR' moves\n%        them back and drops the extra variable.\n%    --- For semidefinte cones, QR adds the strict upper triangle to the\n%        strict lower triangle; QR' copies the strict lower triangle to the\n%        strict upper triangle, ensuring symmetry.\n%    --- QR adds a row for the self-dual variable; QR' removes it.\n[dummy,ndxs] = sort(cellfun(@(x) x(1),jj)); %#ok\nQR = sparse( horzcat(ii{ndxs})+1, horzcat(jj{ndxs}), horzcat(vv{ndxs}), K.N, length(c) );\nAt = real( sparse( QR * At ) );\nc  = real( sparse( QR * c  ) );\nb  = sparse( b );\nprep.QR = QR;\nclear ii jj vv\n\n% -------------------------------------------------------------------------\n% Now K has field K.{l,q,s}\n% Generate a more detailed description of cone K:\n% Let K.blkstart(i):K.blkstart(i+1)-1 give the index range of block i.\n% Compute maxN=max(order), len=sum(order) for LORENTZ, real PSD, herm PSD\n% yields: K.{l,q,s,rsdpN,blkstart,rLen,hLen,qMaxn,rMaxn,hMaxn}\n% -------------------------------------------------------------------------\nKsr = K.s(1:K.rsdpN);\nKsc = K.s(K.rsdpN+1:end);\nK.blkstart = cumsum([K.l+1,length(K.q)+length(K.r),K.q-1,Ksr.^2,2*Ksc.^2]);\nK.rLen = sum(Ksr);\nK.hLen = sum(Ksc);\nK.qMaxn = max([0,K.q]);\nK.rMaxn = max([0,Ksr]);\nK.hMaxn = max([0,Ksc]);\nK.mainblks = K.blkstart(cumsum([1 1 length(K.q)]));\nK.qblkstart = K.blkstart(2:2+length(K.q));  % Also include blkend\nK.sblkstart = K.blkstart(2+length(K.q):end);\nK.lq = K.mainblks(end)-1;\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/pretransfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.2116256390724574}}
{"text": "function data = loadSUN3Dv2(sequenceName, frameIDs)\n\nif ~exist('sequenceName','var')\n    sequenceName = '2014-04-29_14-39-49_094959634447';\nend\n\n\nSUN3Dpath = '/n/fs/sun3d/sun3dv2/';\n\n%{\nfileID = fopen(fullfile(SUN3Dpath,sequenceName,'image/time.dat'));\nimageTimestamp = fread(fileID,'int64');\nfclose(fileID);\ndata.image = VideoReader(fullfile(SUN3Dpath,sequenceName,'image/image.mp4'));  \n%}\n\nimageFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'image/'),'jpg');\nimageFrameID = zeros(1,length(imageFiles));\nimageTimestamp = zeros(1,length(imageFiles));\nfor i=1:length(imageFiles)\n    id_time = sscanf(imageFiles(i).name, '%d-%ld.jpg');\n    imageFrameID(i) = id_time(1);\n    imageTimestamp(i) = id_time(2);\n    \n    data.imageAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'image',imageFiles(i).name));\nend\n\n\ndepthFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'depth/'),'tif');\nirFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'ir/'),'tif');\n\ndepthFrameID = zeros(1,length(depthFiles));\ndepthTimestamp = zeros(1,length(depthFiles));\nfor i=1:length(depthFiles)\n    id_time = sscanf(depthFiles(i).name, '%d-%ld.tif');\n    depthFrameID(i) = id_time(1);\n    depthTimestamp(i) = id_time(2);\n    \n    data.depthAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'depth',depthFiles(i).name));\nend\n\nirFrameID = zeros(1,length(irFiles));\nirTimestamp = zeros(1,length(irFiles));\nfor i=1:length(irFiles)\n    id_time = sscanf(irFiles(i).name, '%d-%ld.tif');\n    irFrameID(i) = id_time(1);\n    irTimestamp(i) = id_time(2);\n    \n    data.irAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'ir',irFiles(i).name));\nend\n\ndata.imageTimestamp = imageTimestamp;\ndata.depthTimestamp = depthTimestamp;\n\ndata.imageTotalFrames = length(data.imageTimestamp);\ndata.depthTotalFrames = length(data.depthTimestamp);\n\n% synchronize: find a depth for each image\nframeCount = length(imageTimestamp);\nIDimage2depth = zeros(1,frameCount);\nfor i=1:frameCount\n    [~, IDimage2depth(i)]=min(abs(double(depthTimestamp)-double(imageTimestamp(i))));\nend\n\nif ~exist('frameIDs','var') || isempty(frameIDs)\n    frameIDs = 1:frameCount;\nend\n\ndata.sequenceName = sequenceName;\n\ncnt = 0;\nfor frameID=frameIDs\n    cnt = cnt + 1;\n    data.depth{cnt} = fullfile(fullfile(SUN3Dpath,sequenceName,'depth',depthFiles(IDimage2depth(frameID)).name));\n    data.ir{cnt} = fullfile(fullfile(SUN3Dpath,sequenceName,'ir',irFiles(IDimage2depth(frameID)).name));\nend\n\n\nkinectID = strsplit(sequenceName,'_');\nkinectID = kinectID{end};\n\ndata.camera = load(fullfile(SUN3Dpath,'intrinsics',[kinectID '.mat']));\n\n\nend\n\n\nfunction files = dirSmart(page, tag)\n    [files, status] = urldir(page, tag);\n    if status == 0\n        files = dir(fullfile(page, ['*.' tag]));\n    end\nend\n\nfunction [files, status] = urldir(page, tag)\n    if nargin == 1\n        tag = '/';\n    else\n        tag = lower(tag);\n        if strcmp(tag, 'dir')\n            tag = '/';\n        end\n        if strcmp(tag, 'img')\n            tag = 'jpg';\n        end\n    end\n    nl = length(tag);\n    nfiles = 0;\n    files = [];\n\n    % Read page\n    page = strrep(page, '\\', '/');\n    [webpage, status] = urlread(page);\n\n    if status\n        % Parse page\n        j1 = findstr(lower(webpage), '<a href=\"');\n        j2 = findstr(lower(webpage), '</a>');\n        Nelements = length(j1);\n        if Nelements>0\n            for f = 1:Nelements\n                % get HREF element\n                chain = webpage(j1(f):j2(f));\n                jc = findstr(lower(chain), '\">');\n                chain = deblank(chain(10:jc(1)-1));\n\n                % check if it is the right type\n                if length(chain)>length(tag)-1\n                    if strcmp(chain(end-nl+1:end), tag)\n                        nfiles = nfiles+1;\n                        chain = strrep(chain, '%20', ' '); % replace space character\n                        files(nfiles).name = chain;\n                        files(nfiles).bytes = 1;\n                    end\n                end\n            end\n        end\n    end\nend\n\nfunction XYZcamera = depth2XYZcamera(K, depth)\n    sz = size(depth);\n    [x,y] = meshgrid(1:sz(2), 1:sz(1));\n    XYZcamera(:,:,1) = (x-K(1,3)).*depth/K(1,1);\n    XYZcamera(:,:,2) = (y-K(2,3)).*depth/K(2,2);\n    XYZcamera(:,:,3) = depth;\n    XYZcamera(:,:,4) = depth~=0;\nend\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/loadSUN3Dv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21161839252759074}}
{"text": "\n% See also: hsvargplvm_init\n\nfunction [options, optionsDyn] = hsvargplvmOptions(globalOpt, timeStampsTraining, labelsTrain)\n\nif nargin < 2\n    timeStampsTraining = [];\nend\n\nif nargin < 3\n    labelsTrain = [];\nend\n\n%-- One options structure where there are some parts shared for all\n% models/layers and some parts specific for a few layers / submodels.\n\n\noptions = vargplvmOptions('dtcvar');\n\n% Taken from globalOpt\noptions.H = globalOpt.H;\noptions.baseKern = globalOpt.baseKern;\noptions.Q = globalOpt.Q;\noptions.K = globalOpt.K;\noptions.enableDgtN = globalOpt.DgtN;\noptions.initial_X = globalOpt.initial_X;\noptions.initX = globalOpt.initX;\noptions.multOutput = globalOpt.multOutput;\nif options.multOutput > 2\n    warning('Multoutput > 2 has wrong derivatives!!')\nend\n% \noptions.optimiser = 'scg2';\n\n\n\n% !!!!! Be careful to use the same type of scaling and bias for all models!!!\n% scale = std(Ytr);\n% scale(find(scale==0)) = 1;\n%options.scaleVal = mean(std(Ytr));\n% options.scaleVal = sqrt(var(Ytr{i}(:))); %%% ??\noptions.scale2var1 = globalOpt.scale2var1;\n\noptions.fixInducing = globalOpt.fixInducing;\n\n%----- Parent prior (we call priors \"dynamics\", but it can actually be some\n% other type of prior, eg labels etc.). \n% The relevant fields of globalOpt are coming from the svargplvm_init\n% (called within hsvargplvm_init).\nif isempty(globalOpt.dynamicsConstrainType) || nargout < 2\n    optionsDyn = [];\nelse\n    if ~isempty(labelsTrain)\n        optionsDyn.labelsTrain = labelsTrain;\n    end\n    % This does not mean it needs time inputs, it's just saying that it'll\n    % use the kernel types and reparametrization used in VGPDS (regressive\n    % \"dynamics\" etc).\n    optionsDyn.type = 'vargpTime';\n    optionsDyn.inverseWidth=30;\n    optionsDyn.vardistCovars = globalOpt.vardistCovarsMult;\n    if iscell(globalOpt.initX)\n        optionsDyn.initX = globalOpt.initX{end};\n    else\n        optionsDyn.initX = globalOpt.initX;\n    end\n    optionsDyn.constrainType = globalOpt.dynamicsConstrainType;\n    if ~isempty(timeStampsTraining)\n        optionsDyn.t = timeStampsTraining;\n    end\n    optionsDyn.kern = globalOpt.dynamicKern;\n    optionsDyn.initCovarMedian = globalOpt.dynamicsInitCovarMedian;\n    optionsDyn.initCovarMedianLowest = globalOpt.initCovarMedianLowest;\n    optionsDyn.initCovarMedianHighest = globalOpt.initCovarMedianHighest;\nend\n\n\n", "meta": {"author": "SheffieldML", "repo": "deepGP", "sha": "f72410a0fb354451f2bf58cfe247d2b5d3b08e58", "save_path": "github-repos/MATLAB/SheffieldML-deepGP", "path": "github-repos/MATLAB/SheffieldML-deepGP/deepGP-f72410a0fb354451f2bf58cfe247d2b5d3b08e58/deepGP/matlab/hsvargplvmOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21161838646710238}}
{"text": "function deep_attention_test()\nclose all;\nclc;\n% clear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(mfilename('fullpath')), 'startup'));\nopts.vocal = true;\n\n%% -------------------- CONFIG --------------------\nopts.dataset{1} = 'pascal';\n%opts.dataset{2} = 'DUT';\n%opts.dataset{3} = 'MIT300';\n%opts.dataset{4} = 'MIT1003';\n%opts.dataset{5} = 'Toronto';\nopts.caffe_version          = 'caffe_faster_rcnn';\nopts.gpu_id                 = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\nopts.use_gpu                = true;\n\nattention_model_dir              = fullfile(pwd, 'models'); %% VGG\nattention_model                  = load_model(attention_model_dir);\n\nattention_net = caffe.Net(attention_model.attention_net_def, 'test');\nattention_net.copy_from(attention_model.attention_net);\n%attention_net.params('final_attention_pred',1).get_data()\n% if opts.use_gpu\n%     attention_model.image_means = gpuArray(attention_model.image_means);\n% end\n\n% set gpu/cpu\nif opts.use_gpu\n    caffe.set_mode_gpu();\nelse\n    caffe.set_mode_cpu();\nend\n\nfor kk = 1:length(opts.dataset)\n    opts.attention_dir = fullfile(pwd, 'datasets', 'result', opts.dataset{kk});\n    mkdir_if_missing(opts.attention_dir);\n                \n    files=dir(['datasets/' opts.dataset{kk} '/*.jpg']);\n    files=struct2cell(files)' ;    \n    image_names=files(:,1);\n       \n    for imnum = 1:length(image_names)\n        imnum\n        image = imread(['datasets/' opts.dataset{kk} '/' image_names{imnum}]);\n        [w,h,c] = size(image);\n%       if opts.use_gpu\n%           im = gpuArray(image);\n%       end\n        [~, ~, ~, final_attentionmap] = fixationmap_detect(attention_model.conf, attention_net, image);\n        final_attentionmap  = imresize(final_attentionmap,[w,h]);\n        imwrite(final_attentionmap,[opts.attention_dir '/'  image_names{imnum}(1:end-4) '.jpg']);\n    end\nend\ncaffe.reset_all(); \nclear mex;\n\nend\n\nfunction model = load_model(model_dir)\n    ld             = load(fullfile(model_dir, 'model'));\n    model = ld.attention_model;\n    clear ld;\n    %% load attention model\n    model.attention_net_def ...\n                                = fullfile(model_dir, model.attention_net_def);\n    model.attention_net ...\n                                = fullfile(model_dir, model.attention_net);                                               \nend\n", "meta": {"author": "wenguanwang", "repo": "deepattention", "sha": "d66e2db4a9dc0ec5ebc4eb275e3199f9a59f6752", "save_path": "github-repos/MATLAB/wenguanwang-deepattention", "path": "github-repos/MATLAB/wenguanwang-deepattention/deepattention-d66e2db4a9dc0ec5ebc4eb275e3199f9a59f6752/deep_attention_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21146296831786504}}
{"text": "function imo = cnn_get_im_flow_batch2(images, varargin)\n\nopts.subTractFlow = 'off';\nopts.nFramesPerVid = 1;\nopts.numAugments = 1;\nopts.frameSample = 'uniformly';\nopts.flowDir = '';\nopts.imageDir = '';\nopts.temporalStride = 0;\n\nopts.imageSize = [227, 227] ;\nopts.border = [29, 29] ;\nopts.averageImage = [] ;\nopts.rgbVariance = [] ;\nopts.augmentation = 'croponly' ;\nopts.interpolation = 'bilinear' ;\nopts.numAugments = 1 ;\nopts.numThreads = 0 ;\nopts.prefetch = false ;\nopts.keepAspect = true;\nopts.flowScales = [];\nopts.cheapResize = 0;\nopts.nFrameStack = 10;\nopts.frameList = NaN;\nopts.nFrames = [];\nopts.subMedian = false;\nopts.stretchAspect = 4/3 ;\nopts.stretchScale = 1.2 ;\nopts.fetchGPU = true ; \n[opts, varargin] = vl_argparse(opts, varargin);\n\nflowDir = opts.flowDir;\nimgDir = opts.imageDir;\n% prefetch is used to load images in a separate thread\nprefetch = opts.prefetch & isempty(opts.frameList);\nfetchOpts= {'numThreads', opts.numThreads};\nif opts.fetchGPU\n  fetchOpts{end+1} = 'Gpu' ;\nend\n\nswitch opts.augmentation\n  case 'croponly'\n    tfs = [.5 ; .5 ; 0 ];\n  case 'f5'\n    tfs = [...\n      .5 0 0 1 1 .5 0 0 1 1 ;\n      .5 0 1 0 1 .5 0 1 0 1 ;\n       0 0 0 0 0  1 1 1 1 1] ;\n  case 'f25'\n    [tx,ty] = meshgrid(linspace(0,1,5)) ;\n    tfs = [tx(:)' ; ty(:)' ; zeros(1,numel(tx))] ;\n    tfs_ = tfs ;\n    tfs_(3,:) = 1 ;\n    tfs = [tfs,tfs_] ;\n  case 'f25noCtr'\n    [tx1,ty1] = meshgrid(linspace(.75,1,20)) ;\n    [tx2,ty2] = meshgrid(linspace(0,.25,20)) ;\n    tx = [tx1 tx2];     ty = [ty1 ty2];\n    tfs = [tx(:)' ; ty(:)' ; zeros(1,numel(tx))] ;\n    tfs_ = tfs ;\n    tfs_(3,:) = 1 ;\n    tfs = [tfs,tfs_] ;       \nend\n\nnStack = opts.imageSize(3);\n\nif iscell(opts.frameList)\n  im = vl_imreadjpeg(opts.frameList{1}, fetchOpts{:}) ; \n  sampled_frame_nr = opts.frameList{2};\nelse\n  sampleFrameLeftRight = floor(nStack/4); % divide by 4 because of left,right,u,v\n  frameOffsets = [-sampleFrameLeftRight:sampleFrameLeftRight-1]';\n\n  frames = cell(numel(images), nStack, opts.nFramesPerVid);\n  frames_rgb = cell(numel(images), 1, opts.nFramesPerVid);\n\n  sampled_frame_nr = cell(numel(images),1);\n\n  for i=1:numel(images)\n    vid_name = images{i};\n    nFrames = opts.nFrames(i);\n\n    if  strcmp(opts.frameSample, 'uniformly')\n      sampleRate = max(floor((nFrames-nStack/2)/opts.nFramesPerVid),1);\n      frameSamples = nStack/4+1:sampleRate:nFrames - nStack/4 ;\n      opts.temporalStride = sampleRate;\n      frameSamples = vl_colsubset(nStack/4+1:nFrames-nStack/4, opts.nFramesPerVid, 'uniform') ;\n      opts.temporalStride =  frameSamples(2) - frameSamples(1);\n    elseif strcmp(opts.frameSample, 'temporalStride')\n      frameSamples = nStack/4+1:opts.temporalStride:nFrames-nStack/4 ;\n      if length(frameSamples) < opts.nFrameStack,\n          frameSamples = round(linspace(nStack/4+1, nFrames - nStack/4, opts.nFramesPerVid)) ;\n          opts.temporalStride = frameSamples(2) - frameSamples(1);\n      end \n    elseif strcmp(opts.frameSample, 'random')\n      frameSamples = randperm(nFrames-nStack/2)+nStack/4;\n    elseif strcmp(opts.frameSample, 'temporalStrideRandom')\n      frameSamples = nStack/4 +1:opts.temporalStride:nFrames - nStack/4 ;\n      if length(frameSamples) < opts.nFrameStack,\n          frameSamples = round(linspace(nStack/4+1, nFrames - nStack/4, opts.nFrameStack)) ;\n          opts.temporalStride = frameSamples(2) - frameSamples(1);\n      end \n    end \n    \n    if length(frameSamples) < opts.nFramesPerVid,\n        if length(frameSamples) > opts.nFrameStack\n          frameSamples = frameSamples(1:length(frameSamples)-mod(length(frameSamples),opts.nFrameStack));\n        end\n        diff =  opts.nFramesPerVid - length(frameSamples);\n        addFrames = 0;\n        while diff > 0\n          last_frame = min(frameSamples(end), max(nFrames - nStack/4 - opts.nFrameStack,nStack/4 )); \n          if mod(addFrames,2) % add to the front\n            addSamples = nStack/4+1:opts.temporalStride:nFrames - nStack/4;\n            addSamples = addSamples(1: length(addSamples) - mod(length(addSamples),opts.nFrameStack));\n            if length(addSamples) > diff, addSamples = addSamples(1:diff); end\n          else % add to the back\n            addSamples = fliplr(nFrames - nStack/4 : -opts.temporalStride: nStack/4+1);           \n            addSamples = addSamples(mod(length(addSamples),opts.nFrameStack)+1:length(addSamples));\n            if length(addSamples) > diff, addSamples = addSamples(end-diff+1:end); end\n          end\n\n          if addFrames > 20\n            addSamples = round(linspace(nStack/4+1, nFrames - nStack/4, opts.nFrameStack)) ;\n          end\n          frameSamples = [frameSamples addSamples]; \n          diff = opts.nFramesPerVid - length(frameSamples); \n          opts.temporalStride = max(ceil(opts.temporalStride-1), 1);\n          addFrames = addFrames+1;\n\n        end\n    end\n    if length(frameSamples) > opts.nFramesPerVid   \n      if strcmp(opts.frameSample, 'temporalStride')\n        s = fix((length(frameSamples)-opts.nFramesPerVid)/2);\n      else % random\n        s = randi(length(frameSamples)-opts.nFramesPerVid);\n      end\n        frameSamples = frameSamples(s+1:s+opts.nFramesPerVid);\n    end\n\n    for k = 1:opts.nFramesPerVid\n        frames_rgb{i,1,k} = [vid_name 'frame' sprintf('%06d.jpg', frameSamples(k))] ;\n    end \n    \n      frameSamples =  repmat(frameSamples,nStack/2,1) +  repmat(frameOffsets,1,size(frameSamples,2));\n      for k = 1:opts.nFramesPerVid\n        for j = 1:nStack/2\n            frames{i,(j-1)*2+1, k} = ['u' filesep vid_name 'frame' sprintf('%06d.jpg', frameSamples(j,k)) ] ;\n            frames{i,(j-1)*2+2, k} = ['v' frames{i,(j-1)*2+1, k}(2:end)];\n        end\n      end\n\n      sampled_frame_nr{i} = frameSamples;\n  end\n  \n    if iscell(opts.imageDir)\n          imgDir = opts.imageDir{i};\n          flowDir = opts.flowDir{i};\n    end\n\n  frames_rgb = strcat([imgDir filesep], frames_rgb);\n  if ~isempty(flowDir)\n    frames = strcat([flowDir filesep], frames);\n    frames = cat(2, frames, frames_rgb);\n  else\n    frames = frames_rgb;\n  end\n  if opts.numThreads > 0\n    if prefetch\n      vl_imreadjpeg(frames, fetchOpts{:}, 'prefetch') ;\n      imo = {frames sampled_frame_nr}  ;\n      return ;\n    end\n    im = vl_imreadjpeg(frames, fetchOpts{:} ) ;\n  end\n\nend\n\nif strcmp(opts.augmentation, 'none')\n\n  szw = cellfun(@(x) size(x,2),im);\n  szh = cellfun(@(x) size(x,1),im);\n  \n  h_min = min(szh(:));\n  w_min =  min(szw(:));\n  sz = [h_min w_min] ;  \n    \n  sz = max(opts.imageSize(1:2), sz);\n  sz = min(2*opts.imageSize(1:2), sz);\n\n  scal = ([h_min w_min] ./ sz);\n\n  imo =  zeros(sz(1), sz(2), opts.imageSize(3)+3, ...\n            numel(images), 2 * opts.nFramesPerVid, 'single') ;\n  if opts.fetchGPU\n    imo = gpuArray(imo);\n  end\n  \n  for i=1:numel(images)\n    si = 1 ;\n    for k = 1:opts.nFramesPerVid\n\n      if numel(unique(szw)) > 1 || numel(unique(szh)) > 1\n        for l=1:size(im,2)\n            im{i,l,k} = im{i,l,k}(1:h_min,1:w_min,:);\n        end\n      end   \n        imt = cat(3, im{i,:,k}) ;      \n\n\n        if any(scal ~= 1)\n          imo(:, :, :, i, si) = imresize(cat(3, im{i,:,k}),sz) ;\n        else\n          imo(:, :, :, i, si) = imt ; \n        end\n        imt = [];\n        imo(:, :, :, i, si+1) =  imo(:, end:-1:1, :, i, si);      \n        imo(:, :, 1:2:nStack, i, si+1) = -imo(:, :, 1:2:nStack, i, si+1) + 255; %invert u if we flip   \n\n        si = si + 2 ;\n\n    end\n  end  \n\n  if opts.subMedian\n    median_flow = median(imo(:,:,1:nStack),1);\n    median_flow = median(median_flow,2);\n    imo(:,:,1:nStack,:,:) = bsxfun(@minus, imo(:,:,1:nStack,:,:), median_flow ) ;\n    imo(:,:,1:nStack,:,:) = bsxfun(@plus, imo(:,:,1:nStack,:,:), 128 ) ; \n  end\n  \n  if ~isempty(opts.averageImage)\n    opts.averageImage = mean(mean(opts.averageImage,1),2) ;\n    imo = bsxfun(@minus, imo,opts.averageImage) ;\n  end\n  return;\nend\n\n\n% augment now\nif exist('tfs', 'var')\n  [~,transformations] = sort(rand(size(tfs,2), numel(images)*opts.nFramesPerVid), 1) ;\nend\n\nimo = ( zeros(opts.imageSize(1), opts.imageSize(2), opts.imageSize(3)+3, ...\n            numel(images), opts.numAugments * opts.nFramesPerVid, 'single') ) ;\n\nif opts.fetchGPU\n  imo = gpuArray(imo);\nend\n\nfor i=1:numel(images)\n  si = 1 ;\n  \n  szw = cellfun(@(x) size(x,2),im);\n  szh = cellfun(@(x) size(x,1),im);  \n  \n  h_min = min(szh(:));\n  w_min =  min(szw(:));\n \n  \n  if  strcmp( opts.augmentation, 'multiScaleRegular')\n    reg_szs = [256, 224, 192, 168] ;          \n    sz(1) = reg_szs(randi(4)); sz(2) = reg_szs(randi(4));\n  elseif strcmp( opts.augmentation, 'stretch')\n    aspect = exp((2*rand-1) * log(opts.stretchAspect)) ;\n    scale = exp((2*rand-1) * log(opts.stretchScale)) ;\n    tw = opts.imageSize(2) * sqrt(aspect) * scale ;\n    th = opts.imageSize(1) / sqrt(aspect) * scale ;\n    reduce = min([w_min / tw, h_min / th, 1]) ;\n    sz = round(reduce * [th ; tw]) ;\n  else\n    sz = round(min(opts.imageSize(1:2)' .* (.75+0.5*rand(2,1)), [h_min; w_min])) ; % 0.75 +- 0.5, not keep aspect  \n  end\n\n  for k = 1:opts.nFramesPerVid\n      \n      if numel(unique(szw)) > 1 || numel(unique(szh)) > 1\n        for l=1:size(im,2)\n          im{i,l,k} = im{i,l,k}(1:h_min,1:w_min,:);\n        end\n      end\n      \n      imt = cat(3, im{i,:,k}) ;\n      if opts.subMedian\n          median_flow = median(imt(:,:,1:nStack),1);\n          median_flow = median(median_flow,2);\n          imt(:,:,1:nStack) = bsxfun(@minus, imt(:,:,1:nStack), median_flow ) ;\n          imt(:,:,1:nStack) = bsxfun(@plus, imt(:,:,1:nStack), 128 ) ; \n      end\n%       imt = gpuArray(imt);\n\n    w = size(imt,2) ;\n    h = size(imt,1) ;\n    if ~strcmp(opts.augmentation, 'uniform')\n      if ~isempty(opts.rgbVariance) % colour jittering only in training case\n        offset = zeros(size(imt));\n        offset = bsxfun(@minus, offset, reshape(opts.rgbVariance * randn(opts.imageSize(3),1), 1,1,opts.imageSize(3))) ;\n        imt = bsxfun(@minus, imt, offset) ;\n      end\n\n      for ai = 1:opts.numAugments\n        switch opts.augmentation\n          case 'stretch'\n            dx = randi(w - sz(2) + 1 ) ;\n            dy = randi(h - sz(1) + 1 ) ;\n            flip = rand > 0.5 ;\n          case 'multiScaleRegular'\n            dy = [0 h-sz(1) 0 h-sz(1)  floor((h-sz(1)+1)/2)] + 1; % 4 corners & centre\n            dx = [0 w-sz(2) w-sz(2) 0 floor((w-sz(2)+1)/2)] + 1;\n            corner = randi(5);\n            dx = dx(corner); dy = dy(corner); % pick one corner of the image\n            flip = rand > 0.5 ;  \n          case 'f25noCtr'\n            tf = tfs(:, transformations(mod(i+ai-1, numel(transformations)) + 1)) ;\n            dx = floor((w - sz(2)) * tf(2)) + 1 ;\n            dy = floor((h - sz(1)) * tf(1)) + 1 ;\n            flip = tf(3) ;  \n          otherwise\n            sz = opts.imageSize(1:2) ;\n            tf = tfs(:, transformations(mod(ai-1, numel(transformations)) + 1)) ;\n            dx = floor((w - sz(2)) * tf(2)) + 1 ;\n            dy = floor((h - sz(1)) * tf(1)) + 1 ;\n            flip = tf(3) ;          \n        end\n        \n        if opts.cheapResize\n          sx = round(linspace(dx, sz(2)+dx-1, opts.imageSize(2))) ;\n          sy = round(linspace(dy, sz(1)+dy-1, opts.imageSize(1))) ;\n        else\n          factor = [opts.imageSize(1)/sz(1) ...\n              opts.imageSize(2)/sz(2)];\n                   \n          if any(abs(factor - 1) > 0.0001)\n            imt =   imresize(imt(dy:sz(1)+dy-1,dx:sz(2)+dx-1,:), [opts.imageSize(1:2)]);\n          end                   \n\n          sx = 1:opts.imageSize(2); sy = 1:opts.imageSize(1);\n        end\n        \n        if flip\n          sx = fliplr(sx) ;\n          imo(:,:,:,i,si) = imt(sy,sx,:) ;\n          imo(:,:,1:2:nStack,i,si) = -imt(sy,sx,1:2:nStack) + 255; %invert u if we flip\n        else\n          imo(:,:,:,i,si) = imt(sy,sx,:) ;\n        end\n\n        si = si + 1 ;\n      end\n    else\n\n      w = size(imt,2) ; h = size(imt,1) ;\n      \n      indices_y = [0 h-opts.imageSize(1)] + 1;\n      indices_x = [0 w-opts.imageSize(2)] + 1;\n      center_y = floor(indices_y(2) / 2)+1;\n      center_x = floor(indices_x(2) / 2)+1;\n\n      if opts.numAugments == 6,  indices_y = center_y;   \n      elseif opts.numAugments == 2,  indices_x = [];   indices_y = [];  \n      elseif opts.numAugments ~= 10, error('only 6 or 10 uniform crops allowed');  end\n        for y = indices_y\n        for x = indices_x\n          imo(:, :, :, i, si) = ...\n              imt(y:y+opts.imageSize(1)-1, x:x+opts.imageSize(2)-1, :);\n                  \n          imo(:, :, :, i, si+1) = imo(:, end:-1:1, :, i, si);          \n          imo(:, :, 1:2:nStack, i, si+1) = -imo(:, end:-1:1, 1:2:nStack, i, si) + 255; %invert u if we flip\n\n          si = si + 2 ;\n        end\n        end\n        imo(:,:,:, i,si) = imt(center_y:center_y+opts.imageSize(1)-1,center_x:center_x+opts.imageSize(2)-1,:);\n        \n        imo(:,:,:, i,si+1) = imo(:, end:-1:1, :, i, si);        \n        imo(:,:,1:2:nStack, i,si+1) = -imo(:, end:-1:1, 1:2:nStack, i, si) + 255; %invert u if we flip\n\n        si = si + 2;\n    end\n  end\nend\n\n\nif ~isempty(opts.averageImage)\n  imo = bsxfun(@minus, imo, opts.averageImage) ;\nend\n\nend\n", "meta": {"author": "feichtenhofer", "repo": "st-resnet", "sha": "8b4f28431b5abe881c3b5192c309ac7a303b5c9d", "save_path": "github-repos/MATLAB/feichtenhofer-st-resnet", "path": "github-repos/MATLAB/feichtenhofer-st-resnet/st-resnet-8b4f28431b5abe881c3b5192c309ac7a303b5c9d/cnn_get_im_flow_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.211462968317865}}
{"text": "function planC = contourSUV(structNum,percent,planC)\n%function contourSUV(structNum,percent,planC)\n%\n%This function creates structure at percent% SUV level for structNum\n%\n%APA,12/15/2006\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nglobal stateS\nif ~exist('planC','var')\n    global planC\nend\nindexS = planC{end};\n\nscanNum                             = getStructureAssociatedScan(structNum,planC);\n[rasterSegments, planC, isError]    = getRasterSegments(structNum,planC);\nif isempty(rasterSegments)\n    warning('Could not create conotour.')\n    return\nend\n[mask3M, uniqueSlices]              = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M                         = double(getScanArray(planC{indexS.scan}(scanNum)));\n%%%% reverse data\n%maxscan=max(scanArray3M(:));\n%scanArray3M =maxscan-scanArray3M;\nSUVvals3M                           = mask3M.*scanArray3M(:,:,uniqueSlices);\nmaxSUVinStruct                      = max(SUVvals3M(:));\ncutoff                              = percent/100*maxSUVinStruct;\n[xVals, yVals, zVals]               = getScanXYZVals(planC{indexS.scan}(scanNum));\nnewStructNum                        = length(planC{indexS.structures}) + 1;\n\nnewStructS = newCERRStructure(scanNum, planC);\nfor slcNum = 1:length(uniqueSlices)\n    C = contourc(xVals, yVals, SUVvals3M(:,:,slcNum),[cutoff cutoff]);\n    indC = getSegIndices(C);\n    if ~isempty(indC)\n        for seg = 1:length(indC)\n            points = [C(:,indC{seg})' zVals(uniqueSlices(slcNum))*ones(length(C(1,indC{seg})),1)];\n            newStructS.contour(uniqueSlices(slcNum)).segments(seg).points = points;\n        end\n    else\n        newStructS.contour(uniqueSlices(slcNum)).segments.points = [];\n    end\nend\n\nfor l = max(uniqueSlices)+1 : length(planC{indexS.scan}(scanNum).scanInfo)\n    newStructS.contour(l).segments.points = [];\nend\n\nnewStructS.structureName    = [planC{indexS.structures}(structNum).structureName 'SUVMax',num2str(percent)];\n\nplanC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructS, newStructNum);\nplanC = getRasterSegs(planC, newStructNum);\nplanC = updateStructureMatrices(planC, newStructNum, uniqueSlices);\n\nif ~isempty(stateS) && isfield(stateS,'handle') && isfield(stateS.handle,'CERRSliceViewer') && ishandle(stateS.handle.CERRSliceViewer)\n    stateS.structsChanged = 1;    \n    % Refresh View\n    CERRRefresh\nend\n\nreturn;\n\nfunction indC = getSegIndices(C)\n% function getSegIndices(C)\n%\n%This function returns the indices for each segment of input contour C.\n%C is output from in-built \"contourc\" function\n%\n%APA, 12/15/2006\n\nstart = 1;\ncounter = 1;\nindC = [];\nwhile start < length(C(2,:))\n    numPts = C(2,start);\n    indC{counter} = [(start+1):(start+numPts) start+1];\n    start = start + numPts + 1;\n    counter = counter + 1;\nend\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/contourSUV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.21138740057732558}}
{"text": "function [DVH,volume_VOI_first,volume_VOI_check] = dicomrt_dvhcal(VOI,study,dose_xmesh,dose_ymesh,dose_zmesh,dvhselect)\n% dicomrt_dvhcal(VOI,study,dose_xmesh,dose_ymesh,dose_zmesh,dvhselect)\n%\n% Calculate DOSE-VOLUME-HISTOGRAMS for VOIs and cell_case_study.\n% This function calculate DVHs for all the available VOIs or for a selected number of them.\n%\n% study is the RTPLAN or the MC generated dataset containing the dose matrix\n% ct is the CT dataset\n% dose_xmesh,dose_ymesh,dose_zmesh are x-y-z coordinates of the center of the dose-voxels \n% VOIs is a cell array and contains all the Volumes of Interest\n% dvhselect is an OPTIONAL vector which contains the number of VOI to calculate DVHs for.\n%\n% NOTE: if dvhselect is omitted DVHs are calculated for all the VOIs\n%\n% DVHs are stored in a cell array with the following structure:\n%\n%  -----------------------------\n%  | [DVH 1] | [3D dose mask]  |\n%  |         -------------------\n%  |         | [dvh data]      |\n%  |         -------------------\n%  |         | VOI volume      | \n%  |         -------------------\n%  |         | Voxel volume    | \n%  -----------------------------\n%  |   ...   |     ...         |  \n%  -----------------------------\n%  | [DVH n] | [3D dose mask]  |\n%  |         -------------------\n%  |         | [dvh data]      |\n%  |         -------------------\n%  |         | VOI volume      | \n%  |         -------------------\n%  |         | Voxel volume    | \n%  -----------------------------\n%\n% [dvh data] is a 2 columns vector with following structure:\n%\n% -----------------\n% | dose | volume |\n% | (Gy) |  (cc)  |\n% -----------------\n% |      |        |\n% |      |        |\n% |      |        |\n% |      |        |\n% -----------------\n%\n%\n% Example:\n%\n% dvh=dicomrt_dvhcal(VOI,dose,dose_xmesh,dose_ymesh,dose_zmesh) returns \n% the dvhs for the DVH for all the VOIs in VOI and the dose distribution in the \n% 3D matrix 'dose'.\n%\n% See also dicomrt_loaddose, roifilt2, roipoly, dicomrt_dvhplot\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check case and set-up some parameters and variables\n[dose_temp,type_dose,doselabel,PatientPosition]=dicomrt_checkinput(study);\ndose=dicomrt_varfilter(dose_temp);\n[VOI_temp]=dicomrt_checkinput(VOI);\nVOI=dicomrt_varfilter(VOI_temp);\n\n% Define cell array\nDVH=cell(size(VOI,1),2);\n\n% Write VOIs labels\nfor k=1:size(VOI,1)\n    DVH{k,1}=VOI{k,1};\nend\n\n% Retrieve dmax\ndmax=max(max(max(dose)));\n\n% Build dose grid\ndosegrid=zeros(double(int32(dmax)),1);\n%for i=1:double(int32(dmax))                    % use with hist \n%    x(i)=dmax/double(int32(dmax))*(0.5+i-1);   % hist uses centers\n%end                                            %\nfor i=1:double(int32(dmax))                     % use with histc\n    dosegrid(i)=i*dmax/double(int32(dmax));     % histc uses edges\nend                                             %\n  \n% Calculate voxel volume\n[voxelvolume, status]=dicomrt_voxelvolumecal(study,dose_xmesh,dose_ymesh,dose_zmesh);\n      \nvolume_VOI_check=[];\nvolume_VOI_first=[];\n\nfor k=1:length(dvhselect) % loop over VOIs\n    % Print header\n    disp(['DVH calculation for VOI: ',VOI{dvhselect(k),1}]);\n    % Retrieve info necessary to get volume_VOI\n    [mask_VOI,volume_VOI,mask4VOI]=dicomrt_mask(VOI_temp,dose_temp,dose_xmesh,dose_ymesh,dose_zmesh,...\n        dvhselect(k),'nan','y'); % dose matrix masked in dicomrt_Vlevel\n    % Build frequency DVH data\n    % case 1: uniform slice thickness\n    volume_VOI_first=[volume_VOI_first,volume_VOI];\n    if status==0\n        vgrid=histc(reshape(mask_VOI{2,1},1,size(mask_VOI{2,1},1)*size(mask_VOI{2,1},2)*size(mask_VOI{2,1},3)),dosegrid);\n        % get back voxels with dose<min(dosegrid) cause histc does not\n        % account for it\n        temp_min=find(mask_VOI{2,1}<dosegrid(1) & mask_VOI{2,1}~=0);\n        %temp_min2=find(mask_VOI{2,1}<dosegrid(1));\n        if isempty(temp_min)~=1\n            vgrid(1)=vgrid(1)+length(temp_min);\n        end\n        vgrid=vgrid.*voxelvolume(1);\n        temp2=cumsum(vgrid);\n        volume_VOI_check=[volume_VOI_check,temp2(end)];\n    else % case 2: non-uniform slice thickness\n        vgrid=zeros(length(dosegrid),1);\n        for i=1:size(mask_VOI{2,1},3)\n            temp_vgrid=histc(reshape(mask_VOI{2,1}(:,:,i),1,size(mask_VOI{2,1}(:,:,i),1)*size(mask_VOI{2,1}(:,:,i),2)),dosegrid);\n            % get back voxels with dose<min(dosegrid) cause histc does not\n            % account for it\n            temp_min=find(mask_VOI{2,1}(:,:,i)<dosegrid(1) & mask_VOI{2,1}~=0);\n            if isempty(temp_min)~=1\n                temp_vgrid(1)=temp_vgrid(1)+length(temp_min);\n            end\n            vgrid=vgrid+temp_vgrid'.*voxelvolume(i);\n        end\n        temp2=cumsum(vgrid);\n        volume_VOI_check=[volume_VOI_check,temp2(end)];\n        %for i=1:length(dosegrid)\n        %    if i==1\n        %        vgrid(i)=dicomrt_Vlevel(mask_VOI,0,dose_xmesh,dose_ymesh,dose_zmesh,...\n        %            [[0 dosegrid(i)] 0 0 0],VOI_temp,dvhselect(k),1,volume_VOI);\n        %    else\n        %        vgrid(i)=dicomrt_Vlevel(mask_VOI,0,dose_xmesh,dose_ymesh,dose_zmesh,...\n        %            [[dosegrid(i-1) dosegrid(i)] 0 0 0],VOI_temp,dvhselect(k),1,volume_VOI);\n        %    end\n        %end\n    end\n    vgrid=dicomrt_makevertical(vgrid);\n    % Store DVH data\n    DVH{dvhselect(k),2}{1,1}=mask_VOI;\n    DVH{dvhselect(k),2}{2,1}=[dosegrid,vgrid];\n    DVH{dvhselect(k),2}{3,1}=volume_VOI;\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/analysis/dicomrt_dvhcal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.61878043374385, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.21136457545669798}}
{"text": "function [data] = ft_resampledata(cfg, data)\n\n% FT_RESAMPLEDATA performs a resampling or downsampling of the data\n%\n% Use as\n%   [data] = ft_resampledata(cfg, data)\n%\n% The data should be organised in a structure as obtained from the FT_PREPROCESSING\n% function. The configuration should contain\n%   cfg.resamplefs      = frequency at which the data will be resampled\n%   cfg.detrend         = 'no' or 'yes', detrend the data prior to resampling (no default specified, see below)\n%   cfg.demean          = 'no' or 'yes', whether to apply baseline correction (default = 'no')\n%   cfg.baselinewindow  = [begin end] in seconds, the default is the complete trial (default = 'all')\n%   cfg.feedback        = 'no', 'text', 'textbar', 'gui' (default = 'text')\n%   cfg.trials          = 'all' or a selection given as a 1xN vector (default = 'all')\n%   cfg.sampleindex     = 'no' or 'yes', add a channel with the original sample indices (default = 'no')\n%\n% Instead of specifying cfg.resamplefs, you can also specify a time axis on which you\n% want the data to be resampled. This is useful for merging data from two acquisition\n% devices, after resampledata you can call FT_APPENDDATA to concatenate the channels\n% from the different acquisition devices.\n%   cfg.time        = cell-array with one time axis per trial (i.e. from another dataset)\n%   cfg.method      = interpolation method, see INTERP1 (default = 'pchip')\n%   cfg.extrapval   = extrapolation behaviour, scalar value or 'extrap' (default = as in INTERP1)\n%\n% When you specify cfg.method='resample' an implicit anti-aliasing low pass filter is applied prior\n% to the resampling. You can also explicitly specify an anti-aliasing low pass filter. This is adviced\n% when downsampling using any other method than 'resample', but also when strong noise components are\n% present just above the new Nyquist frequency.\n%   cfg.lpfilter    = 'yes' or 'no' (default = 'no')\n%   cfg.lpfreq      = scalar value for low pass frequency (there is no default, so needs to be always specified)\n%   cfg.lpfilttype  = string, filter type (default is set in ft_preproc_lowpassfilter)\n%   cfg.lpfiltord   = scalar, filter order (default is set in ft_preproc_lowpassfilter)\n%\n% More documentation about anti-alias filtering can be found in this <a href=\"matlab:\n% web('https://www.fieldtriptoolbox.org/faq/resampling_lowpassfilter')\">FAQ</a> on the FieldTrip website.\n%\n% Previously this function used to detrend the data by default to avoid edge artifacts fue to the\n% anti-aliassing filter. Detrending is fine for removing slow drifts in data prior to frequency analysis,\n% but not recommended if you want to look at ERPs or ERFs. Therefore the old default value 'yes' has been\n% removed; you now explicitly have to specify whether you want to detrend or not.\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_PREPROCESSING, FT_APPENDDATA, FT_PREPROC_LOWPASSFILTER, ESAMPLE, DOWNSAMPLE, INTERP1\n\n% Copyright (C) 2003-2006, FC Donders Centre, Markus Siegel\n% Copyright (C) 2004-2022, FC Donders Centre, Robert Oostenveld\n% Copyright (C) 2022, DCCN, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar data\nft_preamble provenance data\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% ft_checkdata is done further down\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden', {'trial'}); % prevent accidental typos, see issue 1729\ncfg = ft_checkconfig(cfg, 'renamed', {'blc', 'demean'});\ncfg = ft_checkconfig(cfg, 'renamed', {'resamplemethod', 'method'});\ncfg = ft_checkconfig(cfg, 'renamed', {'fsample', 'resamplefs'});\n\n% set the defaults\ncfg.resamplefs       = ft_getopt(cfg, 'resamplefs',      []);\ncfg.time             = ft_getopt(cfg, 'time',            {});\ncfg.factor           = ft_getopt(cfg, 'factor',          {});\ncfg.detrend          = ft_getopt(cfg, 'detrend',         'no');\ncfg.demean           = ft_getopt(cfg, 'demean',          'no');\ncfg.baselinewindow   = ft_getopt(cfg, 'baselinewindow',  'all');\ncfg.feedback         = ft_getopt(cfg, 'feedback',        'text');\ncfg.trials           = ft_getopt(cfg, 'trials',          'all', 1);\ncfg.method           = ft_getopt(cfg, 'method',          []);\ncfg.sampleindex      = ft_getopt(cfg, 'sampleindex',     'no');\ncfg.extrapval        = ft_getopt(cfg, 'extrapval',       []);\ncfg.lpfilter         = ft_getopt(cfg, 'lpfilter');\n\n% store original datatype\nconvert = ft_datatype(data);\n\n% check if the input data is valid for this function, this will convert it to raw if needed\ndata = ft_checkdata(data, 'datatype', {'raw+comp', 'raw'}, 'feedback', 'yes');\n\nif isempty(cfg.method) && ~isempty(cfg.time)\n  % see INTERP1, shape-preserving piecewise cubic interpolation\n  cfg.method = 'pchip';\nelseif isempty(cfg.method)\n  % see RESAMPLE\n  cfg.method = 'resample';\nend\n\nusefsample = any(strcmp(cfg.method, {'resample', 'downsample', 'decimate', 'mean', 'median'}));\nusetime    = ~usefsample;\n\n% select trials of interest\ntmpcfg = keepfields(cfg, {'trials', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ndata   = ft_selectdata(tmpcfg, data);\n% restore the provenance information\n[cfg, data] = rollback_provenance(cfg, data);\n\nif strcmp(cfg.sampleindex, 'yes') && isfield(data, 'sampleinfo')\n  data.label{end+1} = 'sampleindex';\n  for i=1:size(data.sampleinfo,1)\n    % this works for one or more trials\n    data.trial{i}(end+1,:) = data.sampleinfo(i,1):data.sampleinfo(i,2);\n  end\nelseif strcmp(cfg.sampleindex, 'yes')\n  ft_warning('no sampleinfo present, cannot add sampleindex as channel');\nend\n\n% sampleinfo, if present, becomes invalid because of the resampling\nif isfield(data, 'sampleinfo')\n  data = rmfield(data, 'sampleinfo');\nend\n\nif usefsample && usetime\n  ft_error('you should either specify cfg.resamplefs or cfg.time')\nend\n\n% remember the original sampling frequency in the configuration\ncfg.origfs = double(data.fsample);\n\n% set this to nan, it will be updated later on\ndata.fsample = nan;\n\nif isempty(cfg.lpfilter), cfg.lpfilter = 'no'; end\ndolpfilt = istrue(cfg.lpfilter);\nif dolpfilt\n  cfg.lpfilttype = ft_getopt(cfg, 'lpfilttype');\n  cfg.lpfiltord  = ft_getopt(cfg, 'lpfiltord');\n  cfg            = ft_checkconfig(cfg, 'required', 'lpfreq');\nend\n\nif usefsample\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % resample/downsample based on new sampling frequency\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  ntr = length(data.trial);\n  nchan  = numel(data.label);\n\n  ft_progress('init', cfg.feedback, 'resampling data');\n  [fsorig, fsres] = rat(cfg.origfs./cfg.resamplefs); %account for non-integer fs\n  cfg.resamplefs  = cfg.origfs.*(fsres./fsorig); %get new fs exact\n\n  % make sure that the resampled time axes are aligned (this is to avoid rounding\n  % errors in the time axes). this procedure relies on the fact that resample assumes\n  % all data outside the data window to be zero anyway. therefore, padding with zeros\n  % (to the left and right) before resampling does not hurt\n  begsample = zeros(ntr, 1);\n  endsample = zeros(ntr, 1);\n  for itr = 1:ntr\n    begsample(itr) = round(cfg.origfs * data.time{itr}(1));\n    endsample(itr) = round(cfg.origfs * data.time{itr}(end));\n  end\n  begpad = begsample-min(begsample);\n  endpad = max(endsample)-endsample;\n\n  if any(begpad~=0) || any(endpad~=0)\n    ft_warning('not all trials have the same time axis; data will be zero-padded prior to resampling to avoid rounding issues in the resampled time axes');\n  end\n\n  if any(strcmp(cfg.method, {'downsample', 'mean', 'median'}))\n    ft_warning('using cfg.method = ''%s''; only use this if you have applied an anti-aliasing filter prior to downsampling!', cfg.method);\n  end\n\n  if any(strcmp(cfg.method, {'decimate', 'downsample', 'mean', 'median'}))\n    if mod(fsorig, fsres) ~= 0\n      ft_error('the new sampling rate needs to be an integer division of the original sampling rate');\n    end\n  end\n\n  for itr = 1:ntr\n    ft_progress(itr/ntr, 'resampling data in trial %d from %d\\n', itr, ntr);\n\n    olddat = data.trial{itr};\n    oldtim = data.time{itr};\n\n    % detrending is in general not recommended\n    if istrue(cfg.detrend)\n      if ~strcmp(cfg.baselinewindow, 'all')\n        olddat = ft_preproc_detrend(olddat, nearest(oldtim, cfg.baselinewindow(1)), nearest(oldtim, cfg.baselinewindow(2)));\n      else\n        olddat = ft_preproc_detrend(olddat);\n      end\n    end\n\n    % remove the mean to avoid edge effects when there's a strong offset, the cfg.demean option is dealt with below\n    if ~strcmp(cfg.baselinewindow, 'all')\n      [olddat, bsl] = ft_preproc_baselinecorrect(olddat, nearest(oldtim, cfg.baselinewindow(1)), nearest(oldtim, cfg.baselinewindow(2)));\n    else\n      [olddat, bsl] = ft_preproc_baselinecorrect(olddat);\n    end\n\n    if istrue(cfg.lpfilter)\n      olddat = ft_preproc_lowpassfilter(olddat, cfg.origfs, cfg.lpfreq, cfg.lpfiltord, cfg.lpfilttype);\n    end\n\n    % pad the data with zeros on both sides\n    olddat = [zeros(nchan, begpad(itr)) olddat zeros(nchan, endpad(itr))];\n    oldtim = ((begsample(itr)-begpad(itr)):(endsample(itr)+endpad(itr))) / cfg.origfs;\n\n    % perform the resampling\n    if strcmp(cfg.method, 'downsample')\n      if isa(olddat, 'single')\n        % temporary convert this trial to double precision\n        newdat = transpose(single(downsample(double(transpose(olddat)),fsorig/fsres)));\n      else\n        newdat = transpose(downsample(transpose(olddat),fsorig/fsres));\n      end\n\n    elseif strcmp(cfg.method, 'resample')\n      if isa(olddat, 'single')\n        % temporary convert this trial to double precision\n        newdat = transpose(single(resample(double(transpose(olddat)),fsres,fsorig)));\n      else\n        newdat = transpose(resample(transpose(olddat),fsres,fsorig));\n      end\n\n    elseif strcmp(cfg.method, 'decimate')\n      if isa(olddat, 'single')\n        % temporary convert this trial to double precision\n        newdat = transpose(single(my_decimate(double(transpose(olddat)),fsorig/fsres)));\n      else\n        newdat = transpose(my_decimate(transpose(olddat),fsorig/fsres));\n      end\n\n    elseif strcmp(cfg.method, 'mean')\n      if isa(olddat, 'single')\n        % temporary convert this trial to double precision\n        newdat = transpose(single(my_mean(double(transpose(olddat)),fsorig/fsres)));\n      else\n        newdat = transpose(my_mean(transpose(olddat),fsorig/fsres));\n      end\n\n    elseif strcmp(cfg.method, 'median')\n      if isa(olddat, 'single')\n        % temporary convert this trial to double precision\n        newdat = transpose(single(my_median(double(transpose(olddat)), fsorig/fsres)));\n      else\n        newdat = transpose(my_median(transpose(olddat), fsorig/fsres));\n      end\n\n    else\n      ft_error('unknown method ''%s''', cfg.method);\n    end\n\n    % add back the mean\n    if ~strcmp(cfg.demean, 'yes')\n      nsmp   = size(newdat,2);\n      newdat = newdat + bsl(:,ones(1,nsmp));\n    end\n\n    % compute the new time axis, assuming that it starts at the same time\n    nsmp   = size(newdat,2);\n    newtim = (0:(nsmp-1))/cfg.resamplefs;\n\n    % the middle of the time bin represented by the first samples are not aligned\n    % the new time axis can be shifted by a sub-sample amount\n    shift  = mean(oldtim) - mean(newtim);\n    newtim = newtim + shift;\n\n    if begpad(itr)>0 || endpad(itr)>0\n      % un-pad the data\n      sel = (1+round(begpad(itr)*cfg.resamplefs/cfg.origfs)):(length(newtim)-round(endpad(itr)*cfg.resamplefs/cfg.origfs));\n      newtim = newtim(   sel);\n      newdat = newdat(:, sel);\n    end\n\n    data.time{itr}  = newtim;\n    data.trial{itr} = newdat;\n\n  end % for itr\n  ft_progress('close');\n\n  % specify the new sampling frequency in the output\n  data.fsample = cfg.resamplefs;\n\nelseif usetime\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % resample based on the specified new time axes for each trial\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  if isempty(cfg.extrapval)\n    if strcmp(cfg.method, 'spline') || strcmp(cfg.method, 'pchip')\n      cfg.extrapval = 'extrap';\n    else\n      cfg.extrapval = nan;\n    end\n  end\n\n  ntr = length(data.trial);\n\n  ft_progress('init', cfg.feedback, 'resampling data');\n  for itr = 1:ntr\n    ft_progress(itr/ntr, 'resampling data in trial %d from %d\\n', itr, ntr);\n\n    olddat = data.trial{itr};\n    oldtim = data.time{itr};\n\n    % detrending is in general not recommended\n    if istrue(cfg.detrend)\n      if ~strcmp(cfg.baselinewindow, 'all')\n        olddat = ft_preproc_detrend(olddat, nearest(oldtim, cfg.baselinewindow(1)), nearest(oldtim, cfg.baselinewindow(2)));\n      else\n        olddat = ft_preproc_detrend(olddat);\n      end\n    end\n\n    % always remove the mean to avoid edge effects when there's a strong offset, the cfg.demean option is dealt with below\n    if ~strcmp(cfg.baselinewindow, 'all')\n      [olddat, bsl] = ft_preproc_baselinecorrect(olddat, nearest(oldtim, cfg.baselinewindow(1)), nearest(oldtim, cfg.baselinewindow(2)));\n    else\n      [olddat, bsl] = ft_preproc_baselinecorrect(olddat);\n    end\n\n    if istrue(cfg.lpfilter)\n      olddat = ft_preproc_lowpassfilter(olddat, cfg.origfs, cfg.lpfreq, cfg.lpfiltord, cfg.lpfilttype);\n    end\n\n    % perform the resampling\n    newtim = cfg.time{itr};\n    if length(oldtim)>1\n      newdat = interp1(oldtim', olddat', newtim', cfg.method, cfg.extrapval)';\n    else\n      newdat = repmat(olddat, [1 numel(newtim)]);\n    end\n\n    % add back the mean\n    if ~strcmp(cfg.demean, 'yes')\n      nsmp   = size(newdat, 2);\n      newdat = newdat + bsl(:,ones(1,nsmp));\n    end\n\n    data.trial{itr} = newdat;\n    data.time{itr}  = newtim;\n\n  end % for itr\n  ft_progress('close');\n\n  % specify the new sampling frequency in the output\n  t1 = cfg.time{1}(1);\n  t2 = cfg.time{1}(2);\n  data.fsample = 1/(t2-t1);\n\nend % if usefsample or usetime\n\nft_info('original sampling rate = %d Hz\\nnew sampling rate = %d Hz\\n', cfg.origfs, data.fsample);\n\n% convert back to input type if necessary\nswitch convert\n  case 'timelock'\n    data = ft_checkdata(data, 'datatype', 'timelock');\n  otherwise\n    % keep the output as it is\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous   data\nft_postamble provenance data\nft_postamble history    data\nft_postamble savevar    data\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that decimates along the columns\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = my_decimate(x, varargin)\n[n, m] = size(x);\n% decimate the first column\ny = decimate(x(:,1), varargin{:});\nif m>1\n  % increase the size of the output matrix\n  y(:,m) = 0;\n  % decimate the subsequent columns\n  for i=2:m\n    y(:,i) = decimate(x(:,i), varargin{:});\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that does a block-wise average along the columns\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = my_mean(x, r)\n[n, m] = size(x);\nn = n - mod(n,r);\nx = x(1:n,:);\nx = reshape(x, [r n/r m]);\ny = mean(x, 1);\ny = reshape(y, [n/r m]);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that does a block-wise median along the columns\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = my_median(x, r)\n[n, m] = size(x);\nn = n - mod(n,r);\nx = x(1:n,:);\nx = reshape(x, [r n/r m]);\ny = median(x, 1);\ny = reshape(y, [n/r m]);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_resampledata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2112351034013042}}
{"text": "function [formula, nH, charge] = getFormulaAndChargeFromInChI(inchi)\n\n% [formula,charge] = getFormulaAndChargeFromInChI(inchi)\n% \n% INPUT\n% inchi.......Nonstandard IUPAC InChI for a particular pseudoisomer of a\n%             metabolite\n% \n% OUTPUTS\n% formula....The chemical formula for the input pseudoisomer\n% charge.....The charge on the input pseudoisomer\n\n\nlayers = regexp(inchi,'/','split');\nf1 = layers{2}; % Fully protonated formula\n\np = {};\nif ~isempty(strmatch('p',layers))\n    p = layers{strmatch('p',layers)}; % nH to add or subtract\nend\n\nq = {};\nif ~isempty(strmatch('q',layers))\n    q = layers{strmatch('q',layers)}; % charge\nend\n\nif ~isempty(q)\n   charge = str2double(q(2:end));\nelse\n    charge = 0;\nend\n\nf1_nH = numAtomsOfElementInFormula(f1,'H'); % nH in fully protonated formula\nif ~isempty(p)\n    nH = f1_nH + str2double(p(2:end)); % nH in pseudoisomer formula\nelse\n    nH = f1_nH;\nend\n\nformula = regexprep(f1,'H[a-z]*[0-9]*',''); % Remove all H from fully protonated formula\nif nH == 1\n    formula = [formula 'H'];\nelseif nH > 1\n    formula = [formula 'H' num2str(nH)]; % Add appropriate nH back in to create pseudoisomer formula\nelseif nH < 0\n    error('Negative number of H in formula.') % Should never get here\nend\n\n% In case there is Hg in formula\nf1_nHg = numAtomsOfElementInFormula(f1,'Hg');\nif f1_nHg == 1\n    formula = [formula 'Hg'];\nelseif f1_nHg > 1\n    formula = [formula 'Hg' num2str(f1_nHg)];\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/inchi/old/getFormulaAndChargeFromInChI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2109839562057856}}
{"text": "function planC = sumDose(doseNums,wtfactor,lqParamS,assocScan,newDoseName,planC)\n%function planC = sumDose(doseNumsV,weightsV,assocScan)\n%\n%This function creates a new dose distribution by adding up doseNums\n%according to factors wtfactor. assocScan is the scan number to associate\n%new dose with. newDoseName is the name of new dose.\n%\n%APA, 12/23/2009\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n%\n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n%\n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n%\n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n%\n% CERR is distributed under the terms of the Lesser GNU Public License.\n%\n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nwtfactorTmp = wtfactor;\nwtfactor = ones(1,max(doseNums));\nwtfactor(doseNums) = wtfactorTmp;\n\nindexS = planC{end};\nif assocScan > 0\n    assocScanUID = planC{indexS.scan}(assocScan).scanUID;\n    %Get associated transM\n    assocTransM = planC{indexS.scan}(assocScan).transM;\n    if isempty(assocTransM)\n        assocTransM = eye(4);\n    end\nelse %No Association\n    assocScanUID = '';\n    assocTransM = eye(4);\nend\n\n% doseNums = checkedDoses;\n\n%Get the x,y,z grid for new dose\nfor i = 1:length(doseNums)\n    doseNum = doseNums(i);\n    %Get x,y,z values for doseNum\n    [xV, yV, zV] = getDoseXYZVals(planC{indexS.dose}(doseNum));\n    \n    %Get the corners of the original dataset.\n    [xCorn, yCorn, zCorn] = meshgrid([min(xV) max(xV)], [min(yV) max(yV)], [min(zV) max(zV)]);\n    \n    %Add ones to the corners so we can apply a transformation matrix.\n    corners = [xCorn(:) yCorn(:) zCorn(:) ones(prod(size(xCorn)), 1)];\n    \n    %Apply transform to corners, so we know boundary of the slice.\n    transM = getTransM(planC{indexS.dose}(doseNum),planC);\n    if isempty(transM) || isequal(transM,eye(4))\n        [xV,yV,zV] = getDoseXYZVals(planC{indexS.dose}(doseNum));\n        xGrid{doseNum} = xV(:)';\n        yGrid{doseNum} = yV(:)';\n        zGrid{doseNum} = zV(:)';\n    else\n        newCorners = inv(assocTransM) * transM * corners';\n        xGrid{doseNum} = linspace(min(newCorners(1,:)), max(newCorners(1,:)), length(xV));\n        yGrid{doseNum} = linspace(max(newCorners(2,:)), min(newCorners(2,:)), length(yV));\n        zGrid{doseNum} = linspace(min(newCorners(3,:)), max(newCorners(3,:)), length(zV));\n    end\n    xRes{doseNum} = length(xV);\n    yRes{doseNum} = length(yV);\n    zRes{doseNum} = length(zV);\n    \n    %Get associated scan\n    % assocScanV{doseNum} = getAssociatedScan(planC{indexS.dose}(doseNum).assocScanUID);\n    assocScanV{doseNum} = getDoseAssociatedScan(doseNum,planC);\nend\nnewXgrid = linspace(min(cell2mat(xGrid)),max(cell2mat(xGrid)),max(cell2mat(xRes)));\nnewYgrid = linspace(max(cell2mat(yGrid)),min(cell2mat(yGrid)),max(cell2mat(yRes)));\nnewZgrid = linspace(min(cell2mat(zGrid)),max(cell2mat(zGrid)),max(cell2mat(zRes)));\n\n%Obtain doses with same grid\nif isempty(assocTransM)\n    assocTransM = eye(4);\nend\ndoseIndC = {};\ndoseNumsTmp = doseNums;\nfor iSortAll = 1:length(doseNums)\n    iSort = doseNums(iSortAll);\n    indRemaining = doseNums;\n    indRemaining(iSortAll) = [];\n    doseSortM = [iSort];\n    if ~ismember(iSort,[doseIndC{:}])\n        for jSortAll = 1:length(indRemaining)\n            jSort = indRemaining(jSortAll);\n            if ~isempty(getTransM('dose',iSort,planC))\n                doseITM = inv(assocTransM) * getTransM('dose',iSort,planC);\n            else\n                doseITM = inv(assocTransM);\n            end\n            if ~isempty(getTransM('dose',jSort,planC))\n                doseJTM = inv(assocTransM) * getTransM('dose',jSort,planC);\n            else\n                doseJTM = inv(assocTransM);\n            end\n            if isequal([xRes{iSort},yRes{iSort},zRes{iSort}],[xRes{jSort},yRes{jSort},zRes{jSort}]) && isequal(doseITM,doseJTM)\n                doseSortM(end+1) = jSort;\n                indJsort = find(doseNumsTmp == jSort);\n                doseNumsTmp(indJsort) = [];\n            end\n        end\n    end\n    doseIndC{iSort} = doseSortM;\nend\n\ndoseNums = doseNumsTmp;\n\n%Loop over doses and add over new grid\nhWait = waitbar(0,'Summing Dose distributions');\ndoseSumM = zeros([length(newYgrid),length(newXgrid),length(newZgrid)],'single');\ndoseEmptyM = zeros([length(newYgrid),length(newXgrid)],'single');\n\n%Assume dose units are same as that of 1st dose\ndoseUnits = getDoseUnitsStr(doseNums(1),planC);\nfor i = 1:length(doseNums)\n    \n    doseNum = doseNums(i);\n    \n    %Check for transM\n    if ~isempty(assocTransM) && ~isequal(assocTransM,eye(4))\n        doseTtransM = getTransM('dose',doseNum,planC);\n        if isempty(doseTtransM)\n            doseTtransM = eye(4);\n        end\n        inputTM = inv(assocTransM) * doseTtransM;\n    else\n        inputTM = getTransM('dose',doseNum,planC);\n        if isempty(inputTM)\n            inputTM = eye(4);\n        end\n    end\n    \n    SOPInstanceUIDv = {planC{indexS.beams}.SOPInstanceUID};\n    if ~isempty(lqParamS)\n        paramS.Tk.val = inf;         %Kick-off time of repopulation (days)\n        paramS.Tp.val = NaN;        %Potential tumor doubling time (days)\n        paramS.alpha.val = NaN;\n        paramS.abRatio.val = lqParamS.abRatio; %10;  %alpha/beta\n        paramS.stdFractionSize = lqParamS.stdFractionSize; % 2;\n    end\n    \n    %Get the summation for this grid\n    doseCombinedM = [];\n    for iDoseAll = 1:length(doseIndC{doseNum})\n        iDose = doseIndC{doseNum}(iDoseAll);\n        doseUnits2 = getDoseUnitsStr(iDose,planC);\n        if strcmpi(doseUnits, 'Gy') && strcmpi(doseUnits2, 'cGy')\n            multFact = 0.01;\n        elseif strcmpi(doseUnits, 'cGy') && strcmpi(doseUnits2, 'Gy')\n            multFact = 100;\n        else\n            multFact = 1;\n        end\n        doseOffset = planC{indexS.dose}(iDose).doseOffset;\n        if isempty(doseOffset)\n            doseOffset = 0;\n        end\n        doseArray = single(getDoseArray(planC{indexS.dose}(iDose)) - doseOffset);\n        \n        % Apply BED/EQD2 correction\n        if ~isempty(lqParamS)\n            ReferencedSOPInstanceUID = planC{indexS.dose}(iDose)...\n                .DICOMHeaders.ReferencedRTPlanSequence.Item_1.ReferencedSOPInstanceUID;\n            planNum = find(strcmpi(ReferencedSOPInstanceUID,SOPInstanceUIDv));\n            paramS.numFractions.val = planC{indexS.beams}(planNum(1)).FractionGroupSequence...\n                .Item_1.NumberOfFractionsPlanned;\n            paramS.numFractions.val = double(paramS.numFractions.val);\n            paramS.frxSize.val = doseArray / paramS.numFractions.val;\n            doseArray = calc_BED(paramS) / (1+paramS.stdFractionSize/paramS.abRatio.val);\n        end\n        \n        if ~isempty(doseCombinedM)\n            doseCombinedM = doseCombinedM + multFact * wtfactor(iDose) * doseArray;\n        else\n            doseCombinedM = multFact * wtfactor(iDose) * doseArray;\n        end\n    end\n    \n    %Check if this dose is on same grid as the new one\n    %if isequal(xGrid{doseNum},newXgrid) && isequal(yGrid{doseNum},newYgrid) && isequal(zGrid{doseNum},newZgrid)\n    chkLength = length(xGrid{doseNum})==length(newXgrid) && length(yGrid{doseNum})==length(newYgrid) && length(zGrid{doseNum})==length(newZgrid);\n    if sum(sum((inputTM-eye(4)).^2)) < 1e-3 && chkLength && max(abs(xGrid{doseNum}-newXgrid)) < 1e-3 && max(abs(yGrid{doseNum}-newYgrid)) < 1e-3 && max(abs(zGrid{doseNum}-newZgrid)) < 1e-3\n        \n        doseSumM = doseSumM + doseCombinedM;\n        waitbar((i-1)/length(doseNums),hWait,['Calculating contribution from Dose ', num2str(doseNum)])\n        \n    else %interpolation required\n        \n        %Transform this dose\n        doseTmpM = [];\n        \n        for slcNum=1:length(newZgrid)\n            [xV, yV, zV] = getDoseXYZVals(planC{indexS.dose}(doseNum));\n            doseTmp = slice3DVol(doseCombinedM, xV, yV, zV, newZgrid(slcNum), 3, 'linear', inputTM, [], newXgrid, newYgrid);\n            if isempty(doseTmp)\n                doseTmpM(:,:,slcNum) = doseEmptyM;\n            else\n                doseTmpM(:,:,slcNum) = doseTmp;\n            end\n            waitbar((i-1)/length(doseNums) + (slcNum-1)/length(newZgrid)/length(doseNums) ,hWait,['Calculating contribution from Dose ', num2str(doseNum)])\n        end\n        \n        doseSumM = doseSumM + doseTmpM;\n        \n    end\n    \nend\n\ndelete(hWait)\n\n%Create new dose distribution\nnewDoseNum = length(planC{indexS.dose}) + 1;\nplanC{indexS.dose}(newDoseNum).doseArray = doseSumM;\nclear doseSumM\nplanC{indexS.dose}(newDoseNum).doseUID = createUID('dose');\nplanC{indexS.dose}(newDoseNum).assocScanUID = assocScanUID;\n\n%Find minimum value in 3d array, use its negative as the offset\nmaxDose = max(max(max(planC{indexS.dose}(newDoseNum).doseArray)));\noffset = -min(min(min(planC{indexS.dose}(newDoseNum).doseArray)));\nif offset > 0\n    planC{indexS.dose}(newDoseNum).doseOffset = offset;\n    planC{indexS.dose}(newDoseNum).doseArray = planC{indexS.dose}(newDoseNum).doseArray + offset;\nend\n\n%set labels on new dose, overwriting some of the copied labels **Check for more labels that need to be replaced\nplanC{indexS.dose}(newDoseNum).doseNumber = newDoseNum;\nplanC{indexS.dose}(newDoseNum).fractionGroupID = newDoseName;\n\n%Remove old caching info.\nplanC{indexS.dose}(newDoseNum).cachedMask = [];\nplanC{indexS.dose}(newDoseNum).cachedColor = [];\nplanC{indexS.dose}(newDoseNum).cachedTime = [];\n\n%Set coordinates.\nplanC{indexS.dose}(newDoseNum).sizeOfDimension1 = length(newXgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension2 = length(newYgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension3 = length(newZgrid);\nplanC{indexS.dose}(newDoseNum).horizontalGridInterval = newXgrid(2)-newXgrid(1);\nplanC{indexS.dose}(newDoseNum).verticalGridInterval = newYgrid(2)-newYgrid(1);\nplanC{indexS.dose}(newDoseNum).depthGridInterval = newZgrid(2)-newZgrid(1);\nplanC{indexS.dose}(newDoseNum).coord1OFFirstPoint = newXgrid(1);\nplanC{indexS.dose}(newDoseNum).coord2OFFirstPoint = newYgrid(1);\nplanC{indexS.dose}(newDoseNum).coord3OfFirstPoint = newZgrid(1);\nplanC{indexS.dose}(newDoseNum).zValues = newZgrid;\nplanC{indexS.dose}(newDoseNum).doseUnits = doseUnits;\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_Data_Extraction/sumDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.21097392951087415}}
{"text": "%% Load the data into MATLAB from a binary log file\n% Usage: >> [datapoints, numpoints] = readdata('datafile.log')\n% Header information format:\n%           String \"MWLOGV##\"\n%           Time/Date 4 bytes (time())\n%           Number of Signals per record Logged 1 bytes (256 max)\n%           Data Type of Signals Logged  1 bytes (1-10)\n%           Number of bytes per record 2 (65535 max)\n% Plot Data Example: plot([1:numpoints], datapoints(1,:), [1:numpoints], datapoints(2,:))\n% MathWorks Pilot Engineering 2015\n% Steve Kuznicki\nfunction [datapts, numpts] = readdata(dataFile)\n%%\ndatapts = 0;\nnumpts = 0;\n\nif nargin == 0\n    dataFile = 'data.bin';\nend\n\nfid = fopen(dataFile, 'r');\n% load the header information\nhdrToken = fread(fid, 8, 'char');\nif strncmp(char(hdrToken),'MWLOGV',6) == true\n    logTime = uint32(fread(fid, 1, 'uint32'));\n    numflds = double(fread(fid, 1, 'uint8'));\n    typefld = uint8(fread(fid, 1, 'uint8'));\n    recSize = uint16(fread(fid, 1, 'uint16'));\n    fieldTypeStr = get_elem_type(typefld);\n    datapts = fread(fid, double([numflds, Inf]), fieldTypeStr);\n    fclose(fid);\n    numpts = size(datapts,2);\nend\n\nend\n\n%% get the element type string\nfunction [dtypeStr] = get_elem_type(dtype)\n    switch(dtype)\n        case 1\n            dtypeStr = 'double';\n        case 2\n            dtypeStr = 'single';\n        case 3\n            dtypeStr = 'int32';\n        case 4\n            dtypeStr = 'uint32';\n        case 5\n            dtypeStr = 'int16';\n        case 6\n            dtypeStr = 'uint16';\n        case 7\n            dtypeStr = 'int8';\n        case 8\n            dtypeStr = 'uint8';\n        case 9\n            dtypeStr = 'logical';\n        case 10\n            dtypeStr = 'embedded.fi';\n    end\nend", "meta": {"author": "RflySim", "repo": "RflyExpCode", "sha": "7dbec4d8796d6e23ee86c523e4ba5712203b1519", "save_path": "github-repos/MATLAB/RflySim-RflyExpCode", "path": "github-repos/MATLAB/RflySim-RflyExpCode/RflyExpCode-7dbec4d8796d6e23ee86c523e4ba5712203b1519/code/e3/e3.1/px4_read_binary_file.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2109739215914423}}
{"text": "function varargout = unique(varargin)\n% - Adds support for 'stable' flag, with all three outputs. If 'stable' or 'sorted'\n% are used they must be the last input\n% - The first ocurrence is returned by default, as in new Matlab versions. Octave,\n% like old Matlab version, returns the last y default.\n% - Second and third outputs are column vectors, as in new Matlab versions. \nif nargin>=2 && strcmp(varargin{end},'stable')\n    if strcmp(varargin{2},'rows')\n        [a, ~, x] = builtin('unique', varargin{1}, 'rows', 'first');\n    else\n        [a, ~, x] = builtin('unique', varargin{1}, 'first');\n    end\n    if ~isempty(x)\n        [~, ind] = max(bsxfun(@eq, x(:), (1:max(x)))); [y, ind2] = sort(ind(:));\n        [~, ind3] = sort(ind2); z =  ind3(x);\n        for n = 1:numel(x)\n            x(n) = x(n) * ~any(x(n)==x(1:n-1));\n        end\n        x = nonzeros(x).';\n    end    \n    if strcmp(varargin{2},'rows')\n        x = a(x,:);\n    else\n        x = a(x);\n    end\n    varargout{1} = x;\n    if nargout>=2, varargout{2} = y; end\n    if nargout>=3, varargout{3} = z; end\nelse\n    if strcmp(varargin{end},'sorted'), varargin(end) = []; end\n    varargout = cell(1,nargout);\n    if ~any(cellfun(@(x) any(strcmp(x, {'first', 'last'})), varargin(2:end))), varargin{end+1} = 'first'; end\n    [varargout{:}] = builtin('unique', varargin{:});\nend\nif nargout>=2, varargout{2} = varargout{2}(:); end\nif nargout>=3, varargout{3} = varargout{3}(:); end\nend", "meta": {"author": "lmendo", "repo": "MATL", "sha": "8c55bdf3cf64c854ec4ea19fcf2d3d312e1881bb", "save_path": "github-repos/MATLAB/lmendo-MATL", "path": "github-repos/MATLAB/lmendo-MATL/MATL-8c55bdf3cf64c854ec4ea19fcf2d3d312e1881bb/compatibility/unique_comp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21096645787755744}}
{"text": "function model = loss_pyramid(h_loss_func, pyra, model, fg_box, ...\n                              bg_boxes, min_fg_overlap, max_bg_overlap)\n% Computes a pyramid of loss function values for each top-level\n% rule in the grammar.\n%   model = loss_pyramid(h_loss_func, pyra, model, fg_box, ...\n%                        bg_boxes, min_fg_overlap, max_bg_overlap)\n%\n%   These loss values are used for computing the loss adjusted inference:\n%     \\max_{s \\in S(x)} w \\dot \\psi(x,s) + L_margin(y,s)\n%   The set of valid outputs S(x) is enforced by making L(y,s) = -inf for\n%   some values of s, which prevents them from being selected in the \n%   maximization.\n%\n% Return value\n%   model           Model augmented to store the computed loss pyramids\n%\n% Arguments\n%   h_loss_func     Handle to loss function\n%   model           Model \n%                   (augmented with DP tables from gdetect_dp.m)\n%   pyra            Feature pyramid\n%                   (augmented with overlaps from gdetect_pos_prepare.m)\n%   fg_box          Selected foreground bounding box index\n%   bg_boxes        Indices of non-selected bounding boxes in image\n%   min_fg_overlap  Minimum required amount of overlap with fg box\n%   max_bg_overlap  Maximum allowed amount of overlap with bg bounding boxes\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nnum_bg_boxes = length(bg_boxes);\n\n% For each model component\nfor comp = 1:length(model.rules{model.start})\n  % For each feature pyramid level\n  for level = 1:pyra.num_levels\n    if pyra.valid_levels(level)\n      % Assign loss for root locations based on the selected foreground box\n      o = pyra.overlaps(comp).box(fg_box).o{level};\n      losses = h_loss_func(o);\n      model.rules{model.start}(comp).loss{level} = losses;\n\n      % Require at least some overlap with the foreground bounding box\n      % Rationale:\n      %  In an image with multiple objects, this constraint encourages a \n      %  diverse set of false positives (otherwise, they will tend to come \n      %  from the same high-scoring / low-overlapping region of the image \n      %  -- i.e. somewhere in the background)\n      I = find(o < min_fg_overlap);\n      model.rules{model.start}(comp).loss{level}(I) = -inf;\n\n      % Mark root locations that have too much overlap with background boxes\n      % as invalid \n      % Rationale:\n      %   We don't want to select detections of other foreground objects\n      %   in the image as false positives (i.e., no true positive should\n      %   be allowed to be used as a false positive)\n      for b = 1:num_bg_boxes\n        o = pyra.overlaps(comp).box(bg_boxes(b)).o{level};\n        inds = find(o >= max_bg_overlap);\n        model.rules{model.start}(comp).loss{level}(inds) = -inf;\n      end\n    else\n      model.rules{model.start}(comp).loss{level} = 0;\n    end\n  end\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/gdetect/loss_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.2108320685131937}}
{"text": "function [dose3D, A_z3D, r3D, PB3D] = getInfluence(IM, structNum, PBWeightsV)\n%Create 3D dose matrix from PB weigths (PBWeightsV) and\n%a list of structures to have dose computed to (structsV).\n%JOD, 14 Nov 03.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nglobal planC\n\n% maskSingle3D = getUniformStr(structNum);\n\nmaskSingle3D = getSurfaceExpand(structNum,0.5,1); %%%Expandewd structure\n\n[rowV, colV, sliceV] = find3d(maskSingle3D);\n\nnumPBs = size(IM.beamlets,2);\n\ninfluenceM = sparse(prod(size(maskSingle3D)),numPBs);\n\ns = size(maskSingle3D);\n\ndoseInStruct = zeros(s);\n\nsampleRate = IM.beamlets(structNum,1).sampleRate;\n\nif sampleRate ~= 1\n    disp('Inflating downsampled dose distribution...')\n  if rem(log2(sampleRate),1) ~= 0\n    error('Sample factor must (currently) be a power of 2.')\n  end\n  maskSample3D = getDown3Mask(maskSingle3D, sampleRate, 1);\n\n  tmp3D = maskSample3D .* maskSingle3D;\n\n  [rowV,colV,sliceV] = find3d(tmp3D);\n\n  clear tmp3D\n\n  toInterp3D = ~maskSample3D .* maskSingle3D;\n\n  [rInterpV,cInterpV,sInterpV] = find3d(toInterp3D);\n\nend\n\ndose3D = zeros(s);\n \nfor PBNum = 1 : size(IM.beamlets,2)       %Loop over beamlets\n\n  if ~isempty(IM.beamlets(structNum,PBNum).influence)\n\n    doseV     = double(IM.beamlets(structNum,PBNum).influence);\n    indV      = IM.beamlets(structNum,PBNum).indexV;\n    maxVal    = IM.beamlets(structNum,PBNum).maxInfluenceVal;\n    sizeParam = IM.beamlets(structNum,PBNum).fullLength;\n\n    doseScaledV = PBWeightsV(PBNum) * (doseV * maxVal) /(2^8 -1);\n\n    %inflate:\n    doseInflateV = zeros(1,sizeParam);\n    doseInflateV(indV) = doseScaledV;\n    \n\n    %Then put into the dose3D matrix:\n    ind2V = sub2ind(size(dose3D), rowV, colV, sliceV);\n      \n\n    doseInStruct(ind2V) = doseInStruct(ind2V) + doseInflateV(:);\n\n    if strcmpi(IM.params.debug(1),'y')\n      ind0V =IM.beamlets(structNum,PBNum).rIndex;\n      AInflate = zeros(1,sizeParam);\n      rInflate = zeros(1,sizeParam);\n      AInflate(ind0V) = PBWeightsV(PBNum) * double(IM.beamlets(structNum,PBNum).A_zV);\n      A_z3D(ind2V) = AInflate(:); %overwrite\n      rInflate(ind0V) = PBWeightsV(PBNum) * double(IM.beamlets(structNum,PBNum).r);\n      r3D(ind2V) = rInflate(:); %overwrite\n      PB3D(ind2V) = PBNum * ones(length(rInflate),1);\n    end\n\n  end\n\nend\n\n%If sub-sampled, use 3-D interpolation to fill out dose.\n\nif sampleRate ~= 1\n\n  %Now do 3-D interpolation:\n  sizeV = size(dose3D);\n\n  doseInterp = doseInStruct;\n  %Get rid of all points which are not sampled\n  [r3V,c3V,s3V] = find3d(maskSample3D);\n  whereV = sub2ind(sizeV,r3V,c3V,s3V);\n  doseInterp = doseInterp(whereV);\n  doseInterp = reshape(doseInterp,[sizeV(1)/2^log2(sampleRate),sizeV(2)/2^log2(sampleRate),sizeV(3)]);\n\n  rDownV = (rInterpV + 2^log2(sampleRate) - 1)/2^log2(sampleRate);\n  cDownV = (cInterpV + 2^log2(sampleRate) - 1)/2^log2(sampleRate);\n\n  fillsV = matInterp3(rDownV,cDownV,sInterpV,doseInterp);\n\n  ind3V = sub2ind(sizeV,rInterpV,cInterpV,sInterpV);  %index for interpolated values\n  doseInStruct(ind3V) = fillsV;\n  disp('Finished inflating.')\nend\n\ndose3D = dose3D + doseInStruct .* [dose3D==0];  %voxel over-adding avoided\n\n\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/getInfluence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2108272844015892}}
{"text": "function X=ctranspose(X)\n%CTRANSPOSE (overloaded)\n\nif isa(X,'blkvar')\n    X = sdpvar(X);\nend\n\nn = X.dim(1);\nm = X.dim(2);\nind = reshape(reshape(1:n*m,n,m)',n*m,1);\nif isreal(X.basis)\n    X.basis = X.basis(ind,:);    \nelse\n   X.basis = conj(X.basis(ind,:));\nend\nX.dim(1) = m;\nX.dim(2) = n;\n% Reset info about conic terms\nX.conicinfo = [0 0];\n\n% Flip noncommuting terms\n% Get all the tables, and expand them so that they correspond to the same\n% number of variables globally (nonCommutingTable is not up to date after a\n% new commuting variables has been defined, to save flops)\nnonCommutingTable         = yalmip('nonCommutingTable');\n[monomtable,variabletype] = yalmip('monomtable');\nif size(monomtable,1)>size(nonCommutingTable,1)\n    nonCommutingTable((1+size(nonCommutingTable,1)):(size(monomtable,1)),1) = (1+size(nonCommutingTable,1)):(size(monomtable,1));\nend\n% Cast commutative variables as nc temporarily by adding them to the table\ncommuting = find(~any(nonCommutingTable,2));\nnonCommutingTable(commuting,1) = commuting;\n\nfor i = 1:length(X.lmi_variables)\n    if nonCommutingTable(X.lmi_variables(i),2)\n        monoms = nonCommutingTable(X.lmi_variables(i),2:end);      \n        monoms(find(monoms)) = fliplr( monoms(find(monoms)));\n        monoms = [nonCommutingTable(X.lmi_variables(i),1) monoms];\n        old = findrows(nonCommutingTable,monoms);\n        old = findrows(nonCommutingTable(:,2:end),monoms(2:end));\n        if ~isempty(old)\n            old = old(find((monoms(1) == nonCommutingTable(old,1)) | isnan(monoms(1)) & isnan(nonCommutingTable(old,1))));\n        end\n        if isempty(old)\n            % Create a new monomial\n            monomtable(end+1,end+1) = 0;\n            variabletype(end+1) = variabletype(X.lmi_variables(i));\n            nonCommutingTable = [nonCommutingTable;monoms];\n            X.lmi_variables(i) = size(nonCommutingTable,1);\n        else\n            X.lmi_variables(i) = old;\n        end\n    end\nend\n% Fucked up order (lmi_variables should be sorted and unique)\nif any(diff(X.lmi_variables)<0)\n    [i,j]=sort(X.lmi_variables);\n    X.basis = [X.basis(:,1) X.basis(:,j+1)];\n    X.lmi_variables = X.lmi_variables(j);\nend\n[un_Z_vars2] = uniquestripped(X.lmi_variables);\nif length(un_Z_vars2) < length(X.lmi_variables)\n    [un_Z_vars,hh,jj] = unique(X.lmi_variables);\n    if length(X.lmi_variables) ~=length(un_X_vars)\n        X.basis = Z.basis*sparse([1 1+jj],[1 1+(1:length(jj))],ones(1,1+length(jj)))';\n        X.lmi_variables = un_Z_vars;\n    end\nend\nif size(monomtable,2) < size(monomtable,1)\n    monomtable(size(monomtable,1),size(monomtable,1)) = 0;\nend\nyalmip('nonCommutingTable',nonCommutingTable);\nyalmip('setmonomtable',monomtable,variabletype);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/ctranspose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.21079114912085864}}
{"text": "function [f,k,s0,gof] = relaxFitMtDist(data,delta,t1,s0,tr,flipAngle,brainMask,fitMethod,outMontage)\n%\n% [f,k,s0,gof] = relaxFitMtDist(data,delta,t1,s0,tr,flipAngle,brainMask,fitMethod,outMontage)\n% \n% Computes a nonlinear fit of the bound-pool (f) map.\n%\n% Returns:\n%\n% SEE ALSO:\n% \n% relaxFitT1.m to fit the t1 and pd maps used by this function.\n%\n% HISTORY:\n% 2008.02.26 RFD: wrote it.\n\nif(~exist('fitMethod','var')||isempty(fitMethod))\n    fitMethod = 'fmin';\nend\nif(lower(fitMethod(1))=='p')\n    fitMethod = fitMethod(2:end);\n    useParfor = true;\nelse\n    useParfor = false;\nend\nfitMethod = lower(fitMethod(1));\n\nif(~exist('outMontage','var')||isempty(outMontage))\n    outMontage = 'f.png';\nend\n\nflipAngle = flipAngle*pi/180;\ntr = tr/1000;\nsz = size(data);\n\n% disp('smoothing s0 map...');\n% deltaT = 1/44;\n% kappa = 200;\n% s0 = dtiSmoothAnisoPM(s0, 4, deltaT, kappa, 1, [1 1 1]);\n% \n%disp('smoothing MT measurments...');\n%kappa = 50;\n%for(ii=1:sz(4))\n%    data(:,:,:,ii) = dtiSmoothAnisoPM(data(:,:,:,ii), 2, deltaT, kappa, 1, [1 1 1]);\n%end\n\nbrainInds = find(brainMask);\nnumVoxelsPerUpdate = 16000;\nnVoxAll = length(brainInds);\nfor(ii=1:size(data,4))\n  tmpVol = data(:,:,:,ii);\n  tmpMT(ii,:) = tmpVol(brainInds);\nend\nclear tmpVol;\ndata = tmpMT;\nclear tmpMT;\nr1 = 1./t1(brainInds);\ns0 = s0(brainInds);\n\nf = zeros(1,nVoxAll); \nk = zeros(1,nVoxAll);\ngof = zeros(1,nVoxAll);\ntotalSecs = 0;\n\ntmpImg = zeros(sz(1:3));\ntmpName = tempname\nnSteps = ceil(nVoxAll/numVoxelsPerUpdate);\ntotalTime = 0;\ntic;\nfor(ii=1:nSteps)\n    if(useParfor), matlabpool; end\n    curInd = (ii-1)*numVoxelsPerUpdate+1;\n    endInd = min(curInd+numVoxelsPerUpdate,nVoxAll);\n    [tf,tk,tgof] = relaxFitMt(data(:,curInd:endInd),delta,r1(curInd:endInd),s0(curInd:endInd),tr,flipAngle,fitMethod,useParfor);\n    prevSecs = toc;\n    totalTime = totalTime+prevSecs;\n    f(curInd:endInd) = tf;\n    k(curInd:endInd) = tk;\n    gof(curInd:endInd) = tgof;\n    secsPerVox = prevSecs/(endInd-curInd+1);\n    estTime = secsPerVox*(nVoxAll-endInd);\n    if(estTime>5400) estTime=estTime./3600; estTimeUnits='hours';\n    elseif(estTime>90) estTime=estTime./60; estTimeUnits='minutes';\n    else estTimeUnits='seconds'; \n    end\n    fprintf('Processed %d of %d voxels- %0.1f %s remaining (%0.3f secs per vox)...\\n',endInd,nVoxAll,estTime,estTimeUnits,secsPerVox);\n    tmpImg(brainInds) = f;\n    m = makeMontage(tmpImg);\n    if(max(f)>0), m = m./max(f); end\n    m = uint8(round(m.*255));\n    imwrite(m,outMontage);\n    save(tmpName,'k','f','gof','brainMask');\n    tic;\n    if(useParfor), matlabpool close; end\nend\nfprintf('Processed %d voxels in %0.2f hours.\\n',totalTime/3600);\n\n% f = vertcat(tf);\n% k = vertcat(tk);\n% gof = vertcat(tgof);\n\nim=zeros(size(brainMask)); im(brainInds) = f; f = im;\nim=zeros(size(brainMask)); im(brainInds) = k; k = im;\nim=zeros(size(brainMask)); im(brainInds) = gof; gof = im;\nim=zeros(size(brainMask)); im(brainInds) = s0; s0 = im;\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrQuant/relaxometry/relaxFitMtDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21079114684943565}}
{"text": "function output = callipopt(model)\n\noptions = [];\ntry\n    options.ipopt = optiRemoveDefaults(model.options.ipopt,ipoptset());\ncatch\n    options.ipopt = model.options.ipopt;\nend\noptions.ipopt.print_level = 2+model.options.verbose;\n\n% Standard NONLINEAR setup\ntempF = model.F_struc;\ntempK = model.K;\ntempx0 = model.x0;\nmodel = yalmip2nonlinearsolver(model);\n% % Try to propagate initial values now that nonlinear evaluation logic is\n% % set up. Do this if some of the intials are nan\nif any(isnan(model.x0)) & ~all(isnan(model.x0))        \n    [~,~,xevaledout] = fmincon_fun(model.x0,model);\n    startNan = nnz(isnan(xevaledout));\n    goon = 1;\n    while goon\n        temp = propagatex0(xevaledout,tempF,tempK);\n        model.x0 = temp(model.linearindicies);\n        [~,~,xevaledout] = fmincon_fun(model.x0,model);\n        goon =  nnz(isnan(xevaledout)) < startNan;\n        startNan = nnz(isnan(xevaledout));\n    end     \nend\nmodel.x0(isnan(model.x0))=0;\n\n\nif ~model.derivative_available\n    disp('Derivate-free call to ipopt not yet implemented')\n    error('Derivate-free call to ipopt not yet implemented')\nend\nif model.options.savedebug\n    save ipoptdebug model\nend\nshowprogress('Calling IPOPT',model.options.showprogress);\n\n% Figure out which variables are artificially introduced to normalize\n% arguments in callback operators to simplify chain rules etc. We can do\n% our function evaluations and gradient computations in our lifted world,\n% but only expose the model in the original variables to the nonlinear\n% solver. \n% model = compressLifted(model);\n\nFupp = [ repmat(0,length(model.bnonlinineq)+length(model.K.q)*(model.K.q(1)>0),1);\n    repmat(0,length(model.bnonlineq),1);\n    repmat(0,length(model.b),1);\n    repmat(0,length(model.beq),1)];\n\nFlow = [ repmat(-inf,length(model.bnonlinineq)+length(model.K.q)*(model.K.q(1)>0),1);\n    repmat(0,length(model.bnonlineq),1);\n    repmat(-inf,length(model.b),1);\n    repmat(0,length(model.beq),1)];\n\nif isempty(Flow)\n    Flow = [];\n    Fupp = [];\nend\n\n% Since ipopt react strangely on lb>ub, we should bail if that is detected\n% (ipopt creates an exception)\nif ~isempty(model.lb)\n    if any(model.lb>model.ub)\n        problem = 1;   \n        solverinput = [];\n        solveroutput = [];  \n        output = createoutput(model.c*0,[],[],problem,'IPOPT',solverinput,solveroutput,0);\n        return\n    end\nend\n\n% These are needed to avoid recomputation due to ipopts double call to get\n% f and df, and g and dg\nglobal latest_x_f\nglobal latest_x_g\nglobal latest_df\nglobal latest_f\nglobal latest_G\nglobal latest_g\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_G = [];\nlatest_g = [];\nlatest_x_f = [];\nlatest_x_g = [];\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\nfuncs.objective = @(x)ipopt_callback_f(x,model);\nfuncs.gradient = @(x)ipopt_callback_df(x,model);\nif ~isempty(Fupp)\n    funcs.constraints = @(x)ipopt_callback_g(x,model);\n    funcs.jacobian  = @(x)ipopt_callback_dg(x,model);\nend\n\noptions.lb = model.lb(:)';\noptions.ub = model.ub(:)';\nif ~isempty(Fupp)\n    options.cl = Flow;\n    options.cu = Fupp;\nend\n\nif ~isempty(Fupp)\n    Z = jacobiansparsityfromnonlinear(model);\n    funcs.jacobianstructure = @() Z;\nend\n\nif ~model.options.usex0\n    model.x0 = (options.lb+options.ub)/2;\n    model.x0(isinf(options.ub)) = options.lb(isinf(options.ub))+1;\n    model.x0(isinf(options.lb)) = options.ub(isinf(options.lb))-1;\n    model.x0(isinf(model.x0)) = 0;\n    if any(model.variabletype == 4)\n        problematic = find(any(model.monomtable(:,model.linearindicies) < 0 ,1));\n        if ~isempty(problematic)\n            problematic = problematic(find(model.x0(problematic)==0));\n            Oneisfeas = problematic(find(model.ub(problematic) > 1));\n            model.x0(Oneisfeas) = 1;\n        end\n    end\n    model.x0(find(model.lb==model.ub)) = model.lb(find(model.lb==model.ub));\nend\n\n% If quadratic objective and no nonlinear constraints, we can supply an\n% Hessian of the Lagrangian\nusedinObjective = find(model.c | any(model.Q,2));\nif ~any(model.variabletype(usedinObjective)) & any(model.Q)\n    if  length(model.bnonlinineq)==0 & length(model.bnonlineq)==0\n        H = model.Q(:,model.linearindicies);\n        H = H(model.linearindicies,:);\n        funcs.hessian = @(x,s,l) tril(2*H);\n        funcs.hessianstructure = @()tril(sparse(double(H | H)));      \n        options.ipopt.hessian_approximation = 'exact';\n    end\nend\n\nsolvertime = tic;\n[xout,info] = ipopt(model.x0,funcs,options);\nsolvertime = toc(solvertime);\n\n% Duals currently not supported\nlambda = [];\n\nif ~isempty(xout) && ~isempty(model.lift);\n    x = zeros(length(model.linearindicies),1);\n    x(model.lift.linearIndex) = xout(:);\n    x(model.lift.liftedIndex) = model.lift.T*xout(:) + model.lift.d;\n    x = RecoverNonlinearSolverSolution(model,x);\nelse\n    x = RecoverNonlinearSolverSolution(model,xout);\nend\n\nswitch info.status\n    case {0,1}\n        problem = 0;\n    case {2}\n        problem = 1;\n    case {-1}\n        problem = 3;\n    case {3,4,-2,-3}\n        problem = 4;\n    case {-11,-12,-13}\n        problem = 7;\n    case {-10,-100,-101,-102,-199}\n        problem = 11;\n    otherwise\n        problem = -1;\nend\n\n% Internal format for duals\nD_struc = [];\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n    solverinput.model = model;\nelse\n    solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n    solveroutput.x = xout;  \n    solveroutput.info = info;\nelse\n    solveroutput = [];\nend\n\n% Standard interface\noutput = createoutput(x,D_struc,[],problem,'IPOPT',solverinput,solveroutput,solvertime);\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/callipopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.21079114684943562}}
{"text": "function shim = cvx_glpk( shim )\n\n% CVX_SOLVER_SHIM\tGLPK interface for CVX.\n%   This procedure returns a 'shim': a structure containing the necessary\n%   information CVX needs to use this solver in its modeling framework.\n\nif ~isempty( shim.solve ),\n    return\nend\nif isempty( shim.name ),\n    fname = 'glpk.m';\n    ps = pathsep;\n    shim.name = 'GLPK';\n    shim.dualize = true;\n    flen = length(fname);\n    fpaths = which( fname, '-all' );\n    if ~iscell(fpaths),\n      fpaths = { fpaths };\n    end\n    old_dir = pwd;\n    oshim = shim;\n    shim = [];\n    for k = 1 : length(fpaths),\n        fpath = fpaths{k};\n        if ~exist( fpath, 'file' ) || any( strcmp( fpath, fpaths(1:k-1) ) ),\n            continue\n        end\n        new_dir = fpath(1:end-flen-1);\n        cd( new_dir );\n        tshim = oshim;\n        tshim.fullpath = fpath;\n        tshim.version = 'unknown';\n        tshim.location = new_dir;\n        if isempty( tshim.error ),\n            tshim.check = @check;\n            tshim.solve = @solve;\n            tshim.eargs = {};\n            if k ~= 1,\n                tshim.path = [ new_dir, ps ];\n            end\n        end\n        shim = [ shim, tshim ]; %#ok\n    end\n    cd( old_dir );\n    if isempty( shim ),\n        shim = oshim;\n        shim.error = 'Could not find a GLPK installation.';\n    end\nelse\n    shim.check = @check;\n    shim.solve = @solve;\nend\n    \nfunction found_bad = check( nonls ) %#ok\nfound_bad = false;\n\nfunction [ x, status, tol, iters, y, z ] = solve( At, b, c, nonls, quiet, prec, settings )\n\nn  = length( c );\nm  = length( b );\nlb = -Inf(n,1);\nub = +Inf(n,1);\nvtype = 'C';\nvtype = vtype(ones(n,1));\nctype = 'S';\nctype = ctype(ones(m,1));\nrr = zeros(0,1);\ncc = rr; \nvv = rr;\nzinv = rr;\nis_ip = false;\nfor k = 1 : length( nonls ),\n    temp = nonls( k ).indices;\n    nn = size( temp, 1 );\n    nv = size( temp, 2 );\n    tt = nonls( k ).type;\n    if strncmp( tt, 'i_', 2 ),\n      is_ip = true;\n      vartype(temp) = 'I';\n      if strcmp(tt,'i_binary'),\n        lb(temp) = 0;\n        ub(temp) = 1;\n      end\n    elseif nn == 1 || isequal( tt, 'nonnegative' ),\n        lb(temp) = 0;\n    elseif isequal( tt, 'lorentz' ),\n        if nn == 2,\n            rr2  = [ temp ; temp ];\n            cc2  = reshape( floor( 1 : 0.5 : 2 * nv + 0.5 ), 4, nv );\n            vv2  = [1;1;-1;1]; vv = vv(:,ones(1,nv));\n            rr   = [ rr ; rr(:) ];\n            cc   = [ cc ; cc(:) ];\n            vv   = [ vv ; vv(:) ];\n            zinv = [ zinv ; temp(:) ];\n        else\n            error('GLPK does not support nonlinear constraints.' );\n        end\n    else\n      error('GLPK does not support nonlinear constraints.' );\n    end\nend\nif ~isempty(rr),\n  znorm = [1:n]';\n  znorm(zinv) = [];\n  rr = [ rr ; znorm ];\n  cc = [ cc ; znorm ];\n  vv = [ vv ; ones(size(znorm)) ];\n  reord = sparse( rr, cc, vv, n, n );\n  At = reord' * At;\n  c  = reord' * c;\nend\nif quiet,\n  param.msglev = 0;\nelse\n  param.msglev = 2;\nend\nparam.scale = 128;\nparam.tolbnd = prec(1);\nparam.toldj = prec(1);\nparam.tolobj = prec(1);\n[ xx, fmin, errnum, extra ] = cvx_run_solver( @glpk, c, At', b, lb, ub, ctype, vtype, 1, param, 'xx', 'fmin', 'errnum', 'extra', settings, 9 );\ntol   = [];\niters = [];\nx = full( xx );\ny = full( extra.lambda );\nz = full( extra.redcosts );\nif ~isempty( rr ),\n  x = reord * x;\n  z = reord * z;\n  z(zinv) = z(zinv) * 0.5;\nend\nstatus = 'Failed';\nswitch errnum,\ncase 0,\n  switch extra.status,\n  case 2,\n    if is_ip,\n      status = 'Suboptimal';\n    elseif errnumn == 0,\n      status = 'Solved';\n    else\n      status = 'Inaccurate/Solved';\n    end  \n  case {3,4},\n    status = 'Infeasible';\n  case 5,\n    status = 'Solved';\n  case 6,\n    status = 'Unbounded';\n  end\ncase 10,\n  status = 'Infeasible';\ncase 11,\n  status = 'Unbounded';\ncase {5,17,15,19}\n  status = 'Failed';\ncase {6,7,8,9,13,14},\n  switch extra.status,\n  case {2,5}\n    if is_ip,\n      status = 'Suboptimal';\n    else\n      status = 'Inaccurate/Solved';\n    end  \n  case { 3,4 },\n    status = 'Inaccurate/Infeasible';\n  case 6,\n    status = 'Inaccurate/Unbounded';\n  end\nend\nif strcmp(status,'Failed'),\n  tol = Inf;\nelseif strncmp(status,'Inaccurate/',11),\n  tol = prec(3);\nelse\n  tol = prec(2);\nend\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/shims/cvx_glpk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.21037225816046315}}
{"text": "function varargout = spm_bms_display(BMS,action)\n% Display results from BMS Maps\n% FORMAT spm_bms_display(BMS,action)\n%\n% Input:\n% BMS    - BMS containing details of excursion set\n% action - 'Init' (Initialise)\n%          'do_plot' (plot voxel results)\n%          'save' (save results as NIfTI image)\n%          'overlays' (options overlays menu)\n%__________________________________________________________________________\n% Copyright (C) 2009-2019 Wellcome Trust Centre for Neuroimaging\n\n% Maria Joao Rosa\n% $Id: spm_bms_display.m 7577 2019-04-24 08:59:56Z guillaume $\n\n\n% Main options (action)\n% =========================================================================\nswitch action\n    \n    % Inititalise - action: 'Init'\n    % =====================================================================\n    case 'Init'\n\n    % Initialise variables\n    % ---------------------------------------------------------------------\n    xSPM  = BMS.xSPM; \n    M     = xSPM.xVol.M;\n    iM    = xSPM.iM;\n    DIM   = xSPM.xVol.DIM;\n    \n    try\n        if strcmp(spm('CheckModality'),'EEG')\n            datatype = {...\n                'Volumetric (2D/3D)',...\n                'Scalp-Time',...\n                'Scalp-Frequency',...\n                'Time-Frequency',...\n                'Frequency-Frequency'};\n            selected = spm_input('Data Type: ','+1','m',datatype);\n            datatype = datatype{selected};\n        else\n            datatype = 'Volumetric (2D/3D)';\n        end\n    catch\n        datatype     = 'Volumetric (2D/3D)';\n    end\n    \n    switch datatype\n        case 'Volumetric (2D/3D)'\n            units    = {'mm' 'mm' 'mm'};\n        case 'Scalp-Time'\n            units    = {'mm' 'mm' 'ms'};\n        case 'Scalp-Frequency'\n            units    = {'mm' 'mm' 'Hz'};\n        case 'Time-Frequency'\n            units    = {'Hz' 'ms' ''};\n        case 'Frequency-Frequency'\n            units    = {'Hz' 'Hz' ''};\n        otherwise\n            error('Unknown data type.');\n    end\n        \n    title = 'Bayesian Model Selection';\n    str   = xSPM.str;\n\n    % Initialise figures\n    % ---------------------------------------------------------------------\n    [Finter,Fgraph,CmdLine] = spm('FnUIsetup','BMS: Results');\n    FS = spm('FontSizes');\n    WS = spm('WinScale');\n    PF = spm_platform('fonts');\n\n    % Clear satellite figure if it exists\n    % ---------------------------------------------------------------------\n    hSat = findobj('tag','Satellite');\n    spm_figure('clear',hSat);\n\n    % Setup Finter (interactive window)\n    % ---------------------------------------------------------------------\n    spm_figure('Clear',Finter);\n    spm('FigName','BMS results',Finter,CmdLine);\n    Finter  = spm_figure('GetWin',Finter);\n\n    hReg    = uicontrol(Finter,'Style','Frame','Position',...\n        [001 001 400 190].*WS,'BackgroundColor',spm('Colour'));\n                       \n    hFResUi = uicontrol(Finter,'Style','Frame','Position',...\n        [008 007 387 178].*WS);\n                       \n    [hReg,xyz] = spm_XYZreg('InitReg',hReg,M,DIM,[0;0;0]);\n\n    % Draw MIP\n    % ---------------------------------------------------------------------\n    hMIPax = axes('Parent',Fgraph,'Position',...\n        [0.125 0.5450 0.59 0.40],'Visible','off');\n    hMIPax = spm_mip_ui(xSPM.Z,xSPM.XYZmm,M,DIM,hMIPax,units);\n    spm_XYZreg('XReg',hReg,hMIPax,'spm_mip_ui');\n    hTitAx = axes('Parent',Fgraph,'Position',[0.02 0.95 0.86 0.02],...\n        'Visible','off');\n    text(0.5,0,title,'Parent',hTitAx,'HorizontalAlignment','center',...\n        'VerticalAlignment','baseline','FontWeight','Bold','FontSize',FS(14))\n\n    text(240,260,str,'Interpreter','TeX','FontSize',FS(14),...\n        'Fontweight','Bold','Parent',hMIPax)\n    \n    % Print BMSresults: Results directory & thresholding info\n    %----------------------------------------------------------------------\n    hResAx = axes('Parent',Fgraph,...\n        'Position',[0.160 0.510 0.45 0.05],...\n        'DefaultTextVerticalAlignment','baseline',...\n        'DefaultTextFontSize',FS(9),...\n        'DefaultTextColor',[1,1,1]*.7,...\n        'Units','points',...\n        'Visible','off');\n    AxPos = get(hResAx,'Position'); set(hResAx,'YLim',[0,AxPos(4)])\n    h     = text(0,24,'BMSresults:','Parent',hResAx,...\n        'FontWeight','Bold','FontSize',FS(14));\n    text(get(h,'Extent')*[0;0;1;0],24,spm_file(pwd,'short30'),'Parent',hResAx)\n    text(0,12,sprintf('Threshold: %0.2d',BMS.xSPM.thres),'Parent',hResAx)\n    \n    % Store handles of results section Graphics window objects\n    %----------------------------------------------------------------------\n    H  = get(Fgraph,'Children');\n    H  = findobj(H,'flat','HandleVisibility','on');\n    H  = findobj(H);\n    Hv = get(H,'Visible');\n    set(hResAx,'Tag','PermRes','UserData',struct('H',H,'Hv',{Hv}))\n    \n    % Draw buttons\n    %----------------------------------------------------------------------\n    Finter = spm_figure('FindWin','Interactive');\n    xyz    = [0;0;0];\n    xyz    = spm_XYZreg('RoundCoords',xyz,M,DIM);\n\n    % Create XYZ control objects\n    % ---------------------------------------------------------------------\n    hFxyz = uicontrol(Finter,'Style','Text',...\n            'Position',[010 010 265 030].*WS);\n    uicontrol(Finter,'Style','Text','String','co-ordinates',...\n            'Position',[020 033 078 016].*WS,...\n            'FontAngle','Italic',...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Left',...\n            'ForegroundColor','w')\n\n    uicontrol(Finter,'Style','Text','String','x =',...\n            'Position',[020 015 024 018].*WS,...\n            'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...\n            'HorizontalAlignment','Center');\n    hX   = uicontrol(Finter,'Style','Edit','String',...\n            sprintf('%.2f',xyz(1)),...\n            'ToolTipString','enter x-coordinate',...\n            'Position',[044 015 056 020].*WS,...\n            'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...\n            'HorizontalAlignment','Right',...\n            'Tag','hX',...\n            'Callback','spm_bms_display('''',''plot_xyz'')');\n\n    uicontrol(Finter,'Style','Text','String','y =',...\n            'Position',[105 015 024 018].*WS,...\n            'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...\n            'HorizontalAlignment','Center')\n    hY   = uicontrol(Finter,'Style','Edit','String',...\n            sprintf('%.2f',xyz(2)),...\n            'ToolTipString','enter y-coordinate',...\n            'Position',[129 015 056 020].*WS,...\n            'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...\n            'HorizontalAlignment','Right',...\n            'Tag','hY',...\n            'Callback','spm_bms_display('''',''plot_xyz'')');\n\n    uicontrol(Finter,'Style','Text','String','z =',...\n            'Position',[190 015 024 018].*WS,...\n            'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...\n            'HorizontalAlignment','Center')\n    hZ   = uicontrol(Finter,'Style','Edit','String',...\n            sprintf('%.2f',xyz(3)),...\n            'ToolTipString','enter z-coordinate',...\n            'Position',[214 015 056 020].*WS,...\n            'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...\n            'HorizontalAlignment','Right',...\n            'Tag','hZ',...\n            'Callback','spm_bms_display('''',''plot_xyz'')');\n        \n    % Voxel value reporting pane\n    % ---------------------------------------------------------------------\n    hFconB = uicontrol(Finter,'Style','Text',...\n            'Position',[280 010 110 030].*WS);\n    uicontrol(Finter,'Style','Text','String','voxel value',...\n            'Position',[285 035 085 016].*WS,...\n            'FontAngle','Italic',...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Left',...\n            'ForegroundColor','w')\n    hSPM = uicontrol(Finter,'Style','Text','String','',...\n            'Position',[285 012 100 020].*WS,...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Center');\n       \n    % Store UserData\n    % ---------------------------------------------------------------------\n    set(hFxyz,'Tag','hFxyz','UserData',struct(...\n              'hReg',   [],...\n              'M',      M,...\n              'iM',     iM,...\n              'DIM',    DIM,...\n              'XYZ',    xSPM.XYZmm,...\n              'Z',      xSPM.Z,...\n              'hX',     hX,...\n              'hY',     hY,...\n              'hZ',     hZ,...\n              'hSPM',   hSPM,...\n              'xSPM',   xSPM,...\n              'fhFxyz', hFxyz,...\n              'hMIPax', hMIPax,...\n              'xyz',    xyz,...\n              'thres',  BMS.xSPM.thres,...\n              'scale',  BMS.xSPM.scale,...\n              'vols',   BMS.xSPM.vols,...\n              'k',      BMS.xSPM.k,...\n              'BMS',    BMS));\n\n    set([hX,hY,hZ],'UserData',hFxyz);\n    \n    % Register with hReg\n    % ---------------------------------------------------------------------\n    spm_XYZreg('XReg',hReg,hFxyz,'spm_results_ui');\n    \n    % Model partition\n    % ---------------------------------------------------------------------\n    uicontrol(Finter,'Style','PushButton','String','compare subsets',...\n                'FontSize',FS(10),...\n                'ToolTipString','Create and compare subsets of models',...\n                'Callback','spm_bms_display('''',''partition'');',...\n                'Interruptible','on','Enable','on',...\n                'Position',[130 055 140 020].*WS,...\n                'ForegroundColor','k');\n            \n    % Compare groups\n    % ---------------------------------------------------------------------\n    uicontrol(Finter,'Style','PushButton','String','compare groups',...\n                'FontSize',FS(10),...\n                'ToolTipString','Compare two groups. E.g. controls vs patients.',...\n                'Callback','spm_bms_display('''',''groups'');',...\n                'Interruptible','on','Enable','on',...\n                'Position',[015 055 100 020].*WS,...\n                'ForegroundColor','k');\n           \n    % Draw Save, Clear and Exit\n    % ---------------------------------------------------------------------\n    hClear = uicontrol(Finter,'Style','PushButton','String','clear',...\n            'ToolTipString','clears results subpane',...\n            'FontSize',FS(9),'ForegroundColor','b',...\n            'Callback',['spm_results_ui(''Clear''); ',...\n            'spm_input(''!DeleteInputObj''),',...\n            'spm_clf(''Satellite'')'],...\n            'Interruptible','on','Enable','on',...\n            'DeleteFcn','spm_clf(''Graphics'')',...\n            'Position',[285 055 035 020].*WS);\n\n    hExit  = uicontrol(Finter,'Style','PushButton','String','exit',...\n            'ToolTipString','exit the results section',...\n            'FontSize',FS(9),'ForegroundColor','r',...\n            'Callback',['spm_clf(''Interactive''),spm_clf(''Graphics''),'...\n            'close(spm_figure(''FindWin'',''Satellite'')),'...\n            'clear'],...\n            'Interruptible','on','Enable','on',...\n            'Position',[325 055 035 020].*WS);\n\n    hHelp  = uicontrol(Finter,'Style','PushButton','String','',...\n            'ToolTipString','',...\n            'FontSize',FS(9),'ForegroundColor','g',...\n            'Callback','',...\n            'Interruptible','on','Enable','off',...\n            'Position',[365 055 020 020].*WS);\n        \n    % Change options\n    % ---------------------------------------------------------------------\n    uicontrol(Finter,'Style','Text',...\n            'Position',[125 090 150 085].*WS)\n    uicontrol(Finter,'Style','Text','String','options',...\n            'Position',[135 168 60 015].*WS,...\n            'FontAngle','Italic',...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Left',...\n            'ForegroundColor','w')\n    uicontrol(Finter,'Style','PushButton','String','results',...\n            'Position',[130 145 140 020].*WS,...\n            'ToolTipString',...\n            'BMS Maps (Results)',...\n            'Callback','spm_run_bms_vis',...\n            'Interruptible','on','Enable','on',...\n            'FontSize',FS(10),'ForegroundColor','k')\n    uicontrol(Finter,'Style','PushButton','String','change model',...\n            'Position',[130 120 140 020].*WS,...\n            'ToolTipString',...\n            'Change model/data',...\n            'Callback','spm_bms_display('''',''change_data'')',...\n            'Interruptible','on','Enable','on',...\n            'FontSize',FS(10),'ForegroundColor','k')\n    uicontrol(Finter,'Style','PushButton','String','threshold',...\n            'Position',[130 95 68 020].*WS,...\n            'ToolTipString',...\n            'Change threshold (same data)',...\n            'Callback','spm_bms_display('''',''change_thres'')',...\n            'Interruptible','on','Enable','on',...\n            'FontSize',FS(8),'ForegroundColor','k')\n    uicontrol(Finter,'Style','PushButton','String','scale',...\n            'Position',[202 95 68 020].*WS,...\n            'ToolTipString',...\n            'Change scale (same data)',...\n            'Callback','spm_bms_display('''',''change_scale'')',...\n            'Interruptible','on','Enable','on',...\n            'FontSize',FS(8),'ForegroundColor','k')\n    \n    %-p-values\n    %------------------------------------------------------------------\n    uicontrol(Finter,'Style','Text','String','p-values',...\n            'Position',[020 168 050 015].*WS,...\n            'FontAngle','Italic',...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Left',...\n            'ForegroundColor','w')\n    uicontrol(Finter,'Style','PushButton','String','whole brain','FontSize',FS(10),...\n            'ToolTipString',...\n            'tabulate summary of local maxima, p-values & statistics',...\n            'Callback','spm_bms_display('''',''list'');',...\n            'Interruptible','on','Enable','on',...\n            'Position',[015 145 100 020].*WS)\n    uicontrol(Finter,'Style','PushButton','String','current cluster','FontSize',FS(10),...\n            'ToolTipString',...\n            'tabulate p-values & statistics for local maxima of nearest cluster',...\n            'Callback','spm_bms_display('''',''listCluster'');',...\n            'Interruptible','on','Enable','on',...\n            'Position',[015 120 100 020].*WS)\n    uicontrol(Finter,'Style','PushButton','String','ROI','FontSize',FS(10),...\n            'ToolTipString',...\n            'plot probabilities for selected ROI',...\n            'Callback','spm_bms_display('''',''plotROI'');',...\n            'Position',[015 095 100 020].*WS)\n        \n    uicontrol(Finter,'Style','PushButton','String','small volume','FontSize',FS(10),...\n            'ToolTipString',['Small Volume Correction - probability values ',...\n            'for a small search region'],...\n            'Callback','spm_bms_display('''',''listVOI'');',...\n            'Interruptible','on','Enable','on',...\n            'Position',[015 095 100 020].*WS)\n        \n    % Draw Options\n    % ---------------------------------------------------------------------\nuicontrol(Finter,'Style','Text',...\n            'Position',[280 090 110 085].*WS)\n    uicontrol(Finter,'Style','Text','String','display',...\n            'Position',[290 168 065 015].*WS,...\n            'FontAngle','Italic',...\n            'FontSize',FS(10),...\n            'HorizontalAlignment','Left',...\n            'ForegroundColor','w')\n        \n    strp  = { 'plot...','current voxel','ROI'};\n    tstrp = { 'plot results from comparisons at: ',...\n        'current voxel / ','region of interest /'};\n    tmpp  = { 'spm_bms_display('''',''do_plot'')',...\n            'spm_bms_display('''',''do_ROI'')'};\n        \n    uicontrol(Finter,'Style','PopUp','String',strp,'FontSize',FS(10),...\n            'ToolTipString',cat(2,tstrp{:}),...\n            'UserData',tmpp,...\n            'Callback','spm_bms_display('''',''overlays'')',...\n            'Interruptible','on','Enable','on',...\n            'Position',[285 145 100 020].*WS)\n    str  = { 'overlays...','slices','sections','render','previous sections'};\n    tstr = { 'overlay results on another image: ',...\n        '3 slices / ''ortho sections / ','render /','previous ortho sections'};\n    tmp  = { 'spm_transverse(''set'',xSPM,hReg)',...\n            'spm_sections(xSPM,hReg);global st;st.vols{1}.blobs{1}.min=xSPM.u;spm_orthviews(''redraw'');',...\n            ['spm_render(   struct( ''XYZ'',    xSPM.XYZ,',...\n            '''t'',     xSPM.Z'',',...\n            '''mat'',   xSPM.M,',...\n            '''dim'',   xSPM.DIM))'],...\n            ['global prevsect;','spm_sections(xSPM,hReg,prevsect)'],...\n            ['global prevrend;','if ~isstruct(prevrend)',...\n            'prevrend = struct(''rendfile'','''',''brt'',[],''col'',[]); end;',...            \n            'spm_render(    struct( ''XYZ'',    xSPM.XYZ,',...\n            '''t'',     xSPM.Z'',',...\n            '''mat'',   xSPM.M,',...\n            '''dim'',   xSPM.DIM),prevrend.brt,prevrend.rendfile)']};\n    uicontrol(Finter,'Style','PopUp','String',str,'FontSize',FS(10),...\n            'ToolTipString',cat(2,tstr{:}),...\n            'Callback','spm_bms_display('''',''overlays'')',...\n            'UserData',tmp,...\n            'Interruptible','on','Enable','on',...\n            'Position',[285 120 100 020].*WS)\n    uicontrol(Finter,'Style','PushButton','String','save','FontSize',...\n            FS(10),'ToolTipString','save thresholded BMS as image',...\n            'Callback','spm_bms_display('''',''save'')',...\n            'Interruptible','on','Enable','on',...\n            'Position',[285 095 100 020].*WS)\n    user_data = get(hFxyz,'UserData');\n    set(Finter,'UserData',user_data,...\n            'HandleVisibility','callback')\n\n    varargout = { hReg };\n        \n    % Do plot - action: 'do_plot'\n    % =====================================================================\n    case 'do_plot'\n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        iM        = user_data.iM;\n        BMS       = user_data.BMS;\n        user_data = get(user_data.hMIPax,'UserData');\n        user_data = get(user_data.hMIPxyz,'UserData');\n        xyz_vx    = iM*[user_data; 1];\n        spm_bms_display_vox(BMS,xyz_vx(1:3));   \n        \n    % Do ROI - action: 'do_ROI'\n    % =====================================================================\n    case 'do_ROI'\n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        iM        = user_data.iM;\n        BMS       = user_data.BMS;\n        user_data = get(user_data.hMIPax,'UserData');\n        user_data = get(user_data.hMIPxyz,'UserData');\n        xyz_vx    = iM*[user_data; 1];\n        spm_bms_display_ROI(BMS);     \n\n    % Do overlays - action: 'overlays'\n    % =====================================================================\n    case 'overlays'\n        \n        h   = gcbo;\n        v   = get(h,'Value');\n        if v==1, return, end\n        set(h,'Value',1)\n        CBs       = get(h,'UserData');\n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        hReg      = user_data.hReg;\n        xSPM      = user_data.xSPM;\n        eval(CBs{v-1})\n      \n    % Save - action: 'save'\n    % =====================================================================\n    case 'save'  \n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        xSPM      = user_data.xSPM;\n        spm_write_filtered(xSPM.Z,xSPM.XYZ,xSPM.DIM,xSPM.M,'Results saved');\n     \n    % Plot xyz BMS values - action: 'plot_xyz'\n    % =====================================================================\n    case 'plot_xyz'\n        \n        hC    = gcbo;\n        d     = find(strcmp(get(hC,'Tag'),{'hX','hY','hZ'}));\n        hFxyz = get(hC,'UserData');\n        UD    = get(hFxyz,'UserData');\n        xyz   = UD.xyz;\n        nxyz  = xyz;\n\n        o = evalin('base',['[',get(hC,'String'),']'],'sprintf(''error'')');\n        if ischar(o) || length(o)>1\n            warning('%s: Error evaluating ordinate:\\n\\t%s',...\n                mfilename,lasterr)\n        else\n            nxyz(d) = o;\n            nxyz = spm_XYZreg('RoundCoords',nxyz,UD.M,UD.DIM);\n        end\n\n        if abs(xyz(d)-nxyz(d))>0\n            UD.xyz = nxyz; set(hFxyz,'UserData',UD)\n            if ~isempty(UD.hReg), spm_XYZreg('SetCoords',nxyz,UD.hReg,hFxyz); end\n            set(hC,'String',sprintf('%.3f',nxyz(d)))\n            i  = spm_XYZreg('FindXYZ',UD.xyz,UD.XYZ);\n            if isempty(i), str = ''; else str = sprintf('%6.2f',UD.Z(i)); end\n               set(UD.hSPM,'String',str);\n        end\n        \n        fig = gcf;\n        set(fig,'UserData',UD)\n     \n    % Change model\n    % =====================================================================    \n    case 'change_data'\n        \n        fig         = gcf;\n        user_data   = get(fig,'UserData');\n        job.img{1}  = '';\n        job.file{1} = user_data.BMS.fname;\n        job.thres   = user_data.thres;\n        job.scale   = user_data.scale;\n        job.k       = user_data.k;\n        spm_run_bms_vis(job);\n    \n    % Change threshold\n    % =====================================================================\n    case 'change_thres'\n        \n        fig         = gcf;\n        user_data   = get(fig,'UserData');\n        job.img{1}  = user_data.vols;\n        job.thres   = [];\n        job.file{1} = user_data.BMS.fname;\n        job.scale   = user_data.scale;\n        job.k       = user_data.k;\n        spm_run_bms_vis(job);\n    \n    % Change scale\n    % =====================================================================\n    case 'change_scale'\n        \n        fig         = gcf;\n        user_data   = get(fig,'UserData');\n        job.img{1}  = user_data.vols;\n        job.thres   = user_data.thres;\n        job.scale   = [];\n        job.k       = user_data.k;\n        job.file{1} = user_data.BMS.fname;\n        spm_run_bms_vis(job);\n    \n    % List p-values\n    % =====================================================================\n    case 'list'\n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        xSPM      = user_data.xSPM;\n        hReg      = user_data.hReg;\n        xSPM.STAT = 'P';\n        xSPM.Z    = xSPM.z_ps;\n        spm_list('List',xSPM,hReg);\n   \n    % List cluster\n    % =====================================================================\n    case 'listCluster'\n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        xSPM      = user_data.xSPM;\n        hReg      = user_data.hReg;\n        xSPM.STAT = 'P';\n        xSPM.Z    = xSPM.z_ps;\n        spm_list('ListCluster',xSPM,hReg);\n        \n    % Small volume\n    % =====================================================================\n    case 'listVOI'\n        \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        xSPM      = user_data.xSPM;\n        hReg      = user_data.hReg;\n        xSPM.STAT = 'P';\n        spm_VOI(xSPM.SPM,xSPM,hReg);\n        \n    % Model partitioning\n    % =====================================================================\n    case 'partition'    \n        fig       = gcf;\n        user_data = get(fig,'UserData');\n        BMS       = user_data.BMS;\n        spm_bms_partition(BMS);\n        \n    % Model partitioning\n    % =====================================================================\n    case 'groups'   \n        \n        fig         = gcf;\n        user_data   = get(fig,'UserData');\n        BMS         = user_data.BMS;\n        \n        con_image   = spm_bms_compare_groups;\n        \n        job.img{1}  = con_image;\n        job.file{1} = user_data.BMS.fname;\n        job.thres   = [];\n        job.scale   = [];\n        job.k       = [];\n        spm_run_bms_vis(job);\n        \nend  % End switch  \n\nend  % End function\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_bms_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.21026438414135165}}
{"text": "function [params] = sv_calcMcNodes_2methods(params,nNodeStart, nNodeEnd)\n% function [params] = sv_calcMcNodes_2methods(params,nNodeStart, nNodeEnd);\n% ----------------------------------------------------------------\n% Calculation of magnitude of completeness specifying the nodes to be calculated for distributing on different CPUs\n% Same as sv_calcMcNodes but just using McEMR and MAXC\n%\n% Input parameters:\n%   params.mCatalog           Earthquake catalog\n%   params.mPolygon           Polygon (defined by ex_selectgrid)\n%   params.vX                 X-vector (defined by ex_selectgrid)\n%   params.vY                 Y-vector (defined by ex_selectgrid)\n%   params.vUsedNodes         Used nodes vX * vY defining the mPolygon (defined by ex_selectgrid)\n%   params.bRandom            Perform random simulation (=1) or real calculation (=0)\n%   params.nCalculation       Number of random simulations\n%   params.bMap               Calculate a map (=1) or a cross-section (=0)\n%   params.bNumber            Use constant number (=1) or constant radius (=0)\n%   params.nNumberEvents      Number of earthquakes if bNumber == 1\n%   params.fMaxRadius         Maximum Radius using a constant number of events; works only with bNumber == 1\n%   params.fRadius            Radius of gridnode if bNumber == 0\n%   params.nMinimumNumber     Minimum number of earthquakes per node for determining a b-value\n%   params.fMinMag            Lower limit of magnitude range for testing\n%   params.fMaxMag            Upper limit of magnitude range for testing\n%   params.bTimePeriod        Calculate seismicity difference for 2 periods (0) until start and end of catalog or\n%                             a specific time period before and after fSplitTime (1)\n%   params.fTimePeriod        Length of time periods\n%   params.bTstart            Check for starting time of temporal mapping\n%   params.fTstart            Starting time for temporal mapping\n%   params.bBstnum            Check for boostrap sampling\n%   params.fBstnum            Number of bootstrap samples\n%   params.fBinning           Bin size for magnitude binning\n%   params.sComment           Comment on calculation\n\n% Output parameters:\n%   Same as input parameters including\n%   params.mValueGrid         Matrix of calculated values\n%   params.vcsGridNames       Names of parameters calculated\n%   Check sv_NodeCalcMc.m for a list of variables!!\n%\n% J. Woessner; j.woessner@sed.ethz.ch\n% last update: 27.07.04\n\nglobal bDebug;\nif bDebug\n    report_this_filefun(mfilename('fullpath'));\nend\n\n% Check calculation for splitting of nodes\nif nargin < 2\n    nNodeStart = 1;\n    nNodeEnd = length(params.mPolygon(:,1));\nend\n\n% Initialize\nvResults = [];\nparams.sComment = [];\nif isempty(params.fBinning)\n    params.fBinning = 0.1;\nend\n\n% Determine time period of catalog\nparams.fTminCat = min(params.mCatalog(:,3));\nparams.fTmaxCat = max(params.mCatalog(:,3));\n% Adjust to decimal years\nfTimePeriod =params.fTimePeriod/365;\n\n% Init result matrix\nmValueGrid_ = [];\n\n% Temporary saving the original catalog\nmCatalog = params.mCatalog;\n\n% Force saving all 500 nodes\nfDivide = length(params.mPolygon(:,1))/500\nfForceSave = length(params.mPolygon(:,1))/fDivide;\n% Check for bootstrapping or not\n% ------------------------------\n% Case of calculations with bootstrapping\nif (params.bBstnum == 1)\n    % Loop over time\n    fTstart = params.fTstart;\n    while fTstart < params.fTmaxCat\n        mValueGrid_ = [];\n        params.mCatalog = mCatalog;\n        % Create Indices to catalog and select quakes in time period\n        vSel = (fTstart <= params.mCatalog(:,3) & params.mCatalog(:,3) < fTstart+fTimePeriod);\n        params.mCatalog = params.mCatalog(vSel,:);\n        [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n         params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n        % Loop over all grid nodes\n        hWaitbar1 = waitbar(0,'Calculating nodes...');\n        set(hWaitbar1,'Numbertitle','off','Name','Node percentage');\n        for nNode_ = nNodeStart:nNodeEnd\n            % Create node catalog\n            mNodeCatalog_ = params.mCatalog(params.caNodeIndices{nNode_}, :);\n            % Check for constant number of events calculations\n            if (params.nGriddingMode == 0)\n                [mNodeCatalog_] = ex_CheckMaxRadius(mNodeCatalog_, params.mPolygon, nNode_, params.caNodeIndices, params.fMaxRadius, params.nNumberEvents, params.bMap);\n            end\n            [nX,nY] = size(mNodeCatalog_);\n            if (nX < params.nMinimumNumber)\n                mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN nX NaN NaN NaN NaN];\n            else\n                [rCalcNodeResult_] = sv_NodeCalcMc_2method(params,mNodeCatalog_);\n                % Store the results\n                mValueGrid_= [mValueGrid_; rCalcNodeResult_.fMc_max rCalcNodeResult_.fMc_EMR rCalcNodeResult_.fMc_Bst...\n                        rCalcNodeResult_.fStd_Mc rCalcNodeResult_.fBvalue_Bst rCalcNodeResult_.fStd_B...\n                        rCalcNodeResult_.fAvalue_Bst rCalcNodeResult_.fStd_A nX...\n                        rCalcNodeResult_.bH_EMR rCalcNodeResult_.fPval rCalcNodeResult_.bH_Bst rCalcNodeResult_.fPval_Bst];\n            end; % End of if on nNode_\n            if rem(nNode_,floor(fForceSave)) == 0\n                waitbar(nNode_/length(params.mPolygon(:,1)))\n                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n                % Temporary saving\n                params.vcsGridNames = cellstr(char('Mc max. curvature', 'Mc EMR-method', 'Mc(Bst-mean)', 'Mc(Bst-2nd-moment)',...\n                    'Mc(Bst-b)', 'Mc(b_2nd-moment)','Mc(Bst-a)', 'Mc(a_2nd-moment)','Number of events',...\n                    'H(KST)','P(KST)','H(KST_Bst)','P(KST_Bst)'));\n                params.mValueGrid = mValueGrid_;\n                % Add parameter to params.sComment\n                if  params.nGriddingMode == 0;   % Constant number\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                            num2str(params.fMaxRadius) ' km'];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                            '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n                elseif params.nGriddingMode == 1;   % Constant radius\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n                else  % Rectangle mode\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                            ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                            '_Nmin_' num2str(params.nMinimumNumber) '.mat'], 'vResults');\n                end; % END of params.nGriddingmode\n                vResults =[];\n            end; % End updating waitbar\n        end; % for nNode\n        close(hWaitbar1);\n        % Parameter description\n        params.vcsGridNames = cellstr(char('Mc max. curvature', 'Mc EMR-method', 'Mc(Bst-mean)', 'Mc(Bst-2nd-moment)',...\n            'Mc(Bst-b)', 'Mc(b_2nd-moment)','Mc(Bst-a)', 'Mc(a_2nd-moment)','Number of events',...\n                    'H(KST)','P(KST)','H(KST_Bst)','P(KST_Bst)'));\n        params.mValueGrid = mValueGrid_;\n        % Add parameter to params.sComment\n        if  params.nGriddingMode == 0;   % Constant number\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                    num2str(params.fMaxRadius) ' km'];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '.mat'], 'vResults');\n        elseif params.nGriddingMode == 1;   % Constant radius\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)...\n                '_Nodes_' num2str(nNodeStart) '.mat'], 'vResults');\n        else  % Rectangle mode\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                    ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '.mat'], 'vResults');\n        end\n        vResults =[];\n        fTstart = fTstart+fTimePeriod;\n    end; % End of while fTstart\n\n    % Case of no bootstrapping\nelse\n    % Loop over time\n    fTstart = params.fTstart;\n    while fTstart < params.fTmaxCat\n        mValueGrid_ = [];\n        params.mCatalog = mCatalog;\n        % Create Indices to catalog and select quakes in time period\n        vSel = (fTstart <= params.mCatalog(:,3) & params.mCatalog(:,3) < fTstart+fTimePeriod);\n        params.mCatalog = params.mCatalog(vSel,:);\n        [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n         params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n        % Loop over all grid nodes\n        hWaitbar1 = waitbar(0,'Calculating nodes...');\n        set(hWaitbar1,'Numbertitle','off','Name','Node percentage');\n        for nNode_ = nNodeStart:nNodeEnd\n            % Create node catalog\n            mNodeCatalog_ = params.mCatalog(params.caNodeIndices{nNode_}, :);\n            % Check for constant number of events calculations\n            if (params.nGriddingMode == 0)\n                [mNodeCatalog_] = ex_CheckMaxRadius(mNodeCatalog_, params.mPolygon, nNode_, params.caNodeIndices, params.fMaxRadius, params.nNumberEvents, params.bMap);\n            end\n            [nX,nY] = size(mNodeCatalog_);\n            if (nX < params.nMinimumNumber)\n                mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN nX];\n            else\n                [rCalcNodeResult_] = sv_NodeCalcMc(params,mNodeCatalog_);\n                mValueGrid_= [mValueGrid_; rCalcNodeResult_.fMc_max rCalcNodeResult_.fMc_90 rCalcNodeResult_.fMc_95 rCalcNodeResult_.fMc_com...\n                        rCalcNodeResult_.fMc_EMR rCalcNodeResult_.fMc_shi nX];\n            end; % End of if on nX\n            if rem(nNode_,500) == 0\n                waitbar(nNode_/length(params.mPolygon(:,1)))\n                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n                % Temporary saving\n                params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n                    'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)','Number of events'));\n                params.mValueGrid = mValueGrid_;\n                % Add parameter to params.sComment\n                if  params.nGriddingMode == 0;   % Constant number\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                            num2str(params.fMaxRadius) ' km'];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                            '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n                elseif params.nGriddingMode == 1;   % Constant radius\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                else  % Rectangle mode\n                    params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                            ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                            ' km, Nmin: ' num2str(params.nMinimumNumber)];\n                    vResults = params;\n                    save(['tmp_result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                            '_Nmin_' num2str(params.nMinimumNumber)  '_Node' num2str(nNode_) '.mat'], 'vResults');\n                end; % END of params.nGriddingmode\n                vResults =[];\n            end; % End updating waitbar\n        end; % for nNode\n        close(hWaitbar1);\n        % Parameter description\n        params.vcsGridNames = cellstr(char('Mc max. curvature' , 'Mc 90% goodness of fit' , 'Mc 95% goodness of fit',...\n            'Mc best combination', 'Mc EMR-method', 'Mc(Shi-b-uncertainty)'));\n        params.mValueGrid = mValueGrid_;\n        % Add parameter to params.sComment\n        if  params.nGriddingMode == 0;   % Constant number\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n                    num2str(params.fMaxRadius) ' km'];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n        elseif params.nGriddingMode == 1;   % Constant radius\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)...\n                '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n        else  % Rectangle mode\n            params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n                    ' Time period ' num2str(params.fTimePeriod) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n                    ' km, Nmin: ' num2str(params.nMinimumNumber)];\n            vResults = params;\n            save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n                    '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n        end\n        vResults =[];\n        fTstart = fTstart+fTimePeriod;\n    end; % End of while fTstart\nend; % END of if params.bBst\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/sv_calcMcNodes_2method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.21018420965564655}}
{"text": "function script_rfcn_VOC0712_ResNet101_rpn()\n% script_rfcn_VOC0712_ResNet101_rpn()\n% RFCN training and testing with OHEM using ResNet101 model and RPN\n% proposals\n% --------------------------------------------------------\n% R-FCN implementation\n% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)\n% Copyright (c) 2016, Jifeng Dai\n% Licensed under The MIT License [see LICENSE for details]\n% --------------------------------------------------------\n\n\nclc;\nclear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));\n%% -------------------- CONFIG --------------------\nopts.caffe_version          = 'caffe_rfcn';\nopts.gpu_id                 = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\n\n% model\nmodel                       = Model.ResNet101_for_RFCN_VOC0712();\n% cache name\nopts.cache_name             = 'rfcn_VOC0712_ResNet101_rpn_resnet101';\n% config\nconf                        = rfcn_config_simple('image_means', model.mean_image);\n% train/test data\nfprintf('Loading dataset...')\ndataset                     = [];\ndataset                     = Dataset.voc0712_trainval_sp(dataset, 'train', conf.use_flipped, 'resnet101');\ndataset                     = Dataset.voc2007_test_sp(dataset, 'test', false, 'resnet101');\nfprintf('Done.\\n');\n\n% do validation, or not\nopts.do_val                 = true; \n\n%% -------------------- TRAINING --------------------\n\nopts.rfcn_model        = rfcn_train(conf, dataset.imdb_train, dataset.roidb_train, ...\n                                'do_val',           opts.do_val, ...\n                                'imdb_val',         dataset.imdb_test, ...\n                                'roidb_val',        dataset.roidb_test, ...\n                                'solver_def_file',  model.solver_def_file, ...\n                                'net_file',         model.net_file, ...\n                                'cache_name',       opts.cache_name, ...\n                                'caffe_version',    opts.caffe_version);\nassert(exist(opts.rfcn_model, 'file') ~= 0, 'not found trained model');\n\n%% -------------------- TESTING --------------------\n                          rfcn_test(conf, dataset.imdb_test, dataset.roidb_test, ...\n                                'net_def_file',     model.test_net_def_file, ...\n                                'net_file',         opts.rfcn_model, ...\n                                'cache_name',       opts.cache_name,...\n                                'ignore_cache',     true);\n\nend\n", "meta": {"author": "daijifeng001", "repo": "R-FCN", "sha": "94797e0e8d15998a9ab0a76cbac3281ad907f04a", "save_path": "github-repos/MATLAB/daijifeng001-R-FCN", "path": "github-repos/MATLAB/daijifeng001-R-FCN/R-FCN-94797e0e8d15998a9ab0a76cbac3281ad907f04a/experiments/script_rfcn_VOC0712_ResNet101_rpn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2101842018115912}}
{"text": "%RandomPath Vehicle driver class\n%\n% Create a \"driver\" object capable of steering a Vehicle object through random \n% waypoints within a rectangular region and at constant speed.\n%\n% The driver object is connected to a Vehicle object by the latter's\n% add_driver() method.  The driver's demand() method is invoked on every\n% call to the Vehicle's step() method.\n%\n% Methods::\n%  init       reset the random number generator\n%  demand     return speed and steer angle to next waypoint\n%  display    display the state and parameters in human readable form\n%  char       convert to string\n%      \n% Properties::\n%  goal          current goal/waypoint coordinate\n%  veh           the Vehicle object being controlled\n%  dim           dimensions of the work space (2x1) [m]\n%  speed         speed of travel [m/s]\n%  closeenough   proximity to waypoint at which next is chosen [m]\n%\n% Example::\n%\n%    veh = Vehicle(V);\n%    veh.add_driver( RandomPath(20, 2) );\n%\n% Notes::\n% - It is possible in some cases for the vehicle to move outside the desired\n%   region, for instance if moving to a waypoint near the edge, the limited\n%   turning circle may cause the vehicle to temporarily move outside.\n% - The vehicle chooses a new waypoint when it is closer than property\n%   closeenough to the current waypoint.\n% - Uses its own random number stream so as to not influence the performance\n%   of other randomized algorithms such as path planning.\n%\n% Reference::\n%\n%   Robotics, Vision & Control, Chap 6,\n%   Peter Corke,\n%   Springer 2011\n%\n% See also Vehicle.\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n% TODO\n%  should be a subclass of VehicleDriver\n%  Vehicle should be an abstract superclass\n\nclassdef RandomPath < handle\n    properties\n        goal        % current goal\n        h_goal      % graphics handle for goal\n        veh         % the vehicle we are driving\n        dim\n        speed       % speed of travel\n        closeenough  % proximity to goal before\n        d_prev\n        randstream  % random stream just for Sensors\n    end\n\n    methods\n\n        function driver = RandomPath(dim, varargin)\n        %RandomPath.RandomPath Create a driver object\n        %\n        % D = RandomPath(DIM, OPTIONS) returns a \"driver\" object capable of driving \n        % a Vehicle object through random waypoints.  The waypoints are positioned \n        % inside a rectangular region bounded by +/- DIM in the x- and y-directions.\n        %\n        % Options::\n        % 'speed',S      Speed along path (default 1m/s).\n        % 'dthresh',D    Distance from goal at which next goal is chosen.\n        %\n        % See also Vehicle.\n\n        % TODO options to specify region, maybe accept a Map object?\n\n            driver.dim = dim;\n\n            opt.speed = 1;\n            opt.dthresh = 0.05 * dim;\n            opt = tb_optparse(opt, varargin);\n\n            driver.speed = opt.speed;\n            driver.closeenough = opt.dthresh;\n            drive.d_prev = Inf;\n            driver.randstream = RandStream.create('mt19937ar');\n        end\n\n        function init(driver)\n        %RandomPath.init Reset random number generator\n        %\n        % R.init() resets the random number generator used to create the waypoints.\n        % This enables the sequence of random waypoints to be repeated.\n        %\n        % See also RANDSTREAM.\n            driver.goal = [];\n            driver.randstream.reset();\n        end\n\n        % not used\n        function visualize(driver)\n            clf\n            d = driver.dim;\n            axis([-d d -d d]);\n            hold on\n            xlabel('x');\n            ylabel('y');\n        end\n\n        % private method, invoked from demand() to compute a new waypoint\n        function setgoal(driver)\n            r = driver.randstream.rand(2,1);\n            driver.goal = 0.8 * driver.dim * (r - 0.5)*2;\n            %fprintf('set goal: (%.1f %.1f)\\n', driver.goal);\n            if isempty(driver.h_goal)\n                %driver.h_goal = plot(driver.goal(1), driver.goal(2), '*')\n            else\n                %set(driver.h_goal, 'Xdata', driver.goal(1), 'Ydata', driver.goal(2))\n            end\n        end\n\n        function [speed, steer] = demand(driver)\n        %RandomPath.demand Compute speed and heading to waypoint\n        %\n        % [SPEED,STEER] = R.demand() returns the speed and steer angle to\n        % drive the vehicle toward the next waypoint.  When the vehicle is\n        % within R.closeenough a new waypoint is chosen.\n        %\n        % See also Vehicle.\n            if isempty(driver.goal)\n                driver.setgoal()\n            end\n\n            speed = driver.speed;\n\n            goal_heading = atan2(driver.goal(2)-driver.veh.x(2), ...\n                driver.goal(1)-driver.veh.x(1));\n            d_heading = angdiff(goal_heading, driver.veh.x(3));\n\n            steer = d_heading;\n\n            % if nearly at goal point, choose the next one\n            d = colnorm(driver.veh.x(1:2) - driver.goal);\n            if d < driver.closeenough\n                driver.setgoal();\n            elseif d > driver.d_prev\n                driver.setgoal();\n            end\n            driver.d_prev = d;\n        end\n\n        function display(driver)\n        %RandomPath.display Display driver parameters and state\n        %\n        % R.display() displays driver parameters and state in compact \n        % human readable form.\n        %\n        % See also RandomPath.char.\n            loose = strcmp( get(0, 'FormatSpacing'), 'loose');\n            if loose\n                disp(' ');\n            end\n            disp([inputname(1), ' = '])\n            disp( char(driver) );\n        end % display()\n\n        function s = char(driver)\n        %RandomPath.char Convert to string\n        %\n        % s = R.char() is a string showing driver parameters and state in in \n        % a compact human readable format. \n            s = 'RandomPath driver object';\n            s = char(s, sprintf('  current goal=(%g,%g), dimension %.1f', ...\n                driver.goal, driver.dim));\n        end\n\n    end % methods\nend % classdef\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/RandomPath.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.21010323881588489}}
{"text": "function importGen3Model\n% Imports Kinova Gen3 Ultra lightweight robot model into a Rigid Body Tree\n%\n% Copyright 2019 The MathWorks, Inc.\n\n    % Load the URDF file\n    %\n    % NOTE: This requires you to have the kortex_description folder on \n    % your path, which you can download from \n    % https://github.com/Kinovarobotics/ros_kortex.git\n    %\n    % Then, you have to convert the gen3.xacro file to a URDF file using\n    % the following commands in a ROS enabled terminal:\n    %  $ cd PATH/TO/ros_kortex/kortex_description/robots\n    %  $ rosrun xacro xacro --inorder -o gen3.urdf gen3.xacro\n    addpath(genpath('kortex_description'))\n    gen3 = importrobot('gen3.urdf');\n\n    % Add a \"dummy\" gripper link\n    gripperLength = 0.1; % Gripper length in meters\n    gripperBody = rigidBody('Gripper');\n    gripperJoint = rigidBodyJoint('GripperLink','fixed');\n    T = rotm2tform([0 1 0;0 0 1;1 0 0]) * trvec2tform([gripperLength 0 0]);\n    setFixedTransform(gripperJoint,T); % Move and orient the gripper\n    gripperBody.Joint = gripperJoint;\n    addBody(gen3,gripperBody,'end_effector_link');\n    % Add a \"dummy\" mesh\n    addVisual(gen3.Bodies{9},'Mesh','cylinder.stl', ... \n              trvec2tform([-0.1 0 0]) * axang2tform([0 1 0 pi/2]));\n        \n    % Configure the data format and show the robot in the home position\n    gen3.DataFormat = 'row';\n    load gen3positions\n    show(gen3,jointAnglesHome');\n\n    % Save the Rigid Body Tree to a file\n    curDir = pwd;\n    saveDir = fileparts(mfilename('fullpath'));\n    cd(saveDir)\n    save gen3 gen3\n    cd(curDir)\n\nend", "meta": {"author": "mathworks-robotics", "repo": "trajectory-planning-robot-manipulators", "sha": "e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e", "save_path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators", "path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators/trajectory-planning-robot-manipulators-e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e/utilities/importGen3Model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21002921340285197}}
{"text": "classdef dme_load < mp.dm_element\n%MP.DME_LOAD  MATPOWER data model class for load data\n\n%   MATPOWER\n%   Copyright (c) 2020-2022, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n    properties\n        bus     %% bus index vector (all loads)\n        pd      %% active power demand (p.u.) for constant power loads that are on\n        qd      %% reactive power demand (p.u.) for constant power loads that are on\n        pd_i    %% active power demand (p.u.) for constant current loads that are on\n        qd_i    %% reactive power demand (p.u.) for constant current loads that are on\n        pd_z    %% active power demand (p.u.) for constant impedance loads that are on\n        qd_z    %% reactive power demand (p.u.) for constant impedance loads that are on\n    end     %% properties\n\n    methods\n        function name = name(obj)\n            name = 'load';\n        end\n\n        function label = label(obj)\n            label = 'Load';\n        end\n\n        function label = labels(obj)\n            label = 'Loads';\n        end\n\n        function name = cxn_type(obj)\n            name = 'bus';\n        end\n\n        function name = cxn_idx_prop(obj)\n            name = 'bus';\n        end\n\n        function names = main_table_var_names(obj)\n            names = horzcat( main_table_var_names@mp.dm_element(obj), ...\n                {'bus', 'pd', 'qd', 'pd_i', 'qd_i', 'pd_z', 'qd_z', ...\n                'p', 'q'});\n        end\n\n        function vars = export_vars(obj)\n            vars = {};\n        end\n\n        function nr = count(obj, dm)\n            nr = count@mp.dm_element(obj, dm);\n            if nr\n                obj.bus = obj.tab.source_uid;\n            end\n        end\n\n        function obj = update_status(obj, dm)\n            %% get bus status info\n            bs = dm.elements.bus.tab.status;    %% bus status\n\n            %% update status of loads at isolated/offline buses\n            obj.tab.status = obj.tab.status & bs(obj.bus);\n\n            %% call parent to fill in on/off\n            update_status@mp.dm_element(obj, dm);\n        end\n\n        function obj = build_params(obj, dm)\n            obj.pd   = obj.tab.pd(obj.on) / dm.base_mva;\n            obj.qd   = obj.tab.qd(obj.on) / dm.base_mva;\n            obj.pd_i = obj.tab.pd_i(obj.on) / dm.base_mva;\n            obj.qd_i = obj.tab.qd_i(obj.on) / dm.base_mva;\n            obj.pd_z = obj.tab.pd_z(obj.on) / dm.base_mva;\n            obj.qd_z = obj.tab.qd_z(obj.on) / dm.base_mva;\n        end\n\n        function TorF = pp_have_section_sum(obj, mpopt, pp_args)\n            TorF = true;\n        end\n\n        function obj = pp_data_sum(obj, dm, rows, out_e, mpopt, fd, pp_args)\n            %% call parent\n            pp_data_sum@mp.dm_element(obj, dm, rows, out_e, mpopt, fd, pp_args);\n\n            %% print load summary\n            fprintf(fd, '  %-29s %12.1f MW', 'Total load', ...\n                                            sum(obj.tab.p));\n            if mpopt.model(1) ~= 'D'    %% AC model\n                fprintf(fd, ' %12.1f MVAr', sum(obj.tab.q));\n            end\n            fprintf(fd, '\\n');\n            if obj.n ~= obj.nr\n                fprintf(fd, '  %-29s %12.1f MW', '  online', ...\n                                                sum(obj.tab.p(obj.on)));\n                if mpopt.model(1) ~= 'D'    %% AC model\n                    fprintf(fd, ' %12.1f MVAr', sum(obj.tab.q(obj.on)));\n                end\n                fprintf(fd, '\\n');\n            end\n        end\n\n        function TorF = pp_have_section_det(obj, mpopt, pp_args)\n            TorF = true;\n        end\n\n        function h = pp_get_headers_det(obj, dm, out_e, mpopt, pp_args)\n            h = [ pp_get_headers_det@mp.dm_element(obj, dm, out_e, mpopt, pp_args) ...\n                {   '                             Power Consumption', ...\n                    'Load ID    Bus ID   Status   P (MW)   Q (MVAr)', ...\n                    '--------  --------  ------  --------  --------' } ];\n            %%       1234567 123456789 -----1 12345678.0 1234567.9\n        end\n\n        function f = pp_get_footers_det(obj, dm, out_e, mpopt, pp_args)\n            f = {'                            --------  --------',\n                sprintf('%18s Total:%10.1f %9.1f', ...\n                    '', sum(obj.tab.p(obj.on)), sum(obj.tab.q(obj.on)))};\n        end\n\n        function str = pp_data_row_det(obj, dm, k, out_e, mpopt, fd, pp_args)\n            if obj.tab.status(k) && abs(obj.tab.p(k)) > 1e-5\n                p = sprintf('%10.1f', obj.tab.p(k));\n            else\n                p = '       -  ';\n            end\n            if obj.tab.status(k) && abs(obj.tab.q(k)) > 1e-5\n                q = sprintf('%9.1f', obj.tab.q(k));\n            else\n                q = '      -  ';\n            end\n            str = sprintf('%7d %9d %6d %10s %9s', ...\n                obj.tab.uid(k), obj.tab.bus(k), obj.tab.status(k), p, q);\n        end\n    end     %% methods\nend         %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/dme_load.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21002921340285194}}
{"text": "% Altitute chart containing relative temperature, pressure and density.\nh=(0:100:80000)';\nchart=h;\nfor i=2:4,\nchart(:,i)=0;\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19470-isa-chart/genchart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20993882131476546}}
{"text": "function varargout = pwq_yalmip(varargin)\n%PWQ_YALMIP Defines a piecewise quadratic function using data from MPT\n%\n%Only intended for internal use in YALMIP\n%\n% Currently only a container for PWQ functions. Can not be\n% used in actual optmization problem.\n\nswitch class(varargin{1})\n\n    case {'struct','cell'} % Should only be called internally\n\n        if isa(varargin{2},'double')\n            % Called from YALMIP to get double\n            pwastruct = varargin{1};\n            x = varargin{2};\n            index = varargin{5};\n\n            val = inf;\n            for i = 1:length(pwastruct)\n                [ii,jj] = isinside(pwastruct{i}.Pn,x);\n                if ii\n                    for k = 1:length(jj)\n                        Q = pwastruct{i}.Ai{jj(k)};\n                        if index>1 | min(size(pwastruct{i}.Bi{jj(k)}))>1\n                            % FIX: Why?? Where is this feature used\n                            val = min(val,x'*Q*x + reshape(pwastruct{i}.Bi{jj(k)}(index,:),1,[])*x+pwastruct{i}.Ci{jj(k)}(index));\n                        else\n                            val = min(val,x'*Q*x + reshape(pwastruct{i}.Bi{jj(k)},1,[])*x+pwastruct{i}.Ci{jj(k)});\n                        end\n                    end\n                end\n            end\n            if isinf(val)\n                val = nan;\n            end\n            varargout{1} = min(val);\n            return\n        end\n\n        if nargin<3\n            pwaclass = 'general'\n        end\n\n        if isa(varargin{1},'struct')\n            varargin{1} = {varargin{1}};\n        end\n\n        % Put in standard format\n        if ~isfield(varargin{1}{1},'Bi')\n            if ~isfield(varargin{1}{1},'Fi')\n                error('Wrong format on input to PWQ (requires Bi or Fi)');\n            else\n                for i = 1:length(varargin{1})\n                    varargin{1}{1}.Ai = cell(1, varargin{1}{i}.Fi);\n                    varargin{1}{i}.Bi = varargin{1}{i}.Fi\n                    varargin{1}{i}.Ci = varargin{1}{i}.Gi\n                end\n            end\n        end\n\n        if ~isfield(varargin{1}{1},'Pfinal')\n            error('Wrong format on input to PWQ (requires field Pn)');\n        end\n\n        % This will be a container for binary variables in the furture\n        varargin{end+1} = binvar(length(varargin{1}{1}.Pn),1);\n\n        % Create one variable for each row\n        % Inefficient but the only way currently in YALMIP\n        varargout{1} = [];\n        varargin{end+1} = 1;\n\n        for i = 1:length(varargin{1}{1}.Ci{1})\n            varargin{end} = i;\n            varargout{1} = [varargout{1};yalmip('define',mfilename,varargin{:})];\n        end\n\n    case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph\n\n\n        switch varargin{1}\n\n            case 'graph'\n\n                varargout{1} = [];\n                varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none');\n                varargout{3} = [];\n\n            case {'integer','exact'}\n\n                % FIX : Should create case for overlapping convex PWAs,\n                % used in a nonconvex fashion...\n\n                % Can only generate the first class of PWA functions\n                t     = varargin{2};     % The YALMIP variables modelling this pwa\n                pwq_struct = varargin{3};% MPT structure\n                x     = varargin{4};     % Argument\n                flag  = varargin{5};     % Type of PWA function\n                d     = varargin{6};     % Binary for nonconvex cases\n                index = varargin{7};     % Which row in Bix+Ci\n\n                switch flag\n\n                    case {'general','convex'}\n\n                        if length(d)==1\n                            % Don't introduce any binary variables when\n                            % there is only one quadratic cost\n                            F = ([]);\n                            cost = x'*pwq_struct{1}.Ai{1}*x+pwq_struct{1}.Bi{1}*x+pwq_struct{1}.Ci{1};\n                        else\n                            n = length(x);\n                            m = length(d);\n                            z = sdpvar(n,m,'full');\n                            F = (sum(d) == 1);\n                            cost = 0;\n                            [Mm,mm] = derivebounds(x);\n                            try\n                                [aux,mx,Mx] = bounding_box(pwq_struct{1}.Pfinal);\n                            catch\n                                Mx = 10000*ones(length(x),1);\n                                mx = -10000*ones(length(x),1);\n                            end\n                            Mx = min([Mx Mm],[],2);\n                            mx = max([mx mm],[],2);\n                            for i = 1:m\n                                %    bounds(z(:,i),mx,Mx);\n                                F = F + (-(Mx-mx)*(1-d(i)) <= z(:,i)-x <= (Mx-mx)*(1-d(i)));\n                                F = F + (mx*d(i) <= z(:,i) <= Mx*d(i));\n                                [H,K] = double(pwq_struct{1}.Pn(i));\n                                [M,m]  = derivebounds(H*x-K);\n                                F = F + (H*x-K <= M*(1-d(i)));\n                                cost = cost + z(:,i)'*pwq_struct{1}.Ai{i}*z(:,i)+pwq_struct{1}.Bi{i}(:)'*z(:,i)+d(i)*pwq_struct{1}.Ci{i};\n                            end\n                        end\n\n                        varargout{1} = F;\n                        varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none','model','integer');\n                        varargout{2}.replacer = cost;\n                        varargout{3} = x;\n\n                    case {'convexoverlapping'}\n\n                        n = length(x);\n                        cost = 0;\n                        r = binvar(length(pwq_struct),1);\n                        d = {};\n\n                        % Derive bounds from polytopes\n                        [aux,mx,Mx] = bounding_box(pwq_struct{1}.Pfinal);\n                        for i = 2:length(pwq_struct)\n                            [aux,L,U] = bounding_box(pwq_struct{i}.Pfinal);\n                            Mx = max([Mx U],[],2);\n                            mx = min([mx L],[],2);\n                        end\n                        bounds(x,mx,Mx);\n\n                        % Some overlapping function is active\n                        % (it will automatically be the smallest one)\n                        F = (sum(r) == 1);\n                        for j = 1:length(pwq_struct)\n\n                            if length(pwq_struct{j}.Pn) == 1\n                                d{j} = r(j);\n                            else\n                                d{j} = binvar(length(pwq_struct{j}.Pn),1);\n                                F = F + (sum(d{j}) == r(j));\n                            end\n                            m = length(d{j});\n                            z = sdpvar(n,m,'full');\n\n                            for i = 1:m\n                                bounds(z(:,i),mx,Mx);\n                                F = F + (-(Mx-mx)*(1-d{j}(i)) <= z(:,i)-x <= (Mx-mx)*(1-d{j}(i)));\n                                F = F + (mx*d{j}(i) <= z(:,i) <= Mx*d{j}(i));\n                                [H,K] = double(pwq_struct{j}.Pn(i));\n                                [M,m]  = derivebounds(H*x-K);\n                                F = F + (H*x-K <= M*(1-d{j}(i)));\n                                cost = cost + z(:,i)'*pwq_struct{j}.Ai{i}*z(:,i)+pwq_struct{j}.Bi{i}*z(:,i)+d{j}(i)*pwq_struct{j}.Ci{i};\n                            end\n                        end\n\n                        varargout{1} = F;\n                        varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none','model','integer');\n                        varargout{2}.replacer = cost;\n                        varargout{3} = x;\n\n                    otherwise\n\n                        varargout{1} = [];\n                        varargout{2} = struct('convexity','convex','monotoncity','none','definiteness','none');\n                        varargout{3} = [];\n                        return\n                end\n\n            otherwise\n                error('PWA_YALMIP called with CHAR argument?');\n        end\n\n    otherwise\n        error('Strange type on first argument in PWQ_YALMIP');\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/pwq_yalmip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.20991605779411715}}
{"text": "function calcAllSeparateTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,scale_mat,algo_cell,Ng_mat,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% function calcAllSeparateTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,scale_mat,Ng_mat,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes SEPARATE texture features for all patients, for\n% all different combinations of the following texture extraction parameters:\n% - Scale: Resolution at which the ROI is isotropically resampled.\n% - Quantization algorith: Type of quantization algorithm used.\n% - Ng: Number of gray-levels in the quantization process. \n%\n% Different extraction parameters are passed as arrays or cells in the\n% function in order to test all possible combinations. This function is \n% used for SEPARATE scans specifically. See Ref. [1,2] and 'prepareVolume.m' \n% for more details.\n%\n% Texture features are computed for all head and neck (HN) DICOM imaging \n% data downloaded from The Cancer Imaging Archive (TCIA) website at: \n% <http://dx.doi.org/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>, and first organized \n% in a 'DATA' directory using the function readAllDICOM_HN.m.  Results are \n% then saved in a folder 'TEXTURES' in the HN WORKSPACE.\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n%     early prediction of different tumour outcomes in head and neck cancer.\n%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n%     doi:\n% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathData: Full path to the HN sData files directory.\n%              --> Ex: '/myProject/WORKSPACE/DATA'\n% 2. pathText: Full path to the HN non texture features directory.\n%              --> Ex: '/myProject/WORKSPACE/FEATURES/TEXTURES'\n% 3. namePT: Cell of strings of all PET sData files to read\n%            --> Ex: {'HGJ_001_PT.PTscan.mat';'HGJ_022_PT.PTscan.mat'}\n% 4. namePT: Cell of strings of all CT sData files to read\n%            --> Ex: {'HGJ_001_CT.CTscan.mat';'HGJ_022_CT.CTscan.mat'}\n% 5. nameROI: Cell of strings specifying the ROI names to analyze for the\n%             patients defined by \"namePT\" and \"nameCT\"\n%             --> Ex: {'GTV';'GTV-P'}\n% 6. outcomes: Structure specifying the status (1 or 0) for different\n%              outcomes in HN cancer. Contains: outcomes.Failure, \n%              outcomes.Locoregional, outcomes.Distant. See ref.[1] for \n%              more details.\n% 7. featType: Either 'GTVp' for primary GTV, or 'GTVtot' for primaty GTV +\n%              nodal GTVs\n%              --> Ex: 'GTVp'\n% 8. scale_mat: Array vector specifying the different 'Scale' values to test.\n%               --> Ex: [1,2,3,4,5]\n% 9. Ng_mat: Array vector specifying the different 'Ng' values to test.\n%            --> Ex: [8,16,32,64]\n% 10. nBatch: Number of parallel batch.\n%             --> Ex: 8\n% 11.  matlabPATH: Full path to the MATLAB excutable on the system.\n%      --> Ex: 'matlab' (symbolic link)\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\nind = strfind(namePT{1},'_'); cohortID = namePT{1}(1:ind-1);\ncd(pathText), mkdir(['batchLog_',cohortID,'_',featType,'_SepText']), cd(['batchLog_',cohortID,'_',featType,'_SepText']), pathBatch = pwd;\ntime = 60; % Number of seconds to wait before checking if parallel computations are done\nnameOutcomes = fieldnames(outcomes); nOutcomes = numel(nameOutcomes);\nscans = {'PT','CT'}; nScans = numel(scans);\n\n% PRODUCE BATCH COMPUTATIONS\nnPatient = numel(namePT); valid = ones(nPatient,1);\nfor i = 1:nPatient\n    if isempty(nameROI{i})\n        valid(i) = 0;\n    end\nend\nindValid = find(valid); nPatient = numel(indValid);\nif nPatient < nBatch\n    nBatch = nPatient;\nend\n[patients] = batchPatients(nPatient,nBatch);\nsave('workspace','pathData','pathText','namePT','nameCT','nameROI','patients','indValid','featType','scale_mat','algo_cell','Ng_mat'), pause(5);\nfor i = 1:nBatch\n    nameScript = ['batch',num2str(i),'_script.m'];\n    fid = fopen(nameScript,'w');\n    fprintf(fid,'load(''workspace'')\\n');\n    fprintf(fid,['calcAllSeparateTextures_HN(pathData,pathText,namePT(indValid(patients{',num2str(i),'})),nameCT(indValid(patients{',num2str(i),'})),nameROI(indValid(patients{',num2str(i),'})),featType,scale_mat,algo_cell,Ng_mat)\\n']);\n    fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n    fprintf(fid,'clear all');\n    fclose(fid);\n    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nBatch)\ndelete('workspace.mat')\n\n% GROUPING RESULTS FROM ALL BATCH\nnPatient = numel(namePT);\nnames = {namePT,nameCT};\nfor scan = 1:nScans\n    cd(pathText)\n    if exist(['HGJ_001_',scans{scan},'_',featType,'_text.mat'],'file')\n        temp = load(['HGJ_001_',scans{scan},'_',featType,'_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields\n    else\n        temp = load(['HGJ_001_',scans{scan},'_','GTVp','_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields\n    end\n    nameType = fieldnames(temp.Experiment1); nameType(end) = []; nType = numel(nameType); % All texture types are the same\n    text = cell(numel(scale_mat),numel(algo_cell),numel(Ng_mat));\n    tempText = cell(1,nPatient); % Cell used to load patient textures only once\n    for p = 1:nPatient\n        ind = strfind(names{scan}{p},'.'); namePatientScan = names{scan}{p}(1:ind(1)-1);\n        if exist([namePatientScan,'_',featType,'_text.mat'],'file')\n            load([namePatientScan,'_',featType,'_text']) % Variable 'textures' is now in MATLAB workspace\n        else\n            load([namePatientScan,'_','GTVp','_text']) % Variable 'textures' is now in MATLAB workspace\n        end\n        tempText{p} = textures;\n    end\n    experiment = 0;\n    for s = 1:numel(scale_mat)\n        for a = 1:numel(algo_cell)\n            for n = 1:numel(Ng_mat)\n                text{s,a,n} = struct;\n                experiment = experiment + 1;\n                strExperiment = ['Experiment',num2str(experiment)];\n                for t = 1:nType\n                    nameFeature = fieldnames(temp.(strExperiment).(nameType{t})); nFeature = numel(nameFeature);\n                    for f = 1:nFeature\n                        data = zeros(nPatient,1);\n                        for p = 1:nPatient\n                            data(p,1) = tempText{p}.(strExperiment).(nameType{t}).(nameFeature{f});\n                        end\n                        text{s,a,n}.(nameType{t}).(nameFeature{f}).Data = data;\n                        for o = 1:nOutcomes\n                            [text{s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).rs,text{s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).p] = corr(data,outcomes.(nameOutcomes{o}),'type','Spearman');\n                        end\n                    end\n                end\n            end\n        end\n    end\n    cd .., save(['text_',cohortID,'_',scans{scan},'_',featType],'text')\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/calcAllSeparateTextures_batchHN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.20970775878335285}}
{"text": "function [Data, para, vocab] = LoadWavLabel_CHiME4(para, step, dataset)\nswitch lower(dataset)\n    case {'dt05','et05'}\n        wavlist = ['../Kaldi/data/' dataset '_multi_noisy/wav.scp'];\n        ali_file = [para.local.aliDir '_dt05/ali.txt'];\n    case 'tr05'\n        wavlist = ['../Kaldi/data/' dataset '_multi_noisy/wav.scp'];\n        ali_file = [para.local.aliDir '/ali.txt'];\nend\n\n[ali, vocab] = LoadKaldiFrameLabel(ali_file);\nwavlist = my_cat(wavlist);\nwavlist = wavlist(step:step:end);\n\nwavreader.name = 'wavfile';\nwavreader.array = 1;\nwavreader.multiArrayFiles = 1;\n\nnCh = 6;\nfs = 16000;   \nframe_size = fs*0.025;\nframe_shift = fs*0.01;\n\n% Load data file list\nwav_noisy = {};  label = {};\nfor si = 1:length(wavlist)\n    words = ExtractWordsFromString_v2(wavlist{si});\n    curr_uttID = words{1};\n    wavfile = words{2};\n    PrintProgress(si, length(wavlist), 100, curr_uttID);\n    \n    % get alignment\n    if ~strcmpi(para.local.data, 'mixed') && isempty(regexp(lower(curr_uttID), para.local.data))\n        continue;\n    end\n    \n    words = ExtractWordsFromString_v2(curr_uttID, '_');\n    curr_uttID2 = [words{2} '_' words{3}(1:3) '_' words{4}];\n    fieldname = ['U_' curr_uttID2];\n    if ~isfield(ali, fieldname); continue; end    % if there is no label for current utterance, skip it.\n    curr_label = ali.(fieldname);\n    curr_label = curr_label(:)'+1;  % convert to row vector and the index starts with 1\n    \n    % read in the waveform\n    % for the two channel track, we may choose a random pair, or use all\n    % the channel pairs. \n    if length(para.topology.useChannel)==1\n        if para.topology.useChannel==6\n            ch_idx = randperm(6);\n        elseif para.topology.useChannel==5\n            ch_idx = randperm(6);\n            ch_idx(ch_idx==2) = [];     % we don't use channel 2\n        elseif strcmpi(para.local.pair, 'randPair')\n            ch_idx = randperm(nCh);\n            ch_idx(ch_idx==2) = [];     % we don't use channel 2\n            ch_idx = sort(ch_idx(1:para.topology.useChannel));\n        elseif strcmpi(para.local.pair, 'allPair')\n            ch_idx = [1 3; 1 4; 1 5; 1 6; 3 4; 3 5; 3 6; 4 5; 4 6; 5 6];\n        end\n    else\n        ch_idx = para.topology.useChannel;\n    end\n    words = ExtractWordsFromString_v2(wavfile, '/');\n    wavfileRoot = [para.local.wavroot_noisy '/' words{end-1} '/' words{end}(1:end-5)];\n    \n    for pi = 1:size(ch_idx,1)   % add all channel pairs to the training data\n        clear wavfileArray\n        for i=1:size(ch_idx,2)\n            wavfileArray{i} = [wavfileRoot num2str(ch_idx(pi,i)) '.wav'];\n        end\n        [wav] = InputReader(wavfileArray, wavreader);\n        wav = StoreWavInt16(wav);\n        \n        % synchronize the length of label and wav\n        nFr_feat = enframe_decide_frame_number(size(wav,2), frame_size, frame_shift);\n        nFr_label = length(curr_label);\n        if nFr_feat>=nFr_label\n            requiredLen = DecideWavLen4XFrames(nFr_label, frame_size, frame_shift);\n            wav(:,requiredLen+1:end) = [];\n        elseif nFr_feat<nFr_label\n            curr_label = curr_label(1:nFr_feat);\n        end\n        \n        if para.local.useFileName\n            for i=1:size(ch_idx,2)\n                wavfileArray{i} = sprintf('%s 0 %2.3f', wavfileArray{i}, size(wav,2)/fs);\n            end\n            wav_noisy{end+1} = wavfileArray;\n        else\n            wav_noisy{end+1} = wav;\n        end\n        label{end+1} = curr_label;\n    end\nend\n\nData(1).data = wav_noisy;\nData(2).data = label;\n\npara.IO.inputFeature = [1 1];\npara.IO.DataSyncSet{1} = [];\npara.IO.frame_rate = [16000 100];\npara.IO.isTensor = [1 1];\nif para.local.useFileName\n    para.IO.inputFeature(1) = 0;\n    wavreader.precision = 'int16';\n    para.IO.fileReader(1) = wavreader;\n    para.IO.fileReader(2).name = '';\nend\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/beamforming/lib/LoadWavLabel_CHiME4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.20970775878335282}}
{"text": "function maskM = getStructureMask(structNum, sliceNum, dim, planC)\n%\"getStructureMask\"\n%   Returns structure's mask on a specified slice number via uniformized\n%   data.\n%\n%   structNum is the number of the requested structure\n%   sliceNum is the slice NUMBER we want the structure on (not coordinate)\n%   dim is the dimension (1,2,3 = x,y,z) that the slice should be taken\n%   from.\n%   planC is the plan (optional parameter: global is used if not passed)\n%\n%   WARNING: This function uses only uniformized data even if dim is 3 (for\n%            zSlices).  In order to get the structure mask on a CT slice\n%            via rasterSegments, use getRasterSegments and rasterToMask.\n%\n% JRA 11/14/03\n%\n%Usage:\n%   function maskM = getStructureMask(structNum, sliceNum, dim, planC)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nif ~exist('planC')\n    global planC\nend\nindexS = planC{end};\n\n[scanNum, relStructNum] = getStructureAssociatedScan(structNum, planC);\n\n[indicesC, structBitsC, planC] = getUniformizedData(planC, scanNum);\n[arraySize] = getUniformScanSize(planC{indexS.scan}(scanNum));\n\nswitch dim\n\tcase 2\n         rowDim = 3;    colDim = 2;     sliceDim = 1;\n    case 1   \n         rowDim = 3;    colDim = 1;     sliceDim = 2;\n    case 3\n         rowDim = 1;    colDim = 2;     sliceDim = 3;        \n    otherwise\n        warning('Valid Dimensions are 1,2,3 (x,y,z respectively.');\n        return;\nend\n\nmaskM = repmat(logical(0), [arraySize(rowDim) arraySize(colDim)]);\nif relStructNum <= 52\n    cellNum = 1;\nelse\n    cellNum = ceil((relStructNum-52)/8)+1;\nend\nindicesM    = indicesC{cellNum};\nstructBitsM = structBitsC{cellNum};\nsliceIndices = (indicesM(:,sliceDim) == sliceNum);\nsliceXYZ = indicesM(sliceIndices,:);\nif relStructNum <= 52\n    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum));\nelse\n    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum-52-8*(cellNum-2)));\nend\nstructXYZ = sliceXYZ(sliceBits,:);\n\nfor i=1:size(structXYZ,1)\n    maskM(structXYZ(i,rowDim), structXYZ(i,colDim)) = logical(1);\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/getStructureMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20966158534864873}}
{"text": "function sv_startSchuster(mCatalog, hFigure, bMap, rContainer)\n% function sv_startSchuster(mCatalog, hFigure, bMap, rContainer)\n% ------------------------------------------------------\n% Starts seismicity variation analysis toolbox: Schuster Test on Mc\n%\n% Input parameters:\n%   mCatalog      Earthquake catalog to be analyzed\n%   hFigure       Handle of figure where the user should select the grid (i.e. the seismicity map)\n%   bMap          Map/cross-section switch. If the testing is carried out on a map set bMap = 1,\n%                 on a cross-section set bMap = 0\n%   rContainer    Just a container (structure proposed) to store any variables\n%\n% J. Woessner; woessner@seismo.ifg.ethz.ch\n% April 4, 2003\n\nglobal bDebug;\nif bDebug\n    report_this_filefun(mfilename('fullpath'));\nend\n\n% Launch GUI\nhMenuFig = sv_gridSchuster(1);\n\n% Set up parameter struct and store input parameters\nparams.mCatalog = mCatalog;\nparams.bMap = bMap;\nparams.rContainer = rContainer;\n\n% Analyze Output\nif ~ishandle(hMenuFig)\n    answer = 0;\nelse\n    handles = guidata(hMenuFig);\n    answer = handles.answer;\n    % OK pressed\n    if answer == 1\n        % Get the values from figure\n        %params.bNumber = get(handles.radNumber, 'Value');   % deprecated\n        if get(handles.radNumber, 'Value') == 1\n            params.nGriddingMode = 0;   % Constant number\n        elseif get(handles.radRadius, 'Value') == 1\n            params.nGriddingMode = 1;   % Constant radius\n        else\n            params.nGriddingMode = 2;   % Rectangle mode\n        end\n        % Setting up the params struct array with variables\n        params.nNumberEvents = str2double(get(handles.txtNumber, 'String'));\n        params.fMaxRadius = str2double(get(handles.txtMaxRadius, 'String'));\n        params.fRadius = str2double(get(handles.txtRadius, 'String'));\n        params.bGridEntireArea = get(handles.chkGridEntireArea, 'Value');\n        params.fSpacingHorizontal = str2double(get(handles.txtSpacingHorizontal, 'String')); % Grid spacing variable\n        params.fSpacingDepth = str2double(get(handles.txtSpacingDepth, 'String'));           % Grid spacing variable\n        params.fSizeRectHorizontal = str2double(get(handles.txtSizeRectHorizontal, 'String')); % Rectangular selection instead radius params.fRadius\n        params.fSizeRectDepth = str2double(get(handles.txtSizeRectDepth, 'String'));           % Rectangular selection instead radius params.fRadius\n        params.nMinimumNumber = str2double(get(handles.txtMinimumNumber, 'String'));\n        params.bTimePeriod = get(handles.chkTimePeriod,'Value');\n        params.fTimePeriod = str2double(get(handles.txtTimePeriod,'String')); % Period lengths to be compared in days\n        params.bTstart = get(handles.chkTstart,'Value'); % Check for starting time of temporal mapping\n        params.fTstart = str2double(get(handles.txtTstart,'String')); % Starting time for temporal mapping\n        params.bBstnum = get(handles.chkBstnum,'Value'); % Check for boostrap sampling\n        params.fBstnum = str2double(get(handles.txtBstnum,'String')); % Number of bootstrap samples\n        params.fBinning = str2double(get(handles.txtBinsize,'String')); % Bin size for magnitude binning\n        params.fStartMag = str2double(get(handles.txtStartMag,'String')); % Lower magnitude to perform Schuster test\n        params.fEndMag = str2double(get(handles.txtEndMag,'String')); % Last magnitude to perform Schuster test\n        params.sComment = get(handles.txtComment, 'String'); % Comment on calculation\n\n        %%%%%%%%%%%%%%%%%%%%%%%%%% Check variable settings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        %\n        %  if ~params.bMinMagMc\n        %      params.fMinMag = str2double(get(handles.txtMinMag, 'String'));\n        %    else\n        %      params.fMinMag = 1;\n        %    end\n        %    params.fMaxMag = str2double(get(handles.txtMaxMag, 'String'));\n        bSaveParameter = get(handles.chkSaveParameter, 'Value');\n        if bSaveParameter\n            sSaveParameter = get(handles.lblSaveParameter, 'String');\n        end\n\n        % Remove figure from memory\n        delete(hMenuFig);\n\n        % Select grid\n        [params.mPolygon, params.vX, params.vY, params.vUsedNodes] = ex_selectgrid(hFigure, params.fSpacingHorizontal, params.fSpacingDepth, params.bGridEntireArea);\n\n        % Validate polygonsize\n        if length(params.vX) < 4  ||  length(params.vY) < 4\n            errordlg('Selection is too small. Please select a larger polygon.');\n            return;\n        end\n\n        % Add parameter to params.sComment\n        params.sComment = [params.sComment ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.'...\n                    ', Time period ' num2str(params.fTimePeriod) ' d'];\n        if bSaveParameter\n            % Save paramters\n            save(sSaveParameter, 'params');\n        else\n            % General calculations\n\n            % Create Indices to catalog\n            [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n                params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n\n            %%%%% Temporarily calculations for %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n            % Perform the calculation\n            [params] = sv_calcSchuster(params);\n\n            sv_result(params);\n        end\n    else\n        delete(hMenuFig);\n    end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/sv_startSchuster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20966158534864873}}
{"text": "function [data,indices] = bz_GetWidebandData(channels,varargin)\n\n% bz_GetWidebandData - Get local field potentials.\n%\n%  Load wide band data from disk (unlike spikes or positions, raw data is way\n%  too large to keep in memory).\n%\n%  USAGE\n%\n%    [data,indices] = bz_GetWidebandData(channels,<options>)\n%\n%    channels       optional list of channels to load (default = all)\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'restrict'    list of time intervals to read from the data file\n%     'intervals'   same as 'restrict' (for backwards compatibility)\n%     'select'      select channel by ID ('id', counted from 0 a la NeuroScope)\n%                   or by number ('number', counted from 1 a la Matlab)\n%                   (default = 'id')\n%    =========================================================================\n%\n%  OUTPUT\n%\n%    data           list of (time,voltage1,...,voltageN) tuples\n%    indices        for each tuple, the index of the interval it falls in\n%\n%  EXAMPLES\n%\n%    % channel ID 5 (= # 6), from 0 to 120 seconds\n%    data = bz_GetWidebandData(5,'intervals',[0 120]);\n%    % same, plus from 240.2 to 265.23 seconds\n%    data = bz_GetWidebandData(5,'intervals',[0 120;240.2 265.23]);\n%    % multiple channels\n%    data = bz_GetWidebandData([1 2 3 4 10 17],'intervals',[0 120]);\n%    % channel # 3 (= ID 2), from 0 to 120 seconds\n%    data = bz_GetWidebandData(3,'intervals',[0 120],'select','number');\n\n% Copyright (C) 2004-2011 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\nglobal DATA;\nif isempty(DATA),\n\terror('No session defined (did you forget to call SetCurrentSession? Type ''help <a href=\"matlab:help Data\">Data</a>'' for details).');\nend\n\n% Default values\nintervals = [0 Inf];\nselect = 'id';\n\n% Optional parameter\nif ischar(channels),\n\tvarargin = {channels,varargin{:}};\n\tchannels = []; % all\nend\n\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n  error('Incorrect number of parameters (type ''help <a href=\"matlab:help bz_GetWidebandData\">bz_GetWidebandData</a>'' for details).');\nend\n\n% Parse parameter list\nfor i = 1:2:length(varargin),\n  if ~ischar(varargin{i}),\n    error(['Parameter ' num2str(i+1) ' is not a property (type ''help <a href=\"matlab:help bz_GetWidebandData\">bz_GetWidebandData</a>'' for details).']);\n  end\n  switch(lower(varargin{i})),\n    case {'intervals','restrict'},\n      intervals = varargin{i+1};\n      if ~isdmatrix(intervals) || size(intervals,2) ~= 2,\n        error('Incorrect value for property ''intervals'' (type ''help <a href=\"matlab:help bz_GetWidebandData\">bz_GetWidebandData</a>'' for details).');\n      end\n    case 'select',\n      select = lower(varargin{i+1});\n      if ~isstring_FMAT(select,'id','number'),\n        error('Incorrect value for property ''select'' (type ''help <a href=\"matlab:help bz_GetWidebandData\">bz_GetWidebandData</a>'' for details).');\n      end\n    otherwise,\n      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help <a href=\"matlab:help bz_GetWidebandData\">bz_GetWidebandData</a>'' for details).']);\n  end\nend\n\nfilename = [DATA.session.path '/' DATA.session.basename '.dat'];\nnChannels = DATA.nChannels;\nif isempty(channels),\n\tchannels = 1:nChannels;\nelseif strcmp(select,'id'),\n\tchannels = channels + 1;\nend\n\nnIntervals = size(intervals,1);\ndata = [];\nindices = [];\nfor i = 1:nIntervals,\n\tduration = (intervals(i,2)-intervals(i,1));\n\tstart = intervals(i,1);\n\t% Load data\n\td = bz_LoadBinary(filename,'duration',duration,'frequency',DATA.rates.wideband,'nchannels',nChannels,'start',start,'channels',channels);\n\t% The following two lines compensate for annoying numerical precision errors in Matlab, whereby the number of samples\n\t% read with LoadBinary is not always exactly that expected, depending on how accurately 'duration' is coded internally\n\tn = size(d,1);\n\tt = linspace(start,start+n/DATA.rates.wideband,n)';\n\tdata = [data ; t d];\n\tindices = [indices ; i*ones(size(t))];\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/io/bz_GetWidebandData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20961303917149013}}
{"text": "function fileOffsets = dtiAppendPathwaysToPDB(fg, filename)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% dtiAppendDatabasePathways(toAppend, filename)\n%\n% toAppend: the pathway database we want to append to this file\n% fileOffsets: an array of file offsets for each pathway.\n% \n% Author: DA\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnumstats = 0; % xxx\nalgoType = 0; % xxx\n\nfid = fopen (filename, 'rb');\n% figure out where num paths is, read it in\noffset = fread (fid, 1, 'uint');\n%fprintf ('Seeking to %d\\n', offset);\nfseek (fid, offset, -1);\n[oldNumPaths, count] = fread (fid, 1, 'uint');\nfclose (fid);\nif count == 0\n    %fprintf ('First time!');\n    oldNumPaths = 0;\nend\nnewNumPaths = oldNumPaths + length(fg.fibers);\nfid = fopen (filename, 'r+b');\nfseek (fid, offset, -1);\nfwrite (fid, newNumPaths, 'uint');\nfclose(fid);\nfid = fopen (filename, 'ab');\nfseek (fid, 0, 1);\nfileOffsets = zeros(length(fg.fibers),1);\n\nfor p = 1:length(fg.fibers)\n    fileOffsets(p) = ftell(fid);\n    path_offset = 3 * 4  + numstats*8; % 3 int, numstats double\n    fwrite(fid,path_offset,'int');\n    \n    nn = size(fg.fibers{p}, 2);\n    \n    fwrite(fid,nn,'int');\n    fwrite(fid,algoType,'int'); % algo type\n    fwrite(fid,0,'int'); % seedpointindex ???\n    \n    fwrite(fid,fg.fibers{p}(:), 'double');\n    % Stats\n    %for as = 1:numstats\n     %   fwrite(fid,toAppend.pathways(p).path_stat_vector(as),'double');\n    %end    \n    \n    % Writing path nodes\n    %fwrite(fid,[holdingchains(p).xpos*mmPerVox(1); holdingchains(p).ypos*mmPerVox(2); holdingchains(p).zpos*mmPerVox(3)],'double');\n    %pos = asMatrixStruct(toAppend.pathways(p));\n    % Change from 0 based to 1 based positions\n    %pos = pos - repmat(toAppend.mm_scale(:),1,size(pos,2));\n    %fwrite(fid,pos,'double');\n    \n    % Writing stats values per position\n    %for as = 1:numstats\n    %    if( toAppend.pathway_statistic_headers(as).is_computed_per_point )\n    %        fwrite(fid,toAppend.pathways(p).point_stat_array(as,:),'double');\n    %    end\n    %end    \nend\n\n%disp('Appended pathways to database.');\nfclose(fid);", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/cinch/utils/dtiAppendPathwaysToPDB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.20961303657302552}}
{"text": "function D = spm_eeg_inv_fmripriors(S)\n% Generate fMRI priors for the M/EEG source reconstruction\n% FORMAT D = spm_eeg_inv_fmripriors(S)\n%\n% S        - optional input struct\n% (optional) fields of S:\n%  .D      - MEEG object or filename of M/EEG mat-file\n%  .fmri   - filename of prior (SPM) image to be used\n%  [.gm    - filename of grey matter (GM) image] {unused}\n%  .space  - native (0) or MNI (1) space (must be same for SPM and GM images)\n%  .hthr   - height threshold of prior image [defaults: 0.5]\n%  .ethr   - extent threshold of clusters in prior image [default: 1]\n%  .ncomp  - maximal number of priors component to be extracted [default: Inf]\n%  .smooth - variance of the smoothing kernel onto the surface [default: 0.2] {unused}\n%  .disp   - whether to display priors on mesh [default: 0]\n%\n% D.inv{D.val}.inverse.fmri.priors   - MAT filename containing a variable 'pQ' that\n%            is a [ncomp] cell array of [nb vertices] vectors describing spatial priors\n% D.inv{D.val}.inverse.fmri.texture  - GIfTI texture filename containing all\n%            spatial priors\n% D.inv{D.val}.inverse.fmri.clusters - image filename containing clusters as labels\n%__________________________________________________________________________\n%\n% Reference:\n%\n% A Parametric Empirical Bayesian framework for fMRI-constrained MEG/EEG \n% source reconstruction. Henson R, Flandin G, Friston K & Mattout J.\n% Human Brain Mapping (in press).\n%__________________________________________________________________________\n% Copyright (C) 2008-2015 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin and Rik Henson\n% $Id: spm_eeg_inv_fmripriors.m 6301 2015-01-12 17:23:08Z guillaume $\n\n%-Get MEEG object\n%--------------------------------------------------------------------------\ntry\n    D = S.D;\ncatch\n    [D, sts]   = spm_select(1, 'mat', 'Select M/EEG mat file');\n    if ~sts, D = []; return; end\n    S.D = D;\nend\n\n[D, val] = spm_eeg_inv_check(D);\n\n%-Input parameters\n%--------------------------------------------------------------------------\ntry\n    S.fmri;\ncatch\n    [S.fmri, sts] = spm_select(1,'image','Select prior (eg thresholded SPM) image...');\n    if ~sts, return; end\nend\n\n% try\n%     S.gm;\n% catch\n%     [S.gm, sts] = spm_select([0 1],'image','Select grey matter (GM) image...');\n% end\n\ntry\n    space = S.space;   % 0 = native, 1 = MNI\ncatch\n    space = spm_input('Image space','+1','b',{'Native|MNI'},[0 1],1);\nend\n\nif space \n    try\n        m = D.inv{val}.mesh.tess_mni;\n        %fprintf('Note: assuming SPM and GM images are in MNI space...\\n');\n    catch\n        error('This D structure has no MNI cortical mesh stored.');\n    end\nelse\n    try\n        m = export(gifti(D.inv{val}.mesh.tess_ctx),'spm');\n        %fprintf('Note: assuming SPM and GM images are in subject''s native MRI space...\\n');\n    catch\n        error('This D structure has no cortical mesh stored.');\n    end  \nend\n\ntry\n    S.hthr;\ncatch\n    S.hthr = 0.5; % assume binary prior\nend\n\ntry\n    S.ethr;\ncatch\n    S.ethr = 1; % no threshold on extent\nend\n\ntry\n    S.ncomp;\ncatch\n    S.ncomp = Inf; % all components\nend\n\ntry\n    S.bincomp;\ncatch\n    S.bincomp = 1; % default to binary priors\nend\n\ntry\n    S.varcomp;\ncatch\n    S.varcomp = 1; % default to variance priors (vectors)\nend\n\n% try\n%     S.smooth;\n% catch\n%     S.smooth = 0.2; \n% end\n\ntry\n    S.disp;\ncatch\n    S.disp = 0; \nend\n\n%-Extracting clusters from functional image\n%==========================================================================\nV     = spm_vol(S.fmri);\nprior = spm_read_vols(V);\n\n%-Height threshold\n%--------------------------------------------------------------------------\nprior = prior > S.hthr;\n\n%-Connected Component labelling\n%--------------------------------------------------------------------------\n[l2, num] = spm_bwlabel(double(prior),26);\nif ~num\n    fprintf('No suprathreshold clusters available.\\n');\n    return\nend\n\n%-Extent threshold, and sort clusters according to their extent\n%--------------------------------------------------------------------------\n[n, ni] = sort(histc(l2(:),0:num), 1, 'descend');\nl  = zeros(size(l2));\nn  = n(2:end);      ni = ni(2:end)-1;\nni = ni(n>=S.ethr); n  = n(n>=S.ethr);\nS.ncomp = min(S.ncomp, length(n));\nfor i=1:S.ncomp\n    l(l2==ni(i)) = i;\nend\nclear l2 ni\nfprintf('Selected %d clusters (out of %d) in prior image.\\n',S.ncomp,num);\n\n%-Projecting volumetric clusters on surface mesh\n%==========================================================================\nq = zeros(S.ncomp, size(m.vert,1));\nfor i=1:S.ncomp\n    q(i,:) = spm_mesh_project(m.vert,struct('dat',double(l==i),'mat',V.mat),'nn');\nend\nq(~any(q,2),:) = [];\nfprintf('After projection, %d clusters remaining.\\n',size(q,1));\nif isempty(q), return; end\n\n%-Smooth, binarize and save in output variable\n%--------------------------------------------------------------------------\npQ = cell(1,size(q,1));\nfor i = 1:size(q,1)\n    qq    = q(i,:)';\n    %qq   = spm_mesh_smooth(struct('faces',double(m.face),'vertices',m.vert),qq, S.smooth);\n    qq    = qq .* (qq > exp(-8));\n    if S.bincomp\n        pQ{i} =  double(qq > 0)';  % binarise\n    end\nend\n\n%-Display and export clusters\n%==========================================================================\nif S.disp\n    for i=1:numel(pQ)\n        spm_eeg_render(struct('faces',double(m.face),'vertices',m.vert),...\n            struct('texture',pQ{i}));\n    end\nend\n\n%-Save clusters as an image of labels\n%--------------------------------------------------------------------------\n[pth,name] = fileparts(S.fmri);\nD.inv{val}.inverse.fmri.clusters = fullfile(pth,['cluster_' name spm_file_ext]);\nV = struct('fname',   D.inv{val}.inverse.fmri.clusters, ...\n           'dim',     V.dim, ...\n           'dt',      [spm_type('uint16') spm_platform('bigend')], ...\n           'mat',     V.mat, ...\n           'pinfo',   [1 0 0]', ...\n           'descrip', 'clusters');\nV = spm_write_vol(V,l);\n\n%-Save spatial priors vectors as GIfTI file\n%--------------------------------------------------------------------------\n[pth,name] = fileparts(D.fname);\nD.inv{val}.inverse.fmri.texture = fullfile(pth,['priors_' name '_' num2str(val) '.func.gii']);\nG          = gifti;\nG.cdata    = cat(1, pQ{:})';\nsave(G,D.inv{val}.inverse.fmri.texture);\n\n%-Save spatial priors vectors as MAT-file\n%--------------------------------------------------------------------------\n[pth,name] = fileparts(D.fname);\nD.inv{val}.inverse.fmri.priors = fullfile(pth,['priors_' name '_' num2str(val) '.mat']);\nif ~S.varcomp\n    pQ = pQ*pQ';\nend\n\nsave(D.inv{val}.inverse.fmri.priors,'pQ', spm_get_defaults('mat.format'));\n\n%-Save D structure\n%--------------------------------------------------------------------------\n%D.save;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_inv_fmripriors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.20951196667885877}}
{"text": "function increaseHumanGEMVersion(bumpType)\n% increaseHumanGEMVersion\n%   Increase version for the humanGEM respositories\n%\n% Input:\n%   bumpType      the value has to be one selected among 'major', 'minor' or 'patch'\n%\n% Usage: increaseHumanGEMVersion(bumpType)\n%\n\n\n%Check if in main:\ncurrentBranch = git('rev-parse --abbrev-ref HEAD');\nif ~strcmp(currentBranch,'main')\n    error('ERROR: not in main')\nend\n\n%Get model path\n[ST, I]=dbstack('-completenames');\nmodelPath=fileparts(fileparts(fileparts(ST(I).file)));\n\n%Bump version number:\nversionFile=fullfile(modelPath,'version.txt');\nfid = fopen(versionFile,'r');\n    oldVersion = fscanf(fid, '%s');\nfclose(fid);\noldVersion = str2double(strsplit(oldVersion,'.'));\nnewVersion = oldVersion;\nswitch bumpType\n    case 'major'\n        newVersion(1) = newVersion(1) + 1;\n        newVersion(2) = 0;\n        newVersion(3) = 0;\n    case 'minor'\n        newVersion(2) = newVersion(2) + 1;\n        newVersion(3) = 0;\n    case 'patch'\n        newVersion(3) = newVersion(3) + 1;\n    otherwise\n        error('ERROR: invalid input. Use either \"major\", \"minor\" or \"patch\"')\nend\nnewVersion = num2str(newVersion,'%d.%d.%d');\n\n%Check if history has been updated:\n%fid     = fopen('../../history.md','r');\n%history = fscanf(fid,'%s');\n%fclose(fid);\n%if ~contains(history,['human' newVersion ':'])\n%    error('ERROR: update history.md first')\n%end\n%To be included\n\n%Load model:\nymlFile=fullfile(modelPath,'model','Human-GEM.yml');\nihuman = importYaml(ymlFile);\n\n%Include tag and save model:\nihuman.version = newVersion;\n\n%Export model to multiple formats\nexportHumanGEM(ihuman,'Human-GEM',modelPath,{'mat', 'txt', 'xml', 'yml', 'xlsx'});\n\n%Update version file:\nfid = fopen(versionFile,'wt');\nfprintf(fid,newVersion);\nfclose(fid);\n\n%Update readme file:\nreadmeFile=fullfile(modelPath,'README.md');\ncontent = fileread(readmeFile);\ncontent = strrep(content,'{{DATE}}',datestr(now,29));\ncontent = strrep(content,'{{nRXN}}',num2str(length(ihuman.rxns)));\ncontent = strrep(content,'{{nMET}}',num2str(length(ihuman.mets)));\ncontent = strrep(content,'{{nGENE}}',num2str(length(ihuman.genes)));\nfid = fopen(readmeFile,'wt');\nfwrite(fid,content);\nfclose(fid);\n\nend\n", "meta": {"author": "SysBioChalmers", "repo": "Human-GEM", "sha": "0b1bd42adaa2e1d7ac52ee83b989fad8a695759d", "save_path": "github-repos/MATLAB/SysBioChalmers-Human-GEM", "path": "github-repos/MATLAB/SysBioChalmers-Human-GEM/Human-GEM-0b1bd42adaa2e1d7ac52ee83b989fad8a695759d/code/io/increaseHumanGEMVersion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2094585956512109}}
{"text": "function gX = whitehKernGradX(kern, X, X2)\n\n% WHITEHKERNGRADX Gradient of WHITEH kernel with respect to input locations.\n% FORMAT\n% DESC computes the gradident of the whiteh noise\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO whitehKernParamInit, kernGradX, whitehKernDiagGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006\n\n% KERN\n\nif nargin<3\n    X2 = X;\nend\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/whitehKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20945859565121086}}
{"text": "function rtf(plot_frq,flag_save)\n\n\nclose all\nevalin('base','stop=0;');\n\n\n\n%=========SET THE BASIC FIGURE=================\nfig = figure('Position',[500,500,800,600],...\n        'NumberTitle','off',...\n        'Name','Scope',...\n        'doublebuffer','on',...\n        'HandleVisibility','on',...\n        'KeyPressFcn', @keypress, ...\n        'Renderer', 'openGL');\n%=============================================\n\n\n%=============OPEN THE DEVICE FOR RECORD======\nsample_frequency = 44100;\nsamples_per_frame = 1024;\n%plot_frq=10;\nrecord_time=600;\nsamples_to_acquire = record_time * sample_frequency;\n\n\n%PREPARE    THE    DEVICE\nai = analoginput('winsound');   \nchan = addchannel( ai, 1 );\nset( ai, 'SampleRate', sample_frequency )\nset( ai, 'SamplesPerTrigger', samples_to_acquire )\nset(ai, 'StopFcn', @stop_dev)\n\nsample_frequency = get( ai, 'SampleRate' );\n\n\n%SETTING CALL BACK FUNCTIONS:\n%The first for capture   the \n%second     for      display\nset(ai, 'SamplesAcquiredFcnCount',samples_per_frame);\nset(ai, 'SamplesAcquiredFcn',@flag);\nset(ai, 'TimerPeriod',(1/plot_frq));\nset(ai, 'TimerFcn',@disply);\n\n\n%=============SAVE THE CONFIGURATION======\nplot_ref=plot(zeros(10,1));\nfid=-1;\n\n\n%SAVE THE CURRENT PARAMETERS:\nname_of_file=sprintf('%s-%d','real-anal',(round(sample_frequency/samples_per_frame)));\nremark={1,...\n        zeros(samples_per_frame*20,1)',...\n        0,...\n        plot_ref,...\n        plot_frq,...\n        cputime,...\n        flag_save,...\n        -1,...\n        name_of_file\n        };\n\nset(ai, 'UserData',remark)\n\n\n\n\n%=============START TO RECORD================\nfprintf ('To stop the program set <stop=1> or press q in the figure window\\n');\nstart (ai)\n\n\n\n\n\n%=============================================\n%=========THE MAIN PROGRAM====================\n%=============================================\n%                   *\n%                  ***\n%                 *****\n%                  ***\n%                  ***\n%                  ***\n%                  ***\n%                  ***\n%                 *****\n%                  ***\n%                   *\n%=============================================\n%==========CALLBACK FUNCTIONS=================\n%=============================================\n\n\n\n%=========Keypress callback===========\nfunction keypress(src, e)\n  keypressed=get(gcf,'CurrentCharacter');\n\n  % ignore raw control, shift, alt keys\n  if keypressed\n    % Quit\n    if strcmp( keypressed, 'q')\n        evalin('base','stop=1;');\n    end\n  end\nreturn\n\n\n%============FLAG FUNCTION===================\n%This function activated when we capture\n%certain    amount  of          samples\nfunction flag(obj,event)\n\n  % CHECK FOR STOP SIGNAL\n  if  evalin('base','stop')\n      stop(obj)\n  end\n \n% GET THE OLD DATA\n remark=get(obj,'UserData');\n flag_write=remark{1};  %Do I have to \n buffer=remark{3};      %What is the old picture\n flag_save=remark{7};   %Are we in saving mode?\n fid=remark{8};         %What file descriptor to save\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %IN CASE - DELETE/SAVE THE OLD DATA\n \n if flag_write>20\n     \n     \n     % IN CASE WE HAVE TO SAVE - CLOSE THE OLD FILE AND MAKE A NEW\n     if flag_save>0\n        fclose(fid);\n        name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));\n        fid=fopen(name_of_data,'w');\n    end\n    \n      %DELETE OLD DATA\n     flag_write=1;\n     buffer=[];\n     remark{1}=flag_write; % SET THE POSITION OF THE READING SHIFT\n end\n  \n   \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % TAKE THE NEW DATA\n \n samples_per_frame=get(obj,'SamplesAcquiredFcnCount');\n data=(getdata(obj,samples_per_frame))';    \n \n % IN CASE - WRITE THE DATA\n if flag_save>0\n     if fid==-1\n         name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));\n         fid=fopen(name_of_data,'w');\n     end\n     fwrite(fid,(data*10000),'short');\n     remark{8}=fid;\n end\n \n \n % Add to buffer\n buffer=[buffer data];\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n remark{3}=buffer;\n set(obj,'UserData',remark); \n \n  \nreturn\n\n\nfunction stop_dev(obj,event)\n\n     remark=get(obj,'UserData');\n     if (remark{8}>0)                 %FID>0 == There is open file\n         fclose (remark{8});\n     end\n     close all\n     \n     fprintf('\\n\\nThanks for using Erlich Real-Time scope\\n');\n     save (remark{9},'remark');\n     \n     delete(obj)\n     clear obj\nreturn\n\n\n\n\n\n\n\n\n\n\n\nfunction disply(obj,event)\n\n\n \n\n  sample_frequency=get(obj,'SampleRate');\n  remark=get(obj,'UserData');\n  refresh_frq=remark{5};\n  read_shift=remark{1};\n  \n  ring=remark{2};\n  buffer=remark{3};\n  \n \n  end_shift=min((read_shift+round(sample_frequency/refresh_frq)),length(buffer));\n  new_data=buffer(read_shift:end_shift);\n  ring=[ring new_data];\n  ring(1:length(new_data))=[];\n  remark{1}=end_shift;\n  remark{2}=ring;\n  \n  \n  start_display(ring,remark{4})\n  \n  set(obj,'UserData',remark);\nreturn\n \n \n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/specscope/rtf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20945859565121086}}
{"text": "function [ama] = loadama(filename);\n\n% LOADAMA read an inverted A-matrix and associated geometry information\n% from an ama file that was written by Tom Oostendorp's DIPOLI\n%\n% Use as\n%   [ama] = loadama(filename)\n%\n% See also LOADTRI, LOADMAT\n\n% Copyright (C) 2005, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id: loadama.m 2885 2011-02-16 09:41:58Z roboos $\n\nfid = fopen(filename, 'rb', 'ieee-le');\n\nversion = fread(fid, 1, 'int');\nif version~=10\n  error(sprintf('%s is either not an inverted A matrix, or one of an old version', filename));\nend\n\nmode = fread(fid, 1, 'int');\nngeo = fread(fid, 1, 'int');\n\ntotpnt = 0;\ntotdhk = 0;\nnrow   = 0;\n\n% read the boundaries\ngeo  = [];\nfor i=1:ngeo\n  geo(i).name    = char(fread(fid, [1 80], 'uchar'));\n  geo(i).npnt    = fread(fid, 1, 'int');\n  geo(i).pnt     = fread(fid, [3 geo(i).npnt], 'float')';\n  geo(i).ndhk    = fread(fid, 1, 'int');\n  geo(i).dhk     = fread(fid, [3 geo(i).ndhk], 'int')' + 1;  % Matlab indexing starts at 1\n  geo(i).sigmam  = fread(fid, 1, 'float');\n  geo(i).sigmap  = fread(fid, 1, 'float');\n  geo(i).geocon  = fread(fid, ngeo, 'int');\n  geo(i).deflat  = fread(fid, ngeo, 'float');\n  totpnt = totpnt + geo(i).npnt;\n  totdhk = totdhk + geo(i).ndhk;\nend\n\n% read the electrodes\nif mode~=1\n  elec.name    = char(fread(fid, [1 80], 'uchar'));\n  elec.npnt    = fread(fid, 1, 'int');\n  for i=1:(elec.npnt+1)\n    elec.el(i).dhk  = fread(fid, 1, 'int') + 1; % Matlab indexing starts at 1\n    elec.el(i).la   = fread(fid, 1, 'float');\n    elec.el(i).mu   = fread(fid, 1, 'float');\n    elec.el(i).name = char(fread(fid, [1 10], 'char'));\n    % the ELECTRODE c-structure is padded to word boundaries, i.e. to 4 bytes\n    dum = fread(fid, 2, 'char');\n  end\n  elec.vertex  = fread(fid, 1, 'int');\n  elec.surface = fread(fid, 1, 'int');\n  nrow = nrow + elec.npnt;\nelse\n  elec = [];\nend\n\n% read the gradiometers\nif mode~=0\n  error('gradiometers not yet implemented');\nelse\n  grad = [];\nend\n\n% read the inverted A-matrix\nbi = fread(fid, [totpnt nrow], 'float')';\n\n% read the isolated source compartment information, if present\niso_sur    = fread(fid, 1, 'int') + 1;  % Matlab indexing starts at 1\ninner_only = fread(fid, 1, 'int');\nif iso_sur~=0\n  iso_totpnt = geo(iso_sur).npnt;\n  iso_b      = fread(fid, [iso_totpnt iso_totpnt], 'float')';\nelse\n  iso_b = [];\nend\n\nfclose(fid);\n\n% put all local variables into a structure, this is a bit unusual programming style\n% the output structure is messy, but contains all relevant information\ntmp = whos;\nama = [];\nfor i=1:length(tmp)\n  if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'}))\n    ama = setfield(ama, tmp(i).name, eval(tmp(i).name));\n  end\nend\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fieldtrip_partial/forward/private/loadama.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20933514461095162}}
{"text": "function [clpot, seppot] = init_pot(engine, clqs, pots, pot_type, onodes, ndx)\n% INIT_POT Initialise potentials with evidence (jtree_inf)\n% function [clpot, seppot] = init_pot(engine, clqs, pots, pot_type, onodes)\n\ncliques = engine.cliques;\nbnet = bnet_from_engine(engine);\n% Set the clique potentials to all 1s\nC = length(cliques);\nclpot = cell(1,C);\nfor i=1:C\n  clpot{i} = mk_initial_pot(pot_type, cliques{i}, bnet.node_sizes(:), bnet.cnodes(:), onodes);\nend\n\n% Multiply on specified potentials\nfor i=1:length(clqs)\n  c = clqs(i);\n  clpot{c} = multiply_by_pot(clpot{c}, pots{i});\nend\n\nseppot = cell(C,C); % implicitely initialized to 1\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/static/@jtree_sparse_inf_engine/old/init_pot1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20926954850482773}}
{"text": "function test_suite=SimTest_qmt_sirfse_test\ntry % assignment of 'localfunctions' is necessary in Matlab >= 2016\ntest_functions=localfunctions();\ncatch % no problem; early Matlab versions can use initTestSuite fine\nend\ninitTestSuite;\n\nfunction TestSetup\nsetenv('ISDISPLAY','0') % go faster! Fit only 2 voxels in FitData.m\nsetenv('ISCITEST','1')\n\nfunction test_Sim\ndisp('===========================================')\ndisp('Running simulation test for qmt_sirfse');\ndisp('testing Simulation Single Voxel Curve...');\n\n\nModel = str2func('qmt_sirfse'); Model = Model();\nsavedModel_fname = fullfile(fileparts(which('qMRLab')),'Test','MoxUnitCompatible','static_savedModelsforRetrocompatibility',['qmt_sirfse.qmrlab.mat']);\nif ~exist(savedModel_fname,'file')\nModel.saveObj(savedModel_fname);\nelse\nModel = Model.loadObj(savedModel_fname);\nend\n\ndisp(class(Model))\ntry Opt = button2opts(Model.Sim_Single_Voxel_Curve_buttons,1); end\ntry st = Model.st; catch, try st = mean([Model.lb(:),Model.ub(:)],2); catch, st = ones(length(Model.xnames),1); end; end\nif exist('Opt','var') && length(Opt)>1\n[Opt(:).SNR] = deal(1000);\nelse\nOpt.SNR=1000;\nend\nfor iopt=1:length(Opt) % Test all simulation options\ndisp(['Testing ' class(Model) ' simulation option:'])\ndisp(Opt(iopt))\nFitResults = Model.Sim_Single_Voxel_Curve(st,Opt(iopt));\n% Compare inputs and outputs\nfnm=fieldnames(FitResults);\nFitResults = rmfield(FitResults,fnm(~ismember(fnm,Model.xnames))); fnm=fieldnames(FitResults);\n[~,FitResults,GroundTruth]=comp_struct(FitResults,mat2struct(st,Model.xnames),[],[],.30);\nassertTrue(isempty(FitResults) & isempty(GroundTruth),evalc('FitResults, GroundTruth'))\nend\ndisp ..ok\n\n\nfunction TestTeardown\nsetenv('ISDISPLAY','') % go faster! Fit only 2 voxels in FitData.m\nsetenv('ISCITEST','')\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/Test/MoxUnitCompatible/simTests/SimTest_qmt_sirfse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2092695485048277}}
{"text": "function rendering = spm_cfg_render\n% SPM Configuration file for Render\n%__________________________________________________________________________\n% Copyright (C) 2013-2016 Wellcome Trust Centre for Neuroimaging\n\n% $Id: spm_cfg_render.m 6925 2016-11-09 17:23:40Z guillaume $\n\n%==========================================================================\n% Extract\n%==========================================================================\n\n%--------------------------------------------------------------------------\n% data Data\n%--------------------------------------------------------------------------\ndata         = cfg_files;\ndata.tag     = 'data';\ndata.name    = 'Data';\ndata.help    = {'Images to create rendering/surface from (usually grey and white matter segmentations).'};\ndata.filter  = 'image';\ndata.ufilter = '.*';\ndata.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% mode Output\n%--------------------------------------------------------------------------\nmode        = cfg_menu;\nmode.tag    = 'mode';\nmode.name   = 'Output';\nmode.help   = {'Operation mode.'};\nmode.labels = {'Save Rendering'\n               'Save Extracted Surface'\n               'Save Rendering and Surface'}';\nmode.values = {1 2 3};\nmode.val    = {3};\n\n%--------------------------------------------------------------------------\n% thresh Surface isovalue(s)\n%--------------------------------------------------------------------------\nthresh         = cfg_entry;\nthresh.tag     = 'thresh';\nthresh.name    = 'Surface isovalue(s)';\nthresh.help    = {...\n    'Enter one or more values at which isosurfaces through the input images will be computed.'\n    'This is only relevant for extracting surfaces, not rendering.'};\nthresh.strtype = 'r';\nthresh.val     = {0.5};\nthresh.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% extract Extract Surface\n%--------------------------------------------------------------------------\nextract      = cfg_exbranch;\nextract.tag  = 'extract';\nextract.name = 'Extract Surface';\nextract.val  = {data mode thresh};\nextract.help = {'Surface extraction.'};\nextract.prog = @spm_surf;\nextract.vout = @vout_extract;\n\n%==========================================================================\n% Render\n%==========================================================================\n\n%--------------------------------------------------------------------------\n% spmmat Select SPM.mat\n%--------------------------------------------------------------------------\nspmmat         = cfg_files;\nspmmat.tag     = 'spmmat';\nspmmat.name    = 'Select SPM.mat';\nspmmat.help    = {'Select the SPM.mat file that contains the design specification.'};\nspmmat.filter  = 'mat';\nspmmat.ufilter = '^SPM\\.mat$';\nspmmat.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% contrasts Contrast(s)\n%--------------------------------------------------------------------------\ncontrasts         = cfg_entry;\ncontrasts.tag     = 'contrasts';\ncontrasts.name    = 'Contrast(s)';\ncontrasts.help    = {'Index of contrast(s). If more than one number is entered, analyse a conjunction hypothesis.'};\ncontrasts.strtype = 'n';\ncontrasts.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% threshdesc Threshold type\n%--------------------------------------------------------------------------\nthreshdesc        = cfg_menu;\nthreshdesc.tag    = 'threshdesc';\nthreshdesc.name   = 'Threshold type';\nthreshdesc.help   = {''};\nthreshdesc.labels = {'FWE' 'none' 'FDR'};\nthreshdesc.values = {'FWE' 'none' 'FDR'};\nthreshdesc.val    = {'FWE'};\n\n%--------------------------------------------------------------------------\n% thresh Threshold\n%--------------------------------------------------------------------------\nthresh         = cfg_entry;\nthresh.tag     = 'thresh';\nthresh.name    = 'Threshold';\nthresh.help    = {''};\nthresh.strtype = 'r';\nthresh.num     = [1 1];\nthresh.val     = {0.05};\n\n%--------------------------------------------------------------------------\n% extent Extent (voxels)\n%--------------------------------------------------------------------------\nextent         = cfg_entry;\nextent.tag     = 'extent';\nextent.name    = 'Extent (voxels)';\nextent.help    = {''};\nextent.strtype = 'w';\nextent.num     = [1 1];\nextent.val     = {0};\n\n%--------------------------------------------------------------------------\n% contrasts Contrast(s)\n%--------------------------------------------------------------------------\ncontrasts1         = cfg_entry;\ncontrasts1.tag     = 'contrasts';\ncontrasts1.name    = 'Contrast(s)';\ncontrasts1.help    = {'Index of contrast(s) for masking - leave empty for no masking.'};\ncontrasts1.strtype = 'n';\ncontrasts1.num     = [1 Inf];\n\n%--------------------------------------------------------------------------\n% thresh Mask threshold\n%--------------------------------------------------------------------------\nthresh1         = cfg_entry;\nthresh1.tag     = 'thresh';\nthresh1.name    = 'Mask threshold';\nthresh1.help    = {''};\nthresh1.strtype = 'r';\nthresh1.num     = [1 1];\nthresh1.val     = {0.05};\n\n%--------------------------------------------------------------------------\n% mtype Nature of mask\n%--------------------------------------------------------------------------\nmtype        = cfg_menu;\nmtype.tag    = 'mtype';\nmtype.name   = 'Nature of mask';\nmtype.help   = {''};\nmtype.labels = {'Inclusive' 'Exclusive'};\nmtype.values = {0 1};\n\n%--------------------------------------------------------------------------\n% mask Mask definition\n%--------------------------------------------------------------------------\nmask      = cfg_branch;\nmask.tag  = 'mask';\nmask.name = 'Mask definition';\nmask.val  = {contrasts1 thresh1 mtype};\nmask.help = {''};\n\n%--------------------------------------------------------------------------\n% generic Masking\n%--------------------------------------------------------------------------\ngeneric1        = cfg_repeat;\ngeneric1.tag    = 'generic';\ngeneric1.name   = 'Masking';\ngeneric1.help   = {''};\ngeneric1.values = {mask};\ngeneric1.num    = [0 1];\n\n%--------------------------------------------------------------------------\n% conspec Contrast query\n%--------------------------------------------------------------------------\nconspec      = cfg_branch;\nconspec.tag  = 'conspec';\nconspec.name = 'Contrast query';\nconspec.val  = {spmmat contrasts threshdesc thresh extent generic1};\nconspec.help = {''};\n\n%--------------------------------------------------------------------------\n% generic Contrasts\n%--------------------------------------------------------------------------\ngeneric        = cfg_repeat;\ngeneric.tag    = 'generic';\ngeneric.name   = 'Contrasts';\ngeneric.help   = {''};\ngeneric.values = {conspec};\ngeneric.num    = [1 3];\n\n%--------------------------------------------------------------------------\n% rendfile Render File\n%--------------------------------------------------------------------------\nrendfile         = cfg_files;\nrendfile.tag     = 'rendfile';\nrendfile.name    = 'Render File';\nrendfile.help    = {'File containing the images to render on to.'};\nrendfile.filter  = {'mat','mesh'};\nrendfile.ufilter = '.*';\nrendfile.num     = [1 1];\n\n%--------------------------------------------------------------------------\n% render Display Surface\n%--------------------------------------------------------------------------\nrender      = cfg_exbranch;\nrender.tag  = 'display';\nrender.name = 'Display Surface';\nrender.val  = {rendfile generic};\nrender.help = {'Surface rendering.'};\nrender.prog = @run_render;\n\n%==========================================================================\n% rendering Rendering\n%==========================================================================\nrendering        = cfg_choice;\nrendering.tag    = 'render';\nrendering.name   = 'Rendering';\nrendering.help   = {'Rendering utilities.'};\nrendering.values = {extract render};\n\n\n%==========================================================================\nfunction run_render(job)\nfor i=1:numel(job.conspec)\n    xSPM.swd       = spm_file(job.conspec(i).spmmat{1},'fpath');\n    xSPM.Ic        = job.conspec(i).contrasts;\n    xSPM.u         = job.conspec(i).thresh;\n    xSPM.Im        = [];\n    if ~isempty(job.conspec(i).mask)\n        xSPM.Im    = job.conspec(i).mask.contrasts;\n        xSPM.pm    = job.conspec(i).mask.thresh;\n        xSPM.Ex    = job.conspec(i).mask.mtype;\n    end\n    xSPM.thresDesc = job.conspec(i).threshdesc;\n    xSPM.k         = job.conspec(i).extent;\n    %xSPM.n        = 1; % conjunction \n    xSPM.units     = {'mm' 'mm' 'mm'};\n    [SPM, xSPM]    = spm_getSPM(xSPM);\n    dat(i) = struct('XYZ', xSPM.XYZ,...\n                    't',   xSPM.Z',...\n                    'mat', xSPM.M,...\n                    'dim', xSPM.DIM);\nend\n% Force non-interactive mode...\nglobal prevrend\nprevrend = struct('rendfile',job.rendfile{1}, 'brt',1, 'col',eye(3));\nspm_render(dat,1,job.rendfile{1});\n\n\n%==========================================================================\nfunction dep = vout_extract(job)\n\ncdep = 1;\nif any(job.mode==[1 3])\n    dep(cdep)            = cfg_dep;\n    dep(cdep).sname      = 'Render .mat File';\n    dep(cdep).src_output = substruct('.','rendfile');\n    dep(cdep).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});\n    cdep = cdep + 1;\nend\n\nif any(job.mode==[2 3])\n    for k=1:numel(job.thresh)\n        dep(cdep)            = cfg_dep;\n        dep(cdep).sname      = sprintf('Surface .gii File (thr=%.02f)', ...\n            job.thresh(k));\n        dep(cdep).src_output = substruct('.','surffile', '()',{k});\n        dep(cdep).tgt_spec   = cfg_findspec({{'filter','mesh','strtype','e'}});\n        cdep = cdep + 1;\n    end\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_render.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.20907008854238526}}
{"text": "function test_bug1637\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY megplanar_sincos channelconnectivity ft_prepare_neighbours ft_channelselection\n\n% this function checks whether megplanar_sincos relies on a fixed channel\n% order or whether this can be totally mixed up (it should be able to deal\n% with that!)\n%\n% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1637\n\n% load neighbours\ncfg = [];\ncfg.method = 'template';\ncfg.template = 'CTF275_neighb';\nneighbours = ft_prepare_neighbours(cfg);\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/test'))\nload bug1637_hdr.mat\nload bug1637_grad.mat\n\nd = pwd;\nftPath = fileparts(mfilename('fullpath')); % get path, strip away 'ft_defaults'\nftPath = strrep(ftPath, '\\', '\\\\');\n\ncd(fullfile(ftPath, '..', 'private'));\nerrored = false;\ntry\n  cfg = [];\n  cfg.neighbours = neighbours;\n  cfg.channel    = ft_channelselection('MEG', hdr.label);\n  [neighbsel] = match_str({cfg.neighbours.label}, cfg.channel);\n  cfg.neighbours = cfg.neighbours(neighbsel);\n  cfg.neighbsel = channelconnectivity(cfg);\n  \n  montage_other = megplanar_sincos(cfg, hdr.grad);\n  \n  montage = [];\n  montage{1} = megplanar_sincos(cfg, grad);\n  \n  [sel12, sel22] = match_str(montage{1}.labelold, montage_other.labelold);\n  [sel11, sel21] = match_str(montage{1}.labelnew, montage_other.labelnew);\n  if ~isequal(montage{1}.tra(sel11, sel12), montage_other.tra(sel21, sel22))\n    warning('tra matrix differs - but that''s because the montage_other.tra consists of nans - checking whether nonzero elements are the same')\n    idx1 = montage{1}.tra(sel11, sel12)~=0;\n    idx2 = montage_other.tra(sel21, sel22)~=0;\n    if ~isequal(idx1, idx2)\n      errored = true;\n      error('tra matrix qualitatively differ!');\n    else\n      disp('...passed!')\n    end\n  elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage_other.labelold(sel22))))\n    errored = true;\n    error('labelold mismatch');\n  elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage_other.labelnew(sel21))))\n    errored = true;\n    error('labelnew mismatch');\n  end\n  \n  for i=1:10 % 10 is an arbitrary number here, just do it for some time\n    labperm = randperm(numel(grad.label));\n    % permute everything\n    grad.chanori    = grad.chanori(labperm, :);\n    grad.chanpos    = grad.chanpos(labperm, :);\n    grad.chantype   = grad.chantype(labperm, :);\n    grad.chanunit   = grad.chanunit(labperm, :);\n    grad.coiloriri  = grad.coilori(labperm, :);\n    grad.coilpos    = grad.coilpos(labperm, :);\n    grad.label      = grad.label(labperm, :);\n    grad.tra        = grad.tra(labperm, :);\n    \n    montage{2} = megplanar_sincos(cfg, grad);\n    \n    % since we now reordered everything according to cfg.channel, the\n    % following should not be necessary - but hey!\n    [sel12, sel22] = match_str(montage{1}.labelold, montage{2}.labelold);\n    [sel11, sel21] = match_str(montage{1}.labelnew, montage{2}.labelnew);\n    if ~(isequal(montage{1}.tra(sel11, sel12), montage{2}.tra(sel21, sel22)))\n      errored = true;\n      error('tra matrix differs')\n    elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage{2}.labelold(sel22))))\n      errored = true;\n      error('labelold mismatch');\n    elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage{2}.labelnew(sel21))))\n      errored = true;\n      error('labelnew mismatch');\n    end\n  end\n  \n  \n  for i=1:10 % 10 is an arbitrary number here, just do it for some time\n    labperm = randperm(numel(grad.label));\n    % permute everything\n    grad.chanori    = hdr.grad.chanori(labperm, :);\n    grad.chanpos    = hdr.grad.chanpos(labperm, :);\n    grad.chantype   = hdr.grad.chantype(labperm, :);\n    grad.chanunit   = hdr.grad.chanunit(labperm, :);\n    grad.coiloriri  = hdr.grad.coilori(labperm, :);\n    grad.coilpos    = hdr.grad.coilpos(labperm, :);\n    grad.label      = hdr.grad.label(labperm, :);\n    grad.tra        = hdr.grad.tra(labperm, :);\n    \n    montage{2} = megplanar_sincos(cfg, hdr.grad);\n    \n    % since we now reordered everything according to cfg.channel, the\n    % following should not be necessary - but hey!\n    [sel12, sel22] = match_str(montage{1}.labelold, montage{2}.labelold);\n    [sel11, sel21] = match_str(montage{1}.labelnew, montage{2}.labelnew);\n    idx1 = montage{1}.tra(sel11, sel12)~=0;\n    idx2 = montage_other.tra(sel21, sel22)~=0;\n    if ~isequal(idx1, idx2)\n      errored = true;\n      error('tra matrix qualitatively differ!');\n    elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage_other.labelold(sel22))))\n      errored = true;\n      error('labelold mismatch');\n    elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage_other.labelnew(sel21))))\n      errored = true;\n      error('labelnew mismatch');\n    end\n  end\n  \nend\ncd(d)\n\nif errored\n  error('channelorder matters whereas it should not!');\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1637.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895467048751784}}
{"text": "% plotcurve() - plot curve(s) with optional significance highlighting.\n%\n% Usage: >> plotcurve(times, data, 'key1', 'val1', 'key2', val2' ...);\n%\n% Required inputs:\n%   times - [float] vector of time indices\n%   data  - [float] data array, size of [n x times]. If n>1 several\n%           curves are plotted (unless 'plotmean' option is used).\n%\n% Optional inputs:\n%  'maskarray' = Input bootstrap limits. Can be 1-D [min max], 2-D (min\n%                and max for all ordinate) or 3-D (min and max for all\n%                ordinates at all time points).\n%  'val2mask'  = Value to use for generating mask. By default use data.\n%  'plotmean' = ['on'|'off'] For 'curve' plots only. Average all\n%                frequencies given as input. Default: 'on'.\n%  'highlightmode'  = ['background'|'bottom'] For 'curve' plots only,\n%                display significant time regions either in the plot\n%                background or underneatht the curve.\n%  'xlabel'    = [string] x label\n%  'ylabel'    = [string] y label\n%  'legend'    = [cell] legend. Cell array of string, with one string\n%                per curve.\n%  'ylim'      = [min max] or [min] limits for the ordinate axis.\n%  'title'     = Optional figure title. If two conditions are given\n%                as input, title can be a cell array with two text\n%                string elements {none}\n%  'vert'      = Latencies to mark with a dotted vertical line   {none}\n%  'linewidth' = Line width for marktimes traces (thick=2, thin=1) {2}\n%  'chanlocs'  = channel location structure.\n%  'plottopo'  = [min max] plot topography within the time limits defined\n%                in this function. If several lines are given as input, one\n%                scalp map is plot for each line.\n%\n% Authors: Arnaud Delorme, 2004, Bhaktivedanta Institute\n\n% Copyright (C) 2004  Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction plotcurve( times, R, varargin);\n\n\tif nargin < 2\n        help plotcurve;\n        return;\n\tend;\n\tg = finputcheck( varargin, { 'maskarray' ''        []       [];\n                             'val2mask'      'real'    []           R;\n                             'highlightmode' 'string'  { 'background' 'bottom' } 'background';\n                             'plotmean'      'string'  { 'on' 'off' }            'off';\n                             'plotindiv'     'string'  { 'on' 'off' }            'on';\n                             'logpval'       'string'  { 'on' 'off' }            'off';\n                             'title'         'string'  []                        '';\n                             'xlabel'        'string'  []                        '';\n                             'plotmode'      'string'  {'single' 'topo'}         'single';\n                             'ylabel'        'string'  []                        '';\n                             'legend'        'cell'    []                        {};\n                             'colors'        'cell'    []                        {};\n                             'plottopotitle' 'cell'    []                        {};\n                             'chanlocs'      'struct'  []                        struct;\n                             'ylim'          'real'    []                        [];\n                             'vert'          'real'    []                        [];\n                             'plottopo'      'real'    []                        [];\n                             'linewidth'     'real'    []                        2;\n                             'marktimes'     'real'    []                        [] });\n   if isstr(g), error(g); end;\n  % keyboard;\n   if isempty(g.colors), g.colors = { 'r' 'g' 'b' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ...\n                   'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' }; end;\n   if strcmpi(g.plotindiv, 'off'), g.plotmean = 'on'; end;\n   \n   if ~any(length(times) == size(R))\n       try,\n           R = reshape(R, length(times), length(R)/length(times))';\n       catch, error('Size of time input and array input does not match');\n       end;\n   end;\n\n   % regions of significance\n   % -----------------------\n   if ~isempty(g.maskarray)\n       if length(unique(g.maskarray)) < 4\n          Rregions = g.maskarray;\n       else\n          Rregions = ones(size(g.val2mask));\n          switch dims(g.maskarray)\n               case 3, Rregions  (find(g.val2mask > g.maskarray(:,:,1) & (g.val2mask < g.maskarray(:,:,2)))) = 0;\n               case 2, if size(g.val2mask,2) == size(g.maskarray,2)\n                           Rregions  (find(g.val2mask < g.maskarray)) = 0;\n                       elseif size(g.val2mask,1) == size(g.maskarray,1)\n                           Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ...\n                             & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0;\n                       else\n                           Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ...\n                             & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0;\n                       end;\n               case 1, Rregions  (find(g.val2mask < repmat(g.maskarray(:),[1 size(g.val2mask,2)]))) = 0;\n           end; \n           Rregions = sum(Rregions,1);\n       end;\n   else \n       Rregions = [];\n   end\n\n  % plotting\n  % --------\n  if size(R,1) == length(times), R = R'; end;\n  if strcmpi(g.plotmean, 'on') | strcmpi(g.plotindiv, 'off')\n      if strcmpi(g.plotindiv, 'on')\n          R = [ R; mean(R,1) ];\n      else\n          R = mean(R,1);\n      end;\n  end;\n  ax = gca;\n  if ~isempty(g.maskarray) & strcmpi(g.highlightmode, 'bottom')\n      pos = get(gca, 'position');\n      set(gca, 'position', [ pos(1)+pos(3)*0.1 pos(2)+pos(4)*0.1 pos(3)*0.9 pos(4)*0.85 ]);\n  end;\n  \n  % plot topographies\n  % -----------------\n  if ~isempty(g.plottopo)\n      tmpax = gca;\n      pos = get(gca, 'position');\n      set(gca, 'position', [ pos(1) pos(2) pos(3) pos(4)/2 ]);\n      \n      for index = 1:size(g.plottopo)\n          axes('position', [ (index-1)*pos(3)/size(g.plottopo,1)+pos(1) pos(2)+pos(4)/2 pos(3)/size(g.plottopo,1) pos(4)/2 ]);\n          %topoplot(g.plottopo(index,:), g.chanlocs, 'maplimits', 'minmax');\n          topoplot(g.plottopo(index,:), g.chanlocs);\n          if ~isempty(g.plottopotitle)\n              title(g.plottopotitle{index}, 'interpreter', 'none');\n          end;\n      end;\n      \n      axes(tmpax);\n  end;\n      \n  for ind = 1:size(R,1)\n      if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1\n           plot(times,R(ind,:), 'k', 'linewidth', 2);\n      elseif ~isempty(g.colors),\n           tmp = plot(times,R(ind,:), 'k'); \n           set(tmp, 'color', g.colors{mod(ind-1, length(g.colors))+1}); \n           \n           % change the line style when number of plots exceed number of colors in g.colors\n           lineStyles = {'-', '--',':','-.'};\n           set(tmp,'LineStyle',lineStyles{min(ceil(ind/length(g.colors)),length(lineStyles))});\n          \n           hold on;\n      else plot(times,R(ind,:));\n      end;\n  end;\n  \n  % ordinate limits\n  % ---------------\n  if isempty(g.ylim), \n      yll = min(reshape(R, [1 prod(size(R))]));\n      ylh = max(reshape(R, [1 prod(size(R))]));\n      yll2 = yll - (ylh-yll)/10;\n      ylh2 = ylh + (ylh-yll)/10;\n      if ~isnan(yll), g.ylim = [yll2 ylh2]; end;\n  end;\n  if ~isempty(g.ylim) & length(g.ylim) == 2 \n      if any(g.ylim)\n          ylim(g.ylim);\n      else\n          ylim([0 1]);\n          axis off;\n          box off;\n      end;\n  elseif ~isempty(g.ylim)\n      yl = ylim;\n      ylim([g.ylim yl(2)]);\n  end\n  yl = ylim; \n\n  % highlight regions\n  % -----------------\n  if ~isempty(g.maskarray)\n      axsignif = highlight(ax, times, Rregions, g.highlightmode, g.xlabel);\n\n      % replot data (above highlighted regions)\n      % ---------\n      axes(ax);\n      for ind = 1:size(R,1)\n          if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1\n               plot(times,R(ind,:), 'k', 'linewidth', 2);\n          elseif ~isempty(g.colors),             \n              tmp = plot(times,R(ind,:), 'k'); set(tmp, 'color', g.colors{mod(ind-1, length(g.colors))+1} ); hold on;\n          else plot(times,R(ind,:));\n          end;\n      end;\n      if strcmpi(g.highlightmode, 'bottom'), xlabel(''); set(ax, 'xtick', []); end;\n  end;\n  box on;\n  \n  ylim(yl);\n  if strcmpi(g.logpval, 'on')\n      set(gca, 'ytickmode', 'manual', 'yticklabel', round(10.^-get(gca, 'ytick')*1000)/1000, 'ydir', 'reverse');\n  end;\n  \n  % vertical lines\n  % --------------\n  hold on\n  xl = xlim;\n  if ~isnan(g.marktimes) % plot marked time\n      for mt = g.marktimes(:)'\n          plot([mt mt],[yl(1) yl(2)],'--k','LineWidth',g.linewidth);\n      end\n  end\n  hold off\n  if ~isempty(g.vert)\n      for index = 1:length(g.vert)\n          line([g.vert(index), g.vert(index)], [yl(1) yl(2)], 'linewidth', 1, 'color', 'm');\n      end;\n  end;\n  xlim([times(1) times(end)]);\n\n  % title and legend\n  % ----------------\n  if strcmpi(g.plotmode, 'topo') % plot in scalp array\n      NAME_OFFSETX = 0.1;\n      NAME_OFFSETY = 0.2;\n      xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff);\n      yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff);\n      t=text(xpos, ypos,g.title);\n      axis off;\n      line([0 0], [yl(1) yl(2)], 'linewidth', 1, 'color', 'k');\n      line([xl(1) xl(2)], [0 0], 'linewidth', 1, 'color', 'k');\n      set(ax, 'userdata', { g.xlabel g.ylabel g.legend });\n  else\n      title(g.title, 'interpreter', 'none')\n      if ~isempty(g.legend)\n          hh = legend(g.legend(:));\n          set(hh, 'unit', 'pixels', 'interpreter', 'none')\n      end;\n      if isempty(g.maskarray)\n          xlabel(g.xlabel);\n      end;\n      ylabel(g.ylabel)\n  end;\n  \n% -----------------\n% highlight regions\n% -----------------\nfunction axsignif = highlight(ax, times, regions, highlightmode, myxlabel);\ncolor1 = [0.75 0.75 0.75];\ncolor2 = [0 0 0];\nyl  = ylim; \nyl(1) = yl(1)-max(abs(yl));\nyl(2) = yl(2)+max(abs(yl));\n\nif ~strcmpi(highlightmode, 'background')\n    pos = get(ax, 'position');\n    set(gca, 'xtick', []);\n    axsignif = axes('position', [pos(1) pos(2)-pos(4)*0.05 pos(3) pos(4)*0.05 ]);\n    plot(times, times, 'w');\n    set(axsignif, 'ytick', []);\n    yl2 = ylim;\n    yl2(1) = yl2(1)-max(abs(yl2));\n    yl2(2) = yl2(2)+max(abs(yl2));\n    xlim([times(1) times(end)]);\n    xlabel(myxlabel);\nelse\n    axsignif = [];\n    xlabel(myxlabel);\nend;\n\nif ~isempty(regions)\n    axes(ax);\n    in_a_region = 0;\n    for index=1:length(regions)\n        if regions(index) & ~in_a_region\n            tmpreg(1) = times(index);\n            in_a_region = 1;\n        end;\n        if (~regions(index) | index == length(regions)) & in_a_region\n            tmpreg(2) = times(index);\n            in_a_region = 0;\n            if strcmpi(highlightmode, 'background')\n                tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ...\n                    [yl(1) yl(1) yl(2) yl(2)], color1); hold on;\n                set(tmph, 'edgecolor', color1);\n            else\n                oldax = ax;\n                axes(axsignif);\n                tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ...\n                    [yl2(1) yl2(1) yl2(2) yl2(2)], color2); hold on;\n                set(tmph, 'edgecolor', color2);\n                axes(oldax);\n            end;\n        end;\n    end;\n    ylim(yl);\nend;\n  \n\n  function res = dims(array)\n    res = min(ndims(array), max(size(array,2),size(array,3)));\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/plotcurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895467048751784}}
{"text": "function mrk= mrk_appendMarkers(mrk1, mrk2, Tmsec)\n%MRK_APPENDMARKERS - Append (timewise) two marker structures\n%\n%Synopsis:\n%  MRK= mrk_appendMarkers(MRK1, MRK2, TMSEC)\n%  MRK= mrk_appendMarkers(MRK1, MRK2, CNT)\n%\n%Arguments:\n%  MRK1, MRK2: marker structures (or empty [])\n%  TMSEC:      duration of first data set in msec\n%  CNT:        struct (like cnt) with fields T (duration of first data set\n%              in samples) and fs (sampling rate).\n%\n%Returns:\n%  mrk:        marker structure\n\n\nmisc_checkType(mrk1, 'STRUCT(time)');\nmisc_checkType(mrk2, 'STRUCT(time)');\nmisc_checkType(Tmsec, '!DOUBLE[1]|struct(T fs)');\n\nif isempty(mrk1),\n  mrk= mrk2;\n  return;\nend\n\nif isstruct(Tmsec),\n  cnt= Tmsec;\n  Tmsec= sum(cnt.T)*1000/cnt.fs;\nend\n\nmrk2.time= mrk2.time + Tmsec;\nif isempty(mrk1),\n  mrk= mrk2;\n  return;\nend\n\nif isfield(mrk1, 'event') && isfield(mrk1.event, 'blkno') && ...\n    isfield(mrk2, 'event') && isfield(mrk2.event, 'blkno'),\n  offset= max(mrk1.event.blkno) - min(mrk2.event.blkno) + 1;\n  mrk2.event.blkno= mrk2.event.blkno + offset;\nend\n\nmrk= mrk_mergeMarkers(mrk1, mrk2);\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/markers/mrk_appendMarkers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.20890214111133126}}
{"text": "%TRUNCQUAD_MODES  Compute colour modes for a truncated quadratic kernel\n%\n%   [modes depth energy inliers] = truncquad_modes(I, thresh[, use_variance[, search_width]])\n%\n% Computes the colour modes for each set of input vectors, using the\n% truncated quadratic kernel.\n%\n% IN:\n%   I - CxLxM array of L input colour vectors with C channels at M depths.\n%   thresh - scalar cost truncation threshold.\n%   use_variance - 0: sum cost over all input vectors; 1: sum cost over\n%                  inlying input vectors / num_inliers; 2: sum cost over\n%                  inliers / (num_inliers - 1). Default: 0.\n%   search_width - scalar indicating depths above and below current depth\n%                  to search for modes within. Default: M.\n%\n% OUT:\n%   modes - CxN matrix of colour modes.\n%   depth - 1xN list of indices of depth for each mode.\n%   energy - 1xN list of costs for each mode.\n%   inliers - LxN logical array indicating inliers used to calculate the\n%             colour of each mode.\n\n% $Id: truncquad_modes.m,v 1.2 2008/11/17 11:27:35 ojw Exp $\n\nfunction varargout = truncquad_modes(varargin)\nfuncName = mfilename;\nsourceList = {[funcName '.cxx']}; % Cell array of source files\nvgg_mexcompile_script; % Compilation happens in this script\nreturn", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/external/imrender/ojw/truncquad_modes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.2088994894732729}}
{"text": "% Wrapper for BilinearSampler block:\n% (c) 2016 Ankush Gupta\n\nclassdef BilinearSampler < dagnn.Layer\n  methods\n    function outputs = forward(obj, inputs, params)\n      outputs = vl_nnbilinearsampler(inputs{1}, inputs{2});\n      outputs = {outputs};\n    end\n\n    function [derInputs, derParams] = backward(obj, inputs, param, derOutputs)\n      [dX,dG] = vl_nnbilinearsampler(inputs{1}, inputs{2}, derOutputs{1});\n      derInputs = {dX,dG};\n      derParams = {};\n    end\n\n    function outputSizes = getOutputSizes(obj, inputSizes)\n      xSize = inputSizes{1};\n      gSize = inputSizes{2};\n      outputSizes = {[gSize(1), gSize(2), xSize(3), xSize(4)]};\n    end\n\n    function obj = BilinearSampler(varargin)\n      obj.load(varargin);\n    end\n  end\nend\n", "meta": {"author": "jiangqy", "repo": "DCMH-CVPR2017", "sha": "67d0e84c0425fdac3fad30d67d5a2beb5e345cea", "save_path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017", "path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017/DCMH-CVPR2017-67d0e84c0425fdac3fad30d67d5a2beb5e345cea/DCMH_matlab/DCMH_matlab/matconvnet/matlab/+dagnn/BilinearSampler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.20889947505816459}}
{"text": "function varargout = det_internal(varargin)\n\nswitch class(varargin{1})\n\n    case 'double'\n        X = varargin{1};\n        X = reshape(X,sqrt(length(X)),[]);\n        varargout{1} = det(X);\n    \n    case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph\n      \n        operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');        \n        operator.range = [-inf inf];\n\n        varargout{1} = [];\n        varargout{2} = operator;\n        varargout{3} = varargin{3};\n\n    otherwise\nend\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/det_internal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.208853288460948}}
{"text": "function [c, ceq] = findEarliestArrivalNonlconFun(arrivalUT, departUT, dvFunc, maxDV)\n    dv = dvFunc(arrivalUT, departUT);\n    c(1) = dv - maxDV;\n%     c(2) = -(arrivalUT-departUT);\n    \n    ceq = [];\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/findEarliestArrivalNonlconFun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20885328846094797}}
{"text": "% demo_e2s2_full()\n%\n% Trains and tests a Region-based semantic segmentation with end-to-end training on SIFT Flow.\n% Requires the version of VGG-16 pretrained with MatConvNet's beta16, and does not\n% work with beta20. This is most likely due to exploding gradients, although the architecture is identical.\n%\n% Copyright by Holger Caesar, 2016\n\n% Add folders to path\nsetup();\n\n% Settings\nglobal glFeaturesFolder; % Define global variables to be used in all scripts\nlabelingsFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', sprintf('%s_e2s2_run1_exp2', 'SiftFlow'), 'labelings-test-epoch25');\n\n% Download dataset\ndownloadSiftFlow();\n\n% Download base network\ndownloadNetwork('version', 'beta16');\n\n% Download Selective Search\ndownloadSelectiveSearch();\n\n% Extract region proposals and labels\nsetupE2S2Regions();\n\n% Train and test network\ne2s2_wrapper_SiftFlow_full();\n\n% Show example segmentation\nfileList = dirSubfolders(labelingsFolder);\nimage = imread(fullfile(labelingsFolder, fileList{1}));\nfigure();\nimshow(image);", "meta": {"author": "nightrome", "repo": "matconvnet-calvin", "sha": "42d7e80bac56741d39404b6646a0866c10aad021", "save_path": "github-repos/MATLAB/nightrome-matconvnet-calvin", "path": "github-repos/MATLAB/nightrome-matconvnet-calvin/matconvnet-calvin-42d7e80bac56741d39404b6646a0866c10aad021/demo_e2s2_full.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.20883738664723103}}
{"text": "classdef ParallelToFrameAtTimeCoordSystem < AbstractGeometricCoordSystem\n    %ParallelToFrameCoordSystem Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        frame AbstractReferenceFrame\n        time(1,1) double = 0;\n        \n        name(1,:) char\n        lvdData LvdData\n    end\n    \n    methods        \n        function obj = ParallelToFrameAtTimeCoordSystem(frame, time, name, lvdData)\n            obj.frame = frame;\n            obj.time = time;\n            \n            obj.name = name;\n            obj.lvdData = lvdData;\n        end\n        \n        function [rotMatToInertial] = getCoordSysAtTime(obj, ~, vehElemSet, ~)\n            [~, ~, ~, rotMatToInertial] = obj.frame.getOffsetsWrtInertialOrigin(obj.time, vehElemSet);\n        end\n        \n        function name = getName(obj)\n            name = obj.name;\n        end\n        \n        function setName(obj, name)\n            obj.name = name;\n        end\n        \n        function listboxStr = getListboxStr(obj)\n            listboxStr = sprintf('%s (Parallel To \"%s\" at UT = %0.3f sec)', obj.getName(), obj.frame.getNameStr(), obj.time);\n        end\n        \n        function useTf = openEditDialog(obj)            \n            output = AppDesignerGUIOutput({false});\n            lvd_EditParallelToFrameAtTimeCoordSysGUI_App(obj, obj.lvdData, output);\n            useTf = output.output{1};\n        end\n        \n        function tf = isVehDependent(obj)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.isVehDependent();\n            else\n                tf = false;\n            end\n        end\n        \n        function tf = usesGroundObj(obj, groundObj)\n            tf = obj.frame.usesGroundObj(groundObj);\n        end\n        \n        function tf = usesGeometricPoint(obj, point)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricPoint(point);\n            else\n                tf = false;\n            end\n        end\n        \n        function tf = usesGeometricVector(obj, vector)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricVector(vector);\n            else\n                tf = false;\n            end\n        end\n        \n        function tf = usesGeometricCoordSys(obj, coordSys)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricCoordSys(coordSys);\n            else\n                tf = false;\n            end\n        end\n        \n        function tf = usesGeometricRefFrame(obj, refFrame)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricRefFrame(refFrame);\n            else\n                tf = false;\n            end\n        end\n        \n        function tf = usesGeometricAngle(obj, angle)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricAngle(angle);\n            else\n                tf = false;\n            end\n        end \n        \n        function tf = usesGeometricPlane(obj, plane)\n            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)\n                tf = obj.frame.geometricFrame.usesGeometricPlane(plane);\n            else\n                tf = false;\n            end\n        end \n        \n        function tf = isInUse(obj, lvdData)\n            tf = lvdData.usesGeometricCoordSys(obj);\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Geometry/CoordSys/@ParallelToFrameAtTimeCoordSystem/ParallelToFrameAtTimeCoordSystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2087669769302314}}
{"text": "function obj = G_func_pTop_new(in1,in2,in3,in4)\ncoef_f0_q_sym2 = in1(:,2);\ncoef_f0_q_sym3 = in1(:,3);\ncoef_f0_q_sym4 = in1(:,4);\ncoef_f0_q_sym11 = in1(:,11);\ncoef_f1_q_sym1 = in2(:,1);\ncoef_f1_q_sym5 = in2(:,5);\ncoef_f1_q_sym6 = in2(:,6);\ncoef_f1_q_sym7 = in2(:,7);\ncoef_f0_q_sym18 = in1(:,18);\ncoef_f1_q_sym8 = in2(:,8);\ncoef_f1_q_sym9 = in2(:,9);\ncoef_f2_q_sym1 = in3(:,1);\ncoef_f0_q_sym22 = in1(:,22);\ncoef_f0_q_sym24 = in1(:,24);\ncoef_f2_q_sym5 = in3(:,5);\ncoef_f2_q_sym6 = in3(:,6);\ncoef_f2_q_sym7 = in3(:,7);\ncoef_f2_q_sym8 = in3(:,8);\ncoef_f2_q_sym9 = in3(:,9);\ncoef_f3_q_sym1 = in4(:,1);\ncoef_f3_q_sym5 = in4(:,5);\ncoef_f3_q_sym6 = in4(:,6);\ncoef_f3_q_sym7 = in4(:,7);\ncoef_f3_q_sym8 = in4(:,8);\ncoef_f3_q_sym9 = in4(:,9);\ncoef_f1_q_sym10 = in2(:,10);\ncoef_f1_q_sym11 = in2(:,11);\ncoef_f1_q_sym18 = in2(:,18);\ncoef_f1_q_sym22 = in2(:,22);\ncoef_f1_q_sym24 = in2(:,24);\ncoef_f2_q_sym10 = in3(:,10);\ncoef_f2_q_sym11 = in3(:,11);\ncoef_f2_q_sym18 = in3(:,18);\ncoef_f2_q_sym22 = in3(:,22);\ncoef_f2_q_sym24 = in3(:,24);\ncoef_f3_q_sym10 = in4(:,10);\ncoef_f3_q_sym11 = in4(:,11);\ncoef_f3_q_sym18 = in4(:,18);\ncoef_f3_q_sym22 = in4(:,22);\ncoef_f3_q_sym24 = in4(:,24);\nt2 = coef_f1_q_sym1.*2.0;\nt3 = coef_f2_q_sym1.*2.0;\nt4 = coef_f3_q_sym1.*2.0;\nobj = reshape([coef_f0_q_sym11-coef_f1_q_sym18,-coef_f2_q_sym18,-coef_f3_q_sym18,-coef_f1_q_sym22,coef_f0_q_sym11-coef_f2_q_sym22,-coef_f3_q_sym22,-coef_f1_q_sym24,-coef_f2_q_sym24,coef_f0_q_sym11-coef_f3_q_sym24,coef_f0_q_sym2-coef_f1_q_sym5+coef_f0_q_sym18+coef_f1_q_sym11+t2,-coef_f2_q_sym5+coef_f2_q_sym11+t3,-coef_f3_q_sym5+coef_f3_q_sym11+t4,coef_f0_q_sym3-coef_f1_q_sym6+coef_f0_q_sym22,coef_f0_q_sym2+coef_f0_q_sym18-coef_f2_q_sym6,-coef_f3_q_sym6,coef_f0_q_sym4-coef_f1_q_sym7+coef_f0_q_sym24,-coef_f2_q_sym7,coef_f0_q_sym2+coef_f0_q_sym18-coef_f3_q_sym7,-coef_f1_q_sym8+coef_f1_q_sym11+t2,coef_f0_q_sym3+coef_f0_q_sym22-coef_f2_q_sym8+coef_f2_q_sym11+t3,-coef_f3_q_sym8+coef_f3_q_sym11+t4,-coef_f1_q_sym9,coef_f0_q_sym4+coef_f0_q_sym24-coef_f2_q_sym9,coef_f0_q_sym3+coef_f0_q_sym22-coef_f3_q_sym9,-coef_f1_q_sym10+coef_f1_q_sym11+t2,-coef_f2_q_sym10+coef_f2_q_sym11+t3,coef_f0_q_sym4+coef_f0_q_sym24-coef_f3_q_sym10+coef_f3_q_sym11+t4],[3,9]);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/func_files/G_func_pTop_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20874496438278653}}
{"text": "function test_bug2160\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_multiplotER ft_selectdata\n\n%%\n\nt1 = [];\nt1.time = 0.001:0.001:2;\nt1.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nt1.avg = randn(numel(t1.label), numel(t1.time));\nt1.dimord = 'chan_time';\n\nt2 = [];\n% note the different length of the time axis\nt2.time = 0.001:0.001:3;\nt2.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nt2.avg = randn(numel(t2.label), numel(t2.time));\nt2.dimord = 'chan_time';\n\nt3 = [];\n% note the different spacing in the time axis\nt3.time = 0.001:0.002:2;\nt3.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nt3.avg = randn(numel(t3.label), numel(t3.time));\nt3.dimord = 'chan_time';\n\nt4 = [];\n% note the shift in the time axis\nt4.time = (0.001:0.001:2) + 10;\nt4.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nt4.avg = randn(numel(t4.label), numel(t4.time));\nt4.dimord = 'chan_time';\n\n% this should work\ncfg = [];\ncfg.layout = 'CTF275.lay';\nft_multiplotER(cfg, t1, t2);\n\n% this also works, by taking a subselection of t3\ncfg = [];\ncfg.layout = 'CTF275.lay';\nft_multiplotER(cfg, t1, t3);\n\n% this should fail\ntry\n  caughterror = false;\n  cfg = [];\n  cfg.layout = 'CTF275.lay';\n  ft_multiplotER(cfg, t1, t4);\ncatch\n  caughterror = true;\nend\n\nif ~caughterror\n  error('ft_multiplotER did not detect different time axes');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% repeat for frequency input\n\nf1 = [];\nf1.freq = 0.001:0.001:2;\nf1.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nf1.powspctrm = randn(numel(f1.label), numel(f1.freq));\nf1.dimord = 'chan_freq';\n\n\nf2 = [];\n% note the different length of the freq axis\nf2.freq = 0.001:0.001:3;\nf2.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nf2.powspctrm = randn(numel(f2.label), numel(f2.freq));\nf2.dimord = 'chan_freq';\n\nf3 = [];\n% note the different spacing in the freq axis\nf3.freq = 0.001:0.002:2;\nf3.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nf3.powspctrm = randn(numel(f3.label), numel(f3.freq));\nf3.dimord = 'chan_freq';\n\nf4 = [];\n% note the shift of the freq axis\nf4.freq = (0.001:0.001:2) + 10;\nf4.label = {'MLC11','MLC12','MLC13','MLC14','MLC15','MLC16','MLC17','MLC21','MLC22','MLC23','MLC24','MLC25','MLC31','MLC32','MLC41','MLC42','MLC51','MLC52','MLC53','MLC54','MLC55','MLC61','MLC62','MLC63','MLF11','MLF12','MLF13','MLF14','MLF21','MLF22','MLF23','MLF24','MLF25','MLF31','MLF32','MLF33','MLF34','MLF35','MLF41','MLF42','MLF43','MLF44','MLF45','MLF46','MLF51','MLF52','MLF53','MLF54','MLF55','MLF56','MLF61','MLF62','MLF63','MLF64','MLF65','MLF66','MLF67','MLO13','MLO14','MLO23','MLO24','MLO31','MLO32','MLO33','MLO34','MLO41','MLO42','MLO43','MLO44','MLO51','MLO52','MLO53','MLP11','MLP12','MLP21','MLP22','MLP23','MLP31','MLP32','MLP33','MLP34','MLP35','MLP41','MLP42','MLP43','MLP44','MLP45','MLP51','MLP52','MLP53','MLP54','MLP55','MLP56','MLP57','MLT11','MLT12','MLT13','MLT14','MLT15','MLT16','MLT21','MLT22','MLT23','MLT24','MLT25','MLT26','MLT27','MLT31','MLT32','MLT33','MLT34','MLT35','MLT36','MLT37','MLT41','MLT42','MLT43','MLT44','MLT45','MLT46','MLT47','MLT51','MLT52','MLT53','MLT54','MLT55','MLT56','MLT57','MRC11','MRC12','MRC13','MRC14','MRC15','MRC16','MRC17','MRC21','MRC22','MRC23','MRC24','MRC25','MRC31','MRC32','MRC41','MRC42','MRC51','MRC52','MRC53','MRC54','MRC55','MRC61','MRC62','MRC63','MRF11','MRF12','MRF13','MRF14','MRF21','MRF22','MRF23','MRF24','MRF25','MRF31','MRF32','MRF33','MRF34','MRF35','MRF41','MRF42','MRF43','MRF44','MRF45','MRF46','MRF51','MRF52','MRF53','MRF54','MRF55','MRF56','MRF61','MRF62','MRF63','MRF64','MRF65','MRF67','MRO11','MRO12','MRO13','MRO14','MRO21','MRO22','MRO23','MRO24','MRO31','MRO32','MRO33','MRO34','MRO41','MRO42','MRO43','MRO44','MRO51','MRO53','MRP11','MRP12','MRP21','MRP22','MRP23','MRP31','MRP32','MRP33','MRP34','MRP35','MRP41','MRP42','MRP43','MRP44','MRP45','MRP51','MRP52','MRP53','MRP54','MRP55','MRP56','MRP57','MRT11','MRT12','MRT13','MRT14','MRT15','MRT16','MRT21','MRT22','MRT23','MRT24','MRT25','MRT26','MRT27','MRT31','MRT32','MRT33','MRT34','MRT35','MRT36','MRT37','MRT41','MRT42','MRT43','MRT44','MRT45','MRT46','MRT47','MRT51','MRT52','MRT53','MRT54','MRT55','MRT56','MRT57','MZC01','MZC02','MZC03','MZC04','MZF01','MZF02','MZF03','MZO01','MZO03','MZP01','MLO11','MLO12','MLO21','MLO22','MZO02'};\nf4.powspctrm = randn(numel(f4.label), numel(f4.freq));\nf4.dimord = 'chan_freq';\n\n% this should work\ncfg = [];\ncfg.layout = 'CTF275.lay';\nft_multiplotER(cfg, f1, f2);\n\n% this also works, by taking a subselection of f3\ncfg = [];\ncfg.layout = 'CTF275.lay';\nft_multiplotER(cfg, f1, f3);\n\n% this should fail\ntry\n  caughterror = false;\n  cfg = [];\n  cfg.layout = 'CTF275.lay';\n  ft_multiplotER(cfg, f1, f14);\ncatch\n  caughterror = true;\nend\n\nif ~caughterror\n  error('ft_multiplotER did not detect different frequency axes');\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2160.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.2087449643827865}}
{"text": "function IESMnew = IESMwithNewFlippedStateQPOTTS(IESM,Q)\n\nIESMnew = IESM;\n\nfor count=1:100000000\n    IESMnew(2,2)=floor(1+Q*rand);\n    if IESMnew(2,2)~=IESM(2,2)\n        break\n    end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34784-monte-carlo-simulation-of-two-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 2D square-lattice - microstructure/IESMwithNewFlippedStateQPOTTS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20874496438278647}}
{"text": "function rtk=update_stat(rtk,obs,sol_stat)\n\nglobal glc\nopt=rtk.opt;\nnobs=size(obs,1);\n\nrtk.sol.time=timeadd(obs(1).time,-rtk.x(rtk.ic+1)/glc.CLIGHT);\nrtk.sol.ns=0;\nfor i=1:nobs\n    for j=1:opt.nf\n        sat=obs(i).sat;\n        if rtk.sat(sat).vsat(j)==0,continue;end\n        rtk.sat(sat).lock(j)=rtk.sat(sat).lock(j)+1;\n        rtk.sat(sat).outc(j)=0;\n        if j==1,rtk.sol.ns=rtk.sol.ns+1;end\n    end\nend\n\nif rtk.sol.ns<4\n    rtk.sol.stat=0;\nelse\n    rtk.sol.stat=sol_stat;\nend\n\nif rtk.sol.stat==glc.SOLQ_FIX\n    \nelse\n    rtk.sol.pos=rtk.x(1:3)';\n    rtk.sol.posP(1)=rtk.P(1,1);\n    rtk.sol.posP(2)=rtk.P(2,2);\n    rtk.sol.posP(3)=rtk.P(3,3);\n    rtk.sol.posP(4)=rtk.P(1,2);\n    rtk.sol.posP(5)=rtk.P(2,3);\n    rtk.sol.posP(6)=rtk.P(1,3);\nend\n\n% clk\nrtk.sol.dtr(1)=rtk.x(rtk.ic+1)/glc.CLIGHT;\n% isb\nrtk.sol.dtr(2)=rtk.x(rtk.ic+2)/glc.CLIGHT;\nrtk.sol.dtr(3)=rtk.x(rtk.ic+3)/glc.CLIGHT;\nrtk.sol.dtr(4)=rtk.x(rtk.ic+4)/glc.CLIGHT;\nrtk.sol.dtr(5)=rtk.x(rtk.ic+5)/glc.CLIGHT;\n\nfor i=1:nobs\n    for j=1:rtk.opt.nf\n        rtk.sat(obs(i).sat).snr(j)=obs(i).S(j);\n    end\nend\n\nfor i=1:glc.MAXSAT\n    for j=1:rtk.opt.nf\n        if bitand(rtk.sat(i).slip(j),3)\n            rtk.sat(i).slip(j)=rtk.sat(sat).slip(j)+1;\n        end\n        if rtk.sat(i).fix(j)==2&&sol_stat~=glc.SOLQ_FIX\n            rtk.sat(i).fix(j)=1;\n        end\n    end\nend\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/ppp/update_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.20873821953638425}}
{"text": "function varargout = run_opf(varargin)\n%run_opf  Run an optimal power flow.\n%\n%   run_opf(d, mpopt)\n%   run_opf(d, mpopt, ...)\n%   task = run_opf(...)\n%\n%   See also run_mp.\n\n%   MATPOWER\n%   Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n[varargout{1:nargout}] = run_mp(@mp.task_opf, varargin{:});\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/run_opf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20843926445410693}}
{"text": "function a = eq( x, y )\n\n%Disciplined convex programming information for EQ (==):\n%   Both the left- and right-hand sides of an equality constraint must\n%   be affine (or constant). If either side of the constraint is complex,\n%   then the real and imaginary portions are constrained separately.\n%\n%Disciplined geometric programming information for EQ (>):\n%   Both the left- and right-hand sides of an equality constraint must\n%   be log-affine, which includes positive constants and monomials.\n\nb = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '==' );\nif nargout, a = b; end\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvxcnst/eq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20843926445410688}}
{"text": "function [document, scores] = report_difficulty(context, experiment, trackers, sequences, varargin)\n% report_difficulty Generate a difficulty report for tags or sequences\n%\n% Performs A-R ranking analysis and generates a report that shows the difficulty of individual\n% tags or sequences.\n%\n% Input:\n% - context (structure): Report context structure.\n% - experiment (struct): An experiment structure.\n% - trackers (cell): An array of tracker structures.\n% - sequences (cell): An array of sequence structures.\n% - varargin[UsePractical] (boolean): Use practical difference.\n% - varargin[UseTags] (boolean): Rank according to tags (otherwise rank according to sequences).\n% - varargin[Alpha] (boolean): Statistical significance parameter.\n%\n% Output:\n% - document (structure): Resulting document structure.\n%\n\nusetags = true;\nusepractical = true;\nalpha = 0.05;\nadaptation = get_global_variable('report_ranking_adaptation', 'mean');\n\nscores = [];\n\nfor i = 1:2:length(varargin)\n    switch lower(varargin{i})\n        case 'usepractical'\n            usepractical = varargin{i+1};\n        case 'usetags'\n            usetags = varargin{i+1};\n        case 'alpha'\n            alpha = varargin{i+1};\n        otherwise\n            error(['Unknown switch ', varargin{i}, '!']) ;\n    end\nend\n\ndocument = create_document(context, 'difficulty', 'title', 'Difficulty');\n\ntrackers_hash = md5hash(strjoin((cellfun(@(x) x.identifier, trackers, 'UniformOutput', false)), '-'), 'Char', 'hex');\nparameters_hash = md5hash(sprintf('%f-%d-%d-%s', alpha, usetags, usepractical, adaptation));\n\nif ~strcmp(experiment.type, 'supervised')\n   error('Difficulty analysis only suitable for supervised experiments!');\nend\n\ndocument.section('Experiment %s', experiment.name);\n\ntags = {};\n\nif usetags && isfield(experiment, 'tags')\n    tags = experiment.tags;\n\n    sequences_hash = md5hash(strjoin(tags, '-'), 'Char', 'hex');\nelse\n    sequences_hash = md5hash(strjoin((cellfun(@(x) x.name, sequences, 'UniformOutput', false)), '-'), 'Char', 'hex');\nend;\n\ncache_identifier = sprintf('ranking_%s_%s_%s_%s', experiment.name, trackers_hash, sequences_hash, parameters_hash);\n\nresult = report_cache(context, cache_identifier, @analyze_ranks, experiment, trackers, ...\n    sequences, 'tags', tags, 'usepractical', usepractical, ...\n    'alpha', alpha, 'adaptation', adaptation);\n\nselector_tags = result.tags;\n\nmedian_accuracy = nanmedian(result.accuracy.values, 2);\nmedian_robustness = nanmedian(result.robustness.normalized, 2);\n\nmedian_diff_accuracy = nanmedian(bsxfun(@minus, result.accuracy.values, mean(result.accuracy.values, 1)), 2);\nmedian_diff_robustness = nanmedian(bsxfun(@minus, result.robustness.normalized, mean(result.robustness.normalized, 1)), 2);\n\ntable_data = [median_accuracy, median_robustness * 100, median_diff_accuracy, median_diff_robustness * 100];\n\ntable_data = highlight_best_rows(num2cell(table_data), {'ascending', 'descending', 'ascending', 'descending'})';\nrow_tags = {'Accuracy', 'Robustness', 'Accuracy difference', 'Robustness difference'};\n\ntitle = sprintf('Difficulty for experiment %s', experiment.name);\n\ndocument.table(table_data, 'columnLabels', selector_tags, 'rowLabels', row_tags', 'title', title);\n\ndocument.raw('<div class=\"imagegrid\">\\n');\n\nhf = figure('Visible', 'off');\nhold on;\nfor i = 1:numel(selector_tags)\n    if median_diff_accuracy(i) > 0\n        rectangle('Position',[i-0.3, 0.5, 0.6, median_diff_accuracy(i)], 'FaceColor', 'green');\n    elseif median_diff_accuracy(i) < 0\n        rectangle('Position',[i-0.3, 0.5+median_diff_accuracy(i), 0.6, -median_diff_accuracy(i)], 'FaceColor', 'red');\n    end;\n\n    plot(ones(size(result.accuracy.values(i, :))) * i, result.accuracy.values(i, :), 'bo');\nend\nhold off;\nset(gca, 'YLim', [0, 1], 'XLim', [0.5, numel(selector_tags) + 0.5], 'XTick', 1:numel(selector_tags), 'XTickLabel', selector_tags);\n\ndocument.figure(hf, sprintf('difficulty_%s_accuracy_scatter', experiment.name), ...\n    sprintf('Accuracy scatter'));\n\nhf = figure('Visible', 'off');\nhold on;\norigin = mean(median_robustness);\nfor i = 1:numel(selector_tags)\n    if median_diff_robustness(i) > 0\n        rectangle('Position',[i-0.3, origin, 0.6, median_diff_robustness(i)], 'FaceColor', 'red');\n    elseif median_diff_robustness(i) < 0\n        rectangle('Position',[i-0.3, origin+median_diff_robustness(i), 0.6, -median_diff_robustness(i)], 'FaceColor', 'green');\n    end;\n\n    plot(ones(size(result.robustness.normalized(i, :))) * i, result.robustness.normalized(i, :), 'bo');\nend\nhold off;\nset(gca, 'YLim', [0, max(result.robustness.normalized(:))], ...\n    'XLim', [0.5, numel(selector_tags) + 0.5], 'XTick', 1:numel(selector_tags), 'XTickLabel', selector_tags);\n\ndocument.figure(hf, sprintf('difficulty_%s_robustness_scatter', experiment.name), ...\n    sprintf('Robustness scatter'));\n\ndocument.raw('</div>\\n');\n\ndocument.write();\n\nend\n\n", "meta": {"author": "votchallenge", "repo": "toolkit-legacy", "sha": "2fb78d5301dadc102fb329b3a3f1bb02c670e8ee", "save_path": "github-repos/MATLAB/votchallenge-toolkit-legacy", "path": "github-repos/MATLAB/votchallenge-toolkit-legacy/toolkit-legacy-2fb78d5301dadc102fb329b3a3f1bb02c670e8ee/report/report_difficulty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.20816430482798742}}
{"text": "function computeAllPrediction_batchVASARI_LGG(pathExperiments,maxOrder,nBoot,imbalance,nBatch,matlabPATH,seed)\n% -------------------------------------------------------------------------\n% function computeAllPrediction_batchVASARI_LGG(pathExperiments,maxOrder,nBoot,imbalance,nBatch,matlabPATH,seed)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes prediction performance estimation for a given \n% feature set type, and for all model orders of all experiments with \n% different degrees of freedom. See ref. [1] for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n%     MRI texture features for the prediction of lung metastases in soft-tissue \n%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n%     5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathExperiments: Full path to where all experiments need to be\n%                     performed.\n%                     --> Ex: /myProject/WORKSPACE/VASARI\n% 2. maxOrder: Integer specifying the maximal model order to construct.\n%              --> Ex: 10\n% 3. nBoot: Number of bootstrap samples to use.\n%           --> Ex: 100\n% 4. imbalance: String specifying the type of imbalance-adjustement strategy\n%               employed. Either 'IABR' for imbalance-adjusted bootstrap\n%               resampling (see ref.[1]), or 'IALR' for imbalance-adjusted\n%               logistic regression (formal reference to come).\n%               --> Ex: 'IALR'\n% 5. nBatch: Number of parallel batch.\n%            --> Ex: 8\n% 6. matlabPATH: Full path to the MATLAB executable on the system.\n%                --> 'matlab' if a symbolic link to the matlab executable\n%                     was previously created.\n% 7. seed: Random generator seed for reproducibility of experiments.\n% -------------------------------------------------------------------------\n% OUTPUTS: Prediction performance results are saved in a folder named 'RESULTS' in the\n% corresponding folder of 'pathExperiments'.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017  Martin Vallieres\n%\n%    This package is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    This package is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\n\n% INITIALIZATON\ntime = 60; % Number of seconds to wait before checking if parallel computations are done\ncd(pathExperiments), load('outcomes')\npathModels = fullfile(pwd,'MODELS'); mkdir('RESULTS'), cd('RESULTS'), pathResults = pwd; \nmkdir('batchLog_Results'), cd('batchLog_Results'), pathBatch = pwd;\nsetNames = {'VASARI'};\n[param] = batchExperiments(setNames,outcomes,nBatch); nBatch = length(param);\n\n% PRODUCE BATCH COMPUTATIONS\nsave('workspace','pathModels','pathResults','outcomes','param','maxOrder','nBoot','imbalance','seed'), pause(5);\nfor i = 1:nBatch\n    nameScript = ['batch',num2str(i),'_script.m'];\n    fid = fopen(nameScript,'w');\n    fprintf(fid,'load(''workspace'')\\n');\n    for j = 1:numel(param{i})\n        fprintf(fid,['computeAllPrediction_VASARI_LGG(pathModels,pathResults,outcomes,param{',num2str(i),'}{',num2str(j),'},maxOrder,nBoot,imbalance,seed)\\n']);\n    end\n    fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n    fprintf(fid,'clear all');\n    fclose(fid);\n    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nBatch)\ndelete('workspace.mat')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/computeAllPrediction_batchVASARI_LGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.20813201574845777}}
{"text": "%kCTRecon 'ML/EM reconstruction of ct-slice '\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros CTRecon.pane file\n%\n% Parameters: \n% InputFile: i 'Sinogram', required: 'First Input data object'\n% InputFile: t 'BeamTable', optional: 'BeamTable file in raw format'\n% Integer: SPos 'Start Projection', default: 0: 'ProjectionNr to start with'\n% Integer: PSize 'Projection Size', default: 768: 'integer'\n% Integer: PNumber 'Projection Number', default: 1056: 'integer'\n% Integer: n 'Iterations', default: 80: 'integer'\n% Toggle: q 'No Quarter Shift', default: 0: 'flag'\n% Integer: IX 'Size X', default: 128: 'integer'\n% Integer: IY 'Size Y', default: 128: 'integer'\n% Toggle: divc 'Use Div Cmp', default: 0: 'compute correction by division'\n% Toggle: nn 'Without Norms', default: 0: 'flag'\n% Toggle: nfn 'No first norm', default: 0: 'do not use norm in forwardprojection'\n% Toggle: rn 'Norms from file', default: 0: 'read the norm from the two files'\n% OutputFile: o 'Reconstructed', required: 'Resulting output data object'\n% OutputFile: c 'Last Correction', required: 'Correction'\n% InputFile: Over 'OverralaxTable', optional: 'optional input file'\n% InputFile: s 'Start Image', optional: 'optional input file'\n% OutputFile: f 'Forward Projection', optional: 'output file'\n%\n% Example: [o, c, f] = kCTRecon({i, t, Over, s}, {'i','';'t','';'SPos',0;'PSize',768;'PNumber',1056;'n',80;'q',0;'IX',128;'IY',128;'divc',0;'nn',0;'nfn',0;'rn',0;'o','';'c','';'Over','';'s','';'f',''})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% CTRecon - ML/EM reconstruction of ct-slice\n%\n%  DESCRIPTION\n%\n%  \n%\n%  EXAMPLES\n%\n%  \"SEE ALSO\"\n%\n%  RESTRICTIONS \n%\n%  REFERENCES \n%\n%  COPYRIGHT\n% Copyright (C) 1996-2003, Rainer Heintzmann,  All rights reserved.\n% \n\n\nfunction varargout = kCTRecon(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kCTRecon(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i', '__input';'t', '__input';'SPos', 0;'PSize', 768;'PNumber', 1056;'n', 80;'q', 0;'IX', 128;'IY', 128;'divc', 0;'nn', 0;'nfn', 0;'rn', 0;'o', '__output';'c', '__output';'Over', '__input';'s', '__input';'f', '__output'};\nmaxval={0,1,1,2,2,2,0,2,2,0,0,0,0,0,0,1,1,1};\nminval={0,1,1,2,2,2,0,2,2,0,0,0,0,0,0,1,1,1};\nistoggle=[0,1,0,0,0,0,1,0,0,1,1,1,1,0,0,1,1,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','InputFile','Integer','Integer','Integer','Integer','Toggle','Integer','Integer','Toggle','Toggle','Toggle','Toggle','OutputFile','OutputFile','InputFile','InputFile','OutputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=2; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'ctreal\"  -k'],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kCTRecon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2080871071116364}}
{"text": "function [dvh,qi] = matRad_indicatorWrapper(cst,pln,resultGUI,refGy,refVol)\n% matRad indictor wrapper\n% \n% call\n%   [dvh,qi] = matRad_indicatorWrapper(cst,pln,resultGUI)\n%   [dvh,qi] = matRad_indicatorWrapper(cst,pln,resultGUI,refGy,refVol)\n%\n% input\n%   cst:                  matRad cst struct\n%   pln:                  matRad pln struct\n%   resultGUI:            matRad resultGUI struct\n%   refGy: (optional)     array of dose values used for V_XGy calculation\n%                         default is [40 50 60]\n%   refVol:(optional)     array of volumes (0-100) used for D_X calculation\n%                         default is [2 5 95 98]\n%                         NOTE: Call either both or none!\n%\n% output\n%   dvh: matRad dvh result struct\n%   qi:  matRad quality indicator result struct\n%   graphical display of all results\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2017 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isfield(resultGUI,'RBExDose')\n    doseCube = resultGUI.RBExDose;\nelse\n    doseCube = resultGUI.physicalDose;\nend\n\nif ~exist('refVol', 'var') \n    refVol = [];\nend\n\nif ~exist('refGy', 'var')\n    refGy = [];\nend\n\ndvh = matRad_calcDVH(cst,doseCube,'cum');\nqi  = matRad_calcQualityIndicators(cst,pln,doseCube,refGy,refVol);\n\nfigure,set(gcf,'Color',[1 1 1]);\nsubplot(2,1,1)\nmatRad_showDVH(dvh,cst,pln);\nsubplot(2,1,2)\nixVoi = cellfun(@(c) c.Visible == 1,cst(:,5));\nqi = qi(ixVoi);\nmatRad_showQualityIndicators(qi);\n\n\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/matRad_indicatorWrapper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20794890118859913}}
{"text": "function model = read_svm_detection_weights( filepath )\nload(filepath, 'weights', 'bias');\nmodel = {weights; bias};\nend", "meta": {"author": "gidariss", "repo": "LocNet", "sha": "a4678b87d9e63dcea07d9afd978d1223174d8be3", "save_path": "github-repos/MATLAB/gidariss-LocNet", "path": "github-repos/MATLAB/gidariss-LocNet/LocNet-a4678b87d9e63dcea07d9afd978d1223174d8be3/code/object_recognition/read_svm_detection_weights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20794889542627432}}
{"text": "function val = v_dtiRawPreprocessGE()\n% Validate dti raw preprocessing of GE data\n%\n%    val = v_dtiRawPreprocessGE()\n%\n% This function checks that the average FA and B0 values resulting from\n% dtiRawPreprocess are consistent with the expected value on different\n% platforms (LINUX, WINDOWS, etc.).\n%\n% Requires vistadata and vistasoft on your path. The directory\n% vistadata/diffusion/dtiRawPreprocess/GE contains all the necessary data\n% files.\n% \n% This function does the following:\n%\n% (1) run dtiRawPreprocess on the files in the raw folder. This will align to the T1 and\n% create a B0, BVECS and FA values (it creates more stuff but we only focus on these for the moment).\n%\n% (2) Show a montage of Alignment i.e., the T1 and DTI overalyed. Check for LR flips and correct alignment. \n%  \n% (3) Compute FA, Mean diffusivity, radial diffusivity nd Axial diffusivity \n%     across the brain and check the value obtained on different\n%     platforms. THis will be done using: [fa,md,rd,ad] = dtiComputeFA(eigVal)\n%\n% (5) Load the stored FA, MD, RD, AD for the whole brain in:\n%     GE/storedMeanDiffusionVals.mat\n%     \n% (6) Recompute them from the data\n% \n% (7) Compute the difference between the stored and the recomputed ones.\n%\n% Example:\n%  This function is meant to be called by mrvValidate, which will \n% compute the difference between the stored values and the re-computed\n% values.\n%\n%   mrvValidate([],[], 'v_dtiRawPreprocessGE');\n%\n% See also: mrvValidateAll.m\n%   \n% FP and MP 7/6/2011\n% Copyright Stanford team, mrVista, 2011\n \n% This function takes too long to run. We want validation functions to be\n% fast (say, less than 10 s). this one takes minutes to hours to run.\n%\nval = [];\nreturn;\n\n%% Get the data pathdata path\n% Changing the last parameter and the function name changes\n% scanner type (e.g., Siemens)\ndataDir = fullfile(mrvDataRootPath,'diffusion','dtiRawPreprocess','GE');\n\n%% Retain original directory, change to data directory\ncurDir = pwd;\ncd(dataDir);\n\n%% Run Preprocess\n% setting clobber to 'always', so that output files will be silently replaced.\ndtiRawPreprocess('raw/dti_g87_b1000.nii.gz', 't1.nii.gz',[],[],'always'); \n\n%% Show alignment to t1\n% this was automatically computed by dtiRawPreprocess.m\nimshow(imread('dti40trilin/t1pdd.png')); \n\n%% Compute mean FA, RD, MD, AD values and check them with the stored one.\n\n% load the stored values\n% by convention mrvValidate.m loads up a storedVals data file\n% with the same name of the validate function thta uses it \nthisfunction = mfilename;\nload(fullfile(mrvDataRootPath,'validate',[thisfunction(3:end),'.mat']));\n\n% load the dti file.\ndt = dtiLoadDt6('dti40trilin/dt6.mat');\n\n% extract the eigen values.\neigVal = dt.dt6;\n\n% compute the fractional, mean, radial and axial diffusivity\n[fa,md,rd,ad] = dtiComputeFA(eigVal);\n\n% compute the mean across the whole brain\nval.fa = nanmean(fa(:));\nval.md = nanmean(md(:));\nval.rd = nanmean(rd(:));\nval.ad = nanmean(ad(:));\n\n% mrvValidate will use the output of this function to compare the\n% recomputed values to the stored values.\n% fr example doing something like this:\n%\n% check the computed with the stored values\n% val.faErr = diff([mean_fa,meanVals.fa]);\n% val.mdErr = diff([mean_md,meanVals.md]);\n% val.rdErr = diff([mean_rd,meanVals.rd]);\n% val.adErr = diff([mean_ad,meanVals.ad]);\n%\n% show results on matlab output\n% errFields = fields(val);\n% meanFields = fields(meanVals);\n% for i = 1:length(fields(val))\n%  fprintf('[%s] Error in ''%s'': %2.8f\\n',mfilename, meanFields{i}, val.(errFields{i}));\n% end\n\n%% go back to the original directory, done!\ncd(curDir)\n\nreturn\n\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrTest/diffusion/extended/test_dtiRawPreprocessGE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.2079435119258977}}
{"text": "%--------------------------------------------------------------------------------------------------------\n% The system is created based on the principles described in the following paper\n% Jimmy SJ. Ren, Li Xu, Qiong Yan, Wenxiu Sun, \"Shepard Convolutional Neural Networks\", \n% Advances in Neural Information Processing Systems (NIPS 2015)\n% email: jimmy.sj.ren@gmail.com\n%--------------------------------------------------------------------------------------------------------\naddpath applications/Shepard_CNN/Shepard_super_res/\naddpath utils/\naddpath cuda/\naddpath mem/\naddpath layers/\naddpath layers_adapters/\naddpath optimization/\naddpath pipeline/\naddpath data/\n\nclearvars -global config;\nclearvars -global mem;\nclear gen_mask_patch_cat_idx_for_super_res;\nclear;\nglobal config mem;\nshepard_sr_x4_configure();\ninit(0);\n\nload('data/Shepard_CNN/Shepard_super_res/x4/val_1ch/val_1');\n\nimages_t = reshape(images_t, size(images_t,1), size(images_t,2), 1, size(images_t,3));\nlabels_t = reshape(labels_t, size(labels_t,1), size(labels_t,2), 1, size(labels_t,3));\n\nperm = randperm(size(images_t, 4));\nimages_t = images_t(:,:,:,perm);\nlabels_t = labels_t(:,:,:,perm);\ntest_samples = config.NEW_MEM(images_t(:,:,:,1:1000));\ntest_labels = config.NEW_MEM(labels_t(:,:,:,1:1000));\n\nmask = config.NEW_MEM([1 0 0 0;0 0 0 0;0 0 0 0;0 0 0 0]);\nmask = repmat(mask, config.input_size(1)/4, config.input_size(2)/4, config.chs);\n%mask = config.NEW_MEM([1 0; 0 0]);\n%mask = repmat(mask, config.input_size(1)/2, config.input_size(2)/2, config.chs);\nmask = repmat(mask, 1,1,1,config.batch_size);\n\ncount = 0;\ncost_avg = 0;\nepoc = 0;\npoints_seen = 0;\ndisplay_points = 5000;\nsave_points = 50000;\nmax_grad = 1;\nfprintf('%s\\n', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));\nfor pass = 1:10\n    for p = 1:50\n        load(strcat('data/Shepard_CNN/Shepard_super_res/x4/train_1ch/patches_', num2str(p), '.mat'));\n        \n        images = reshape(images, size(images,1), size(images,2), 1, size(images,3));\n        labels = reshape(labels, size(labels,1), size(labels,2), 1, size(labels,3));\n        \n        perm = randperm(20000);\n        images = images(:,:,:,perm);\n        labels = labels(:,:,:,perm);\n        train_imgs = config.NEW_MEM(images);\n        train_labels = config.NEW_MEM(labels);\n        \n        for i = 1:size(train_labels, 4) / config.batch_size            \n            points_seen = points_seen + config.batch_size;\n            in = train_imgs(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            %in = train_labels(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            out = train_labels(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);\n            out = out((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...\n                      (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :, :);\n            \n                  \n            % make the mask list\n            mask_li = {};\n            mask_li{1} = mask;\n            % operate the training pipeline\n            op_train_pipe_with_mask(in.*mask, mask_li, out);\n            % update the weights\n            config.UPDATE_WEIGHTS();\n            \n            if(cost_avg == 0)\n                cost_avg = config.cost;\n            else\n                cost_avg = (cost_avg + config.cost) / 2;\n            end\n\n            % display point\n            if(mod(points_seen, display_points) == 0)\n                count = count + 1;\n                fprintf('%d ', count);\n            end\n            % save point\n            if(mod(points_seen, save_points) == 0)\n                fprintf('\\n%s', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));\n                epoc = epoc + 1;\n                test_cost = 0;\n                for t = 1:size(test_samples, 4) / config.batch_size\n                    t_label = test_labels(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size);\n                    t_label = config.NEW_MEM(t_label((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...\n                                            (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :));\n                    \n                    op_test_pipe_with_mask(test_samples(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size).*mask, mask_li, t_label);\n                    \n                    test_out = gather(mem.output);\n                    test_cost = test_cost + config.cost;\n                end\n                test_cost = test_cost / (size(test_samples, 4) / config.batch_size);\n                fprintf('\\nepoc %d, training avg cost: %f, test avg cost: %f\\n', epoc, cost_avg, test_cost);                \n                \n                save_weights(strcat('applications/Shepard_CNN/Shepard_super_res/results/shepard_layer_x4/epoc', num2str(epoc), '.mat'));\n                \n                cost_avg = 0;\n            end\n        end\n    end\nend\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/applications/Shepard_CNN/Shepard_super_res/shepard_sr_x4_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.20787668631005074}}
{"text": "function success=testJAABAWindowdata()\n\n% This tests to make sure that loading cached windowdata and computing\n% windowdata again learn the same classifier.\n\n% AL20150602. This test doesn't work when I run it on the current codebase;\n% I think it's because window feature computation is no longer\n% deterministic, even with the setting of RNG state below.\n% ComputeWindowFeatures() is called within a parfor and has a call to\n% randsample.\n\n%%\nsuccess = false;\njabFileName='/groups/branson/home/kabram/bransonlab/projects/JAABA/test_data/test_windowdata.jab';\ngtMode = false;\ndata=JLabelData('setstatusfn',@(str)(fprintf('%s\\n',str)), ...\n                'clearstatusfn',@()(nop()));\ndata.openJabFile(jabFileName,gtMode);\n\nif matlabpool('size')>0, matlabpool('close'); end\noldcl = data.classifier;\n\ns = RandStream('mt19937ar','Seed',1);\nRandStream.setGlobalStream(s);\n\ndata.Train;\nnewcl1 = data.classifier;\n\ndata.setWindowFeaturesParams(data.windowfeaturesparams);\n\ns = RandStream('mt19937ar','Seed',1);\nRandStream.setGlobalStream(s);\n\ndata.Train;\nnewcl2 = data.classifier;\n\nif ~isequal(oldcl,newcl1) || ~isequal(newcl1,newcl2),\n  error('Classifiers trained are not same');\n  \nend\nsuccess = true;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/tests/testJAABAWindowdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2078766674611982}}
{"text": "function [fid, sens, label, sens_label] = read_zebris(Fname_zeb,skip)\n\n% Reads Zebris files:\n%   fiducials locations, and\n%   either sensor file or headshape file or both\n%\n% FORMAT [fid, sens, label] = read_zebris(Fname_zeb,skip)\n% Input:\n% Fname_zeb  - Zebris ASCII file containing sensor locations (mm)\n%             (headshape can also be considered here instead of sensors)\n% skip       - first channels to skip\n%\n% Output:\n% fid        - fiducial         locations (mm) in rows\n% sens       - sensor/headshape locations (mm) in rows\n% label      - labels of the fiducials\n% sens_label - labels of the surface points, electrodes + headshape\n%\n% IMPORTANT: Note that Zebris data files should be -ASCII files with\n% extension .sfp\n% It is assumed that the .sfp file contains the location (mm) of fiducials\n% (possibly twice), possibly followed by some additional named points for\n% the electrodes, and then so more named location starting with 'sfl' for\n% headshape locations.\n% In some instances the first few channel locations may pertain to\n% reference channels; the skip variable allows these to be skipped if\n% necessary.\n% The fiducial locations are flaged with the strings 'fidt9','fidnz' and\n% 'fidt10'; indicating the leaft ear, nasion, and right ear, respectively.\n% _________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Christophe Phillips\n% $Id$\n\n\n% checks and assigments\n%--------------------------------------------------------------------------\ntry, skip;    catch, skip    = 0; end\n\n[pth,nam,ext] = fileparts(Fname_zeb);\nif ~strcmp(ext,'.sfp')\n  warndlg(sprintf('Wrong input file format\\n'));\n  return\nend\n\n\n% --- READ Zebris Sensor + fiducial locations ---\n%==========================================================================\ntry\n  file = textread(Fname_zeb,'%s');\ncatch\n  file = textread(fullfile(pwd,[nam ext]),'%s');\nend\n% remove zeros at the end\nbool = 0;\nwhile bool == 0\n  if strcmp(file{end},'0')\n    file = file(1:end-1);\n  else\n    bool = 1;\n  end\nend\n\n% read fiducials\n%--------------------------------------------------------------------------\nNZ   = [];\nLE   = [];\nRE   = [];\ntemp = 0;\nnl   = 1;\n\nwhile temp == 0\n  if strcmp(file{nl},'fidnz')\n    NZ = [NZ ; str2num(file{nl+1}) str2num(file{nl+2}) str2num(file{nl+3}) ];\n    nl = nl + 4;\n  elseif strcmp(file{nl},'fidt9')\n    LE = [LE ; str2num(file{nl+1}) str2num(file{nl+2}) str2num(file{nl+3}) ];\n    nl = nl + 4;\n  elseif strcmp(file{nl},'fidt10')\n    RE = [RE ; str2num(file{nl+1}) str2num(file{nl+2}) str2num(file{nl+3}) ];\n    nl = nl + 4;\n  else\n    temp = 1;\n  end\nend\n\n% convert from cm to mm\n%--------------------------------------------------------------------------\nNZ    = mean(NZ,1); LE = mean(LE,1); RE = mean(RE,1);\nfid   = [NZ; LE; RE];\n\nlabel = [{'nas', 'lpa', 'rpa'}];\n\n% read sensor locations or headshape locations\n%--------------------------------------------------------------------------\nsens  = [];\nsens_label = [];\n\nstart = nl + skip*3;\nfor ii = start:4:length(file)\n  sens_label = [sens_label, file(ii)];\n  sens = [sens; ...\n    str2num(file{ii+1}) str2num(file{ii+2}) str2num(file{ii+3})];\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_zebris.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.20754846519808753}}
{"text": "% Copyright 2011 Zdenek Kalal\n%\n% This file is part of TLD.\n% \n% TLD is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TLD is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TLD.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [pX,pEx,bbP0] = tldGeneratePositiveData(tld,overlap,im0,p_par)\n\npX   = [];\npEx  = [];%zeros(prod(tld.patchsize),numWarps);\n\n% Get closest bbox\n[~,idxP] = max(overlap);\nbbP0 =  tld.grid(1:4,idxP);\n\n% Get overlapping bboxes\nidxP = find(overlap > 0.6);\nif length(idxP) > p_par.num_closest\n    [~,sIdx] = sort(overlap(idxP),'descend');    \n    idxP = idxP(sIdx(1:p_par.num_closest));\nend\nbbP  = tld.grid(:,idxP);\nif isempty(bbP), return; end\n\n% Get hull\nbbH  = bb_hull(bbP);\ncols = bbH(1):bbH(3);\nrows = bbH(2):bbH(4);\n\nim1 = im0;\npEx = tldGetPattern(im1,bbP0,tld.model.patchsize);\nif tld.model.fliplr\npEx = [pEx tldGetPattern(im1,bbP0,tld.model.patchsize,1)];\nend\nfor i = 1:p_par.num_warps\n    if i > 1\n        randomize = rand; % Sets the internal randomizer to the same state\n        %patch_input = img_patch(im0.input,bbH,randomize,p_par);\n        patch_blur = img_patch(im0.blur,bbH,randomize,p_par);\n        im1.blur(rows,cols) = patch_blur;\n        %im1.input(rows,cols) = patch_input;\n    end\n    \n    % Measures on blured image\n    pX  = [pX fern(5,im1,idxP,0)];\n    \n    % Measures on input image\n    %pEx(:,i) = tldGetPattern(im1,bbP0,tld.model.patchsize);\n    %pEx = [pEx tldGetPattern(im1,tld.grid(1:4,idxP),tld.model.patchsize)];\n    \nend", "meta": {"author": "zk00006", "repo": "OpenTLD", "sha": "953e2df96575ba9e3e0720b8f91e936c26c9b2e3", "save_path": "github-repos/MATLAB/zk00006-OpenTLD", "path": "github-repos/MATLAB/zk00006-OpenTLD/OpenTLD-953e2df96575ba9e3e0720b8f91e936c26c9b2e3/tld/tldGeneratePositiveData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.20753113743250104}}
{"text": "function F = in_fread_brainamp(sFile, sfid, SamplesBounds)\n% IN_FREAD_BRAINAMP:  Read a block of recordings from BrainVision BrainAmp .eeg file\n%\n% USAGE:  F = in_fread_brainamp(sFile, sfid, SamplesBounds=[])\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012-2013\n\n% Parse inputs\nif (nargin < 3) || isempty(SamplesBounds)\n    SamplesBounds = round(sFile.prop.times .* sFile.prop.sfreq);\nend\n\n% BINARY files\nif strcmpi(sFile.header.DataFormat, 'BINARY')\n    nChan = sFile.header.NumberOfChannels;\n    nSamplesToRead = SamplesBounds(2) - SamplesBounds(1) + 1;\n    % MULTIPLEXED files\n    if strcmpi(sFile.header.DataOrientation, 'MULTIPLEXED')\n        % Get start and length of block to read\n        offsetData = SamplesBounds(1) * nChan * sFile.header.bytesize;\n        % Position file at the beginning of the data block\n        fseek(sfid, offsetData, 'bof');\n        % Read all values at once\n        F = fread(sfid, [nChan, nSamplesToRead], sFile.header.byteformat);\n    % VECTORIZED\n    elseif strcmpi(sFile.header.DataOrientation, 'VECTORIZED')\n        % Get blocks of samples to skip at the beginning and end of each channel\n        offsetStart = SamplesBounds(1) * sFile.header.bytesize;\n        offsetEnd = (round(sFile.prop.times(2) .* sFile.prop.sfreq) - SamplesBounds(2)) * sFile.header.bytesize;\n        % Blocks of samples to skip between two blocks to read\n        offsetSkip = offsetStart + offsetEnd;\n        % Position file at the beginning of the trial\n        fseek(sfid, offsetStart, 'bof');\n        % Read the requested samples for all the channels\n        % => WARNING: CALL TO FREAD WITH SKIP=0 DOES NOT WORK PROPERLY\n        if (offsetSkip == 0)\n            F = fread(sfid, [nSamplesToRead, nChan], sFile.header.byteformat)';\n        else\n            precision = sprintf('%d*%s', nSamplesToRead, sFile.header.byteformat);\n            F = fread(sfid, [nSamplesToRead, nChan], precision, offsetSkip)';\n        end\n    end\n% ASCII and VECTORIZED files\nelseif (strcmpi(sFile.header.DataFormat, 'ASCII') && strcmpi(sFile.header.DataOrientation, 'VECTORIZED'))\n    % Open file\n    fid = fopen(sFile.filename, 'r');\n    % Initialize data matrix\n    F = zeros(sFile.header.NumberOfChannels, sFile.header.DataPoints);\n    iChannel = 1;\n    % Read the entire file line by line\n    while(1)\n        % Display message \n        % disp(sprintf('BRAINAMP> Reading channel #%d...', iChannel));\n        % Reached the end of the file: exit the loop\n        if feof(fid)\n            break; \n        end\n        % Read one line\n        strChan = strtrim(fgetl(fid));\n        if isempty(strChan)\n            continue;\n        end\n        % Find the first separator\n        iSep = min([find(strChan == ' ',1), find(strChan == sprintf('\\t'),1)]);\n        % Replace \",\" with \".\" for the numbers\n        strChan(strChan == ',') = '.';\n        % Read the values\n        F(iChannel,:) = sscanf(strChan(iSep+1:end), '%f')';\n        iChannel = iChannel+1;\n    end\n    % Close file\n    fclose(fid);\n    % Select only the requested time points\n    iTime = (SamplesBounds(1):SamplesBounds(2)) - round(sFile.prop.times(1) .* sFile.prop.sfreq) + 1;\n    F = F(:,iTime);\nend\n\n% Apply gains, if available\nif isfield(sFile.header, 'chgain') && (length(sFile.header.chgain) == size(F,1))\n    F = bst_bsxfun(@times, F, sFile.header.chgain(:));\n% Else: Convert from microVolts to Volts by default\nelse\n    F = F * 1e-6;\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_brainamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.2074965777371278}}
{"text": "function out = spm_run_tissue_volumes(cmd, job)\n% SPM job execution function for Tissue Volumes\n%\n% See also: spm_cfg_tissue_volumes, spm_summarise\n%__________________________________________________________________________\n% Copyright (C) 2013-2018 Wellcome Trust Centre for Neuroimaging\n\n% Ged Ridgway\n% $Id: spm_run_tissue_volumes.m 7460 2018-10-29 15:55:12Z john $\n\n\nswitch lower(cmd)\n    %----------------------------------------------------------------------    \n    case 'exec'\n        \n        %%\n        mat = job.matfiles;\n        T   = job.tmax;\n        msk = char(job.mask);\n        outf = job.outf;\n        if isempty(msk)\n            msk = 'all';\n        end\n        \n        %%\n        N = numel(mat);\n        vol = nan(N, T);\n        for n = 1:N\n            res = load(mat{n});\n            \n            % check for previously computed volumes (to save time if there)\n            if isfield(res, 'volumes') && strcmp(res.volumes.mask, msk) ...\n                    && numel(res.volumes.litres) >= T\n                vol(n, :) = res.volumes.litres(1:T);\n                continue\n            end\n            \n            % determine number of tissue classes Kb\n            if isfield(res, 'mg'),\n                Kb  = max(res.lkp);\n            else\n                Kb  = size(res.intensity(1).lik, 2);\n            end\n            tc  = false(Kb, 4);\n            \n            % look for existing mwc files\n            mwc = cell(T, 1);\n            for t = 1:T\n                mwc{t} = spm_file(res.image(1).fname, 'prefix', ['mwc' num2str(t)],'ext','nii');\n                if ~exist(mwc{t}, 'file')\n                    tc(t, 4) = true; % i.e. need to produce this mwc\n                end\n            end\n            \n            % produce mwc files if required\n            if any(tc(:, 4))\n                for f = 1:numel(res.image)\n                    if ~exist(res.image(f).fname, 'file')\n                        error('Original image no longer found at:\\n%s\\n', res.image(f).fname)\n                    end\n                end\n                spm_preproc_write8(res, tc);\n            end\n            \n            % compute tissue volumes\n            vol(n, :) = spm_summarise(mwc, msk, 'litres');\n            \n            % add to mat file for future reuse\n            volumes.litres  = vol(n, :);\n            volumes.mask    = msk;\n            save(mat{n}, 'volumes', '-append')\n            \n            % if mwc newly created above, delete now\n            for t = 1:T\n                if tc(t, 4), spm_unlink(mwc{t}), end\n            end\n        end\n        \n        %% Put into output structure for use with dependencies\n        for t = 1:T\n            out.(sprintf('vol%d', t)) = vol(:, t);\n        end\n        out.vol_sum = sum(vol, 2); % (total intracranial volume if T=1:3)\n        \n        %% Optionally save in CSV format\n        if ~isempty(outf)\n            [pth, nam, ext] = spm_fileparts(outf);\n            if isempty(ext), ext = '.csv'; end\n            fnm = fullfile(pth, [nam ext]);\n            fid = fopen(fnm, 'wt');\n            if fid < 0, error('Failed to open %s\\n', fnm); end\n            delim = ',';\n            fprintf(fid, 'File');\n            fprintf(fid, [delim 'Volume%d'], 1:T);\n            for n = 1:N\n                fprintf(fid, '\\n''%s''', mat{n});\n                fprintf(fid, [delim '%d'], vol(n, :));\n            end\n            fprintf(fid, '\\n');\n            fclose(fid);\n        end\n        \n        %% Display in command window\n        fprintf('\\nSegmentation files:\\n');\n        fprintf('\\t%s\\n', mat{:});\n        fprintf('\\nVolumes (litres):\\n');\n        disp(vol);\n        %------------------------------------------------------------------\n    case 'vout'\n        try\n            T = job.tmax;\n        catch\n            T = 3;\n        end\n        out(T+1) = cfg_dep;\n        for t = 1:T\n            out(t).sname        = num2str(t);\n            out(t).src_output   = substruct('.', sprintf('vol%d', t));\n            out(t).tgt_spec     = cfg_findspec({\n                {'strtype','e', 'strtype','r'}\n                });\n        end\n        out(T+1).sname      = 'Sum';\n        out(T+1).src_output = substruct('.', 'vol_sum');\n        out(T+1).tgt_spec   = cfg_findspec({\n            {'strtype','e', 'strtype','r'}\n            });\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_tissue_volumes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.20732208329216661}}
{"text": "function output = exportAsOpenQuakeCatalogueCsv(catalog, filename)\n    % export a Catalog to a csv file readable as a Catalogue\n    if isa(catalog, 'ZmapCatalog')\n        catalog = catalog.table();\n    end\n    if ~istable(catalog)\n        error('expected a ZmapCatalog')\n    end\n    ymdHMS = datevec(catalog.Date);\n    output = table;\n    output.year = ymdHMS(:,1);\n    output.month = ymdHMS(:,2);\n    output.day = ymdHMS(:,3);\n    output.hour = ymdHMS(:,4);\n    output.minute = ymdHMS(:,5);\n    output.second = ymdHMS(:,6);\n    output.latitude = catalog.Latitude;\n    output.longitude = catalog.Longitude;\n    output.depth = catalog.Depth;\n    output.magnitude = catalog.Magnitude;\n    % output.moment = 10.^(1.5*magnitude + 9.05);\n    output.eventID = \"id\"+string(1:height(output))';\n    output.magnitudeType = catalog.MagnitudeType;\n    if exist('filename','var') && (~exist(filename,'file') ||...\n            questdlg(['File ',filename,' exists, overwrite?'],'export catalog')==\"Yes\")\n        writetable(output,filename);\n    end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/exportAsOpenQuakeCatalogueCsv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20731013779372892}}
{"text": "%% runstats.m\n% This script collects statistics about positions of each component,\n% creates matrix S 4xM [xmin_0, ..., xmin_{M-1}; ymin_0, ..., ymin_{M-1};\n% xmin_0, ..., xmax_{M-1}; ymax_0, ..., ymax_{M-1}] each column defines\n% bounding box for one component. \n% \n% Parameters in structure options are now set to cover approx. 97.5% of all\n% tested images (about 12200 images, original database was pruned - file\n% ./MAT/eye_on_lfw_pruned.mat - so now it does not contain images with\n% multiple faces annotated or detected. Also images with incomplete\n% annotations were discarded.) \n% \n% 15-07-10 Michal Uricar\n% 26-02-11 Michal Uricar\n\n% clc;\nclearvars; close all;\n\n%% Timestamp\n\nfprintf(1,'Started on %s\\n\\n', datestr(now));\n\n%% Load data (images with detected frames)\n\naddpath('./Functions');\naddpath('../../matlab_toolbox/mex/');\n\nload('./MAT/paths.mat');\nload('./MAT/options.mat');\n\n% load('./MAT/eyefd_on_lfw_pruned.mat');\nannotation_struct = read_lfw_annotation_file(['../' DB_ANN]);\n\n%% Print parameters\n\nfprintf('Parameters: \\nbw = [%d; %d]\\n', options.bw);\nfprintf('bw_margin = [%d; %d]\\n', options.bw_margin);\nfprintf('components= \\n'); disp(options.components);\nfprintf('M = %d\\n', options.M);\nfprintf('image_path = ''%s''\\n', options.image_path);\nfprintf('....................................\\n');\nfprintf('\\nStarting test...\\n');\n\n%% run test\n\ntic\n[cnt, S, bad_idx] = paramStats(annotation_struct, options);\n% [cnt, S, bad_idx] = paramStats(annotation_struct, options, 1);\ntoc\n\npercent = cnt/annotation_struct.N * 100;\nfprintf('Passed %d images. That is %f%%.\\n', cnt, percent);\n\n%% create new database - only images that passed through test\n\nidx = 1:annotation_struct.N;\nidx(bad_idx) = [];\n% image = image(idx);\nannotation_struct.bbox = annotation_struct.bbox(idx, :);\nannotation_struct.names = annotation_struct.names(idx);\nannotation_struct.eye_r = annotation_struct.eye_r(idx, :);\nannotation_struct.eye_l = annotation_struct.eye_l(idx, :);\nannotation_struct.canthus_rr = annotation_struct.canthus_rr(idx, :);\nannotation_struct.canthus_rl = annotation_struct.canthus_rl(idx, :);\nannotation_struct.canthus_lr = annotation_struct.canthus_lr(idx, :);\nannotation_struct.canthus_ll = annotation_struct.canthus_ll(idx, :);\nannotation_struct.mouth = annotation_struct.mouth(idx, :);\nannotation_struct.mouth_corner_r = annotation_struct.mouth_corner_r(idx, :);\nannotation_struct.mouth_corner_l = annotation_struct.mouth_corner_l(idx, :);\nannotation_struct.nose = annotation_struct.nose(idx, :);\nannotation_struct.N = numel(annotation_struct.names);\n\nfprintf('Creating new database (db_good.mat)...\\n');\nsave('./MAT/db_good.mat', 'annotation_struct');\n\n%% Save data\n\nfprintf('Saving statistics...\\n');\nsave('./results/statistics_orig.mat', 'cnt', 'S', 'percent', 'options');\n\n %% shrink S (S boundary must represent positions of components center)\n\nload('./results/statistics_orig.mat', 'S');\n \nfor i = 1 : options.M\n    S(1, i) = S(1, i) + options.components(1, i)/2;\n    S(2, i) = S(2, i) + options.components(2, i)/2;\n    S(3, i) = S(3, i) - options.components(1, i)/2;\n    S(4, i) = S(4, i) - options.components(2, i)/2;\nend;\n\nsave('./results/statistics_orig.mat', 'cnt', 'S', 'percent', 'options');\n\n%% Show computed S\n\n[Iframe, Annotation] = getImageFrame(options, 1, annotation_struct);\nPoints = Annotation.P;\nPoints = prepareS0gt(Annotation.P, options);    % transform nose to the center of face\nPoints = Points(:, options.comselect);          % extract relevant points only (name list in options.compnames)\nPoints(:, options.M) = Annotation.P(:, 10);             % copy back original nose position\n\ncolors = colormap(hsv(options.M)); close gcf;\n% names = fieldnames(Annotation.face);\nnames = options.compnames;\n\nscrsz = get(0,'ScreenSize');\n\nfigure;\nimshow(Iframe, [], 'Border', 'tight'); hold on;\nset(gcf, 'OuterPosition', [scrsz(1) scrsz(2) scrsz(3) scrsz(4)]);\n% set(gcf, 'Position', [100, 100, 800, 600]);\nfor k = 1 : options.M\n%     plot(Points(1, k), Points(2, k), 'r.', 'LineWidth', 2, 'MarkerSize', 10);\n    plot(Points(1, k), Points(2, k), '.', 'color', colors(k, :), 'LineWidth', 2, 'MarkerSize', 10);\n    bb = makeAABB(S(:, k));\n    line([bb(1,:) bb(1,1)], [bb(2,:) bb(2,1)], 'color', colors(k, :));\n    bb = makeAABB([Points(1, k) - options.components(1, k)/2 Points(2, k) - options.components(2, k)/2 ...\n                   Points(1, k) + options.components(1, k)/2 Points(2, k) + options.components(2, k)/2 ]);\n%     text(Points(1, k)-1, Points(2, k)+1, names(k+3), 'color', colors(k, :));\n    text(Points(1, k)-1, Points(2, k)+1, names(k), 'color', colors(k, :));\n    line([bb(1,:) bb(1,1)], [bb(2,:) bb(2,1)], 'color', 'y');\nend;\nhold off;\n\nif (~exist('./img/', 'dir'))\n    mkdir('./img');\nend;\n\nsaveas(gcf, './img/S.png');\n\n%% Show S\n\nS = ceil(S);\n\ncolors = colormap(hsv(options.M)); close gcf;\n% names = fieldnames(Annotation.face);\nnames = options.compnames;\ni = 1;\n\nfigure;\nsubplot(1, 2, 1);\nimshow(Iframe, []); hold on;\nfor j = 1 : options.M;\n    bb = makeAABB(S(:, j));\n    line([bb(1,:) bb(1,1)], [bb(2,:) bb(2,1)], 'color', colors(j, :));\n    text(Points(1, j), Points(2, j), names(j), 'color', colors(j, :));\nend;\nline([20 20], [0 41], 'color', 'm', 'LineWidth', 2);\nhold off;\nsaveas(gcf, './img/S.png');\n\n%% make each frame of component in S symetric (this works only on lfw database with 4 components!)\n\nS_new = S;\n\n% canthus - inner\nS_new(2, 2) = min(S(2, 2), S(2, 3)); S_new(2, 3) = min(S(2, 2), S(2, 3));   % ymin\nS_new(4, 2) = max(S(4, 2), S(4, 3)); S_new(4, 3) = max(S(4, 2), S(4, 3));   % ymax\nS_new(3, 2) = options.bw(1)/2 + max(S(3, 2) - options.bw(1)/2, options.bw(1)/2 - S(1, 3));     % x_max\nS_new(1, 3) = options.bw(1)/2 - max(S(3, 2) - options.bw(1)/2, options.bw(1)/2 - S(1, 3));\nS_new(1, 2) = min(S(1, 2), options.bw(1) - S(3, 3));\nS_new(3, 3) = options.bw(1) - min(S(1, 2), options.bw(1) - S(3, 3));\n% canthus - outer\nS_new(2, 6) = min(S(2, 6), S(2, 7)); S_new(2, 7) = min(S(2, 6), S(2, 7));   % ymin\nS_new(4, 6) = max(S(4, 6), S(4, 7)); S_new(4, 7) = max(S(4, 6), S(4, 7));   % ymax\nS_new(3, 6) = options.bw(1)/2 + max(S(3, 6) - options.bw(1)/2, options.bw(1)/2 - S(1, 7));     % x_max\nS_new(1, 7) = options.bw(1)/2 - max(S(3, 6) - options.bw(1)/2, options.bw(1)/2 - S(1, 7));\nS_new(1, 6) = min(S(1, 6), options.bw(1) - S(3, 7));\nS_new(3, 7) = options.bw(1) - min(S(1, 6), options.bw(1) - S(3, 7));\n% mouth corners\nS_new(2, 4) = min(S(2, 4), S(2, 5)); S_new(2, 5) = min(S(2, 4), S(2, 5));   % ymin\nS_new(4, 4) = max(S(4, 4), S(4, 5)); S_new(4, 5) = max(S(4, 4), S(4, 5));   % ymax\nS_new(3, 4) = options.bw(1)/2 + max(S(3, 4) - options.bw(1)/2, options.bw(1)/2 - S(1, 5));     % x_max\nS_new(1, 5) = options.bw(1)/2 - max(S(3, 4) - options.bw(1)/2, options.bw(1)/2 - S(1, 5));\nS_new(1, 4) = min(S(1, 4), options.bw(1) - S(3, 5));\nS_new(3, 5) = options.bw(1) - min(S(1, 4), options.bw(1) - S(3, 5));\n% center of face\nS_new(3, 1) = options.bw(1)/2 + max(S(3, 1) - options.bw(1)/2, options.bw(1)/2 - S(1, 1));     % x_max\nS_new(1, 1) = options.bw(1)/2 - max(S(3, 1) - options.bw(1)/2, options.bw(1)/2 - S(1, 1));\n% nose\nS_new(3, 8) = options.bw(1)/2 + max(S(3, 8) - options.bw(1)/2, options.bw(1)/2 - S(1, 8));     % x_max\nS_new(1, 8) = options.bw(1)/2 - max(S(3, 8) - options.bw(1)/2, options.bw(1)/2 - S(1, 8));\n\nsubplot(1, 2, 2);\nimshow(Iframe); hold on;\nfor j = 1 : options.M;\n    bb = makeAABB(S_new(:, j));\n    line([bb(1,:) bb(1,1)], [bb(2,:) bb(2,1)], 'color', colors(j, :));\n    text(Points(1, j), Points(2, j), names(j), 'color', colors(j, :));\nend;\nline([20 20], [0 41], 'color', 'm', 'LineWidth', 2);\nhold off;\nsaveas(gcf, './img/S_symetric.png');\n\n%% Save symetric S for 4 components\nS2 = S_new;\n% save('./results/symetric_S_orig.mat', 'S');\n\n% set new options.S\noptions.S = S2;\n\nfname = './results/options.mat';\nfprintf('Saving new options struct to file %s...', fname);\nsave(fname, 'options');\nfprintf(' done.\\n');\n\n%% Check for TRN, VAL and TST annotation files\n\n% if (exist('./MAT/LFW_TRN_annotation.txt', 'file') && exist('./MAT/LFW_VAL_annotation.txt', 'file') && exist('./MAT/LFW_TST_annotation.txt', 'file'))\n%     annotation_struct = read_lfw_annotation_file('./MAT/LFW_TRN_annotation.txt');\n%     save('./MAT/TRN.mat', 'annotation_struct');\n%     annotation_struct = read_lfw_annotation_file('./MAT/LFW_VAL_annotation.txt');\n%     save('./MAT/VAL.mat', 'annotation_struct');\n%     annotation_struct = read_lfw_annotation_file('./MAT/LFW_TST_annotation.txt');\n%     save('./MAT/TST.mat', 'annotation_struct');\n% end;\nif (~isempty(TRN_EXAMPLES)  && ~isempty(VAL_EXAMPLES) && ~isempty(TST_EXAMPLES))\n    if (exist(['../' TRN_EXAMPLES], 'file') && exist(['../' VAL_EXAMPLES], 'file') && exist(['../' TST_EXAMPLES], 'file'))\n        annotation_struct = read_lfw_annotation_file(['../' TRN_EXAMPLES]);\n        save('./MAT/TRN.mat', 'annotation_struct');\n        annotation_struct = read_lfw_annotation_file(['../' VAL_EXAMPLES]);\n        save('./MAT/VAL.mat', 'annotation_struct');\n        annotation_struct = read_lfw_annotation_file(['../' TST_EXAMPLES]);\n        save('./MAT/TST.mat', 'annotation_struct');\n    end;\nend;\n\n%% Timestamp\n\nfprintf(1,'\\nFinished on %s\\n\\n', datestr(now));", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/runstats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20731013779372892}}
{"text": "function D = spm_eeg_inv_forward(varargin)\n% Compute M/EEG leadfield\n% FORMAT D = spm_eeg_inv_forward(D,val)\n%\n% D                - input struct\n% (optional) fields of S:\n% D                - filename of EEG/MEG mat-file\n%\n% Output:\n% D                - EEG/MEG struct with filenames of Gain matrices)\n%__________________________________________________________________________\n% Copyright (C) 2008-2018 Wellcome Trust Centre for Neuroimaging\n\n% Jeremie Mattout & Christophe Phillips\n% $Id: spm_eeg_inv_forward.m 7702 2019-11-22 11:32:26Z guillaume $\n\n\nSVNrev = '$Rev: 7702 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('FnBanner', mfilename, SVNrev);\n\n%-Initialisation\n%--------------------------------------------------------------------------\n[D, val] = spm_eeg_inv_check(varargin{:});\n\nif numel(D.inv{val}.datareg) ~= numel(D.inv{val}.forward)\n    error('Separate coregistration is required for every modality.');\nend\n\nFgraph = spm_figure('FindWin','Graphics');\nspm_figure('Clear',Fgraph);\nspm('Pointer', 'Watch');\nif isempty(Fgraph) || spm('CmdLine'), graph = 'no'; else, graph = 'yes'; end\n\nfor i = 1:numel(D.inv{val}.forward)\n    M    = D.inv{val}.datareg(i).fromMNI*D.inv{val}.mesh.Affine;\n    \n    M    = diag([1e-3 1e-3 1e-3 1])*M; % convert to m\n    \n    mesh = spm_eeg_inv_transform_mesh(M, D.inv{val}.mesh);\n    \n    mesh_correction = [];\n    \n    sens = D.inv{val}.datareg(i).sensors;\n    \n    if isequal(D.inv{val}.datareg(i).modality, 'MEG')\n        sens = ft_datatype_sens(sens, 'amplitude', 'T', 'distance', 'm');\n    else\n        sens = ft_datatype_sens(sens, 'amplitude', 'V', 'distance', 'm');\n    end\n        \n    switch D.inv{val}.forward(i).voltype\n        case 'EEG interpolated'\n            vol = D.inv{val}.forward(i).vol;\n            modality = 'EEG';\n        case '3-Shell Sphere'\n            cfg              = [];\n            cfg.feedback     = graph;\n            cfg.siunits      = 'yes';\n            cfg.showcallinfo = 'no';\n          \n            headshape(1) = export(gifti(mesh.tess_scalp),  'ft');\n            headshape(2) = export(gifti(mesh.tess_oskull), 'ft');\n            headshape(3) = export(gifti(mesh.tess_iskull), 'ft');\n            \n            % determine the convex hull of the brain, to determine the support points\n            pnt  = mesh.tess_ctx.vert;\n            tric = convhulln(pnt);\n            sel  = unique(tric(:));\n            \n            % create a triangulation for only the support points\n            headshape(4).pnt = pnt(sel, :);\n            headshape(4).tri = convhulln(pnt(sel, :));\n            \n            cfg.method = 'concentricspheres';\n            \n            vol  = ft_prepare_headmodel(cfg, headshape);\n            \n            cfg = [];\n            cfg.headmodel = vol;\n            cfg.grid.pos  = mesh.tess_ctx.vert;\n            cfg.spherify  = 'yes';\n            gridsphere    = ft_prepare_sourcemodel(cfg);\n            \n            mesh_correction    = rmfield(cfg, {'headmodel', 'grid'});\n            \n            mesh.tess_ctx.vert = gridsphere.pos;\n            modality = 'EEG';\n            \n        case 'EEG BEM'                        \n            volfile = spm_file(mesh.sMRI, 'suffix','_EEG_BEM', 'ext','mat');\n            vol = [];\n            \n            if exist(volfile, 'file')\n                vol = ft_read_headmodel(volfile);\n                if ~isfield(vol, 'unit') || ~isequal(vol.unit, 'm')\n                    vol = [];\n                end\n            end\n                \n            if isempty(vol)\n                \n                vol.cond   = [0.3300 0.0041 0.3300];\n                vol.source = 1; % index of source compartment\n                vol.skin   = 3; % index of skin surface\n                % brain\n                vol.bnd(1) = export(gifti(mesh.tess_iskull), 'ft');\n                % skull\n                vol.bnd(2) = export(gifti(mesh.tess_oskull), 'ft');\n                % skin\n                vol.bnd(3) = export(gifti(mesh.tess_scalp),  'ft');\n                \n                % create the BEM system matrix\n                cfg        = [];\n                cfg.method = 'bemcp';\n                cfg.showcallinfo = 'no';\n                cfg.siunits      = 'yes';\n                vol = ft_prepare_headmodel(cfg, vol);\n                \n                spm_progress_bar('Set', 1);\n                \n                save(volfile, 'vol', spm_get_defaults('mat.format'));\n                \n                spm_progress_bar('Clear');\n                spm('Pointer', 'Arrow');\n            end\n            \n            cfg = [];\n            cfg.headmodel = vol;\n            cfg.grid.pos = mesh.tess_ctx.vert;         \n            cfg.moveinward = 6e-3; %move to empirically determined BEM safe zone\n            gridcorrect = ft_prepare_sourcemodel(cfg);\n            \n            mesh_correction    = rmfield(cfg, {'headmodel', 'grid'});\n            \n            mesh.tess_ctx.vert = gridcorrect.pos;\n            \n            vol = volfile;\n            modality = 'EEG';\n            \n        case 'OpenMEEG BEM'\n            vol        = [];\n            vol.cond   = [0.3300 0.0041 0.3300];\n            vol.source = 1; % index of source compartment\n            vol.skin   = 3; % index of skin surface\n            % brain\n            vol.bnd(1) = export(gifti(mesh.tess_iskull), 'ft');\n            % skull\n            vol.bnd(2) = export(gifti(mesh.tess_oskull), 'ft');\n            % skin\n            vol.bnd(3) = export(gifti(mesh.tess_scalp),  'ft');\n            \n            cfg                         = [];\n            cfg.method                 = 'openmeeg';\n            cfg.siunits                = 'yes';\n            cfg.showcallinfo           = 'no';         \n            vol                        = ft_prepare_headmodel(cfg, vol);\n            \n            cfg                        = [];\n            cfg.vol                    = vol;\n            cfg.grid.pos               = mesh.tess_ctx.vert;          \n            cfg.moveinward             = 6e-3; % smaller shift might suffice for OpenMEEG\n            gridcorrect                = ft_prepare_sourcemodel(cfg);\n            \n            mesh_correction            = rmfield(cfg, {'vol', 'grid'});\n            \n            mesh.tess_ctx.vert         = gridcorrect.pos;            \n            \n            modality = 'EEG';\n        case 'Single Sphere'\n            cfg                        = [];\n            cfg.feedback               = 'yes';\n            cfg.showcallinfo           = 'no';\n            cfg.grad                   = D.inv{val}.datareg(i).sensors;            \n            cfg.method                 = 'singlesphere';\n            cfg.siunits                = 'yes';\n            \n            headshape                  = export(gifti(mesh.tess_scalp), 'ft');\n            \n            vol                        = ft_prepare_headmodel(cfg, headshape);\n            modality                   = 'MEG';\n        case 'MEG Local Spheres'\n            cfg                        = [];\n            cfg.feedback               = 'yes';\n            cfg.showcallinfo           = 'no';\n            cfg.grad                   = sens;           \n            cfg.method                 = 'localspheres';\n            cfg.siunits                = 'yes';\n            \n            headshape                  = export(gifti(mesh.tess_scalp), 'ft');\n            vol                        = ft_prepare_headmodel(cfg, headshape);\n            modality                   = 'MEG';\n        case  'Single Shell'\n            cfg                        = [];\n            cfg.feedback               = 'yes';\n            cfg.showcallinfo           = 'no';\n            cfg.grad                   = sens;           \n            cfg.method                 = 'singleshell';\n            cfg.siunits                = 'yes';\n            \n            headshape                  = export(gifti(mesh.tess_iskull), 'ft');\n            \n            vol                        = ft_prepare_headmodel(cfg, headshape);\n            modality                   = 'MEG';\n            \n        otherwise\n            error('Unsupported volume model type.');\n    end\n    \n    D.inv{val}.forward(i).vol             = vol;\n    D.inv{val}.forward(i).mesh            = mesh.tess_ctx;\n    D.inv{val}.forward(i).mesh_correction = mesh_correction;\n    D.inv{val}.forward(i).modality        = modality;   \n    D.inv{val}.forward(i).siunits         = 1;    \n    \n    D.inv{val}.forward(i).sensors  = sens;  \n        \n    D.inv{val}.forward(i).toMNI    = D.inv{val}.datareg(i).toMNI*diag([1e3 1e3 1e3 1]);\n    D.inv{val}.forward(i).fromMNI  = diag([1e-3 1e-3 1e-3 1])*D.inv{val}.datareg(i).fromMNI;\n    \n    spm_figure('Clear',Fgraph);\nend\n\n% This is to force recomputing the lead fields\ntry, D.inv{val} = rmfield(D.inv{val}, 'gainmat'); end\n\nfprintf('%-40s: %30s\\n','Completed',spm('time'));                       %-#\nspm('Pointer', 'Arrow');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_inv_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.2070374042891572}}
{"text": "classdef generalization_DS < handle\n    \n%  This datasource object (DS) allows one to train a classifier on a specific \n%  set of labels, and then test the classifier on a different set of \n%  labels - which enables one to evaluate how similar neural representations \n%  are across different but related conditions (i.e., does training on one set of\n%  conditions generalization to a different but related set of conditions?). This datasource\n%  is a subclass of the handle class (i.e., it has a persistent state) and \n%  contains a basic_DS where it gets most of its functionality.  \n%\n%  The constructor for this datasource has the same arguments\n%  as basic_DS, plus two additional arguments 'the_training_label_names' \n%  and 'the_test_label_names' i.e., the constructor has the form:  \n%\n%     ds = generalization_DS(binned_data_name, specific_binned_label_name, num_cv_splits, the_training_label_names, the_test_label_names, load_data_as_spike_counts)\n%   \n%      the_training_label_names and the_test_label_names are cell arrays that\n%        specify which labels should belong to which class, with the first element\n%        of these cells arrays specifying the training/test labels for the first class\n%        the second element of the cell array specifies which labels belong to \n%        the second class, etc..  For example, suppose one was interested in testing\n%        position invariance, and had done an experiment in which data was recorded \n%        while 7 different objects were shown at three different locations.  If the\n%        labels for the 7 objects at the first location had labels 'obj1_loc1', 'obj2_loc1', ..., 'obj7_loc1',\n%        at the second location were 'obj1_loc2', 'obj2_loc2', ..., 'obj7_loc2',\n%        and at the third location were 'obj1_loc3', 'obj2_loc3', ..., 'obj7_loc3',\n%        then one could do a test of position invariance by setting the_training_label_names{1} = {'obj1_loc1},\n%        setting the_training_label_names{2} = {'obj2_loc1'}, ...,  the_training_label_names{7} = {'obj7_loc1},\n%        and setting the the_test_label_names{1} = {'obj1_loc2', 'obj1_loc3'}, \n%        the_test_label_names{2} = {'obj2_loc2', 'obj2_loc3'}, ..., the_test_label_names{7} = {'obj7_loc2', 'obj7_loc3'}. \n%        The object is able to test such generalization from training on one set of labels and\n%        testing on a different set of labels by remapping the training label numbers to the\n%        index number in the_training_label_names cell array, and remapping the \n%        test label numbers with the the index number into the the_test_label_names cell array.  \n%\n%  This object has all of the same properites as the basic_DS object (except that label_names_to_use which \n%    has been replaced by the the_training_label_names, and the_test_label_names properties).  There\n%    is also an additional property that can be set for this object which is:  \n%  \n%       use_unique_data_in_each_CV_split  (default value is 0).\n%  \n%       When this argument is set to 0, the get_data method returns the normal leave one split\n%        out training and test data sets (i.e., the training set consists of \n%        (num_cv_splits - 1) splits of the data and the test set consists of 1 split of the data).\n%        The data in the training still comes from different splits as the data in the \n%        test set, thus one can have some of the same labels in the both \n%        the_training_label_names and in the_test_label_names (in fact, if ones sets\n%        the_test_label_names = the_training_label_names, then the get_data\n%        method will be the same as the basic_DS get_data method).  However, \n%        if use_unique_data_in_each_CV_split = 1, then each training \n%        and test set will consist data from only split, and thus each cross-validation\n%        run is essentially like running an independent decoding experiment.  \n%        In this case the_training_label_names and the_test_label_names must not contain \n%        any of the same labels (otherwise, they would be copies of the same data \n%        which would violate the fact that the training and the test set must not have any of the same data).  \n\n\n%==========================================================================\n\n%     This code is part of the Neural Decoding Toolbox.\n%     Copyright (C) 2011 by Ethan Meyers (emeyers@mit.edu)\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n    \n%==========================================================================  \n\n\n\nproperties \n    \n    \n    the_basic_DS = [];      % the basic_DS that will be used to give this object most of its functionality\n    \n    the_training_label_names = [];   % a cell array specifying which label names (or numbers) should be used for training the classifier\n                                       %   i.e., the_training_label_names{1} = {class_1_training_names}; the_training_label_names{2} = {class_2_training_names}; etc.\n    the_test_label_names = [];       % a cell array specifying which label names (or numbers) should be used for testing the classifier\n                                       %   i.e., the_test_label_names{1} = {class_1_test_names}; the_test_label_names{2} = {class_2_test_names}; etc.\n                                       \n    use_unique_data_in_each_CV_split = 0;  % if this is set to 1 then each CV splits has unique data, i.e.,\n                                                         %  each CV split has the amount of data that is typically only in the test set, \n                                                         %  and every CV training set does not consist of (num_cv_splits -1) * num_labels data points\n                                                         %  but instead consists of length(cell2mat(the_test_label_names)) training points.\n                                                         \n                                                         \n    % some properties of basic_DS that will also be available in generalization_DS by setting the basic_DS properties\n                                                         \n    num_times_to_repeat_each_label_per_cv_split = 1;     %  how many of each unique label should be in each CV block\n    \n    sample_sites_with_replacement = 0;  %  specify whether to sample neurons with replacement - if they are sampled with replacement, then some features will be repeated within a single point data vector\n    num_resample_sites = -1;            %  how many sites should be used for each resample iteration - must be less than length(the_data)\n    \n    create_simultaneously_recorded_populations = 0;   % to use pseudo-populations or simultaneous populations (2 => that the training set is pseudo and test is simultaneous)\n      \n    sites_to_use = -1;                   %  a list of indices of which sites (neurons) to use in the the_data cell array \n    sites_to_exclude = [];               %  a list of features that should explicitly be excluded\n    time_periods_to_get_data_from = [];  %  a cell array containing vectors that specify which time bins to use from the_data \n\n                                        \n    % randomly shuffles the labels prior to the get_data method being called - which is useful for creating one point in a null distribution to check if decoding results are above what is expected by change.\n    randomly_shuffle_labels_before_running = 0;                                                        \n                                                         \n                                  \nend\n\n\n\nproperties (GetAccess = 'public', SetAccess = 'private')\n \n      initialized = 0;\n            \n      the_training_label_numbers = [];   % numbers that the_training_label_names were mapping on to\n      the_test_label_numbers = [];       % numbers that the_test_label_names were mapping on to\nend\n\n    \n\nmethods \n\n    \n    function ds = generalization_DS(binned_data_name, specific_binned_label_name, num_cv_splits, the_training_label_names, the_test_label_names, load_data_as_spike_counts)\n \n       if nargin < 6\n           load_data_as_spike_counts = 0;\n       end\n        \n       \n       ds.the_basic_DS = basic_DS(binned_data_name, specific_binned_label_name, num_cv_splits, load_data_as_spike_counts);   % set properties using parent constructor\n                      \n       ds.the_training_label_names = the_training_label_names;   % set properties that are unique to this object\n       ds.the_test_label_names = the_test_label_names;\n          \n       % get all the unique labels\n       if length(the_training_label_names) ~= length(the_test_label_names)\n            error('The cell arrays the_training_label_names and the_test_label_names must have the same number of cells (with the names/numbers in cell i containing which labels belong to class i)');\n       end\n       \n\n    end\n    \n\n       \n    function the_properties = get_DS_properties(ds)    \n    \n        the_properties = ds.the_basic_DS.get_DS_properties;\n        \n        the_properties.the_training_label_names = ds.the_training_label_names;\n        the_properties.the_test_label_names  = ds.the_test_label_names; \n        \n        the_properties.use_unique_data_in_each_CV_split = ds.use_unique_data_in_each_CV_split;\n        \n    end\n    \n    \n    \n    function  [XTr_all_time_cv YTr_all XTe_all_time_cv YTe_all] = get_data(ds)\n    %function  [XTr_all_time_cv YTr_all XTe_all_time_cv YTe_all ADDITIONAL_DATASOURCE_INFO] = get_data(ds)\n        \n\n        \n        % initialize things here....\n        if ds.initialized == 0   \n            \n            \n            % creating separate variables for this since calling a field of an object in Matlab is slow \n            the_training_label_names = ds.the_training_label_names;\n            the_test_label_names = ds.the_test_label_names;\n        \n \n            ds.the_basic_DS.num_times_to_repeat_each_label_per_cv_split = ds.num_times_to_repeat_each_label_per_cv_split;\n\n            ds.the_basic_DS.sample_sites_with_replacement = ds.sample_sites_with_replacement ;\n            ds.the_basic_DS.num_resample_sites = ds.num_resample_sites;\n            \n            ds.the_basic_DS.create_simultaneously_recorded_populations = ds.create_simultaneously_recorded_populations;\n\n            ds.the_basic_DS.sites_to_use = ds.sites_to_use;\n            ds.the_basic_DS.sites_to_exclude = ds.sites_to_exclude;\n            ds.the_basic_DS.time_periods_to_get_data_from = ds.time_periods_to_get_data_from;\n\n            ds.the_basic_DS.randomly_shuffle_labels_before_running = ds.randomly_shuffle_labels_before_running;                                                  \n\n    \n            \n            % if the_labels are strings, convert these names into label numbers...\n            if iscell(ds.the_basic_DS.the_labels{1})\n                \n                \n                % put all the training and test names into one cell array called all_training_and_test_names\n                cTrainingNames = 0;\n                cTestNames = 0;\n                for iClass = 1:length(the_training_label_names)\n                    for iTrain = 1:size(the_training_label_names{iClass}, 2)\n                        cTrainingNames = cTrainingNames + 1;\n                        all_training_names{cTrainingNames} = the_training_label_names{iClass}{iTrain};\n                    end\n                    \n                    for iTest = 1:size(the_test_label_names{iClass}, 2)\n                        cTestNames = cTestNames + 1;\n                        all_test_names{cTestNames} = the_test_label_names{iClass}{iTest}; \n                    end                  \n                end\n                    \n                \n               all_training_and_test_names = union(all_training_names, all_test_names);\n\n               \n               % sanity checka that the same label is not in multiple training classes (and the the same label is not in multiple test classes)\n               if length(unique(all_training_names)) ~= length(all_training_names)\n                    warning('some of the same strings in the_training_label_names are in multiple classes');\n               end  \n               if length(unique(all_test_names)) ~= length(all_test_names)  % same sanity check for the_test_label_names\n                    warning('some of the same strings in the_test_label_names are in multiple classes');\n               end\n               \n               \n\n               % convert the_labels into numebrs\n               ignore_case_of_strings = 0;  % for now, always respect the case of the strings used in the labels\n\n                \n                % by passing all_training_and_test_names as the 3rd argument convert_label_strings_into_numbers this keeps the mapping from the_test_label_names to the_test_label_numbers correct                \n                % an erorr in convert_label_strings_into_numbers will be thrown if some of the training or test label names are strings that are not in binned labels the_labels\n                the_labels_as_numbers = convert_label_strings_into_numbers(ds.the_basic_DS.the_labels, ignore_case_of_strings, all_training_and_test_names); \n\n                ds.the_basic_DS.the_labels = the_labels_as_numbers;\n                 \n                \n                % remap the_training_label_names and the_training_label_names into numbers\n                cTrainingNames = 0;\n                cTestNames = 0;\n                for iClass = 1:length(the_training_label_names)\n                    for iTrain = 1:size(the_training_label_names{iClass}, 2)\n                        cTrainingNames = cTrainingNames + 1;\n                        the_training_label_numbers{iClass}(iTrain) = find(ismember(all_training_and_test_names, the_training_label_names{iClass}{iTrain}));\n                    end\n\n                    for iTest = 1:size(the_test_label_names{iClass}, 2)\n                        cTestNames = cTestNames + 1;\n                        the_test_label_numbers{iClass}(iTest) = find(ismember(all_training_and_test_names, the_test_label_names{iClass}{iTest}));\n                    end      \n                end\n\n                \n               %  sanity check to make sure that one is not training with label l in class k and then has test label l in class j\n               some_of_the_same_labels_are_in_multiple_classes = 0;\n               for iClass = 1:length(the_training_label_names)                   \n                    temp_test_label_numbers = the_test_label_numbers;\n                    temp_test_label_numbers{iClass} = [];\n                    temp_test_label_numbers = cell2mat(temp_test_label_numbers);\n                    if ~isempty(intersect(temp_test_label_numbers, the_test_label_numbers{iClass}))\n                        some_of_the_same_labels_are_in_multiple_classes = 1;\n                    end                    \n               end  \n               \n               if  some_of_the_same_labels_are_in_multiple_classes == 1\n                    warning('some labels that are in training class k, are in a different test class j')\n               end\n               \n                      \n               ds.the_training_label_numbers = the_training_label_numbers;\n               ds.the_test_label_numbers = the_test_label_numbers;\n                 \n                              \n            else  % if numbers for labels have been specified instead of names, just use those numbers\n                \n               ds.the_training_label_numbers = ds.the_training_label_names;\n               ds.the_test_label_numbers = ds.the_test_label_names;\n               \n            end\n            \n\n            % only use labels that are listed in the_training_label_numbers and the_test_label_numbers\n            the_training_nums = cell2mat(ds.the_training_label_numbers);\n            the_test_nums = cell2mat(ds.the_test_label_numbers);\n            label_numbers_to_use = unique([the_training_nums(:); the_test_nums(:)]);\n            ds.the_basic_DS.label_names_to_use = label_numbers_to_use;\n \n            \n            ds.initialized = 1;         \n        end\n        \n        \n                    \n         % creating separate variables for this since calling a field of an object in Matlab is slow \n         the_training_label_numbers = ds.the_training_label_numbers;\n         the_test_label_numbers = ds.the_test_label_numbers;\n\n                \n        \n        %[XTr_all_time_cv YTr_all XTe_all_time_cv YTe_all] = get_data@basic_DS(ds);  % old version where this object was a subclass of basic_DS\n         [XTr_all_time_cv YTr_all XTe_all_time_cv YTe_all] = ds.the_basic_DS.get_data;  % this might be much slower than inheriting from basic_DS :(\n        \n         \n        if ds.use_unique_data_in_each_CV_split == 1\n            \n            \n            % if running each training and test set separately, there can not be any overlap between the labels listed in the training and test sets \n            %(otherwise there could be some of the same data in the training and test sets which is completely forbidden!!!!!\n            all_unique_training_labels = unique(cell2mat(the_training_label_numbers));\n            all_unique_test_labels = unique(cell2mat(the_test_label_numbers));\n\n    \n            if length(intersect(all_unique_training_labels,  all_unique_test_labels)) > 0\n                error('if running each split separately (i.e., use_unique_data_in_each_CV_split == 1), then none of the same labels can be in the training and test sets, otherwise there will be some of the same data in the training and test sets')\n            end\n        \n            \n            % remap labels (only using old 'test' data because I want each CV split to be independent)\n            remapped_YTr_all = NaN .* ones(size(YTr_all));  % only getting labels (and data) from test set b/c want each CV split to contain unique data\n            remapped_YTe_all = NaN .* ones(size(YTe_al));\n\n            for iGroup = 1:length(the_training_label_numbers)\n                remapped_YTr_all(ismember(YTr_all_cv, the_training_label_numbers{iGroup})) = iGroup;\n                remapped_YTe_all(ismember(YTe_all, the_test_label_numbers{iGroup})) = iGroup;\n            end\n            \n            \n           % remove data from trials in which the labels are not appropriate for the training/test sets\n           train_inds  = ~isnan(remapped_YTr_all);\n           test_inds  = ~isnan(remapped_YTe_all);\n\n           YTr_all = remapped_YTr_all(train_inds);   % remove NaNs from remapped labels\n           YTe_all = remapped_YTe_all(test_inds);\n                   \n            for iCV = 1:length(XTr_all_time_cv{1})    \n               for iTime = 1:length(XTr_all_time_cv) \n                   XTr_all_time_cv{iTime}{iCV} = XTr_all_time_cv{iTime}{iCV}(:, train_inds);   % only getting data from test set b/c want each CV split to be independent\n                   XTe_all_time_cv{iTime}{iCV} = XTe_all_time_cv{iTime}{iCV}(:, test_inds);\n               end\n            end\n   \n           \n\n        else\n \n            \n            % remap labels\n            remapped_YTr_all = NaN .* ones(size(YTr_all));\n            remapped_YTe_all = NaN .* ones(size(YTe_all));\n\n            for iGroup = 1:length(the_training_label_numbers)\n                remapped_YTr_all(ismember(YTr_all, the_training_label_numbers{iGroup})) = iGroup;\n                remapped_YTe_all(ismember(YTe_all, the_test_label_numbers{iGroup})) = iGroup;\n            end\n            \n            \n           % remove data from trials in which the labels are not appropriate for the training/test sets\n           training_data_inds_to_remove = isnan(remapped_YTr_all);\n           test_data_inds_to_remove = isnan(remapped_YTe_all);\n\n           for iTime = 1:length(XTr_all_time_cv)\n               for iCV = 1:length(XTr_all_time_cv{1}) \n                    XTr_all_time_cv{iTime}{iCV}(:, training_data_inds_to_remove) = [];\n                    XTe_all_time_cv{iTime}{iCV}(:, test_data_inds_to_remove) = [];  \n               end\n           end\n           \n           remapped_YTr_all(training_data_inds_to_remove) = [];\n           remapped_YTe_all(test_data_inds_to_remove) = [];\n           \n           YTr_all = remapped_YTr_all;\n           YTe_all = remapped_YTe_all;\n             \n        \n        end\n        \n        \n        \n    end  % end get_data method\n        \n    \n    \n    \n    \nend   % end methods\n\n\n\n\nend % end class\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/ndt_1_0_4/datasources/@generalization_DS/generalization_DS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20695011098627905}}
{"text": "classdef NomadOptimizer < AbstractOptimizer\n    %NomadOptimizer Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        options(1,1) NomadOptions = NomadOptions();\n    end\n    \n    methods\n        function obj = NomadOptimizer()\n            obj.options = NomadOptions();\n        end\n        \n        function [exitflag, message] = optimize(obj, lvdOpt, writeOutput, callOutputFcn, hLvdMainGUI)\n            [x0All, actVars, varNameStrs] = lvdOpt.vars.getTotalScaledXVector();\n            [lbAll, ubAll, lbUsAll, ubUsAll] = lvdOpt.vars.getTotalScaledBndsVector();\n            typicalX = lvdOpt.vars.getTypicalScaledXVector();\n            lvdData = lvdOpt.lvdData;\n            \n            if(isempty(x0All) && isempty(actVars))\n                exitflag = 0;\n                message = 'No variables enabled on script.  Aborting optimization.';\n\n                return;\n            end\n            \n            evtNumToStartScriptExecAt = obj.getEvtNumToStartScriptExecAt(lvdOpt, actVars);\n            evtToStartScriptExecAt = lvdOpt.lvdData.script.getEventForInd(evtNumToStartScriptExecAt);\n            \n            objFuncWrapper = @(x) lvdOpt.objFcn.evalObjFcn(x, evtToStartScriptExecAt);\n            nonlcon = @(x, tfRunScript, stateLog) lvdOpt.constraints.evalConstraints(x, tfRunScript, evtToStartScriptExecAt, true, stateLog);\n                        \n            opts = obj.options.getOptionsForOptimizer();\n            constrTypeStr = obj.options.getConstrTypeStr();\n            useParallel = obj.options.usesParallel();\n            \n            [c, ceq] = lvdOpt.constraints.evalConstraints(x0All, true, evtToStartScriptExecAt, false, []);\n            numConstr = length(c) + 2*length(ceq);\n            bboutput = horzcat({'OBJ'}, repmat({constrTypeStr},1,numConstr));\n            numElemPerOutput = length(bboutput);\n            bboutput = strjoin(bboutput,' ');\n            nomadNonlconWrapper = @(x) NomadOptimizer.nomadConstrWrapper(x, nonlcon);\n            \n            pp = gcp('nocreate');\n            if(isempty(pp) || useParallel == false) %\n                numWorkers = 0;\n                useParallel = false;\n            else\n                numWorkers = pp.NumWorkers;\n                useParallel = true;\n            end\n            \n            numVars = length(x0All);\n            f = @(x) NomadOptimizer.nomadObjConstrWrapper(x, objFuncWrapper, nomadNonlconWrapper, numVars, numElemPerOutput, numWorkers, lvdData);\n            opts = nomadset(opts, 'bb_output_type',bboutput);\n            \n            problem.objective = f; %f\n            problem.x0 = x0All;\n            problem.lb = lbAll;\n            problem.ub = ubAll;\n            problem.options = opts;\n            \n            problem.solver = 'nomad';\n            \n            problem.lvdData = lvdOpt.lvdData; %need to get lvdData in somehow\n                    \n            %%% Run optimizer\n            celBodyData = lvdOpt.lvdData.celBodyData;\n            recorder = ma_OptimRecorder();\n            \n            if(callOutputFcn)\n                propNames = lvdOpt.lvdData.launchVehicle.tankTypes.getFirstThreeTypesCellArr();\n%                 handlesObsOptimGui = ma_ObserveOptimGUI(celBodyData, problem, true, writeOutput, [], varNameStrs, lbUsAll, ubUsAll);\n\n                out = AppDesignerGUIOutput();\n                ma_ObserveOptimGUI_App(out);\n                handlesObsOptimGui = out.output{1};\n\n%                 outputFnc = @(x, optimValues, state) ma_OptimOutputFunc(x, optimValues, state, handlesObsOptimGui, problem.objective, problem.lb, problem.ub, celBodyData, recorder, propNames, writeOutput, varNameStrs, lbUsAll, ubUsAll);\n                hOptimStatusLabel = handlesObsOptimGui.optimStatusLabel;\n                hFinalStateOptimLabel = handlesObsOptimGui.finalStateOptimLabel;\n                hDispAxes = handlesObsOptimGui.dispAxesPanel;\n                hCancelButton = handlesObsOptimGui.cancelButton;\n                optimStartTic = tic();\n                \n                outputFnc = @(x, optimValues, state) NomadOptimizer.getOutputFunction(x, optimValues, state, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...\n                                                                                      problem.objective, problem.lb, problem.ub, celBodyData, recorder, propNames, writeOutput, varNameStrs, lbUsAll, ubUsAll, optimStartTic);\n\n                nomadOutput1 = @(iter, fval, x, state) NomadOptimizer.nomadIterFunWrapper(iter, fval, x, outputFnc, state, numVars);\n                nomadOutput2 = @(iter, fval, x) nomadOutput1(iter, fval, x, 'iter');\n                problem.options = nomadset(problem.options, 'iterfun',nomadOutput2);\n                nomadOutput1(0,NaN,x0All,'init');\n            end\n            \n            problem.UseParallel = useParallel;\n            [exitflag, message] = lvd_executeOptimProblem(celBodyData, writeOutput, problem, recorder, callOutputFcn);\n            \n            if(callOutputFcn)\n                close(handlesObsOptimGui.ma_ObserveOptimGUI);\n            end\n        end\n        \n        function options = getOptions(obj)\n            options = obj.options;\n        end\n        \n        function tf = usesParallel(obj)\n            tf = obj.getOptions().usesParallel();\n        end\n        \n        function numWorkers = getNumParaWorkers(obj)\n            numWorkers = obj.options.getNumParaWorkers();\n        end\n        \n        function openOptionsDialog(obj)\n%             lvd_editNomadOptionsGUI(obj);\n            \n            output = AppDesignerGUIOutput({false});\n            lvd_editNomadOptionsGUI_App(obj, output);\n        end\n    end\n    \n    methods(Static, Access=private)\n        function [f, stateLog] = nomadObjFuncWrapper(x, objFuncWrapper)\n            global nomadCachedX nomadCachedStateLog\n            \n            [f, stateLog] = objFuncWrapper(x);\n            \n            nomadCachedX = x;\n            nomadCachedStateLog = stateLog;\n        end\n        \n        function c = nomadConstrWrapper(x, nonlcon)\n            global nomadCachedX nomadCachedStateLog\n            \n            if(numel(x) ~= numel(nomadCachedX))\n                nomadCachedX = NaN(size(x));\n            end\n            \n            if(all(x(:) == nomadCachedX(:)))\n                [cM, ceqM] = nonlcon(x, false, nomadCachedStateLog);\n            else\n                [cM, ceqM] = nonlcon(x, true, []);\n            end\n            \n            c = [cM(:); ceqM(:); -1*ceqM(:)]';\n            c = c(:);\n        end\n        \n        function [fc, stateLogs] = nomadObjConstrWrapper(x, objFun, nonlcon, numVars, numElementsInEachOutput, M, lvdData)\n            try\n                if(numel(x) == numVars)\n                    numEvals = 1;\n                else\n                    numEvals = size(x,1);\n                end\n\n                x = reshape(x, numEvals, numel(x)/numEvals);\n\n                fc = NaN(numEvals,numElementsInEachOutput);\n\n                for(i=1:numEvals) %#ok<NO4LP>\n                    stateLogs(i) = LaunchVehicleStateLog(lvdData); %#ok<AGROW>\n                end\n\n                if(M > 0 && numEvals > 1)\n                    pp = gcp();\n                    opts = parforOptions(pp,'RangePartitionMethod','fixed','SubrangeSize',ceil(pp.NumWorkers/numEvals));\n                    parfor(i=1:numEvals,opts)\n                        xI = x(i,:);\n                        [fcRow, stateLog] = NomadOptimizer.loopInternal(xI, objFun, nonlcon);\n\n                        fc(i,:) = fcRow;\n                        stateLogs(i) = stateLog;\n                    end\n                else\n                    for(i=1:numEvals)\n                        xI = x(i,:);\n                        [fcRow, stateLog] = NomadOptimizer.loopInternal(xI, objFun, nonlcon);\n\n                        fc(i,:) = fcRow;\n                        stateLogs(i) = stateLog;\n                    end\n                end\n            catch ME\n                disp(ME.message);\n            end\n        end\n        \n        function [fcRow, stateLog] = loopInternal(xI, objFun, nonlcon)\n            [f, stateLog] = objFun(xI);\n            [c] = nonlcon(xI);\n\n            fcRow = [f; c(:);]';\n        end\n        \n        function stop = nomadIterFunWrapper(iter, fval, x, outputFnc, state, numVars)\n            if(numel(x) == numVars)\n                numEvals = 1;\n            else\n                numEvals = size(x,1);\n            end\n\n            x = reshape(x, numEvals, numel(x)/numEvals);\n            \n            f = fval(:,1);\n            c = fval(:,2:end);\n            \n            if(isempty(c))\n                [fval,I] = min(f);\n                cViol = 0;\n                xx = x(I,:);\n            else\n                c(c <= 0) = 0;\n                cViol = sqrt(sum(c.^2,2));\n                \n                [minViolation,I] = min(cViol);\n                \n                if(sum(cViol == minViolation) > 1)\n                    boolC = cViol == minViolation;\n                    fBool = f(boolC);\n                    [minFBool,~] = min(fBool);\n                    \n                    boolF = f == minFBool;\n                    II = find(boolF & boolC,1,'first');\n                    \n                    fval = f(II);\n                    cViol = minViolation;\n                    xx = x(II,:);\n                else\n                    fval = f(I);\n                    cViol = minViolation;\n                    xx = x(I,:);\n                end\n            end\n            \n            optimValues.constrviolation = max(cViol, 0);\n            optimValues.funccount = iter;\n            optimValues.fval = fval;\n            optimValues.iteration = iter;\n            optimValues.stepsize = 0;\n            optimValues.firstorderopt = 0;\n\n            stop = outputFnc(xx, optimValues, state);\n            stop = logical(stop);\n        end\n        \n        function stop = getOutputFunction(x, optimValues, state, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...\n                                                               objFcn, lb, ub, celBodyData, recorder, propNames, writeOutput, varLabels, lbUsAll, ubUsAll, optimStartTic)\n            switch state\n                case 'iter'\n                    stop = get(hCancelButton,'Value');\n\n                    recorder.iterNums(end+1) = optimValues.iteration;\n                    recorder.xVals(end+1) = {x};\n                    recorder.fVals(end+1) = optimValues.fval;            \n                    recorder.maxCVal(end+1) = optimValues.constrviolation;\n                case {'init','interrupt','done'}\n                    stop = get(hCancelButton,'Value');\n            end\n            \n            if(stop == true)\n                return;\n            end\n            \n            [~, stateLog] = objFcn(x);\n            \n%             finalStateLogEntry = stateLog.getFinalStateLogEntry();\n%             finalStateLogEntryMA = finalStateLogEntry.getMAFormattedStateLogMatrix(true);\n\n            stateLogMA = stateLog.getMAFormattedStateLogMatrix(true);\n            \n            if(strcmpi(state,'init') || strcmpi(state,'iter'))\n                NomadOptimizer.writeOptimStatus(hOptimStatusLabel, optimValues, state, writeOutput, optimStartTic);\n                ma_UpdateStateReadout(hFinalStateOptimLabel, 'final', propNames, stateLogMA, celBodyData);\n                NomadOptimizer.generatePlots(x, optimValues, state, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll);\n                drawnow;\n            end\n        end\n        \n        function writeOptimStatus(hOptimStatusLabel, optimValues, state, writeOutput, timer)\n            elapTime = toc(timer);\n\n            outStr = {};\n            outStr{end+1} = ['State                = ', state];\n            outStr{end+1} = '                        ';\n            outStr{end+1} = ['Iterations           = ', num2str(optimValues.iteration)];\n            outStr{end+1} = ['Function Evals       = ', num2str(optimValues.funccount)];\n            outStr{end+1} = ['Objective Value      = ', num2str(optimValues.fval)];\n            outStr{end+1} = ['Constraint Violation = ', num2str(optimValues.constrviolation)];\n            outStr{end+1} = '                       ';\n            outStr{end+1} = ['Elapsed Time         = ', num2str(elapTime), ' sec'];\n            \n            set(hOptimStatusLabel, 'String', outStr);\n            \n            switch state\n                case 'iter'\n                    formatstr = ' %- 12.1i %- 12.0i %- 12.6g %- 12.3g';\n\n                    iter = optimValues.iteration;\n                    fcnt = optimValues.funccount;\n                    val  = optimValues.fval;\n                    feas = optimValues.constrviolation;\n\n                    hRow = sprintf(formatstr,iter,fcnt,val,feas);\n                    writeOutput(hRow,'append');\n                case 'init'\n                    hdrStr = sprintf('%- 13s%- 13s%- 13s%- 13s', 'Iteration','Fcn-Count','f(x)-Value', 'Feasibility');\n                    writeOutput(hdrStr,'append');\n            end\n        end\n        \n        function generatePlots(x, optimValues, state, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll)\n            persistent fValPlotIsLog tLayout hPlot1 hPlot2 hPlot3\n\n            if(isempty(fValPlotIsLog))\n                fValPlotIsLog = true;\n            end\n\n            switch state\n                case 'init'\n                    if(isvalid(hDispAxes))\n%                         set(hDispAxes,'Visible','on');\n%                         subplot(hDispAxes);\n%                         axes(hDispAxes);\n                        tLayout = tiledlayout(hDispAxes, 3,1);\n                    end\n                    fValPlotIsLog = true;\n            end\n\n            hPlot1 = nexttile(tLayout, 1);\n            if(strcmpi(state,'init'))\n                \n                hPlot1.XTickLabel= [];\n                hPlot1.YTickLabel= [];\n                hPlot1.ZTickLabel= [];\n%                 axes(hPlot1);\n            else\n%                 axes(hPlot1);\n            end\n            optimplotxKsptot(x, optimValues, state, lb, ub, varLabels, lbUsAll, ubUsAll);\n\n            hPlot2 = nexttile(tLayout, 2);\n            if(strcmpi(state,'init'))\n                \n                hPlot2.XTickLabel= [];\n                hPlot2.YTickLabel= [];\n                hPlot2.ZTickLabel= [];\n                h = hPlot2;\n            else\n                h = hPlot2;\n%                 axes(hPlot2);\n            end\n            if(optimValues.fval<=0)\n                fValPlotIsLog = false;\n                set(h,'yscale','linear');\n            end\n            optimplotfvalKsptot(x, optimValues, state);\n            if(fValPlotIsLog)\n                set(h,'yscale','log');\n            else\n                set(h,'yscale','linear');\n            end\n            grid on;\n            grid minor;\n\n            hPlot3 = nexttile(tLayout, 3);\n            if(strcmpi(state,'init'))\n                hPlot3.XTickLabel= [];\n                hPlot3.YTickLabel= [];\n                hPlot3.ZTickLabel= [];\n                h = hPlot3;\n            else\n                h = hPlot3;\n%                 axes(hPlot3);\n            end\n            optimplotconstrviolationKsptot(x, optimValues, state);\n\n            if(not(isempty(h.Children)))\n                hLine = h.Children(1);\n                if(isa(hLine,'matlab.graphics.chart.primitive.Line'))\n                    yDataLine = hLine.YData;\n                    if(abs(max(yDataLine) / min(yDataLine)) >= 10 && all(yDataLine > 0))\n                        set(h,'yscale','log');\n                    else\n                        set(h,'yscale','linear');\n                    end\n                else\n                    set(h,'yscale','linear');\n                end\n            end\n\n            grid on;\n            grid minor;\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/optimizers/@NomadOptimizer/NomadOptimizer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20695010534741193}}
{"text": "classdef Generic3DTrajectoryViewType < AbstractTrajectoryViewType\n    %Inertial3DTrajectoryViewType Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n\n    end\n    \n    methods\n        function obj = Generic3DTrajectoryViewType()\n            \n        end\n        \n        function [hCBodySurf, childrenHGs] = plotStateLog(obj, orbitNumToPlot, lvdData, viewProfile, handles, app)\n%             dAxes = app.dispAxes;\n            dAxes = handles.dispAxes;\n            hFig = app.ma_LvdMainGUI;\n            celBodyData = lvdData.celBodyData;\n            stateLog = lvdData.stateLog;\n            \n%             axes(dAxes);\n%             cla(dAxes);\n%             cla(dAxes,'reset');\n            delete(dAxes.Children);\n            dAxes.Color = viewProfile.backgroundColor.color;\n            \n            hFig.Renderer = viewProfile.renderer.renderer;\n            if(viewProfile.renderer == FigureRendererEnum.OpenGL && ~isunix())\n                d = opengl('data');\n                if(strcmpi(d.HardwareSupportLevel,'full'))\n                    opengl hardware;\n                elseif(strcmpi(d.HardwareSupportLevel,'basic'))\n                    opengl hardwarebasic;\n                end\n            end\n            \n            hFig.GraphicsSmoothing = 'on';\n            \n            if(stateLog.getNumberOfEntries() == 0)\n                return;\n            end\n            \n            viewInFrame = viewProfile.frame;\n            viewCentralBody = viewInFrame.getOriginBody();\n            lvdStateLogEntries = LaunchVehicleStateLogEntry.empty(1,0);\n            switch viewProfile.trajEvtsViewType\n                case ViewEventsTypeEnum.SoIChunk\n                    entries = stateLog.getAllEntries();\n%                     maStateLog = stateLog.getMAFormattedStateLogMatrix(false);\n\n%                     chunkedStateLog = breakStateLogIntoSoIChunks(maStateLog);\n                    chunkedStateLog = stateLog.breakUpStateLogBySoIChunk();\n                    if(orbitNumToPlot > size(chunkedStateLog,1))\n                        orbitNumToPlot = size(chunkedStateLog,1);\n                        set(dAxes,'UserData',orbitNumToPlot);\n                    end\n                    subStateLogs = chunkedStateLog(orbitNumToPlot,:);\n                    \n                    bodyId = subStateLogs{1}(1,8);\n                    bodyInfo = celBodyData.getBodyInfoById(bodyId);\n                    evtIds = [];\n                    for(i=1:length(subStateLogs))\n                        subStateLog = subStateLogs{i};\n                        \n                        if(isempty(subStateLog))\n                            continue;\n                        end\n                        \n                        bodyId = subStateLog(1,8);\n                        bodyInfo = celBodyData.getBodyInfoById(bodyId);\n                        inertialFrame = bodyInfo.getBodyCenteredInertialFrame();\n                        \n                        elemSet = CartesianElementSet(subStateLog(:,1), subStateLog(:,2:4)', subStateLog(:,5:7)', inertialFrame);\n%                         elemSet = repmat(CartesianElementSet.getDefaultElements(), [1, size(subStateLog,1)]);\n%                         for(j=1:size(subStateLog,1))\n%                             elemSet(j) = CartesianElementSet(subStateLog(j,1), subStateLog(j,2:4)', subStateLog(j,5:7)', inertialFrame);\n%                         end\n                        elemSet = convertToFrame(elemSet, viewInFrame);\n\n                        subStateLog(:,2:4) = [elemSet.rVect]';\n                        subStateLog(:,5:7) = [elemSet.vVect]';\n                        \n                        evtIds = [evtIds, unique(subStateLog(:,13))']; %#ok<AGROW>\n                        \n                        subStateLogs{i} = subStateLog;\n                    end\n                    \n                    evtIds = unique(evtIds);\n                    for(i=1:length(entries))\n                        entry = entries(i);\n                        \n                        if(not(isempty(entry.event.getEventNum())) && ...\n                           ismember(entry.event.getEventNum(), evtIds) && ...\n                           entry.centralBody == bodyInfo)\n                            lvdStateLogEntries(end+1) = entry; %#ok<AGROW>\n                        end\n                    end\n\n                    numTotMissionSegs = size(chunkedStateLog,1);\n                    \n%                     curMissionSegStr = num2str(orbitNumToPlot);\n%                     totalMissionSegStr = num2str(numTotMissionSegs);\n                \n                    if(numTotMissionSegs <= 1)\n                        app.decrOrbitToPlotNum.Enable = 'off';\n                        app.incrOrbitToPlotNum.Enable = 'off';\n                    else\n                        app.decrOrbitToPlotNum.Enable = 'on';\n                        app.incrOrbitToPlotNum.Enable = 'on';\n                    end\n                case ViewEventsTypeEnum.All\n                    entries = stateLog.getAllEntries();\n                    maStateLogMatrix = stateLog.getMAFormattedStateLogMatrix(false);\n                    numRows = size(maStateLogMatrix,1);\n%                     subStateLogsMat = NaN(numRows, 13);\n                    \n                    cartesianEntry = convertToFrame(getCartesianElementSetRepresentation(entries, false),viewInFrame);\n                    times = [cartesianEntry.time]';\n                    rVect = [cartesianEntry.rVect]';\n                    vVect = [cartesianEntry.vVect]';\n                    bodyId = viewCentralBody.id + zeros(numRows,1);\n                    subStateLogsMat = [times, rVect, vVect, bodyId, maStateLogMatrix(:,9:13)];\n%                     for(i=1:numRows)\n%                         tempMaMatrix = entries(i).getMAFormattedStateLogMatrix(false);\n% \n%                         cartesianEntry = \n%                         cartesianEntry = cartesianEntry.convertToFrame(viewInFrame); \n% \n%                         subStateLogsMat(i,:) = [entries(i).time, cartesianEntry.rVect', cartesianEntry.vVect', viewCentralBody.id, maStateLogMatrix(i,9:13)];\n%                     end\n\n                    subStateLogs = {};\n                    for(evtNum=1:max(subStateLogsMat(:,13)))\n                        subStateLogs{evtNum} = subStateLogsMat(subStateLogsMat(:,13) == evtNum,:); %#ok<AGROW>\n                    end\n\n%                     curMissionSegStr = num2str(1);\n%                     totalMissionSegStr = num2str(1);\n                    \n                    lvdStateLogEntries = entries;\n                otherwise\n                    error('Unknown trajectory view type when plotting trajectory: %s', viewProfile.frame.name);\n            end\n                                  \n            eventsList = [];\n            minTime = Inf;\n            maxTime = -Inf;\n            for(i=1:length(subStateLogs))\n                if(~isempty(subStateLogs{i}))\n                    eventsList = [eventsList;unique(subStateLogs{i}(:,13))]; %#ok<AGROW>\n                end\n                if(i>1)\n                    prevSubStateLog = subStateLogs{i-1};\n                else\n                    prevSubStateLog = NaN(1,size(subStateLogs{i},2));\n                end\n\n                if(size(subStateLogs{i},1)>1)\n                    [childrenHGs] = plotSubStateLog(subStateLogs{i}, prevSubStateLog, lvdData, dAxes);\n                    \n                    minTime = min([minTime, min(subStateLogs{i}(:,1))]);\n                    maxTime = max([maxTime, max(subStateLogs{i}(:,1))]);\n                end\n            end\n                       \n            if(viewInFrame.typeEnum == ReferenceFrameEnum.BodyFixedRotating && ...\n               viewProfile.showLongLatAnnotations)\n                plotBodyFixedGrid(dAxes, viewCentralBody);\n            end\n            \n            showSoI = viewProfile.showSoIRadius;\n            \n            if(viewProfile.showThrustVectors)\n                entryInc = viewProfile.thrustVectEntryIncr;\n                scale = viewProfile.thrustVectScale;\n                color = viewProfile.thrustVectColor.color;\n                lineStyle = viewProfile.thrustVectLineType.linespec;\n                \n                subsetLvdStateLogEntries = lvdStateLogEntries(1:entryInc:length(lvdStateLogEntries));\n                subsetLvdStateLogEntries = subsetLvdStateLogEntries(:)';\n                cartesianEntries = convertToFrame(getCartesianElementSetRepresentation(subsetLvdStateLogEntries), viewInFrame);\n                \n                rVects = [cartesianEntries.rVect];\n                tVects = [];\n                \n                [~, ~, ~, rotMatToInertial12] = viewInFrame.getOffsetsWrtInertialOrigin([cartesianEntries.time], cartesianEntries);\n                for(i=1:length(subsetLvdStateLogEntries)) %#ok<*NO4LP>\n                    entry = subsetLvdStateLogEntries(i);\n                    cartesianEntry = cartesianEntries(i);       \n                    \n                    tVect = lvd_ThrottleTask(entry, 'thrust_vector', cartesianEntry.frame);\n                    \n                    if(norm(tVect) > 0)                       \n                        [~, ~, ~, rotMatToInertial32] = entry.centralBody.getBodyCenteredInertialFrame().getOffsetsWrtInertialOrigin(entry.time, cartesianEntry);\n                        \n                        tVectNew = rotMatToInertial32 * rotMatToInertial12(:,:,i)' * tVect;\n                    else\n                        tVectNew = [0;0;0];\n                    end\n                    \n                    tVects = [tVects, tVectNew]; %#ok<AGROW>\n                end\n                \n                tVects = scale .* tVects;\n                \n                hold(dAxes,'on');\n                quiver3(dAxes, rVects(1,:),rVects(2,:),rVects(3,:), tVects(1,:),tVects(2,:),tVects(3,:), 0, 'Color',color, 'LineStyle',lineStyle);\n                hold(dAxes,'off');\n            end\n\n%             lfm = LiftForceModel();\n%             rVects = NaN([3, length(lvdStateLogEntries)]);\n%             forceVect = NaN([3, length(lvdStateLogEntries)]);\n%             for(i=1:length(lvdStateLogEntries))\n%                 stateLogEntry = lvdStateLogEntries(i);\n% \n%                 bodyInfo = stateLogEntry.centralBody;\n%                 ut = stateLogEntry.time;\n%                 rVect = stateLogEntry.position;\n%                 vVect = stateLogEntry.velocity;\n%                 aero = stateLogEntry.aero;\n%                 mass = stateLogEntry.getTotalVehicleMass();\n%                 attState = stateLogEntry.attitude;\n% \n%                 rVects(:,i) = rVect;\n%                 force = lfm.getForce(ut, rVect, vVect, mass, bodyInfo, aero, [], [], [], [], [], [], [], [], [], [], attState);\n%                 forceVect(:,i) = 1000*force;\n%             end\n% \n%             hold(dAxes,'on');\n%             quiver3(dAxes, rVects(1,:),rVects(2,:),rVects(3,:), forceVect(1,:),forceVect(2,:),forceVect(3,:), 0, 'Color','c', 'LineStyle','-');\n%             hold(dAxes,'off');\n\n            if(showSoI && ~isempty(viewCentralBody.getParBodyInfo(celBodyData)))\n                hold(dAxes,'on');\n                \n                r = getSOIRadius(viewCentralBody, viewCentralBody.getParBodyInfo(celBodyData));\n\n                x = r*sin(0:0.01:2*pi);\n                y = r*cos(0:0.01:2*pi);\n                z = zeros(size(x));\n                plot3(dAxes, x, y, z, 'k--','LineWidth',0.5);\n                plot3(dAxes, y, z, x, 'k--','LineWidth',0.5);\n                plot3(dAxes, z, x, y, 'k--','LineWidth',0.5);\n                \n                hold(dAxes,'off');\n            end\n                       \n            if(viewProfile.dispXAxis || viewProfile.dispYAxis || viewProfile.dispZAxis)\n                axisLength = 2*viewCentralBody.radius;\n                \n                hold(dAxes,'on');\n                if(viewProfile.dispXAxis)\n                    quiver3(dAxes, 0,0,0, axisLength,0,0, 'r', 'LineWidth',2);\n                end\n                \n                if(viewProfile.dispYAxis)\n                    quiver3(dAxes, 0,0,0, 0,axisLength,0, 'g', 'LineWidth',2);\n                end\n                \n                if(viewProfile.dispZAxis)\n                    quiver3(dAxes, 0,0,0, 0,0,axisLength, 'b', 'LineWidth',2);\n                end\n                hold(dAxes,'off');\n            end\n                                    \n            %plot central body\n            [hCBodySurf, hCBodySurfXForm] = ma_initOrbPlot(hFig, dAxes, viewCentralBody);\n            hCBodySurf.EdgeAlpha = viewProfile.meshEdgeAlpha; \n  \n            if(viewProfile.showAtmosphere && viewCentralBody.atmohgt > 0)\n                hold(dAxes,'on');\n                atmoRadius = viewCentralBody.radius + viewCentralBody.atmohgt;\n                [X,Y,Z] = sphere(50);\n                hCBodySurf = surf(dAxes, atmoRadius*X,atmoRadius*Y,atmoRadius*Z, 'BackFaceLighting','lit', 'FaceLighting','gouraud', 'FaceColor',[223 223 223]/255, 'FaceAlpha',0.2, 'EdgeLighting','gouraud', 'LineWidth',0.1, 'EdgeColor','none');\n                hold(dAxes,'off');\n            end\n            \n            eventsList = unique(eventsList);\n            minEventNum = min(eventsList);\n            maxEventNum = max(eventsList);\n            \n            if(minEventNum < maxEventNum)\n                eventStr = ['Events ', num2str(minEventNum), ' - ', num2str(maxEventNum)];\n            else\n                eventStr = ['Event ', num2str(minEventNum)];\n            end\n            \n            hDispAxisTitleLabel = handles.dispAxisTitleLabel;\n            titleStr = sprintf('%s Orbit -- %s\\n%s', viewCentralBody.name, eventStr, viewInFrame.getNameStr());\n            hDispAxisTitleLabel.String = titleStr;\n            hDispAxisTitleLabel.TooltipString = sprintf('Frame: %s', viewInFrame.getNameStr());\n            \n            set(dAxes,'LineWidth',1);\n            set(dAxes,'Box','on');\n            grid(dAxes,viewProfile.gridType.gridStr);\n            dAxes.GridColor = viewProfile.majorGridColor.color;\n            dAxes.MinorGridColor = viewProfile.minorGridColor.color;\n            dAxes.GridAlpha = viewProfile.gridTransparency;\n%             axis(dAxes,'equal');\n%             axis(dAxes,'tight');\n            \n%             xlabel(dAxes, '');\n%             ylabel(dAxes, '');\n            \n            set(dAxes,'XTickLabel',[]);\n            set(dAxes,'YTickLabel',[]);\n            set(dAxes,'ZTickLabel',[]);\n            \n            hold(dAxes,'off');\n            \n            if(not(viewProfile.updateViewAxesLimits))\n%                 setappdata(handles.ma_LvdMainGUI,'dispOrbitXLim',xlim(dAxes));\n%                 setappdata(handles.ma_LvdMainGUI,'dispOrbitYLim',ylim(dAxes));\n%                 setappdata(handles.ma_LvdMainGUI,'dispOrbitZLim',zlim(dAxes));\n                \n%                 zoom reset;\n                \n%                 view(dAxes,viewProfile.viewAzEl);\n                \n                camPos = viewProfile.viewCameraPosition;\n                camTgt = viewProfile.viewCameraTarget;\n                camUpVec = viewProfile.viewCameraUpVector;\n                camVA = viewProfile.viewCameraViewAngle;\n                if(not(any(isnan(camPos))))\n                    dAxes.CameraPosition = camPos;\n                end\n                \n                if(not(any(isnan(camTgt))))\n                    dAxes.CameraTarget = camTgt;\n                end\n                \n                if(not(any(isnan(camUpVec))))\n                    dAxes.CameraUpVector = camUpVec;\n                end\n                \n                if(not(any(isnan(camVA))))\n                    dAxes.CameraViewAngle = camVA;\n                end\n                \n%                 if(any(isnan(viewProfile.viewZoomAxLims)))\n%                     viewProfile.viewZoomAxLims = [xlim(dAxes);\n%                                                   ylim(dAxes);\n%                                                   zlim(dAxes)];\n%                 else\n%                     dAxes.XLim = viewProfile.viewZoomAxLims(1,:);\n%                     dAxes.YLim = viewProfile.viewZoomAxLims(2,:);\n%                     dAxes.ZLim = viewProfile.viewZoomAxLims(3,:);\n%                 end\n%                 \n            else\n                cameratoolbar('ResetCamera');\n                view(dAxes, 3);\n            end\n                        \n            vehPosVelData = LaunchVehicleViewProfile.createVehPosVelData(subStateLogs, lvdData.script.evts, viewInFrame);\n            vehAttData = LaunchVehicleViewProfile.createVehAttitudeData(vehPosVelData, lvdStateLogEntries, lvdData.script.evts, viewInFrame);\n            \n            hold(dAxes,'on');\n            viewProfile.createBodyMarkerData(dAxes, subStateLogs, viewInFrame, showSoI, viewProfile.meshEdgeAlpha, lvdData.script.evts);           \n            viewProfile.createTrajectoryMarkerData(subStateLogs, lvdData.script.evts);\n            viewProfile.createBodyAxesData(vehPosVelData, vehAttData); %lvdStateLogEntries, lvdData.script.evts, viewInFrame\n            viewProfile.createSunLightSrc(dAxes, viewInFrame);\n            viewProfile.createGroundObjMarkerData(dAxes, lvdStateLogEntries, vehPosVelData, lvdData.script.evts, viewInFrame, celBodyData);\n            viewProfile.createCentralBodyData(viewCentralBody, hCBodySurfXForm, viewInFrame);\n            viewProfile.createPointData(viewInFrame, subStateLogs, lvdData.script.evts);           \n            viewProfile.createVectorData(viewInFrame, subStateLogs, lvdData.script.evts);\n            viewProfile.createRefFrameData(viewInFrame, subStateLogs, lvdData.script.evts);\n            viewProfile.createAngleData(viewInFrame, subStateLogs, lvdData.script.evts);\n            viewProfile.createPlaneData(viewInFrame, subStateLogs, lvdData.script.evts);           \n            viewProfile.createSensorData(lvdStateLogEntries, vehPosVelData, vehAttData, viewInFrame);\n            viewProfile.createSensorTargetData(viewInFrame);\n            \n            viewProfile.configureTimeSlider(minTime, maxTime, subStateLogs, handles, app);\n            hold(dAxes,'off');\n\n            switch viewProfile.projType\n                case ViewProjectionTypeEnum.Orthographic\n                    camproj(dAxes, 'orthographic');\n    \n                case ViewProjectionTypeEnum.Perspective\n                    camproj(dAxes, 'perspective');\n\n                otherwise\n                    error('Unknown projection type: %s', viewProfile.projType.name);\n\n            end\n        end\n    end\nend\n\nfunction [childrenHGs] = plotSubStateLog(subStateLog, prevSubStateLog, lvdData, dAxes)    \n    if(isempty(subStateLog))\n        childrenHGs = [];\n        return;\n    end\n    \n%     bodyID = subStateLog(1,8);\n%     bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);\n\n    eventNum = subStateLog(1,13);\n    event = lvdData.script.getEventForInd(eventNum);\n    if(isempty(event))\n        childrenHGs = [];\n        return;\n    end\n    \n    plotLineColor = event.colorLineSpec.color.color;\n    plotLineStyle = event.colorLineSpec.lineSpec.linespec;\n    plotLineWidth = event.colorLineSpec.lineWidth;\n    plotMarkerType = event.colorLineSpec.markerSpec.shape;\n    plotMarkerSize = event.colorLineSpec.markerSize;\n    plotMethodEnum = event.plotMethod;\n\n    hold(dAxes,'on');\n    \n    switch plotMethodEnum\n        case EventPlottingMethodEnum.PlotContinuous\n            t = [prevSubStateLog(end,1);subStateLog(1:end,1)];\n            x = [prevSubStateLog(end,2);subStateLog(1:end,2)];\n            y = [prevSubStateLog(end,3);subStateLog(1:end,3)];\n            z = [prevSubStateLog(end,4);subStateLog(1:end,4)];\n\n            [~,I] = sort(t);\n            x = x(I);\n            y = y(I);\n            z = z(I);\n\n        case EventPlottingMethodEnum.SkipFirstState\n            x = subStateLog(2:end,2);\n            y = subStateLog(2:end,3);\n            z = subStateLog(2:end,4);\n        case EventPlottingMethodEnum.DoNotPlot\n            x = [];\n            y = [];\n            z = [];\n        otherwise\n            error('Unknown event plotting method enum: %s', plotMethodEnum.name);\n    end\n\n    plot3(dAxes, x, y, z, 'Color', plotLineColor, 'LineStyle', plotLineStyle, 'LineWidth',plotLineWidth, 'Marker',plotMarkerType, 'MarkerSize',plotMarkerSize, 'MarkerEdgeColor','none', 'MarkerFaceColor',plotLineColor);   \n    childrenHGs = cell(0,4);\nend\n\nfunction plotBodyFixedGrid(dAxes, bodyInfo)\n    r = 1.2*bodyInfo.radius;\n    rTxt = 1.3*bodyInfo.radius;\n\n    %draw longitude circle and text\n    th = linspace(0, 2*pi, 100);\n    xunit = r * cos(th);\n    yunit = r * sin(th);\n    patch(dAxes, 'XData',xunit,'YData',yunit, 'FaceColor', 'k', 'FaceAlpha',0.15);\n\n    th = linspace(0,2*pi - (1/12)*2*pi, 12);\n    xunit = r * cos(th);\n    yunit = r * sin(th);\n\n    xToPlot = [];\n    yToPlot = [];\n    for(i=1:length(th))\n        xToPlot = [xToPlot, 0, xunit(i), NaN]; %#ok<AGROW>\n        yToPlot = [yToPlot, 0, yunit(i), NaN]; %#ok<AGROW>\n    end\n\n    plot(dAxes, xToPlot, yToPlot, 'k');\n\n    xunitTxt = rTxt * cos(th);\n    yunitTxt = rTxt * sin(th);\n\n    for(i=1:length(xunitTxt))\n        text(dAxes, xunitTxt(i),yunitTxt(i),sprintf('%.0f%s', rad2deg(th(i)), char(176)));\n    end\n\n    %draw latitude circle and text\n    th = linspace(-pi/2, pi/2, 100);\n    xunit = r * cos(th);\n    yunit = zeros(size(th));\n    zunit = r * sin(th);\n    patch(dAxes, 'XData',xunit,'YData',yunit,'ZData',zunit, 'FaceColor', 'k', 'FaceAlpha',0.15);\n\n    th = rad2deg(linspace(-pi/2, pi/2, 7));\n    xunit = r * cosd(th);\n    yunit = zeros(size(th));\n    zunit = r * sind(th);\n\n    xToPlot = [];\n    yToPlot = [];\n    zToPlot = [];\n    for(i=1:length(th))\n        xToPlot = [xToPlot, 0, xunit(i), NaN]; %#ok<AGROW>\n        yToPlot = [yToPlot, 0, yunit(i), NaN]; %#ok<AGROW>\n        zToPlot = [zToPlot, 0, zunit(i), NaN]; %#ok<AGROW>\n    end\n\n    plot3(dAxes, xToPlot, yToPlot, zToPlot, 'k');\n\n    xunitTxt = rTxt * cosd(th);\n    yunitTxt = zeros(size(th));\n    zunitTxt = rTxt * sind(th);\n\n    for(i=1:length(xunitTxt))\n        text(dAxes, xunitTxt(i),yunitTxt(i),zunitTxt(i), sprintf('%.0f%s', th(i), char(176)));\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/View/viewTypes/@Generic3DTrajectoryViewType/Generic3DTrajectoryViewType.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2068856932774793}}
{"text": "% MSH_TO_VTK: Export to VTK format for plotting.\n%\n%  MSH_to_vtk (pts, values, filename, fieldnames)\n%\n% INPUT:\n%\n%     pts:        points at which the field was computed\n%     values:     cell-array, with values of the fields at the selected points\n%     filename:   name of the output file\n%     fieldnames: how to name the saved variables in the vtk file\n%\n% OUTPUT:\n%\n%    a vtk structured mesh file named <filename> is produced \n% \n% Copyright (C) 2009, 2010 Carlo de Falco, Rafael Vazquez\n% Copyright (C) 2011, 2015 Rafael Vazquez\n%\n%    This program is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n\n%    This program is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction msh_to_vtk (pts, values, filename, fieldnames)\n\n  if (iscell (values))\n    if (numel (values) ~= numel (fieldnames))\n      error ('The number of fields and the number of names should be the same')\n    end\n  else\n    values = {values};\n    if (~iscell (fieldnames))\n      fieldnames = {fieldnames};\n    end\n  end\n\n  ndim = numel (size (pts)) - 1;\n  rdim = size (pts, 1);\n  \n  str1 = cat (2,'<?xml version=\"1.0\"?> \\n', ...\n'<VTKFile type=\"StructuredGrid\" version=\"0.1\"> \\n', ...\n'<StructuredGrid WholeExtent=\"0 %d 0 %d 0 %d\"> \\n', ...\n'<Piece Extent=\"0 %d 0 %d 0 %d\"> \\n', ...\n'<PointData>\\n');\n\n  str1b = cat (2, ...\n'<DataArray type=\"Float32\" Name=\"%s\" format=\"ascii\" NumberOfComponents=\"%d\"> \\n');\n\n  str1c = cat (2,'</DataArray> \\n');\n\n  str2 = cat (2,'</PointData> \\n', ...\n'<Points> \\n', ...\n'<DataArray type=\"Float32\" NumberOfComponents=\"3\"> \\n');\n\n  str3 = cat (2, '\\n', ...\n'</DataArray>\\n', ...\n'</Points> \\n', ...\n'</Piece> \\n', ...\n'</StructuredGrid> \\n', ...\n'</VTKFile> \\n');\n\n% Even for 2D data, everything is saved in 3D \n% ndims (or size) do not work properly for the 1D case. I remove singleton\n% dimensions using this trick\n\n  size_pts = size (pts);\n  npts = size_pts (2:end);\n  \n  if (ndim < 3)\n    npts (ndim+1:3) = 1;\n  end\n  if (rdim < 3)\n    pts(ndim+1:3,:,:) = 0;\n  end\n\n  if (length (filename) < 4 || ~strcmp (filename(end-3:end), '.vts'))\n    filename = cat (2, filename, '.vts');\n  end\n\n  fid = fopen (filename, 'w');\n  if (fid < 0)\n    error ('msh_to_vtk: could not open file %s', filename);\n  end\n\n  fprintf (fid, str1, ...\n           npts(1)-1, npts(2)-1, npts(3)-1, ...\n           npts(1)-1, npts(2)-1, npts(3)-1);\n\n  for iopt = 1:numel(values)\n    if (sum (size (values{iopt}) > 1) == ndim)\n      ncomp = 1;\n    elseif (sum (size (values{iopt}) > 1) == ndim + 1)\n      ncomp = 3;\n    else\n      ncomp = 9;\n    end\n    if (ncomp == 3 && rdim < 3)\n      values{iopt}(rdim+1:3,:,:) = 0;\n    elseif (ncomp == 9 && rdim < 3)\n      values{iopt}(rdim+1:3,rdim+1:3,:,:) = 0;\n    end\n    fprintf (fid, str1b, fieldnames{iopt}, ncomp);\n    fprintf (fid, '%g ', values{iopt}(:));\n    fprintf (fid, str1c);\n  end\n  fprintf (fid, str2);\n  fprintf (fid, '%g ', pts(:));\n  fprintf (fid, str3);\n\n  fclose (fid);\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/utils/msh_to_vtk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20684873326051081}}
{"text": "%SPH   Implement spherical IBVS for point features\n%\n%  results = sph(T)\n%  results = sph(T, params)\n%\n%  Simulate IBVS with for a square target comprising 4 points is placed \n%  in the world XY plane. The camera/robot is initially at pose T and is\n%  driven to the orgin.\n%\n%  Two windows are shown and animated:\n%   1. The camera view, showing the desired view (*) and the \n%      current view (o)\n%   2. The external view, showing the target points and the camera\n%\n% The results structure contains time-history information about the image\n% plane, camera pose, error, Jacobian condition number, error norm, image\n% plane size and desired feature locations.\n%\n% The params structure can be used to override simulation defaults by\n% providing elements, defaults in parentheses:\n%\n%   target_size    - the side length of the target in world units (0.5)\n%   target_center  - center of the target in world coords (0,0,2)\n%   niter          - the number of iterations to run the simulation (500)\n%   eterm          - a stopping criteria on feature error norm (0)\n%   lambda         - gain, can be scalar or diagonal 6x6 matrix (0.01)\n%   ci             - camera intrinsic structure (camparam)\n%   depth          - depth of points to use for Jacobian, scalar for\n%                    all points, of 4-vector.  If null take actual value\n%                    from simulation      ([])\n%\n% SEE ALSO: ibvsplot\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n% IMPLEMENTATION NOTE\n%\n% 1.  As per task function notation (Chaumette papers) the error is\n%     defined as actual-demand, the reverse of normal control system\n%     notation.\n% 2.  The gain, lambda, is always positive\n% 3.  The negative sign is written into the control law\n\nfunction results = sph(T0, params)\n\n    %% default parameters\n    \n    % define default target geometry\n    vw = 2; vh = 2;       % dimensions of target\n    Tct_star = transl(0, 0, -2);    % desired pose of target wrt camera\n\n    % define default IBVS parameters\n    niter = 500;            % number of iterations\n    eterm = 0;\n    lambda = 0.04;         % control gain\n    cam = scamera;\n    depth = [];\n    estim = [];\n    \n    if nargin == 2,\n        % override default target size\n        if isfield(params, 'target_size'),\n            vw = params.target_size(1);\n            vh = params.target_height(1);\n        end\n        % override default camera desired pose\n        if isfield(params, 'target_center'),\n            Tct_star = params.Tct_star;\n        end\n        % override default number of iterations\n        if isfield(params, 'niter'),\n            niter = params.niter;\n        end\n        % override default gain (can be scalar or diag 6x6)\n        if isfield(params, 'lambda'),\n            lambda = params.lambda;\n        end\n        % override default camera intrinsics\n        if isfield(params, 'ci'),\n            ci = params.ci;\n        end\n        % override default point depth\n        if isfield(params, 'depth'),\n            if length(params.depth) == 1,\n                depth = params.depth * ones(4,1);\n            else\n                depth = params.depth;\n            end\n        end\n        if isfield(params, 'estim'),\n            estim = params.estim;\n        end\n    end\n\n    % define feature points in XY plane\n    %  make vertices of a square\n    P = mkgrid(2, [vw vh]);\n    \n    % show the reference location, this is the view we wish to achieve\n    % when Tc = Tct_star\n    figure(1)\n    clf\n    P\n    Tct_star\n    % HACKuv_star = cam.plot(P, inv(Tct_star));    % create the camera view\n    uv_star = cam.plot(P, (Tct_star));    % create the camera view\n    k=1\n    plot(uv_star(2,k), uv_star(1,k), '*');\n    hold on\n    for k=2:4\n        plot(uv_star(2,k), uv_star(1,k), '*');\n    end\n    %plot(uv_star(:,1), uv_star(:,2), '*');  % show desired view\n    %hold off\n    %cam.plot(P, T0);    % show initial view\n    pause(1)\n\n    % this is the 'external' view of the points and the camera\n    figure(2)\n    plot3(P(1,:), P(2,:), P(3,:), '*')\n    showcam(T0, P)\n    grid\n    xlabel('x');\n    ylabel('y');\n    zlabel('z');\n    pause\n    figure(1)\n    %cam2 = showcamera(T0);\n    %camup([0,-1,0]);\n\n    %% initialize the vservo variables\n\n    Tcam = T0;                % initial camera/robot pose\n\n    % initialize some history variables, suffix _h, to hold time series data\n    % about the IBVS run\n    v_h = [];       % velocity demand to robot\n    e_h = [];       % feature error\n    en_h = [];      % scalar norm of the feature error\n    c_h = [];       % Jacobian condition number\n    uv_h = [];      % image plane feature coordinates\n    Tcam_h = [];\n    Z_h = [];\n    PP = eye(1,1);\n    theta = 0;\n    smoothing = 0.95;\n\n    for k=1:niter,\n         % set and show the camera pose\n        cam.Tcam = Tcam;\n        %showcamera(cam2, Tcam);\n        figure(2)\n        plot3(P(1,:), P(2,:), P(3,:), '*')\n        grid on\n        xlabel('x');\n        ylabel('y');\n        zlabel('z');\n        showcam(Tcam, P);\n        figure(1)\n        \n        % compute the view\n        uv = cam.plot(P);\n\n        e = uv - uv_star;   % as per task function notation\n        uv\n        uv_star\n        e\n        if 1\n            for i=1:numcols(e)\n                % vectorize this\n                if e(2,i) > pi\n                    e(2,i) = e(2,i) - 2*pi;\n                elseif e(2,i) < -pi\n                    e(2,i) = 2*pi + e(2,i);\n                end\n            end\n        end\n        e\n        e = reshape(e, numel(e), 1);\n        \n        if estim,\n            % run the depth estimator\n            if k > 1,\n\n                % compute Jacobian for unit depth, r=1\n                J = jac(uv, ones(numcols(uv),1));\n                Jv = J(:,1:3);  % velocity part, depends on 1/z\n                Jw = J(:,4:6);  % rotational part, indepedent of 1/z\n\n                % estimate image plane velocity\n                uv_d =  reshape(uv, 1, [])' - reshape(uv_p, 1, [])';\n                \n                % estimate coefficients for A (1/z) = B\n                B = uv_d - Jw*v(4:6);\n                A = Jv * v(1:3);\n\n                eta = A\\B;          % least squares solution\n                \n                % first order smoothing\n                theta = (1-smoothing) * 1/eta + smoothing * theta;\n\n                pt = transformp(inv(Tcam), P);\n\n                fprintf('depth %.4g, est depth %.4g, rls depth %.4g\\n', pt(3,1), 1/eta, theta);\n                Z_h(k,:) = [theta pt(3,1)];   % estimated depth, true depth\n            end\n            uv_p = uv;\n        end\n        \n        \n        % compute the Jacobian\n        if isempty(depth),\n            % exact depth from simulation (not possible in practice)\n            pt = transformp(inv(Tcam), P);\n            J = jac(uv, colnorm(pt) );\n        else\n            J = jac(uv, depth );\n        end\n        J\n\n        % compute the velocity of camera in camera frame\n\n        v = -lambda * pinv(J) * e;\n        fprintf('v: %.3f %.3f %.3f %.3f %.3f %.3f\\n', v);\n        norm(e)\n\n        % update the camera pose\n        Td = (eye(4,4) + delta2tr( v ) );    % differential motion\n        Td = trnorm(Td);\n\n        Tcam = Tcam * Td;       % apply it to current pose\n\n        % update the history variables\n        uv_h(k,:) = reshape(uv([2 1],:), 1, []);\n        e_h(k,:) = e';\n        en_h(k,:) = norm(e);   \n        c_h(k,:) = cond(J);\n        v_h(k,:) = v';\n        Tcam_h(:,:,k) = Tcam;\n        \n        if norm(e) < eterm,\n            fprintf('completed on error tolerance\\n');\n            break;\n        end\n        drawnow\n        pause(0.05)\n        pause\n    end\n    fprintf('completed on iteration count\\n');\n    \n    results.uv = uv_h;\n    results.uv_labels = {'\\phi (rad)', '\\theta (rad)'};\n    results.c = c_h;\n    results.e = e_h;\n    results.en = en_h;\n    results.v = v_h;\n    results.Tcam = Tcam_h;\n    %results.limits = [0 cam.nu 0 cam.nv];\n    results.limits = [-pi pi 0 pi];\n    results.uv_star = uv_star([2 1],:);\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/@SphericalCamera/sph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20684873326051081}}
{"text": "\ndata = caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('data')).get_data();\nrois = squeeze(caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('rois')).get_data());\nlabels = squeeze(caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('labels')).get_data());\nbbox_targets = squeeze(caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('bbox_targets')).get_data());\nbbox_loss_weights = squeeze(caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('bbox_loss_weights')).get_data());\ncls_score = squeeze(caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('cls_score')).get_data());\n\n\nscores = squeeze(caffe_solver.net.blobs('cls_score').get_data());\nclasses = [{'bg'} imdb_train{1}.classes];\nfigure(1);\nfor k = 1:size(data,4)\n\n  img = permute((data(:,:,:,k)+128)/256, [2 1 3 4 5 6]);\n  img_ = img(:,:, [3 2 1]);\ninds = rois(1,:)==k-1;\n  boxes = rois(2:end,inds)';\n  \n  bbox_reg_boxes = find( bbox_loss_weights(5,inds) > 0 ) ;\n  bbox_reg_weights = bbox_targets(:,bbox_reg_boxes) ;\n\n  boxes_cell = {boxes(bbox_reg_boxes,:)};\n          \n  subplot(1,size(data,4),k); \n  try\n    track_deltas = caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('bbox_disp')).get_data();\n    track_boxes = caffe_solver.net.blob_vec(caffe_solver.net.name2blob_index('rois_disp')).get_data();\n    track_boxes = squeeze(track_boxes)' +1;\n    pred_boxes = rfcn_bbox_transform_inv(track_boxes(:,2:end), squeeze(track_deltas)');\n    pred_boxes = pred_boxes(:, 5:end);\n    if k==track_boxes(1),   boxes_cell = {track_boxes(:,2:end)};\n    else\n       boxes_cell = {pred_boxes};\n    end\n  catch\n  end\n  this_scrs = scores(:,inds);\n  [votes,predictions] = sort(this_scrs(:,bbox_reg_boxes), 1, 'descend') ;\n        top5pred =  squeeze(predictions(1:5,:));\n        highest_class_names = strrep(classes(top5pred), '_', '\\_');\n\n  if size(img,3) > 3\n    subplot(2,2,1);showboxes(img_, boxes_cell);\n    subplot(2,2,2); image(img(:,:,[4 : 6],:)); axis image;\n    if size(img,3) > 10\n      subplot(2,2,3); image(img(:,:,[7 : 9],:)); axis image;\n      subplot(2,2,4); image(img(:,:,[9 : 11],:)); axis image;\n    end\n  else\n    showboxes(img_, boxes_cell);\n  end\n  title(['top5 classes=' highest_class_names{1:5} ]);\n\nend\n", "meta": {"author": "feichtenhofer", "repo": "Detect-Track", "sha": "e013785dc229ff3d60e7cad69858ae0a4e384fe2", "save_path": "github-repos/MATLAB/feichtenhofer-Detect-Track", "path": "github-repos/MATLAB/feichtenhofer-Detect-Track/Detect-Track-e013785dc229ff3d60e7cad69858ae0a4e384fe2/utils/vis_inputs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.20683897200071807}}
{"text": "% POP_INTERP - interpolate data channels\n%\n% Usage: EEGOUT = pop_interp(EEG, badchans, method, t_range);\n%\n% Inputs: \n%     EEG      - EEGLAB dataset\n%     badchans - [integer array] indices of channels to interpolate.\n%                For instance, these channels might be bad.\n%                [chanlocs structure] channel location structure containing\n%                either locations of channels to interpolate or a full\n%                channel structure (missing channels in the current \n%                dataset are interpolated).\n%     method   - [string] method used for interpolation (default is 'spherical').\n%                'invdist'/'v4' uses inverse distance on the scalp\n%                'spherical' uses superfast spherical interpolation. \n%                'spacetime' uses griddata3 to interpolate both in space \n%                and time (very slow and cannot be interrupted).\n%     t_range  - [integer array with just two elements] time interval of the\n%                badchans which should be interpolated. First element is\n%                the start time and the second element is the end time.\n% Output: \n%     EEGOUT   - data set with bad electrode data replaced by\n%                interpolated data\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2009-\n\n% Copyright (C) Arnaud Delorme, CERCO, 2009, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [EEG com] = pop_interp(EEG, bad_elec, method, t_range)\n\n    com = '';\n    t_range = '';\n    if nargin < 1\n        help pop_interp;\n        return;\n    end\n    if nargin > 1 && nargin < 3\n        method = 'spherical';\n    end\n    \n    if nargin < 2\n        disp('Warning: interpolation can be done on the fly in studies'); \n        disp('         this function will actually create channels in the dataset'); \n        disp('Warning: do not interpolate channels before running ICA'); \n        disp('You may define channel location to interpolate in the channel'); \n        disp('editor and declare such channels as non-data channels'); \n         \n        enablenondat = 'off';\n        if isfield(EEG.chaninfo, 'removedchans')\n            if ~isempty(EEG.chaninfo.removedchans)\n                enablenondat = 'on';\n            end\n        end\n        if isempty(EEG.epoch)\n            uilist = { { 'Style' 'text' 'string' 'What channel(s) do you want to interpolate' 'fontweight' 'bold' } ...\n                       { 'style' 'text' 'string' 'none selected' 'tag' 'chanlist' } ...\n                       { 'style' 'pushbutton' 'string' 'Select from removed channels' 'callback' 'pop_interp(''nondatchan'',gcbf);' 'enable' enablenondat } ...                   \n                       { 'style' 'pushbutton' 'string' 'Select from data channels'    'callback' 'pop_interp(''datchan'',gcbf);' } ...                   \n                       { 'style' 'pushbutton' 'string' 'Use specific channels of other dataset' 'callback' 'pop_interp(''selectchan'',gcbf);'} ...\n                       { 'style' 'pushbutton' 'string' 'Use all channels from other dataset' 'callback' 'pop_interp(''uselist'',gcbf);'} ...\n                       { } ...\n                       { 'style' 'text'  'string' 'Interpolation method'} ...\n                       { 'style' 'popupmenu'  'string' 'Spherical|Planar (slow)'  'tag' 'method' } ...\n                       { } ...\n                       { 'Style', 'text', 'string', 'Time range [min max] (s)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') } ...\n                       { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') } ...\n                       {} { 'Style' 'text' 'string' 'Note: for group level analysis, interpolate in STUDY' } ...\n                       };\n\n            geom     = { 1 1 1 1 1 1 1 [1.1 1] 1 [1.1 1] 1   1 };\n            geomvert = [ 1 1 1 1 1 1 1 1       0.5 1      0.5  1 ];\n        else\n            uilist = { { 'Style' 'text' 'string' 'What channel(s) do you want to interpolate' 'fontweight' 'bold' } ...\n                   { 'style' 'text' 'string' 'none selected' 'tag' 'chanlist' } ...\n                   { 'style' 'pushbutton' 'string' 'Select from removed channels' 'callback' 'pop_interp(''removedchans'',gcbf);' 'enable' enablenondat } ...                   \n                   { 'style' 'pushbutton' 'string' 'Select from data channels'    'callback' 'pop_interp(''datchan'',gcbf);' } ...                   \n                   { 'style' 'pushbutton' 'string' 'Use specific channels of other dataset' 'callback' 'pop_interp(''selectchan'',gcbf);'} ...\n                   { 'style' 'pushbutton' 'string' 'Use all channels from other dataset' 'callback' 'pop_interp(''uselist'',gcbf);'} ...\n                   { } ...\n                   { 'style' 'text'  'string' 'Interpolation method'} ...\n                   { 'style' 'popupmenu'  'string' 'Spherical|Planar (slow)'  'tag' 'method' } ...\n                   {} { 'Style' 'text' 'string' 'Note: for group level analysis, interpolate in STUDY' } ...\n                   };\n               \n            geom     = { 1 1 1 1 1 1 1 [1.1 1] 1   1 };\n            geomvert = [ 1 1 1 1 1 1 1 1       0.5 1 ];\n        end\n        [res, userdata, ~, restag ] = inputgui( 'uilist', uilist, 'title', 'Interpolate channel(s) -- pop_interp()', 'geometry', geom, 'geomvert', geomvert, 'helpcom', 'pophelp(''pop_interp'')');\n        if isempty(res) || isempty(userdata), return; end\n        \n        if restag.method == 1\n             method = 'spherical';\n        else method = 'invdist';\n        end\n        bad_elec = userdata.chans;\n        if nargin < 4\n            if numel(res) > 1\n                t_range = res{2};\n            else\n                t_range = '';\n            end\n        end\n        if isempty(t_range)\n            t_range = [EEG.xmin EEG.xmax];\n        else\n            t_range = eval( [ '[' t_range ']' ] );\n        end\n        if size(t_range,2) ~= 2\n            error('Time/point range must contain 2 columns exactly');\n        end\n        if floor(max(t_range)) > EEG.xmax \n            error('Time/point range exceed upper data limits');\n        end\n        if min(t_range) < EEG.xmin\n            error('Time/point range exceed lower data limits');\n        end\n        \n        com = sprintf('EEG = pop_interp(EEG, %s, ''%s'');', userdata.chanstr, method);\n        if ~isempty(findstr('removedchans', userdata.chanstr))\n            eval( [ userdata.chanstr '=[];' ] );\n        end\n        \n    elseif ischar(EEG)\n        command = EEG;\n        clear EEG;\n        fig = bad_elec;\n        userdata = get(fig, 'userdata');\n        \n        if strcmpi(command, 'removedchans')\n            global EEG;\n            tmpchaninfo = EEG.chaninfo;\n            [chanlisttmp, chanliststr] = pop_chansel( { tmpchaninfo.removedchans.labels } );\n            if ~isempty(chanlisttmp)\n                userdata.chans   = EEG.chaninfo.removedchans(chanlisttmp);\n                userdata.chanstr = [ 'EEG.chaninfo.removedchans([' num2str(chanlisttmp) '])' ];\n                set(fig, 'userdata', userdata);\n                set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr);\n            end\n        elseif strcmpi(command, 'datchan')\n            global EEG;\n            tmpchaninfo = EEG.chanlocs;\n            [chanlisttmp, chanliststr] = pop_chansel( { tmpchaninfo.labels } );\n            if ~isempty(chanlisttmp)\n                userdata.chans   = chanlisttmp;\n                userdata.chanstr = [ '[' num2str(chanlisttmp) ']' ];\n                set(fig, 'userdata', userdata);\n                set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr);\n            end\n        else\n            global ALLEEG EEG;\n            tmpanswer = inputdlg2({ 'Dataset index' }, 'Choose dataset', 1, { '' });\n            if ~isempty(tmpanswer)\n                tmpanswernum = round(str2num(tmpanswer{1}));\n                if ~isempty(tmpanswernum)\n                    if tmpanswernum > 0 && tmpanswernum <= length(ALLEEG)\n                        TMPEEG = ALLEEG(tmpanswernum);\n                        \n                        tmpchans1 = TMPEEG.chanlocs;\n                        if strcmpi(command, 'selectchan')\n                            chanlist = pop_chansel( { tmpchans1.labels } );\n                        else\n                            chanlist = 1:length(TMPEEG.chanlocs); % use all channels\n                        end\n                        \n                        % look at what new channels are selected\n                        tmpchans2 = EEG.chanlocs;\n                        [tmpchanlist, chaninds] = setdiff_bc( { tmpchans1(chanlist).labels }, { tmpchans2.labels } );\n                        if ~isempty(tmpchanlist)\n                            if length(chanlist) == length(TMPEEG.chanlocs)\n                                userdata.chans   = TMPEEG.chanlocs;\n                                userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs' ];\n                            else\n                                userdata.chans   = TMPEEG.chanlocs(chanlist(sort(chaninds)));\n                                userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs([' num2str(chanlist(sort(chaninds))) '])' ];\n                            end\n                            set(fig, 'userdata', userdata);\n                            tmpchanlist(2,:) = { ' ' };\n                            set(findobj(gcbf, 'tag', 'chanlist'), 'string', [ tmpchanlist{:} ]);\n                        else\n                            warndlg2('No new channels selected');\n                        end\n                    else\n                        warndlg2('Wrong index');\n                    end\n                end\n            end\n        end\n        return;\n    end\n    \n    % remove from removedchans if interpolated\n    if isfield(EEG.chaninfo, 'removedchans') && ~isempty(EEG.chaninfo.removedchans) && isstruct(bad_elec)\n        for iChan = 1:length(bad_elec)\n            ind = strmatch(lower(bad_elec(iChan).labels), lower({EEG.chaninfo.removedchans.labels}), 'exact');\n            if ~isempty(ind)\n                EEG.chaninfo.removedchans(ind) = [];\n            end\n        end\n    end\n    \n    EEG = eeg_interp(EEG, bad_elec, method, t_range);\n    \n    \n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/popfunc/pop_interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.20683897200071805}}
{"text": "function [sFile, ChannelMat] = in_fopen_spm(DataFile)\n% IN_FOPEN_SPM: Open a SPM .mat/.dat file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2017\n\n\n%% ===== READ HEADER =====\n% Check if SPM is in the path\nif ~exist('file_array', 'file')\n    error('SPM must be in the Matlab path to use this feature.');\nend\n% Get the two input file names: .mat and .dat\n[fPath, fBase, fExt] = bst_fileparts(DataFile);\nMatFile = bst_fullfile(fPath, [fBase, '.mat']);\nDatFile = bst_fullfile(fPath, [fBase, '.dat']);\n% If one is missing: error\nif ~file_exist(MatFile) || ~file_exist(DatFile)\n    error('The two files .dat and .mat must be available in the same folder.');\nend\n% Read header\nsMat = load(MatFile, 'D');\nD = sMat.D;\nnChannels = length(D.channels);\n\n% Warning: Supporting only files with one epoch\nif (length(D.trials) > 1)\n    error(['Only continuous SPM files are currently supported. Files with multiple trials cannot be imported.' 10 ...\n           'Please contact us through the Brainstorm user forum to request this feature.']);\nend\n\n\n%% ===== FILL STRUCTURE =====\n% Initialize returned file structure\nsFile = db_template('sfile');\n% Add information read from header\nsFile.byteorder    = 'l';\nsFile.filename     = MatFile;\nsFile.format       = 'SPM-DAT';\nsFile.prop.sfreq   = double(D.Fsample);\nsFile.prop.nAvg    = 1;\nsFile.prop.times   = (round(D.timeOnset(1) .* sFile.prop.sfreq) + [0, (D.Nsamples - 1)]) ./ sFile.prop.sfreq;\nsFile.channelflag  = ones(nChannels,1);\nsFile.device       = 'SPM';\nsFile.comment      = fBase;\nif isa(D.data, 'file_array')\n    sFile.header.file_array = D.data;\nelseif isstruct(D.data) && isfield(D.data, 'y') && isa(D.data.y, 'file_array')\n    sFile.header.file_array = D.data.y;\nelse\n    error('Could not find the file_array object in the SPM structure.');\nend\nsFile.header.nChannels  = nChannels;\nsFile.header.gain       = ones(nChannels,1);\n\n\n%% ===== CHANNEL FILE =====\n% Initialize structure\nChannelMat = db_template('ChannelMat');\nChannelMat.Comment = [sFile.device ' channels'];\nChannelMat.Channel = repmat(db_template('channeldesc'), [1, nChannels]);\n% Loop on each channel\nfor i = 1:nChannels\n    if (D.channels(i).bad)\n        sFile.channelflag(i) = -1;\n    end\n    if iscell(D.channels(i).label) && ~isempty(D.channels(i).label)\n        ChannelMat.Channel(i).Name = D.channels(i).label{1};\n    elseif ischar(D.channels(i).label) && ~isempty(D.channels(i).label)\n        ChannelMat.Channel(i).Name = D.channels(i).label;\n    else\n        disp(sprintf('BST> Warning: No information avaible for channel #%d.', i));\n    end\n    % Convert channel types\n    switch upper(D.channels(i).type)\n        case 'MEGPLANAR',   ChannelMat.Channel(i).Type = 'MEG GRAD';\n        case 'MEGMAG',      ChannelMat.Channel(i).Type = 'MEG MAG';\n        otherwise,          ChannelMat.Channel(i).Type = upper(D.channels(i).type);\n    end\n    % Channel gains\n    if isfield(D.channels(i), 'units') && ~isempty(D.channels(i).units)\n        switch (D.channels(i).units)\n            case 'fT',        sFile.header.gain(i) = 1e-15;\n            case 'fT/mm',     sFile.header.gain(i) = 1e-12;\n            case 'mV',        sFile.header.gain(i) = 1e-3;\n            case {'uV','?V'}, sFile.header.gain(i) = 1e-6;\n            otherwise,        sFile.header.gain(i) = 1;\n        end\n    end\nend\n% Read detailed information from .meg and .eeg fields\nChannelMat = read_fieldtrip_chaninfo(ChannelMat, D.sensors);\n\n% Convert head points\nif isfield(D, 'fiducials') && isfield(D.fiducials, 'pnt') && isfield(D.fiducials, 'label')\n    for i = 1:length(D.fiducials.label)\n        ChannelMat.HeadPoints.Label = D.fiducials.label(:)';\n        ChannelMat.HeadPoints.Type  = repmat({'EXTRA'}, size(ChannelMat.HeadPoints.Label));\n        ChannelMat.HeadPoints.Loc   = bst_units_ui(D.fiducials.unit, D.fiducials.pnt');\n    end\nend\n% Convert fiducials\nif isfield(D, 'fiducials') && isfield(D.fiducials, 'fid') && isfield(D.fiducials.fid, 'label') && isfield(D.fiducials.fid, 'pnt')\n    for i = 1:length(D.fiducials.fid.label)\n        switch lower(D.fiducials.fid.label{i})\n            case {'nas', 'nasion', 'nz', 'fidnas', 'fidnz'}  % NASION\n                ChannelMat.SCS.NAS = bst_units_ui(D.fiducials.unit, D.fiducials.fid.pnt(i,:));\n            case {'lpa', 'pal', 'og', 'left', 'fidt9', 'leftear'} % LEFT EAR\n                ChannelMat.SCS.LPA = bst_units_ui(D.fiducials.unit, D.fiducials.fid.pnt(i,:));\n            case {'rpa', 'par', 'od', 'right', 'fidt10', 'rightear'} % RIGHT EAR\n                ChannelMat.SCS.RPA = bst_units_ui(D.fiducials.unit, D.fiducials.fid.pnt(i,:));\n        end\n    end\n    % Force re-alignment on the new set of NAS/LPA/RPA\n    if ~isempty(ChannelMat.SCS) && ~isempty(ChannelMat.SCS.NAS) && ~isempty(ChannelMat.SCS.LPA) && ~isempty(ChannelMat.SCS.RPA)\n        ChannelMat = channel_detect_type(ChannelMat, 1, 0);\n    end\nend\n\n\n%% ===== EVENTS =====\nif isfield(D, 'trials') && isfield(D.trials, 'events') && isfield(D.trials.events, 'type')\n    % Get all the event types\n    evtList = {D.trials.events.type};\n    % Events list\n    [uniqueEvt, iUnique] = unique(evtList);\n    uniqueEvt = evtList(sort(iUnique));\n    % Initialize events list\n    sFile.events = repmat(db_template('event'), 1, length(uniqueEvt));\n    % Build events list\n    for iEvt = 1:length(uniqueEvt)\n        % Find all the occurrences of this event\n        iOcc = find(strcmpi(uniqueEvt{iEvt}, evtList));\n        % Concatenate all times\n        t = [D.trials.events(iOcc).time];\n        % If there is a duration: add it\n        occDuration = [D.trials.events(iOcc).duration];\n        if (length(occDuration) == length(t))\n            t(2,:) = t(1,:) + occDuration;\n        end\n        % Set event\n        sFile.events(iEvt).label   = strtrim(uniqueEvt{iEvt});\n        sFile.events(iEvt).times   = t;\n        sFile.events(iEvt).epochs  = 1 + 0*t(1,:);\n        sFile.events(iEvt).select  = 1;\n        sFile.events(iEvt).channels = [];\n        sFile.events(iEvt).notes    = [];\n    end\nend\n\nend\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fopen_spm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.20683895491710802}}
{"text": "function r = mldivide(a,b)\n% o \\ v \n%\n% Syntax\n%   h = o \\ r\n%\n% Input\n%  o - @orientation\n%  r - @vector3d\n%\n% Output\n%  h - @Miller\n%\n\n\nr = inv(a) * b; %#ok<MINV>\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@orientation/mldivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.20681304517312477}}
{"text": "function layout=cosmo_meeg_read_layout(fn)\n% Read FieldTrip layout\n%\n% layout=cosmo_meeg_read_layout(fn)\n%\n% Inputs:\n%   fn                  Filename of layout file, or a string containing the\n%                       layout. In the latter case fn must contain at least\n%                       one newline ('\\n') character.\n%                       A layout file is a text file with one line per\n%                       sensor, with each line containing the following\n%                       data separated by white-space:\n%                       1) sensor number (integer)\n%                       2) horizontal position (float)\n%                       3) vertical position (float)\n%                       4) width (float)\n%                       5) height (float)\n%                       6) label (string)\n%\n% Output:\n%   layout              struct with fields containing data for N sensors:\n%     .pos              Nx2 matrix with x and y position\n%     .width            Nx1 vector\n%     .height           Nx1 vector\n%     .label            Nx1 cell string with channel labels\n%\n% Notes:\n%   - whitespace is trimmed from the labels\n%   - the sensor number is not used; the order of the sensors in layout is\n%     the same as in the layout file\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n\n    check_layout_input(fn)\n\n    if string_contains_newline(fn)\n        lay_string=fn;\n        fn_descr=@()sprintf('input:\\n''%s''',lay_string);\n    else\n        lay_string=read_lay_string_from_file(fn);\n        fn_descr=@()sprintf('file %s',fn);\n    end\n\n    layout=parse_layout(lay_string, fn_descr);\n\nfunction lay_string=read_lay_string_from_file(fn)\n    if ~exist(fn,'file')\n        error('layout file %s does ont exist', fn);\n    end\n\n    % read FT layout (.lay) file\n    fid=fopen(fn);\n    file_closer=onCleanup(@()fclose(fid));\n    lay_string=fread(fid,inf,'char=>char')';\n\n\nfunction check_layout_input(fn)\n    if ~ischar(fn)\n        error('first argument must be string, found %s', class(fn));\n    end\n\nfunction tf=string_contains_newline(fn)\n    tf=any(fn==sprintf('\\n'));\n\n\nfunction layout=parse_layout(lay_string, fn_descr)\n    % pattern to match is integer, then 4 numeric values followed by a\n    % string that can contain whitespaces and plus characters, followed by\n    % newline\n    integer='(\\d+)';\n    float='([\\d\\.-]+)';\n    space='\\s+';\n    channel_label='([\\w \\t\\r\\f\\v\\+\\-]+)';\n    single_newline='\\n';\n\n    pat=[integer, space, ...\n         float, space, ...\n         float, space, ...\n         float, space, ...\n         float, space, ...\n         channel_label, single_newline];\n\n    matches=regexp(sprintf('%s\\n',lay_string),pat,'tokens');\n    if isempty(matches)\n        error('No valid layout definition found in %s', fn_descr());\n    end\n\n    % convert to (nchannel x 6) matrix\n    layout_matrix=cat(1,matches{:});\n\n    % convert values in first five columns to numeric\n    num_values_cell=layout_matrix(:,1:5)';\n\n\n    str_values=sprintf('%s %s %s %s %s; ', num_values_cell{:});\n    num_values=str2num(str_values);\n\n    % store layout information (omit channel number in first column)\n    layout.pos    = num_values(:,2:3);\n    layout.width  = num_values(:,4);\n    layout.height = num_values(:,5);\n\n    % trim whitespace around channel names\n    label=layout_matrix(:,6);\n    label=regexprep(label,'^\\s*','');\n    label=regexprep(label,'\\s*$','');\n    layout.label  = label;", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_meeg_read_layout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.2067068174735572}}
{"text": "function signal = flt_beamformer(varargin)\n% Recovers activity from the given ROIs via a beamformer.\n% function Signal = flt_laplace(Signal,ROIs,)\n%\n% In:\n%   Signal : EEGLAB data set, either continuous or epoched\n%\n%   ROIs   : Regions of interest from which to recover signals.\n%\n%   FieldType : type of field to recover ('axial' or 'normal')\n%\n%   ReferenceType : type of referencing used before this filter ('nasion' or 'common_average')\n%\n%   OverrideOriginal : whether to override the original signal\n%\n% Out:\n%   Signal : activity from the given ROIs\n%\n% Notes:\n%   This function currently does not perform activity renormalization.\n%\n% Examples:\n%   % recover activity from four regions\n%   eeg = flt_beamformer(eeg,{'Precentral_L', 'Precentral_R', 'Frontal_Sup_L', 'Frontal_Sup_R'},'normal')\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2014-02-11\n\nif ~exp_beginfun('filter') return; end\n\ndeclare_properties('name','Beamformer', 'follows',{'flt_selchans','flt_repair_bursts','flt_clean_settings'}, 'cannot_follow','flt_ica', 'independent_channels',false, 'independent_trials',true);\n\narg_define(varargin, ...\n    arg_norep({'signal','Signal'}), ...\n    arg({'roi_labels','ROIs','ROILabels'},{}, {'Precentral_L', 'Precentral_R', 'Frontal_Sup_L', 'Frontal_Sup_R', 'Frontal_Sup_Orb_L', 'Frontal_Sup_Orb_R', 'Frontal_Mid_L', 'Frontal_Mid_R', 'Frontal_Mid_Orb_L', 'Frontal_Mid_Orb_R', 'Frontal_Inf_Oper_L', 'Frontal_Inf_Oper_R', 'Frontal_Inf_Tri_L', 'Frontal_Inf_Tri_R', 'Frontal_Inf_Orb_L', 'Frontal_Inf_Orb_R', 'Rolandic_Oper_L', 'Rolandic_Oper_R', 'Supp_Motor_Area_L', 'Supp_Motor_Area_R', 'Frontal_Sup_Medial_L', 'Frontal_Sup_Medial_R', 'Frontal_Med_Orb_L', 'Frontal_Med_Orb_R', 'Insula_L', 'Insula_R', 'Cingulum_Ant_L', 'Cingulum_Ant_R', 'Cingulum_Mid_L', 'Cingulum_Mid_R', 'Cingulum_Post_L', 'Cingulum_Post_R', 'Hippocampus_L', 'Hippocampus_R', 'ParaHippocampal_L', 'ParaHippocampal_R', 'Calcarine_L', 'Calcarine_R', 'Cuneus_L', 'Cuneus_R', 'Lingual_L', 'Lingual_R', 'Occipital_Sup_L', 'Occipital_Sup_R', 'Occipital_Mid_L', 'Occipital_Mid_R', 'Occipital_Inf_L', 'Occipital_Inf_R', 'Fusiform_L', 'Fusiform_R', 'Postcentral_L', 'Postcentral_R', 'Parietal_Sup_L', 'Parietal_Sup_R', 'Parietal_Inf_L', 'Parietal_Inf_R', 'SupraMarginal_L', 'SupraMarginal_R', 'Angular_L', 'Angular_R', 'Precuneus_L', 'Precuneus_R', 'Paracentral_Lobule_L', 'Paracentral_Lobule_R', 'Temporal_Sup_L', 'Temporal_Sup_R', 'Temporal_Pole_Sup_L', 'Temporal_Pole_Sup_R', 'Temporal_Mid_L', 'Temporal_Mid_R', 'Temporal_Pole_Mid_L', 'Temporal_Pole_Mid_R', 'Temporal_Inf_L', 'Temporal_Inf_R', 'Olfactory_L', 'Olfactory_R', 'Rectus_L', 'Rectus_R', 'Amygdala_L', 'Amygdala_R', 'Caudate_L', 'Caudate_R', 'Thalamus_L', 'Thalamus_R', 'Heschl_L', 'Heschl_R'}, ...\n        'Cortical anchor locations. List of locations to which components shall be constrained. The first k components are encouraged to lie close to the given locations, in the order of appearance. This is experimental and currently requires a) 10-20 locations and b) Guido Nolte''s source analysis toolbox (not included).','experimental',true), ...\n    arg({'field_type','FieldType'},'normal',{'normal','axial'},'Regions of interest. These are the regions from which to recover signals.'), ...\n    arg({'reference_type','ReferenceType'},'common_average',{'nasion','common_average'},'Referencing scheme. This is the type of re-referencing that was applied before flt_beamformer.'), ...\n    arg({'override_original','OverrideOriginal'},true,[],'Override original data. If checked, the original signals will be replaced by the recovery.'), ...\n    arg({'override_chanlabels','OverrideChanlabels'},{},[],'Override channel labels.'), ...\n    arg({'cov_shrinkage','CovShrinkage'},0,[],'Covariance shrinkage parameter. For better conditioning.'), ...\n    arg({'cov_robust','CovRobust'},false,[],'Use robust covariance estimate.'), ...\n    arg_norep('M'), ...\n    arg_norep('channel_mask'));\n\n% calculate spatial filter matrix, if necessary\nif ~exist('M','var')\n    if isempty(override_chanlabels)\n        chan_labels = {signal.chanlocs.labels};\n    else\n        chan_labels = override_chanlabels;\n    end    \n    [dummy,dummy,channel_mask,dummy,dummy,dummy,normField,leadField] = hlp_diskcache('filterdesign',@calc_beamformer_constraints,chan_labels,roi_labels,eye(signal.nbchan),reference_type); %#ok<ASGLU>\n    if strcmp(field_type,'normal')\n        LF = normField;        \n    elseif strcmp(field_type,'axial')\n        LF = leadField(:,:);\n    else\n        error('Unsupported field type requested: %s',hlp_tostring(field_type,1000));\n    end\n    if cov_robust\n        C = cov_blockgeom(signal.data(channel_mask,:)');\n    else\n        C = cov(signal.data(channel_mask,:)');\n    end\n    C = (1-cov_shrinkage)*C + cov_shrinkage*mean(trace(C))*eye(length(C));\n    M = LF'/C;\nend\n\n% apply M\nsignal = utl_register_field(signal,'timeseries','srcpot',reshape(M*signal.data(channel_mask,:,:),[],size(signal.data,2),size(signal.data,3)));\nsignal.etc.roi_labels = roi_labels; \n\nif override_original\n    % override signal.data & relabel channels\n    signal.data = signal.srcpot;\n    if size(signal.data,1) == signal.nbchan\n        signal.chanlocs = struct('labels',roi_labels);\n    else\n        signal.nbchan = size(signal.data,1);\n        signal.chanlocs = hlp_nanocache('cached_labels',10,@make_labels,roi_labels); \n    end\nend\n\n% append the M and ok arguments to the online expression\nexp_endfun('append_online',{'M',M,'channel_mask',channel_mask});\n\nfunction chanlocs = make_labels(roi_labels)\nchanlocs = struct('labels',[cellfun(@(f){sprintf('%s_X',f)},roi_labels) cellfun(@(f){sprintf('%s_Y',f)},roi_labels) cellfun(@(f){sprintf('%s_Z',f)},roi_labels)]);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/filters/flt_beamformer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.2066942552110179}}
{"text": "% plot(x,NC(2012,:),'o');\nplot(x,dC(2012,:),'o');", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/Coupled/Draw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20643753844815968}}
{"text": "% 'region' is a class of objects that contains information on groups of\n% voxels (\"regions\") defined in various ways (contiguous voxels above a\n% threshold in an analysis, based on atlases, etc.)\n%\n% the region class replaces the \"clusters\" structure in the scnlab toolbox,\n% and all or almost all of the \"clusters\" functions should work for regions\n% structures as well.  The advantage of 'region' is that the class\n% definition can help constrain the use and provide additional error\n% checking, etc.\n%\n% Defining a region and initializing:\n%\n% *Usage:*\n%   - r = region(obj1, [obj2], [keywords] )\n%     - obj1: [fmri_data/statistic_image object to define regions]\n%             Can also be char array of image filename\n%     - obj2: Optional: fmri_data/statistic_image object to extract data from\n%     - keywords: Optional: 'unique_mask_values' or 'contiguous_regions'\n%     - 'noverbose' : suppress verbose output\n%\n%   - cl = region;  % generates an empty structure\n%                   % You can add fields yourself if you want to, but best to\n%                   define based on existing file name or image_vector object\n%\n% Define regions based on continuous voxel values (in this example image,\n% there is only one set of contiguous voxels, so 1 region...)\n%\n%   - mask_image = which('brainmask.nii');\n%   - cl = region(mask_image);\n%\n% *Inputs:*\n%\n% There are two ways to define which voxels are grouped into a 'region',\n% which becomes an element of the region variable cl.\n%\n% enter 'contiguous_regions' -> group by contiguous blobs\n%\n% or    'unique_mask_values' -> group by unique values in mask .dat field\n%\n% *Note:* 'contiguous_regions' uses contiguity/clustering information stored\n% in mask.volInfo.cluster, which may not have veridical contiguity info if\n% you have manipulated it or incorporated anatomical information in working with\n% the mask object, or if you have borrowed the volInfo structure from\n% another source in creating it.\n%\n% *Examples:*\n%\n% Define regions based on continuous values in an anatomical mask:\n%   - mask_image = which('atlas_labels_combined.img');\n%   - cl = region(mask_image, 'unique_mask_values');\n%\n% Resample mask_image to space of data_comb fmri_data object, and extract\n% averages.  Space is defined by data_comb.\n%   - cl = extract_roi_averages(data_comb, mask_image, 'unique_mask_values');\n%\n% Define regions based on unique voxels values in mask_image, and extract\n% data stored in data_comb object, resampled to space of mask_image.\n% Space is defined by mask_image:\n%   - cl = region(mask_image, data_comb, 'unique_mask_values');\n%\n% Reslice mask to space of functional images and define regions based on\n% mask values in the functional space (good for extracting data, etc.)\n%   - mask_image = which('anat_lbpa_thal.img');\n%   - mask = fmri_mask_image(mask_image);\n%   - mask = resample_to_image_space(mask, image_names(1, :));\n%   - cl = region(mask);\n%\n% *Methods*\n%\n% Try typing methods(cl)\n%\n% methods for 'regions' include:\n%\n% Visualization methods:\n%     montage, orthviews, surf, etc.\n%\n% *Programmers' Notes:*\n%\n% 8/3/2015 : Tor Wager: Fixed bug when applying region to thresholded\n% statistic_image object.  Did not consider thresholding.\n%\n% 5/24/2017: Tor and Phil Kragel: first attempt to make compatible with\n% use of enforce_variable_types method.\n%\n% 7/2018 : Tor - check for empty mask and skip data extraction if so\n\nclassdef region\n    \n    properties\n        title = 'Untitled';     % Title of region object\n        shorttitle = 'region';\n        descrip1 = 'Region: a group of voxels.'\n        descrip2 ='Some methods: orthviews, montage, surface, extract_data, table';\n        \n        XYZ\n        XYZmm\n        val\n        val_descrip = 'Description of values for each voxel in val field.';\n        \n        Z\n        Z_descrip = 'Legacy values for each voxel; Z-scores or other max stat';\n        \n        threshold % legacy, for compatibility\n        voxSize\n        M\n        dim\n        numVox\n        numpeaks\n        \n        center\n        mm_center\n        \n        timeseries\n        contrastdata\n        dat\n        all_data\n        \n        source_images\n        \n        custom_info1\n        custom_info1_descrip\n        \n        custom_info2\n        custom_info2_descrip\n        \n    end % properties\n    \n    methods\n        \n        % class constructor method\n        % takes maskinput in one of several forms:\n        % 1) mask object\n        % 2) mask image file\n        % 3) mask vector data (???)\n        %\n        % takes one of two string inputs for how to define regions (see below)\n        % 'contiguous_regions' (default)\n        % 'unique_mask_values'\n        \n        function obj = region(maskinput, varargin)\n            \n            % initialize empty\n            % return if no additional args\n            \n            obj.title = 'Untitled';\n            obj.shorttitle = 'region';\n            obj.descrip1 = 'Region: a group of voxels.';\n            obj.descrip2 ='Some methods: orthviews, montage, surface, extract_data, table';\n            obj.XYZ = [];\n            obj.XYZmm = [];\n            obj.val = [];\n            obj.Z = [];\n            obj.val_descrip = 'Values for each voxel, usually max stat.';\n            obj.Z_descrip = 'Legacy values for each voxel; Z-scores or other max stat';\n            obj.threshold = []; % legacy, for compatibility\n            obj.voxSize = [];\n            obj.M = [];\n            obj.dim = [];\n            obj.numVox = 0;\n            obj.numpeaks = NaN;\n            obj.center = [];\n            obj.mm_center = [];\n            obj.timeseries = [];\n            obj.contrastdata = [];\n            obj.dat = [];\n            obj.all_data = [];\n            obj.source_images = char([]);\n            obj.custom_info1 = [];\n            obj.custom_info1_descrip = 'Mask image name for region definition';\n            obj.custom_info2 = [];\n            obj.custom_info2_descrip = char([]);\n            \n            if nargin == 0\n                return\n            end\n            \n            % ---------------------------------\n            % define mask object\n            % ---------------------------------\n            \n            % Load mask into object if needed, apply .sig field for\n            % statistic_image objects\n            \n            [mask, maskData] = prep_mask_object(maskinput);\n            \n            % Check for an incompatibility. Don't try to fix here, force\n            % proper intended use.\n            if isa(maskinput, 'atlas') && isa(maskinput.dat, 'int32')\n                \n                %atlas_obj.dat = double(atlas_obj.dat);\n                error('Do not use region() for atlas objects. Use atlas2region instead.');  \n                \n            end\n            \n            % ---------------------------------\n            % define what to average over\n            % ---------------------------------\n            \n            average_over = 'contiguous_regions'; %'contiguous_regions'  or 'unique_mask_values';\n            doverbose = true;\n            \n            for varg = 1:length(varargin)\n                if ischar(varargin{varg})\n                    switch varargin{varg}\n                        \n                        % reserved keywords\n                        case 'contiguous_regions', average_over = 'contiguous_regions';\n                        case 'unique_mask_values', average_over = 'unique_mask_values';\n                            \n                        case 'noverbose'\n                            doverbose = false;\n                            \n                        otherwise\n                            disp('region class constructor: Illegal string value for average_over.');\n                            fprintf('You entered ''%s''\\n Valid values are %s or %s\\n', varargin{varg}, '''contiguous_regions''', '''unique_mask_values''');\n                            error('Exiting');\n                    end\n                elseif isa(varargin{varg}, 'image_vector')\n                        % data object to extract from at end\n                        \n                        dataobj = varargin{varg};\n                        varargin{varg} = [];\n                        \n                        % Note: If you have manipulated an image_vector (e.g., fmri_data,\n                        % statistic_image) object and eliminated some voxels, in order to create\n                        % regions, contiguous voxels are automatically reparsed into regions using\n                        % fmri_data.reparse_contiguous below.\n                        \n                        dataobj = reparse_contiguous(dataobj, 'nonempty');\n                else\n                    % unknown input\n                end\n            end\n            \n            \n            % If extracting data, we'll recreate the regions in\n            % extract_roi_averages, so do that here and then exit.\n            % Otherwise, continue to region definition.\n            \n            if exist('dataobj', 'var')\n                % extract data\n                if doverbose\n                    disp('> Found image data, extracting region averages.');\n                end\n                \n                dataobj = replace_empty(dataobj); % may need to do this to get voxels to line up\n                \n                cs = compare_space(dataobj, mask);\n                \n                % if empty, skip\n                isemptymask = isempty(mask.dat) || all(mask.dat(:) == 0);\n                if isemptymask\n                    if doverbose\n                        disp('No in-region voxels from which to extract data.');\n                    end\n                    return\n                end\n                \n                if cs == 3\n                    disp('Spaces for data object and mask object line up, but voxel numbers do not. Check.');\n                    if doverbose, disp('> Resampling to mask space first.'); end\n                    dataobj = resample_space(dataobj, mask); % resample data to mask space\n                elseif cs\n                    if doverbose, disp('> Resampling to mask space first.'); end\n                    dataobj = resample_space(dataobj, mask); % resample data to mask space\n                end\n                \n                if doverbose\n                    obj = extract_roi_averages(dataobj, mask, average_over);\n                else\n                    obj = extract_roi_averages(dataobj, mask, average_over, 'noverbose');\n                end\n                \n                return\n            end\n            \n            % ---------------------------------\n            % get which values to save later\n            % ---------------------------------\n            \n            maskValues = maskData;  % values to save in .val field \n            maskZ = maskData;       % values to save in .Z field later\n            \n            val_descrip = 'Input mask image values for each voxel.';\n            Z_descrip = 'Input mask image values for each voxel.';\n             \n            if isa(mask, 'statistic_image')\n                \n                 val_descrip = 'Statistic effect value (.dat) for each voxel.';\n    \n                 mask = replace_empty(mask);            % after this p and dat now have all in-mask voxels\n                 \n                 if ~isempty(mask.dat)\n                     % Use values from image. These can be more precise and\n                     % we don't want to convert them to Z-values if we\n                     % don't have to.\n                     \n                     maskZ = mask.dat;\n                     Z_descrip = mask.type;\n                     \n                 elseif ~isempty(mask.p)\n                     \n                     if doverbose('Converting .dat data values to Z-values based on P-values'); end\n                     \n                     \n                     Z_descrip = 'Z-score for each voxel.';\n                     mask.p(mask.p==0) = eps;               % not to have Inf values in Z field\n                     maskZ = sign(mask.dat) .* norminv(1 - mask.p ./ 2); % Z-score based on p-value, assuming two-tailed p-vals.\n                     \n                 end     \n                \n            end\n            \n            % ---------------------------------\n            % get unique values for voxel grouping code\n            % ---------------------------------\n            \n            switch average_over\n                \n                % Define integer codes for sets of voxels to average over.\n                \n                case 'unique_mask_values'\n                    \n                    maskData = round(maskData);\n                    u = unique(maskData)'; u(u == 0) = [];\n                    nregions = length(u);\n                    \n                    if doverbose\n                        fprintf('Grouping voxels with unique mask values, assuming integer-valued mask: %3.0f regions\\n', nregions);\n                    end\n                    \n                case 'contiguous_regions'\n                    \n                    isinmask = maskData ~= 0 & ~isnan(maskData);\n                    \n                    % re-make cluster ID for in-mask voxels\n                    mask.volInfo.cluster(isinmask) = spm_clusters(mask.volInfo.xyzlist(isinmask, :)')';\n                    \n                    % Old, no longer needed with newer SPM\n                    %                     if sum(isinmask) < 50000\n                    %                         mask.volInfo.cluster(isinmask) = spm_clusters(mask.volInfo.xyzlist(isinmask, :)')';\n                    %                     else\n                    %                         % don't, and print warning\n                    %                         mask.volInfo.cluster(isinmask) = ones(sum(isinmask), 1);\n                    %                         disp('Warning: spm_cluster will not parse clusters for masks with > 50000 voxels.');\n                    %                     end\n                    \n                    u = unique(mask.volInfo.cluster(isinmask)); u(u == 0) = [];\n                    maskData(isinmask) = mask.volInfo.cluster(isinmask);\n                    nregions = length(u);\n                    \n                    if doverbose\n                        fprintf('Grouping contiguous voxels: %3.0f regions\\n', nregions);\n                    end\n                    \n                otherwise\n                    error('This should never happen.');\n            end\n            \n            % ---------------------------------\n            % Now define the regions\n            % ---------------------------------\n            \n            obj(1:nregions) = obj;  % fill in all empty fields\n            \n            for i = 1:nregions\n                imgvec = maskData == u(i);\n                \n                obj(i).title = sprintf('Region %3.0f', i);\n                obj(i).shorttitle = sprintf('Region%03d', i);\n                obj(i).XYZ = double(mask.volInfo.xyzlist(imgvec,:))';\n                \n                myXYZ = double(obj(i).XYZ);                         % 5/24/17 tor&phil: recast as double. future: could recast XYZmm as int16\n                obj(i).XYZmm = voxel2mm(myXYZ, mask.volInfo.mat);\n                \n                obj(i).val = maskValues(imgvec); %ones(1,size(obj(i).XYZ,2));\n                obj(i).Z = maskZ(imgvec)'; %ones(1,size(obj(i).XYZ,2));\n                \n                obj(i).val_descrip = val_descrip;\n                obj(i).Z_descrip = Z_descrip;\n                \n                obj(i).voxSize = abs(diag(mask.volInfo.mat(1:3, 1:3)));\n                obj(i).M = mask.volInfo.mat;\n                obj(i).dim = mask.volInfo.dim;\n                obj(i).numVox = size(obj(i).XYZ, 2);\n                \n                obj(i).center = center_of_mass(myXYZ, double(obj(i).Z));\n                obj(i).mm_center = center_of_mass(obj(i).XYZmm, double(obj(i).Z));\n                \n                if ~isempty(mask.volInfo.fname)\n                    [~, ff, ee] = fileparts(mask.volInfo.fname);\n                    obj(i).custom_info1 = [ff ee];\n                    obj(i).custom_info1_descrip = 'Mask image name for region definition';\n                else\n                    obj(i).custom_info1 = 'No filename to associate';\n                    obj(i).custom_info1_descrip = '';\n                end\n                \n            end\n            \n            if nregions == 0\n                % obligatory things even for empty regions\n                obj(1).voxSize = abs(diag(mask.volInfo.mat(1:3, 1:3)));\n                obj(1).M = mask.volInfo.mat;\n                obj(1).dim = mask.volInfo.dim;\n                \n                obj(1).val_descrip = val_descrip;\n                obj(1).Z_descrip = Z_descrip;\n                \n            end\n            \n        end % class constructor function\n        \n    end % methods\n    \n    \nend % classdef\n\n\n\n\n% Load mask into object if needed, apply .sig field for\n% statistic_image objects\n% * NOTE: some functionality may be redundant here; to-do is to refactor\n% and run unit test\n\nfunction  [mask, maskData] = prep_mask_object(maskinput)\n\n\nif isa(maskinput, 'char') % string file name\n    mask = fmri_mask_image(maskinput);\n    \nelseif isa(maskinput, 'image_vector')\n    % case {'fmri_data', 'fmri_mask_image', 'statistic_image', 'image_vector'}\n    \n    % special for thresholded stats images: use threshold\n    \n    % if sig field exists, use sig voxels only\n    if isa(maskinput, 'statistic_image') && ~isempty(maskinput.sig)\n        \n        for img = 1:size(maskinput.dat, 2)\n            \n            maskinput.dat(~maskinput.sig(:, img), img) = 0;\n            \n        end\n        \n    end\n    \n    mask = maskinput;\n    \nelseif isa(maskinput, 'atlas')\n    error('Use atlas2region to convert an atlas object to a region object.');\n    \nelse\n    error('region class constructor: unknown mask input type.')\nend\n\n\n% Mask data can already be reduced to those indexed by\n% wh_inmask or not.\n% In addition, voxels/images with empty values may be removed.\n% So insert those first.\n% Note: .dat can sometimes have 2+ cols, so use only first one\nmask = replace_empty(mask);\n\nif size(mask.dat, 2) > 1\n    disp('Warning: Mask has multiple images, will use first only.');\nend\n\nif size(mask.dat, 1) == mask.volInfo.n_inmask\n    maskData = mask.dat(:, 1);\n    \nelseif size(mask.dat, 1) == mask.volInfo.nvox\n    % We have a full-length vector\n    maskData = mask.dat(mask.volInfo.wh_inmask(:, 1));\nelse\n    error('Illegal size for mask.dat, because it does not match its volInfo structure.')\nend\n\n% If statistic_image, we need to consider thresholding\n% so apply .sig field\nif isa(mask, 'statistic_image')\n    \n    % old... we could delete these.. but just in case, I just comment them out for now (Wani).\n    % if size(mask.dat, 1) == mask.volInfo.nvox\n    %    error('statistic_image objects should not have data vector (.dat) the length of full image space.')\n    % end\n    \n    maskData = maskData .* mask.sig(:, 1);\n    \nend\n\n\n\n% may need to reparse contiguous voxels in the mask.\nmask = reparse_contiguous(mask, 'nonempty');\n\n\nend % function\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@region/region.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2064158875577332}}
{"text": "%DYADICM Dyadic dataset mapping\n%\n%   B = [C1,C2]*DYADICM([],P,Q,SIZE)\n%   B = [C1,C2]*DYADICM([],FNAME,[],SIZE)\n%   W = A*DYADICM([],{U1,U2,FNAME},[],SIZE)\n%   B = A*DYADICM([],{V1,V2,FNAME},[],SIZE)\n%\n% INPUT\n%  C1,C2   Datasets / datafiles to be combined\n%  A       Input dataset used for training or classification\n%  P,Q     Scalar multiplication factors (default 1) to compute P*A1+Q*A2\n%          or string (name of a routine)\n%  FNAME   String with the name of a function to combine two datasets or\n%          mappings, 'plus' for PLUS(U1,U2)\n%  U1,U2   Untrained mappings to be combined\n%  V1,V2   Trained or fixe mappings to be combined\n%  SIZE    Desired images size of output dataset objects\n%\n% OUTPUT\n%  B       Dataset\n%  W       Combined mapping\n%\n% DESCRIPTION\n% This special mapping is a low-level routine to facilitate dyadic \n% operations on datafiles, datasets and mappings. Datasets to be combined \n% should have the same number of objects. Image objects should have the \n% same image size. Datafiles should be preprocessed or postprocessed \n% versions of the same original datafile. Mappings should have the same\n% input and output size. \n%\n% This routine has been written for use by PRTools programmers only. Users\n% are discouraged to call it directly. The routine is called by the \n% dyadic operations of the classes 'prmapping' and 'prdatafile'.\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, DATAFILES\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction b = dyadicm(a,p,q,fsize)\n  \n  if nargin < 4, fsize = []; end\n  if nargin < 3, q = []; end\n  if nargin < 2, p = []; end\n  \n  if nargin < 1 | isempty(a)\n    % note that this routine is sometimes externally set to a combiner\n    b = prmapping(mfilename,'fixed',{p,q,fsize});\n    b = setsize_out(b,prod(fsize));\n    b = setname(b,'dyadicm');\n    return\n  end\n  \n  if isempty(p)\n    p = 1; \n  end\n      \n  if iscell(a) & ismapping(a{1})\n    % combining mappings. We are just here because the dyadic mapping \n    % operations like mapping/plus.m are programmed like this. \n    if isfixed(a{1})\n      b = prmapping(mfilename,'fixed',{{a{1},a{2},p}});\n    elseif isuntrained(a{1})\n      b = prmapping(mfilename,'untrained',{{a{1},a{2},p},[],[]});\n    elseif istrained(a{1})\n      if isempty(fsize), fsize = getsize(a{1},2); end\n      b = prmapping(mfilename,'trained',{a{1},a{2},p},getlabels(a{1}),getsize(a{1},1));\n    else\n      error('Wrong type')\n    end\n  \n  elseif isdatafile(a)\n    nodatafile; % forces to store this routine as postprocessing\n    \n  elseif iscell(p) & isuntrained(p{1}) % train mappings stored in p\n    v1 = p{1};     % untrained mapping\n    v2 = p{2};     % fixed or trained mapping or constant   \n    p = p{3};      % operation\n    v1 = a*v1;     % train first mapping\n    [kin,kout] = size(v1);\n    if ismapping(v2) & (isfixed(v2) | istrained(v2))\n      ;            % leave it and hope for the best\n    elseif ismapping(v2) & isuntrained(v2)\n      v2 = a*v2;   % train it\n    else           % should be scalar constant\n      ;            % leave it \n    end\n    % store a standard trained mapping\n    b = prmapping(mfilename,'trained',{v1,v2,p},getlabels(v1),kin,kout);\n    \n  elseif iscell(p) % execute mappings stored in p\n    v1 = p{1};     % fixed or trained mapping\n    v2 = p{2};     % fixed or trained mapping or constant   \n    p = p{3};      % operation\n    a1 = a*v1;     % prepare datasets\n    if ismapping(v2)\n      a2 = a*v2;\n    else\n      a2 = setdata(a1,v2*ones(size(a1)));\n    end\n    b = feval(p,a1,a2);\n    \n  elseif ismapping(p) % execute standard PRTools trained mapping\n    v1 = getdata(p,1);     % fixed or trained mapping\n    v2 = getdata(p,2);     % fixed or trained mapping or constant   \n    p = getdata(p,3);      % operation\n    a1 = a*v1;     % prepare datasets\n    if ismapping(v2)\n      a2 = a*v2;\n    else\n      a2 = setdata(a1,v2*ones(size(a1)));\n    end\n    b = feval(p,a1,a2);\n      \n  else % the basic call by data and parameters\n    \n    % The dataset A has horizontally to be split in two datasets A1, A2. \n    % If P and Q are scalars or if Q = [], this is done half-half.\n    % If P is a string (name of a routine) it is used to combine A1 and A2.\n    \n    [a1,a2,fsize] = split_dataset(a,p,q,fsize);\n\n    if ischar(p) % function name in p\n      b = feval(p,a1,a2);  \n    else % addition\n      if isempty(q), q = 1; end\n      b = a1*p + a2*q;\n    end\n    \n    if isdataset(b)\n      b = setfeatsize(b,fsize);\n    end\n    \n  end\n  \nreturn\n\nfunction [a1,a2,fsize] = split_dataset(a,p,q,fsize)\n\n  if iscell(a)\n    \n    a1 = a{1};\n    a2 = a{2};\n    \n  %elseif ischar(p) & ~isempty(q)\n%   elseif ~isempty(q)\n%     % split as defined by q\n%     fsize = q;\n%     a1 = a(:,1:q);\n%     a2 = a(:,q+1:end);\n    \n  else\n    % 50-50 split, but preserve possible image structure\n    if isempty(fsize) | fsize == 0\n      if isdataset(a)\n        fsize = getfeatsize(a);\n      else % may be a is set of images\n        a = double(a);\n        fsize = size(a);\n      end\n      while (fsize(end) == 1) & (length(fsize) > 1)\n        fsize = fsize(1:end-1);\n      end\n      fsize(end) = fsize(end)/2;\n    end\n    k = size(a,2);\n  \n    if k ~= 2*floor(k/2)\n      error('Feature size of dataset should be multiple of 2')\n    end\n        \n    a1 = a(:,1:k/2);\n    a2 = a(:,k/2+1:k);\n    if isdataset(a)\n      a1 = setfeatsize(a1,fsize);\n      a2 = setfeatsize(a2,fsize);\n    end\n    \n  end\n  \nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/dyadicm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.20635717550823637}}
{"text": "\n%changeCobraSolver('tomlab_cplex','lp');\n%modelClosed = modelConsistent;\nclear FF R\n% add demands for all metabolites in Recon\n%modelClosed = model;\n%modelClosed = addDemandReaction(modelClosed,modelClosed.mets);\n\nmodelexchanges1 = strmatch('Ex_',modelClosed.rxns);\nmodelexchanges4 = strmatch('EX_',modelClosed.rxns);\nmodelexchanges2 = strmatch('DM_',modelClosed.rxns);\nmodelexchanges3 = strmatch('sink_',modelClosed.rxns);\nselExc = (find( full((sum(abs(modelClosed.S)==1,1) ==1) & (sum(modelClosed.S~=0) == 1))))';\n\nmodelexchanges = unique([modelexchanges1;modelexchanges2;modelexchanges3;modelexchanges4;selExc]);\nmodelClosed.lb(ismember(modelClosed.rxns,modelClosed.rxns(modelexchanges)))=0;\n%modelClosed.ub(find(ismember(modelClosed.rxns,modelClosed.rxns(modelexchanges))))=0;\n\n[LeakMets,modelClosed] = fastLeakTest(modelClosed, modelClosed.rxns(modelexchanges),0);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/wholeBody/PSCMToolbox/LeakTestRecon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.20635716723865993}}
{"text": "% std_setcomps2cell - convert .sets and .comps to cell array. The .sets and\n%                     .comps format is useful for GUI but the cell array\n%                     format is used for plotting and statistics.\n%            \n% Usage:\n%   [ struct setinds allinds ] = std_setcomps2cell(STUDY, clustind);\n%   [ struct setinds allinds ] = std_setcomps2cell(STUDY, sets, comps);\n%\n% Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2009-\n\n% Copyright (C) Arnaud Delorme, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [ tmpstruct setinds allinds ] = std_setcomps2cell(STUDY, sets, comps, generateerror)\n\nif nargin < 4\n    generateerror = 0;\nend;\nif nargin < 3\n    tmpstruct = STUDY.cluster(sets);\n    sets  = tmpstruct.sets;\n    comps = tmpstruct.comps; % old format\nelse\n    tmpstruct     = [];\nend;\ncomps   = repmat(comps, [size(sets,1) 1]);\noldsets = sets;\nsets    = reshape(sets , 1, size(sets ,1)*size(sets ,2));\ncomps   = reshape(comps, 1, size(comps,1)*size(comps,2));\n\n% get indices for all groups and conditions\n% -----------------------------------------\nsetinfo       = STUDY.design(STUDY.currentdesign).cell;\nallconditions = STUDY.design(STUDY.currentdesign).variable(1).value;\nallgroups     = STUDY.design(STUDY.currentdesign).variable(2).value;\nnc = max(length(allconditions),1);\nng = max(length(allgroups),    1);\nallinds = cell( nc, ng );\nsetinds = cell( nc, ng );\n\nfor index = 1:length(setinfo)\n    % get index of independent variables\n    % ----------------------------------\n    condind = std_indvarmatch( setinfo(index).value{1}, allconditions);\n    grpind  = std_indvarmatch( setinfo(index).value{2}, allgroups    );\n    if isempty(allconditions), condind = 1; end;\n    if isempty(allgroups),     grpind  = 1; end;\n\n    % get the position in sets where the dataset is\n    % if several datasets check that they all have the same\n    % ICA and component index\n    % -----------------------\n    datind  = setinfo(index).dataset;\n    ind     = find(datind(1) == sets);\n    if ~isempty(ind) && length(datind) > 1\n        [ind1 ind2] = find(datind(1) == oldsets);\n        columnica   = oldsets(:,ind2(1));\n        if ~all(ismember(datind, columnica));\n            disp('Warning: ***** change STUDY design as it combines datasets with different ICA decompositions');\n        end;\n    end;\n        \n    allinds{ condind, grpind } = [ allinds{ condind, grpind } comps(ind) ];\n    setinds{ condind, grpind } = [ setinds{ condind, grpind } repmat(index, [1 length(ind)]) ];\nend;\ntmpstruct.allinds = allinds;\ntmpstruct.setinds = setinds;\n\nif generateerror && isempty(setinds{1})\n    error( [ 'Some datasets not included in preclustering' 10 ... \n             'because of partial STUDY design. You need to' 10 ...\n             'use a STUDY design that includes all datasets.' ]);\nend;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_setcomps2cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.20596588367265203}}
{"text": "% Copyright 2011 Zdenek Kalal\n%\n% This file is part of TLD.\n% \n% TLD is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TLD is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TLD.  If not, see <http://www.gnu.org/licenses/>.\n\naddpath(genpath('.')); init_workspace; \n\nopt.source          = struct('camera',0,'input','_input/','bb0',[]); % camera/directory swith, directory_name, initial_bounding_box (if empty, it will be selected by the user)\nopt.output          = '_output/'; mkdir(opt.output); % output directory that will contain bounding boxes + confidence\n\nmin_win             = 24; % minimal size of the object's bounding box in the scanning grid, it may significantly influence speed of TLD, set it to minimal size of the object\npatchsize           = [15 15]; % size of normalized patch in the object detector, larger sizes increase discriminability, must be square\nfliplr              = 0; % if set to one, the model automatically learns mirrored versions of the object\nmaxbbox             = 1; % fraction of evaluated bounding boxes in every frame, maxbox = 0 means detector is truned off, if you don't care about speed set it to 1\nupdate_detector     = 1; % online learning on/off, of 0 detector is trained only in the first frame and then remains fixed\nopt.plot            = struct('pex',1,'nex',1,'dt',1,'confidence',1,'target',1,'replace',0,'drawoutput',3,'draw',0,'pts',1,'help', 0,'patch_rescale',1,'save',0); \n\n% Do-not-change -----------------------------------------------------------\n\nopt.model           = struct('min_win',min_win,'patchsize',patchsize,'fliplr',fliplr,'ncc_thesame',0.95,'valid',0.5,'num_trees',10,'num_features',13,'thr_fern',0.5,'thr_nn',0.65,'thr_nn_valid',0.7);\nopt.p_par_init      = struct('num_closest',10,'num_warps',20,'noise',5,'angle',20,'shift',0.02,'scale',0.02); % synthesis of positive examples during initialization\nopt.p_par_update    = struct('num_closest',10,'num_warps',10,'noise',5,'angle',10,'shift',0.02,'scale',0.02); % synthesis of positive examples during update\nopt.n_par           = struct('overlap',0.2,'num_patches',100); % negative examples initialization/update\nopt.tracker         = struct('occlusion',10);\nopt.control         = struct('maxbbox',maxbbox,'update_detector',update_detector,'drop_img',1,'repeat',1);\n\n        \n% Run TLD -----------------------------------------------------------------\n%profile on;\n[bb,conf] = tldExample(opt);\n%profile off;\n%profile viewer;\n\n% Save results ------------------------------------------------------------\ndlmwrite([opt.output '/tld.txt'],[bb; conf]');\ndisp('Results saved to ./_output.');", "meta": {"author": "zk00006", "repo": "OpenTLD", "sha": "953e2df96575ba9e3e0720b8f91e936c26c9b2e3", "save_path": "github-repos/MATLAB/zk00006-OpenTLD", "path": "github-repos/MATLAB/zk00006-OpenTLD/OpenTLD-953e2df96575ba9e3e0720b8f91e936c26c9b2e3/run_TLD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.20583222161603357}}
{"text": "function [source] = ft_dipolefitting(cfg, data)\n\n% FT_DIPOLEFITTING perform grid search and non-linear fit with one or multiple\n% dipoles and try to find the location where the dipole model is best able\n% to explain the measured EEG or MEG topography.\n%\n% This function will initially scan the whole brain with a single dipole on\n% a regular coarse grid, and subsequently start at the most optimal location\n% with a non-linear search. Alternatively you can specify the initial\n% location of the dipole(s) and the non-linear search will start from there.\n%\n% Use as\n%   [source] = ft_dipolefitting(cfg, data)\n%\n% The configuration has the following general fields\n%   cfg.numdipoles  = number, default is 1\n%   cfg.symmetry    = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = [])\n%   cfg.channel     = Nx1 cell-array with selection of channels (default = 'all'),\n%                     see FT_CHANNELSELECTION for details\n%   cfg.gridsearch  = 'yes' or 'no', perform global search for initial\n%                     guess for the dipole parameters (default = 'yes')\n%   cfg.nonlinear   = 'yes' or 'no', perform nonlinear search for optimal\n%                     dipole parameters (default = 'yes')\n%\n% If you start with a grid search, the complete grid with dipole positions and\n% optionally precomputed leadfields is constructed using FT_PREPARE_SOURCEMODEL. It\n% can be specified as as a regular 3-D grid that is aligned with the axes of the head\n% coordinate system using\n%   cfg.xgrid               = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.ygrid               = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.zgrid               = vector (e.g.   0:1:20) or 'auto' (default = 'auto')\n%   cfg.resolution          = number (e.g. 1 cm) for automatic grid generation\n% If the source model destribes a triangulated cortical sheet, it is described as\n%   cfg.sourcemodel.pos     = N*3 matrix with the vertex positions of the cortical sheet\n%   cfg.sourcemodel.tri     = M*3 matrix that describes the triangles connecting the vertices\n% Alternatively the position of a few dipoles at locations of interest can be\n% user-specified, for example obtained from an anatomical or functional MRI\n%   cfg.sourcemodel.pos     = N*3 matrix with position of each source\n%   cfg.sourcemodel.inside  = N*1 vector with boolean value whether grid point is inside brain (optional)\n%   cfg.sourcemodel.dim     = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional)\n%\n% If you do not start with a grid search, you have to give a starting location\n% for the nonlinear search\n%   cfg.dip.pos     = initial dipole position, matrix of Ndipoles x 3\n%\n% The conventional approach is to fit dipoles to event-related averages, which\n% within FieldTrip can be obtained from the FT_TIMELOCKANALYSIS or from\n% the FT_TIMELOCKGRANDAVERAGE function. This has the additional options\n%   cfg.latency     = [begin end] in seconds or 'all' (default = 'all')\n%   cfg.model       = 'moving' or 'regional'\n% A moving dipole model has a different position (and orientation) for each\n% timepoint, or for each component. A regional dipole model has the same\n% position for each timepoint or component, and a different orientation.\n%\n% You can also fit dipoles to the spatial topographies of an independent\n% component analysis, obtained from the FT_COMPONENTANALYSIS function.\n% This has the additional options\n%   cfg.component   = array with numbers (can be empty -> all)\n%\n% You can also fit dipoles to the spatial topographies that are present\n% in the data in the frequency domain, which can be obtained using the\n% FT_FREQANALYSIS function. This has the additional options\n%   cfg.frequency   = single number (in Hz)\n%\n% Low level details of the fitting can be specified in the cfg.dipfit structure\n%   cfg.dipfit.display      = level of display, can be 'off', 'iter', 'notify' or 'final' (default = 'iter')\n%   cfg.dipfit.optimfun     = function to use, can be 'fminsearch' or 'fminunc' (default is determined automatic)\n%   cfg.dipfit.maxiter      = maximum number of function evaluations allowed (default depends on the optimfun)\n%   cfg.dipfit.checkinside  = boolean, check that the dipole remains in the source compartment (default = false)\n%\n% Optionally, you can modify the leadfields by reducing the rank, i.e. remove the weakest orientation\n%   cfg.reducerank      = 'no', or number (default = 3 for EEG, 2 for MEG)\n%   cfg.normalize       = 'no', 'yes' or 'column'\n%   cfg.normalizeparam  = parameter for depth normalization (default = 0.5)\n%   cfg.weight          = number or 1xN vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1)\n%   cfg.backproject     = 'yes' (default) or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace\n%\n% The volume conduction model of the head should be specified as\n%   cfg.headmodel     = structure with volume conduction model, see FT_PREPARE_HEADMODEL\n%\n% The EEG or MEG sensor positions can be present in the data or can be specified as\n%   cfg.elec          = structure with electrode positions or filename, see FT_READ_SENS\n%   cfg.grad          = structure with gradiometer definition or filename, see FT_READ_SENS\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_SOURCEANALYSIS, FT_PREPARE_LEADFIELD, FT_PREPARE_HEADMODEL\n\n% TODO change the output format, more suitable would be something like:\n% dip.label\n% dip.time\n% dip.avg (instead of Vdata)\n% dip.dip.pos\n% dip.dip.mom\n% dip.dip.model, or dip.dip.avg\n% dip.dimord\n\n% Undocumented local options:\n%   cfg.dipfit.constr   = Source model constraints, depends on cfg.symmetry\n% Optionally, you can include a noise covariance structure to sphere the data (is useful when using both\n% magnetometers and gradiometers to fit your dipole)\n%   cfg.dipfit.noisecov       = noise covariance matrix, see e.g. FT_TIMELOCK_ANALYSIS\n\n% Copyright (C) 2004-2013, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar data\nft_preamble provenance data\nft_preamble trackconfig\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% check if the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', {'comp', 'timelock', 'freq'}, 'feedback', 'yes');\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed', {'elecfile', 'elec'});\ncfg = ft_checkconfig(cfg, 'renamed', {'gradfile', 'grad'});\ncfg = ft_checkconfig(cfg, 'renamed', {'optofile', 'opto'});\ncfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'vol',     'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'grid',    'sourcemodel'});\n\n% get the defaults\ncfg.channel         = ft_getopt(cfg, 'channel', 'all');\ncfg.component       = ft_getopt(cfg, 'component');        % for comp input\ncfg.frequency       = ft_getopt(cfg, 'frequency');        % for freq input\ncfg.latency         = ft_getopt(cfg, 'latency', 'all');   % for timeclock input\ncfg.feedback        = ft_getopt(cfg, 'feedback', 'text');\ncfg.gridsearch      = ft_getopt(cfg, 'gridsearch', 'yes');\ncfg.nonlinear       = ft_getopt(cfg, 'nonlinear', 'yes');\ncfg.symmetry        = ft_getopt(cfg, 'symmetry');\ncfg.dipfit          = ft_getopt(cfg, 'dipfit', []);     % the default for this is handled below\n% the following options are for on-the-fly leadfield computation\ncfg.reducerank      = ft_getopt(cfg, 'reducerank', []); % the default for this is handled below\ncfg.normalize       = ft_getopt(cfg, 'normalize');      % this is better not used in dipole fitting\ncfg.normalizeparam  = ft_getopt(cfg, 'normalizeparam'); % this is better not used in dipole fitting\ncfg.backproject     = ft_getopt(cfg, 'backproject');    % this is better not used in dipole fitting\ncfg.weight          = ft_getopt(cfg, 'weight');         % this is better not used in dipole fitting\n\ncfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\n% the default for this depends on the data type\nif ~isfield(cfg, 'model')\n  if ~isempty(cfg.component)\n    % each component is fitted independently\n    cfg.model = 'moving';\n  elseif ~isempty(cfg.frequency)\n    % fit the data with a dipole at one location\n    cfg.model = 'regional';\n  elseif ~isempty(cfg.latency)\n    % fit the data with a dipole at one location\n    cfg.model = 'regional';\n  end\nend\n\nif ~isfield(cfg, 'numdipoles')\n  if isfield(cfg, 'dip')\n    cfg.numdipoles = size(cfg.dip(1).pos,1);\n  else\n    cfg.numdipoles = 1;\n  end\nend\n\n% set up the symmetry constraints\nif ~isempty(cfg.symmetry)\n  if cfg.numdipoles~=2\n    ft_error('symmetry constraints are only supported for two-dipole models');\n  elseif strcmp(cfg.symmetry, 'x')\n    % this structure is passed onto the low-level ft_dipole_fit function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 -1 1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 -x1 y1 z1]\n  elseif strcmp(cfg.symmetry, 'y')\n    % this structure is passed onto the low-level ft_dipole_fit function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 1 -1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 -y1 z1]\n  elseif strcmp(cfg.symmetry, 'z')\n    % this structure is passed onto the low-level ft_dipole_fit function\n    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]\n    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]\n    cfg.dipfit.constr.mirror = [1 1 1 1 1 -1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 y1 -z1]\n  else\n    ft_error('unrecognized symmetry constraint');\n  end\nelseif ~isfield(cfg, 'dipfit') || ~isfield(cfg.dipfit, 'constr')\n  % no symmetry constraints have been specified\n  cfg.dipfit.constr = [];\nend\n\nif ft_getopt(cfg.dipfit.constr, 'sequential', false) && strcmp(cfg.model, 'moving')\n  ft_error('the moving dipole model does not combine with the sequential constraint')\n  % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3119\nend\n\nif isfield(data, 'topolabel')\n  % this looks like a component analysis\n  iscomp = 1;\n  % transform the data into a representation on which the timelocked dipole fit can perform its trick\n  data = comp2timelock(cfg, data);\nelse\n  iscomp = 0;\nend\n\nif isfield(data, 'freq')\n  % this looks like a frequency analysis\n  isfreq = 1;\n  % transform the data into a representation on which the timelocked dipole fit can perform its trick\n  data = freq2timelock(cfg, data);\nelse\n  isfreq = 0;\nend\n\n% prepare the volume conduction model and the sensor array\n% this updates the configuration with the appropriate fields\n[headmodel, sens, cfg] = prepare_headmodel(cfg, data);\n\n% set the default for reducing the rank of the leadfields\nif isempty(cfg.reducerank)\n  if ft_senstype(sens, 'eeg')\n    cfg.reducerank = 'no';    % for EEG\n  elseif ft_senstype(sens, 'meg') && ft_headmodeltype(headmodel, 'infinite')\n    cfg.reducerank = 'no';    % for MEG with a magnetic dipole, e.g. a HPI coil\n  elseif ft_senstype(sens, 'meg')\n    cfg.reducerank = 'yes';   % for MEG with a current dipole in a volume conductor\n  end\nend\n\n% construct the options for the leadfield computation, the same options are also passed to DIPOLE_FIT\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     cfg.reducerank);\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      cfg.normalize);\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', cfg.normalizeparam);\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         cfg.weight);\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    cfg.backproject);\n\n% select the desired channels, ordered according to the sensor structure\n[selsens, seldata] = match_str(sens.label, data.label);\n% take the selected channels from the data structure\nVdata = data.avg(seldata, :);\n\n% sphere the date using the noise covariance matrix supplied, if any\n% this affects both the gridsearch and the nonlinear optimization\nnoisecov = ft_getopt(cfg.dipfit, 'noisecov');\nif ~isempty(noisecov)\n  [u, s] = svd(noisecov);\n  tol = max(size(noisecov)) * eps(norm(s, inf));\n  s = diag(s);\n  r1 = sum(s > tol) + 1;\n  s(1:(r1 - 1)) = 1 ./ sqrt(s(1:(r1 - 1)));\n  s(r1:end)     = 0;\n  sphere = diag(s) * u';\n  % apply the sphering to the data\n  Vdata = sphere * Vdata;\n  % apply the sphering as a pre-multiplication to the sensor definition\n  montage = [];\n  montage.labelold = cfg.channel;\n  montage.labelnew = cfg.channel;\n  montage.tra = sphere;\n  sens = ft_apply_montage(sens, montage, 'balancename', 'sphering');\nend\n\nif iscomp\n  % select the desired component topographies\n  Vdata = Vdata(:, cfg.component);\nelseif isfreq\n  % the desired frequencies have already been selected\n  Vdata = Vdata(:, :);\nelse\n  % select the desired latencies\n  if ischar(cfg.latency) && strcmp(cfg.latency, 'all')\n    cfg.latency = data.time([1 end]);\n  end\n  tbeg = nearest(data.time, cfg.latency(1));\n  tend = nearest(data.time, cfg.latency(end));\n  cfg.latency = [data.time(tbeg) data.time(tend)];\n  Vdata = Vdata(:, tbeg:tend);\nend\n\nnchans = size(Vdata,1);\nntime  = size(Vdata,2);\nVmodel = zeros(nchans, ntime);\nfprintf('selected %d channels\\n', nchans);\nfprintf('selected %d topographies\\n', ntime);\n\nif nchans<cfg.numdipoles*3\n  ft_warning('not enough channels to perform a dipole fit');\nend\n\nif ntime<1\n  ft_error('no spatial topography selected');\nend\n\n% check whether EEG is average referenced\nif ft_senstype(sens, 'eeg')\n  if any(rv(Vdata, avgref(Vdata))>0.001)\n    ft_warning('the EEG data is not average referenced, correcting this');\n  end\n  Vdata = avgref(Vdata);\nend\n\n% set to zeros if no initial dipole was specified\nif ~isfield(cfg, 'dip')\n  cfg.dip.pos = zeros(cfg.numdipoles, 3);\n  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);\nend\n\n% set to zeros if no initial dipole position was specified\nif ~isfield(cfg.dip, 'pos')\n  cfg.dip.pos = zeros(cfg.numdipoles, 3);\nend\n\n% set to zeros if no initial dipole moment was specified\nif ~isfield(cfg.dip, 'mom')\n  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);\nend\n\n% check the specified dipole model\nif numel(cfg.dip.pos)~=cfg.numdipoles*3 || numel(cfg.dip.mom)~=cfg.numdipoles*3\n  ft_error('inconsistent number of dipoles in configuration')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% perform the dipole scan, this is usefull for generating an initial guess\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif strcmp(cfg.gridsearch, 'yes')\n  % test whether we have a valid configuration for dipole scanning\n  if cfg.numdipoles==1\n    % this is ok\n  elseif cfg.numdipoles==2 && ~isempty(cfg.dipfit.constr)\n    % this is also ok\n  elseif isfield(cfg.sourcemodel, 'pos') && size(cfg.sourcemodel.pos,2)==cfg.numdipoles*3\n    % this is also ok\n  else\n    ft_error('dipole scanning is only possible for a single dipole or a symmetric dipole pair');\n  end\n\n  % copy all options that are potentially used in ft_prepare_sourcemodel\n  tmpcfg           = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo'});\n  tmpcfg.headmodel = headmodel;\n  if ft_senstype(sens, 'eeg')\n    tmpcfg.elec = sens;\n  elseif ft_senstype(sens, 'meg')\n    tmpcfg.grad = sens;\n  end\n  % construct the dipole grid on which the gridsearch will be done\n  sourcemodel = ft_prepare_sourcemodel(tmpcfg);\n\n  ngrid = size(sourcemodel.pos,1);\n\n  switch cfg.model\n    case 'regional'\n      sourcemodel.error = nan(ngrid, 1);\n    case 'moving'\n      sourcemodel.error = nan(ngrid, ntime);\n    otherwise\n      ft_error('unsupported cfg.model');\n  end\n\n  insideindx = find(sourcemodel.inside);\n  ft_progress('init', cfg.feedback, 'scanning grid');\n  for i=1:length(insideindx)\n    ft_progress(i/length(insideindx), 'scanning grid location %d/%d\\n', i, length(insideindx));\n    thisindx = insideindx(i);\n    if isfield(sourcemodel, 'leadfield')\n      % reuse the previously computed leadfield\n      lf = sourcemodel.leadfield{thisindx};\n    else\n      lf = ft_compute_leadfield(sourcemodel.pos(thisindx,:), sens, headmodel, leadfieldopt{:});\n    end\n    % the model is V=lf*mom+noise, therefore mom=pinv(lf)*V estimates the\n    % dipole moment this makes the model potential U=lf*pinv(lf)*V and the\n    % model error is norm(V-U) = norm(V-lf*pinv(lf)*V) = norm((eye-lf*pinv(lf))*V)\n    if any(isnan(lf(:)))\n      % this might happen if one of the dipole locations of the grid is\n      % outside the brain compartment\n      lf(:) = 0;\n    end\n    switch cfg.model\n      case 'regional'\n        % sum the error over all latencies\n        sourcemodel.error(thisindx,1) = sum(sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2));\n      case 'moving'\n        % remember the error for each latency independently\n        sourcemodel.error(thisindx,:) = sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2);\n      otherwise\n        ft_error('unsupported cfg.model');\n    end % switch model\n  end % looping over the grid\n  ft_progress('close');\n\n  switch cfg.model\n    case 'regional'\n      % find the source position with the minimum error\n      [err, indx] = min(sourcemodel.error);\n      dip.pos = sourcemodel.pos(indx,:);                % note that for a symmetric dipole pair this results in a vector\n      dip.pos = reshape(dip.pos,3,cfg.numdipoles)';     % convert to a Nx3 array\n      dip.mom = zeros(cfg.numdipoles*3,1);              % set the dipole moment to zero\n      if cfg.numdipoles==1\n        fprintf('found minimum after scanning on grid point [%g %g %g]\\n', dip.pos(1), dip.pos(2), dip.pos(3));\n      elseif cfg.numdipoles==2\n        fprintf('found minimum after scanning on grid point [%g %g %g; %g %g %g]\\n', dip.pos(1), dip.pos(2), dip.pos(3), dip.pos(4), dip.pos(5), dip.pos(6));\n      end\n\n    case 'moving'\n      for t=1:ntime\n        % find the source position with the minimum error\n        [err, indx] = min(sourcemodel.error(:,t));\n        dip(t).pos = sourcemodel.pos(indx,:);                        % note that for a symmetric dipole pair this results in a vector\n        dip(t).pos = reshape(dip(t).pos,3,cfg.numdipoles)';   % convert to a Nx3 array\n        dip(t).mom = zeros(cfg.numdipoles*3,1);               % set the dipole moment to zero\n        if cfg.numdipoles==1\n          fprintf('found minimum after scanning for topography %d on grid point [%g %g %g]\\n', t, dip(t).pos(1), dip(t).pos(2), dip(t).pos(3));\n        elseif cfg.numdipoles==2\n          fprintf('found minimum after scanning for topography %d on grid point [%g %g %g; %g %g %g]\\n', t, dip(t).pos(1), dip(t).pos(2), dip(t).pos(3), dip(t).pos(4), dip(t).pos(5), dip(t).pos(6));\n        end\n      end\n\n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\n\nelseif strcmp(cfg.gridsearch, 'no')\n  % use the initial guess supplied in the configuration for the remainder\n  switch cfg.model\n    case 'regional'\n      dip = struct(cfg.dip);      % ensure that it is a struct, not a config object\n    case 'moving'\n      for t=1:ntime\n        dip(t) = struct(cfg.dip); % ensure that it is a struct, not a config object\n      end\n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\n\nend % if gridsearch yes/no\n% multiple dipoles can be represented either as a 1x(N*3) vector or as a Nx3 matrix,\n% i.e. [x1 y1 z1 x2 y2 z2] or [x1 y1 z1; x2 y2 z2]\nswitch cfg.model\n  case 'regional'\n    dip = fixdipole(dip);\n  case 'moving'\n    for t=1:ntime\n      dip(t) = fixdipole(dip(t));\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\n% convert the structure with the additional low-level options into key-value pairs\ndipfitopt = ft_cfg2keyval(cfg.dipfit);\n\n% add the options for the leadfield computation\ndipfitopt = ft_setopt(dipfitopt, 'reducerank',     cfg.reducerank);\ndipfitopt = ft_setopt(dipfitopt, 'normalize',      cfg.normalize);\ndipfitopt = ft_setopt(dipfitopt, 'normalizeparam', cfg.normalizeparam);\ndipfitopt = ft_setopt(dipfitopt, 'weight',         cfg.weight);\ndipfitopt = ft_setopt(dipfitopt, 'backproject',    cfg.backproject);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% perform the non-linear fit\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif strcmp(cfg.nonlinear, 'yes')\n  switch cfg.model\n    case 'regional'\n      % perform the non-linear dipole fit for all latencies together\n      % catch errors due to non-convergence\n      try\n        dip = dipole_fit(dip, sens, headmodel, Vdata, dipfitopt{:});\n        success = 1;\n        if cfg.numdipoles==1\n          fprintf('found minimum after non-linear optimization on [%g %g %g]\\n', dip.pos(1), dip.pos(2), dip.pos(3));\n        elseif cfg.numdipoles==2\n          fprintf('found minimum after non-linear optimization on [%g %g %g; %g %g %g]\\n', dip.pos(1,1), dip.pos(1,2), dip.pos(1,3), dip.pos(2,1), dip.pos(2,2), dip.pos(2,3));\n        end\n      catch\n        success = 0;\n        disp(lasterr);\n      end\n\n    case 'moving'\n      % perform the non-linear dipole fit for each latency independently\n      % instead of using dip(t) = dipole_fit(dip(t),...), I am using temporary variables dipin and dipout\n      % to prevent errors like \"Subscripted assignment between dissimilar structures\"\n      dipin = dip;\n      for t=1:ntime\n        % catch errors due to non-convergence\n        try\n          dipout(t) = dipole_fit(dipin(t), sens, headmodel, Vdata(:,t), dipfitopt{:});\n          success(t) = 1;\n          if cfg.numdipoles==1\n            fprintf('found minimum after non-linear optimization for topography %d on [%g %g %g]\\n', t, dipout(t).pos(1), dipout(t).pos(2), dipout(t).pos(3));\n          elseif cfg.numdipoles==2\n            fprintf('found minimum after non-linear optimization for topography %d on [%g %g %g; %g %g %g]\\n', t, dipout(t).pos(1,1), dipout(t).pos(1,2), dipout(t).pos(1,3), dipout(t).pos(2,1), dipout(t).pos(2,2), dipout(t).pos(2,3));\n          end\n        catch\n          % keep the position and moment according to the initial guess\n          dipout(t).pos = dipin(t).pos;\n          dipout(t).mom = dipin(t).mom;\n          success(t) = 0;\n          disp(lasterr);\n        end\n      end\n      dip = dipout;\n      clear dipin dipout\n    otherwise\n      ft_error('unsupported cfg.model');\n  end % switch model\nend % if nonlinear\n\nif strcmp(cfg.nonlinear, 'no')\n  % the optimal dipole positions are either obtained from scanning\n  % or from the initial configured specified by the user\n  switch cfg.model\n    case 'regional'\n      success = 1;\n    case 'moving'\n      success = ones(1,ntime);\n    otherwise\n      ft_error('unsupported cfg.model');\n\n  end % switch model\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute the model potential distribution and the residual variance\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch cfg.model\n  case 'regional'\n    if success\n      % re-compute the leadfield in order to compute the model potential and dipole moment\n      lf = ft_compute_leadfield(dip.pos, sens, headmodel, leadfieldopt{:});\n      if isfield(dip, 'mom') && isfield(dip, 'ampl')\n        % the orientation and amplitude have already been estimated, this applies to the case of a fixed dipole orientation\n        dip.pot = (lf * dip.mom) * dip.ampl;\n      else\n        % compute all details of the final dipole model using linear estimation\n        dip.mom = pinv(lf)*Vdata;\n        dip.pot = lf*dip.mom;\n      end\n      dip.rv  = rv(Vdata, dip.pot);\n      Vmodel  = dip.pot;\n    end\n  case 'moving'\n    for t=1:ntime\n      if success(t)\n        % re-compute the leadfield in order to compute the model potential and dipole moment\n        lf = ft_compute_leadfield(dip(t).pos, sens, headmodel, leadfieldopt{:});\n        % compute all details of the final dipole model\n        dip(t).mom = pinv(lf)*Vdata(:,t);\n        dip(t).pot = lf*dip(t).mom;\n        dip(t).rv  = rv(Vdata(:,t), dip(t).pot);\n        Vmodel(:,t) = dip(t).pot;\n      end\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\nswitch cfg.model\n  case 'regional'\n    if isfreq\n      % the matrix with the dipole moment is encrypted and cannot be interpreted straight away\n      % reconstruct the frequency representation of the data at the source level\n      if isfield(dip, 'mom') && isfield(dip, 'ampl')\n        % this applies to the case of a fixed dipole orientation\n        [dip.pow, dip.csd, dip.fourier] = timelock2freq(dip.mom * dip.ampl);\n      else\n        [dip.pow, dip.csd, dip.fourier] = timelock2freq(dip.mom);\n      end\n    end\n  case 'moving'\n    if isfreq\n      % although this is technically possible so far, it does not make any sense\n      ft_warning('a moving dipole model in the frequency domain is not supported');\n    end\n  otherwise\n    ft_error('unsupported cfg.model');\nend % switch model\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% collect the results\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsource.label  = cfg.channel; % these channels were used in fitting\nsource.dip    = dip;\nsource.Vdata  = Vdata;  % FIXME this should be renamed (if possible w.r.t. EEGLAB)\nsource.Vmodel = Vmodel; % FIXME this should be renamed (if possible w.r.t. EEGLAB)\n\n% the units of the fitted source are the same as the units of the headmodel and the sensor array\nfor i=1:length(source.dip)\n  source.dip(i).unit = headmodel.unit;\nend\n\n% assign a latency, frequeny or component axis to the output\nif iscomp\n  source.component = cfg.component;\n  % FIXME assign Vdata to an output variable, idem for the model potential\nelseif isfreq\n  source.freq   = cfg.frequency;\n  source.dimord = 'chan_freq';\n  % FIXME assign Vdata to an output variable, idem for the model potential\nelse\n  tbeg = nearest(data.time, cfg.latency(1));\n  tend = nearest(data.time, cfg.latency(end));\n  source.time   = data.time(tbeg:tend);\n  source.dimord = 'chan_time';\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble trackconfig\nft_postamble previous   data\nft_postamble provenance source\nft_postamble history    source\nft_postamble savevar    source\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/ft_dipolefitting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.20580189781752886}}
{"text": "%train\n%dataset_dir = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/NYU/dataset/train/';\n%save_dir = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/NYU/dataset/train/parsed/';\n%tot_frame_num = 72757;\n\n%test\ndataset_dir = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/NYU/dataset/test/';\nsave_dir = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/NYU/dataset/test/parsed/';\ntot_frame_num = 8252;\n\nkinect_index = 1;\n\nfor image_index = 1:tot_frame_num\n    filename_prefix = sprintf('%d_%07d', kinect_index, image_index);\n\n    if exist([dataset_dir, 'depth_', filename_prefix, '.png'], 'file')\n\n        %% Load and display a depth example\n        % The top 8 bits of depth are packed into green and the lower 8 bits into blue.\n        depth = imread([dataset_dir, 'depth_', filename_prefix, '.png']);\n        depth = uint16(depth(:,:,3)) + bitsll(uint16(depth(:,:,2)), 8);\n        \n        fp_save = fopen([save_dir, 'depth_', filename_prefix, '.bin'],'w');\n        fwrite(fp_save,permute(depth,[2,1,3]),'float');\n        fclose(fp_save);\n\n        %delete(strcat(folderpath,img_name));\n    end\n\nend\n", "meta": {"author": "mks0601", "repo": "V2V-PoseNet_RELEASE", "sha": "8b436182161337bba3adb1690e0bc834ef72e9f2", "save_path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE", "path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE/V2V-PoseNet_RELEASE-8b436182161337bba3adb1690e0bc834ef72e9f2/data/NYU/PNG2BIN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2057658573258315}}
{"text": "function [image] = LoadImage(directory, timestamp, LUT)\n  \n% LoadImage - load a rectified image from disk\n%\n% [image] = LoadImage(directory, timestamp, LUT)\n%\n% eg.\n% timestamps = dlmread('<dataset_root>/stereo.timestamps');\n% [ ~, ~, ~, ~, ~, LUT] = ...\n%     ReadCameraModel('<models_dir>/stereo_wide_left_undistortion.bin');\n% image = LoadImage('<dataset_root>/stereo/left', timestamps(100,1), LUT);\n%\n% INPUTS:\n%   directory: directory containing images named <timestamp>.png\n%   timestamp: timestamp of image to load\n%   LUT (optional): lookup table for image rectification, as returned from \n%     ReadCameraModel. If not supplied, original distorted image will be \n%     returned.\n%     See ReadCameraModel and UndistortImage\n%   \n% OUTPUTS:\n%   image: image at the given timestamp. If an undistortion lookup table is\n%     supplied, image will be undistorted.\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (c) 2016 University of Oxford\n% Authors: \n%  Geoff Pascoe (gmp@robots.ox.ac.uk)\n%  Will Maddern (wm@robots.ox.ac.uk)\n%\n% This work is licensed under the Creative Commons \n% Attribution-NonCommercial-ShareAlike 4.0 International License. \n% To view a copy of this license, visit \n% http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to \n% Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  if directory(end) ~= '/'\n    directory = [directory '/'];\n  end\n  \n  path = [directory num2str(timestamp) '.png'];\n  if ~exist(path, 'file')\n    image = false;\n    return;\n  end\n  \n  if regexp(directory, 'stereo')\n    bayer_pattern = 'gbrg';\n  else\n    bayer_pattern = 'rggb';\n  end\n  \n  image = demosaic(imread(path), bayer_pattern);\n  \n  if exist('LUT', 'var')\n    image = UndistortImage(image, LUT);\n  end\n  \nend\n", "meta": {"author": "ori-mrg", "repo": "robotcar-dataset-sdk", "sha": "16ce3329223ca418fe5106277b91aea8d9b672b2", "save_path": "github-repos/MATLAB/ori-mrg-robotcar-dataset-sdk", "path": "github-repos/MATLAB/ori-mrg-robotcar-dataset-sdk/robotcar-dataset-sdk-16ce3329223ca418fe5106277b91aea8d9b672b2/matlab/LoadImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20576585732583147}}
{"text": "% Run setupThermoModel for the E. coli metabolic reconstruction iAF1260\n\n% Requires an installation of:\n% OpenBabel\n\n%% Add required fields and directories to path\ninitVonBertalanffy\n\n%todo, clean up this so it is not needed\nglobal CBTDIR\npth=which('initCobraToolbox.m');\nCBTDIR = pth(1:end-(length('initCobraToolbox.m')+1));\n\ncd([CBTDIR filesep 'test' filesep 'testVonBertalanffy'])\n\n%% Configure inputs\nload iAF1260\nif model.S(952,350)==0\n    model.S(952,350)=1; % One reaction needing mass balancing in iAF1260\nend\nmodel.metCharges(strcmp('asntrna[c]',model.mets))=0; % One reaction needing charge balancing\n\nmolfileDir = 'iAF1260Molfiles'; % Directory containing molfiles\n\ncid = []; % KEGG Compound identifiers. Not required since molfile directory is specified.\n\nT = 310.15; % Temperature in Kelvin\ncellCompartments = ['c'; 'e'; 'p']; % Cell compartment identifiers\nph = [7.7; 7.7; 7.7]; % Compartment specific pH\nis = [0.25; 0.25; 0.25]; % Compartment specific ionic strength in mol/L\nchi = [0; 90; 90]; % Compartment specific electrical potential relative to cytosol in mV\n\nxmin = 1e-5*ones(size(model.mets)); % Lower bounds on metabolite concentrations in mol/L\nxmax = 0.02*ones(size(model.mets)); % Upper bounds on metabolite concentrations in mol/L\n\nconfidenceLevel = 0.95; % Confidence level for estimated standard transformed reaction Gibbs energies. Used to quantitatively assign reaction directionality.\n\n%% Call setupThermoModel\nmodelT = setupThermoModel(model,molfileDir,cid,T,cellCompartments,ph,is,chi,xmin,xmax,confidenceLevel);\n\nsave('iAF1260Thermo_test.mat', 'modelT', '-v7');\n\n%% Compare test results to expected results\nclear all;\n\nold = load('iAF1260Thermo.mat');\nnew = load('iAF1260Thermo_test.mat');\n\n% Check for differences in estimated standard transformed Gibbs energies of formation\nfig = figure(1);\nsubplot(1,3,1);\nrmse1 = sqrt(mean( (new.modelT.DfGt0 - old.modelT.DfGt0).^2 ));\nfprintf('RMSE difference between the old and new DfGt0: %g\\n', rmse1);\ncdfplot(abs((new.modelT.DfGt0 - old.modelT.DfGt0)));\nxlabel('|D_f G^{\\prime\\circ}(new) - D_f G^{\\prime\\circ}(old)|');\ntitle(['\\Delta_f G^{\\prime\\circ} RMSE = ' sprintf('%g', rmse1)]);\n\n% Check for differences in estimated standard transformed reaction Gibbs energies\nsubplot(1,3,2);\nrmse2 = sqrt(mean( (new.modelT.DrGt0 - old.modelT.DrGt0).^2 ));\nfprintf('RMSE difference between the old and new DrGt0: %g\\n', rmse2);\ncdfplot(abs((new.modelT.DrGt0 - old.modelT.DrGt0)));\nxlabel('|D_r G^{\\prime\\circ}(new) - D_r G^{\\prime\\circ}(old)|');\ntitle(['\\Delta_r G^{\\prime\\circ} RMSE = ' sprintf('%g', rmse2)]);\n\n% Check for differences in uncertainty levels - indicative of differences in coverage\nsubplot(1,3,3);\nrmse3 = sqrt(mean( (new.modelT.uf - old.modelT.uf).^2 ));\nfprintf('RMSE difference between the old and new uf: %g\\n', rmse3);\ncdfplot(abs((new.modelT.uf - old.modelT.uf)));\nxlabel('|U_f (new) - U_f (old)|');\ntitle(['U_f RMSE = ' sprintf('%g', rmse3)]);\n\nprint(fig, 'iAF1260_compare.eps', '-deps');\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/additionalTests/testVonBertalanffy/testVonBertalanffy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20576585143295228}}
{"text": "function kern = componentKernReadParamsFromFID(kern, FID, version)\n\n% COMPONENTKERNREADPARAMSFROMFID Read a component based kernel from a C++ file.\n% FORMAT\n% DESC reads the components fo a kernel from a file written by C++ code.\n% ARG kern : the base kernel to add components to.\n% ARG FID : the input file stream to add from.\n% RETURN kern : the kernel with the components added in.\n%\n% SEEALSO : modelReadFromFID, kernReadFromFID\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2008\n  \n% KERN\n\nkern.inputDimension = readIntFromFID(FID, 'inputDim');\nnumParams = readIntFromFID(FID, 'numParams');\nnumKerns = readIntFromFID(FID, 'numKerns');\n\nfor i=1:numKerns\n  if version > 0.11\n    kern.comp{i} = modelReadFromFID(FID);\n  else\n    kern.comp{i} = kernReadFromFID(FID, version);\n  end\nend\n\nfor i = 1:length(kern.comp)\n  kern.nParams = kern.nParams + kern.comp{i}.nParams;\n  kern.comp{i}.index = [];\nend\nkern.paramGroups = speye(kern.nParams);\n\nif strcmp(kern.type, 'cmpnd')\n  % Summarise the total white variance in the field whiteVariance.\n  kern.whiteVariance = 0;\n  for i = 1:length(kern.comp)\n    if strcmp(kern.comp{i}.type, 'white')\n      kern.whiteVariance = kern.whiteVariance + kern.comp{i}.variance;\n    else\n      if(isfield(kern.comp{i}, 'whiteVariance'))\n        kern.whiteVariance = kern.whiteVariance + ...\n            kern.comp{i}.whiteVariance;\n      end\n    end\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/componentKernReadParamsFromFID.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20547094960990167}}
{"text": "% IO utility functions to\n% - save data to files.\n% - read, edit mat file timestamps\n%\n% Binary Format for matrices and cell arrays (with matrix and cell array\n% elements) inspired by Arvid Bottiger's write_matrix_bin,\n% 1. 1*uint32               Indicator of cell array\n% 2. 1*uint32               Dimensions of array\n% 3. dimensions*uint32      Lengths of dimensions\n% 4. a. Cell Array => recurse\n%    b. Matrix\n%       1*uint32            Indicator of character array\n%       uint32 or float32   Dat%\n%\n%\n%References:\n%===============\n%- write_matrix_bin by Arvid Bottiger\n%   http://www.mathworks.com/matlabcentral/fileexchange/24483\n%\n% Author: Jonathan Karr\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 7/14/2009\nclassdef IOUtil\n    properties (Constant = true)\n        memmapfileHeaderSize = 1024\n        memmapfileDataField = 'data'\n    end\n    \n    methods (Static)\n        %Writes data to disk in binary format\n        function writeBinary(filename, data)\n            import edu.stanford.covert.util.IOUtil;\n            \n            %open file\n            fid = fopen(filename, 'w');\n            \n            %write data\n            IOUtil.writeDataBinary(fid, data);\n            \n            %close file\n            fclose(fid);\n        end\n        \n        %Reads data from disk in binary format\n        function data = readBinary(filename)\n            import edu.stanford.covert.util.IOUtil;\n            \n            %open file\n            fid = fopen(filename, 'r');\n            \n            %read data\n            data = IOUtil.readDataBinary(fid);\n            \n            %close file\n            fclose(fid);\n        end\n    end\n    \n    methods (Static, Access = protected)\n        %Writes data to disk in binary format\n        function writeDataBinary(fid, data)\n            import edu.stanford.covert.util.IOUtil;\n            \n            %cell array, number of dimensions, size\n            dataIsCell = iscell(data);\n            dataSize = size(data);\n            dimensions = length(dataSize);\n            fwrite(fid, [dataIsCell dimensions dataSize], 'uint32');\n            \n            %reshape data\n            data = reshape(data,1,[]);\n            \n            %write data\n            if dataIsCell\n                for i = 1:length(data)\n                    IOUtil.writeDataBinary(fid, data{i});\n                end\n            else\n                switch class(data)\n                    case 'char',    dataType = 1;\n                    case 'uint8',   dataType = 2;\n                    case 'uint16',  dataType = 3;\n                    case 'uint32',  dataType = 4;\n                    case 'uint64',  dataType = 5;\n                    case 'int8',    dataType = 6;\n                    case 'int16',   dataType = 7;\n                    case 'int32',   dataType = 8;\n                    case 'int64',   dataType = 9;\n                    case 'single',  dataType = 10;\n                    case 'double',  dataType = 11;\n                    case 'logical', dataType = 12;\n                    otherwise\n                        throw(MException('IOUtil:unsupportedDatatype', 'Data type ''%s'' not supported', class(data)));\n                end\n                \n                %character, write no. dimensions, size\n                fwrite(fid,  dataType, 'uint32');\n                \n                %write data\n                switch dataType\n                    case 1,  fwrite(fid, data+0, 'uint16');\n                    case 2,  fwrite(fid, data, 'uint16');  %Note not using uint8\n                    case 3,  fwrite(fid, data, 'uint16');\n                    case 4,  fwrite(fid, data, 'uint32');\n                    case 5,  fwrite(fid, data, 'float64'); %Note not using uint64\n                    case 6,  fwrite(fid, data, 'int16');   %Note not using int8\n                    case 7,  fwrite(fid, data, 'int16');\n                    case 8,  fwrite(fid, data, 'int32');\n                    case 9,  fwrite(fid, data, 'float64'); %Note not using int64\n                    case 10, fwrite(fid, data, 'float32');\n                    case 11, fwrite(fid, data, 'float64');\n                    case 12, fwrite(fid, data, 'uint16');  %Note not using ubit1\n                    otherwise\n                        throw(MException('IOUtil:unsupportedDatatype', 'Data type ''%s'' not supported', dataType));\n                end\n            end\n        end\n        \n        %Reads data from disk in binary format\n        function data = readDataBinary(fid)\n            import edu.stanford.covert.util.IOUtil;\n            \n            %cell array, number of dimensions, size\n            dataIsCell = fread(fid, 1, 'uint32');\n            dimensions = fread(fid, 1, 'uint32');\n            dataSize = fread(fid, dimensions, 'uint32')';\n            count = prod(dataSize);\n            \n            %read data\n            if dataIsCell\n                data = cell(count, 1);\n                for i = 1:count\n                    data{i} = IOUtil.readDataBinary(fid);\n                end\n            else\n                dataType = fread(fid, 1, 'uint32');\n                switch dataType\n                    case 1,  data = char(fread(fid, count, 'uint16')); %#ok<FREAD>\n                    case 2,  data = uint8(fread(fid, count, 'uint16'));\n                    case 3,  data = uint16(fread(fid, count, 'uint16'));\n                    case 4,  data = uint32(fread(fid, count, 'uint32'));\n                    case 5,  data = uint64(fread(fid, count, 'uint64'));\n                    case 6,  data = int8(fread(fid, count, 'int16'));\n                    case 7,  data = int16(fread(fid, count, 'int16'));\n                    case 8,  data = int32(fread(fid, count, 'int32'));\n                    case 9,  data = int64(fread(fid, count, 'int64'));\n                    case 10, data = single(fread(fid, count, 'float32'));\n                    case 11, data = double(fread(fid, count, 'float64'));\n                    case 12, data = logical(fread(fid, count, 'uint16'));\n                    otherwise\n                        throw(MException('IOUtil:unsupportedDatatype', 'Data type ''%d'' not supported', dataType));\n                end\n            end\n            \n            if dimensions > 1\n                data = reshape(data, dataSize);\n            end\n        end\n    end\n    \n    methods (Static)\n        function writeMemmapFile(data, fileName)\n            import edu.stanford.covert.util.IOUtil;\n            \n            %write header\n            format = {class(data) size(data) IOUtil.memmapfileDataField};\n            IOUtil.writeBinary(fileName, format);\n            \n            %write spacing between header and data, and data\n            fileInfo = dir(fileName);\n            if fileInfo.bytes > IOUtil.memmapfileHeaderSize\n                throw(MException('IOUtil:invalidHeader', 'Header size cannot be greater than %d bytes', IOUtil.memmapfileHeaderSize));\n            end\n            \n            fid = fopen(fileName, 'a');\n            fwrite(fid, zeros(IOUtil.memmapfileHeaderSize - fileInfo.bytes, 1, 'uint8'), 'uint8'); %spacing\n            fwrite(fid, data, class(data)); %data\n            fclose(fid);\n        end\n        \n        function result = readMemmapFile(fileName)\n            import edu.stanford.covert.util.IOUtil;\n            \n            format = IOUtil.readBinary(fileName);\n            if all(format{2})\n                result = memmapfile(fileName, ...\n                    'Offset', IOUtil.memmapfileHeaderSize, ...\n                    'Format', format, ...\n                    'Repeat', 1, ...\n                    'Writable', false);\n            else\n                result = struct('Data', struct(format{3}, []));\n                result.Data.(format{3}) = zeros(format{2}, format{1});\n            end\n        end\n    end\n    \n    methods (Static)\n        function directories = getDirectoryNamesRecursively(directory)\n            import edu.stanford.covert.util.IOUtil;\n            if directory(end) == '/' || directory(end) == '\\'\n                directory = directory(1:end-1);\n            end\n            directories = {directory};\n            files = dir(directory);\n\t\t\tfiles = files([files.isdir]);\n            for i = 1:numel(files)\n                if files(i).name(1) ~= '.'\n                    directories = [directories;\n                        IOUtil.getDirectoryNamesRecursively([directory filesep files(i).name])]; %#ok<AGROW>\n                end\n            end\n        end\n    end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+util/IOUtil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.20545835205359722}}
{"text": "% ------------------------------------------------------------------------ \n%  Copyright (C)\n%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n%  University of California Berkeley (UCB) - USA\n% \n%  Jordi Pont-Tuset <jordi.pont@upc.edu>\n%  Pablo Arbelaez <arbelaez@berkeley.edu>\n%  June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n%    \"Multiscale Combinatorial Grouping,\"\n%    Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------\n%\n% This function builds all the MEX files needed.\n% Dependencies needed to build: Boost C++ libraries (http://www.boost.org)\n%\n% ------------------------------------------------------------------------\nfunction build()\n% Check that 'root_dir' has been set\nif ~exist(root_dir,'dir')\n    error('Error building MCG, try updating the value of root_dir in the file \"root_dir.m\"')\nend\n\n%% Include the generic paths and files to compile\ninclude{1} = fullfile(root_dir, 'src', 'aux');  % To get matlab_multiarray.hpp\nif (strcmp(computer(),'PCWIN64') || strcmp(computer(),'PCWIN32'))\n    include{2} = 'C:\\Program Files\\boost_1_55_0';  % Boost libraries (change it if necessary)\nelse\n    include{2} = '/opt/local/include/';  % Boost libraries (change it if necessary)\nend\ninclude{3} = fullfile(root_dir, 'src', 'external','piotr_toolbox'); % To build Piotr toolbox\n\ninclude_str = '';\nfor ii=1:length(include)\n    include_str = [include_str ' -I''' include{ii} '''']; %#ok<AGROW>\nend\n\nbuild_file{1}     = fullfile(root_dir, 'src', 'cands'    ,'mex_assess_one_sel.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_base_perimeters.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_features.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_intersections.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_reduction.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_get_tree_cands.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_prune_tree_to_regions.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_max_margin.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_hole_filling.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_intersect_hierarchies.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_ucm2hier.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_cands2masks.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_cands2labels.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'benchmark','mex_eval_masks.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'benchmark','mex_eval_labels.cpp');\nbuild_file{end+1} = fullfile(root_dir, 'src', 'external' ,'paretofront','paretofront.cpp');\n\n%% Build everything\nif ~exist(fullfile(root_dir, 'lib'),'dir')\n    mkdir(fullfile(root_dir, 'lib'))\nend\n            \nfor ii=1:length(build_file)\n    eval(['mex ''' build_file{ii} ''' -outdir ''' fullfile(root_dir, 'lib') '''' include_str])\nend\n\n%% Build random forest files\nfile1   = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'mex_regressionRF_train.cpp');\nfile2   = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'mex_regressionRF_predict.cpp');\ndep1    = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'cokus.cpp');\ndep2    = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'reg_RF.cpp');\no_file1 = fullfile(root_dir, 'lib', 'mexRF_train');\no_file2 = fullfile(root_dir, 'lib', 'mexRF_predict');\n\neval(['mex ' file1 ' ' dep1 ' ' dep2 ' -output ' o_file1 ' -DMATLAB -O'])\neval(['mex ' file2 ' ' dep1 ' ' dep2 ' -output ' o_file2 ' -DMATLAB -O'])\n\n%% Build structured forest files\neval(['mex ' fullfile(root_dir, 'src', 'external','structured_forest', 'edgesDetectMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\n\n%% Build piotr_toolbox files\neval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',     'convConst.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\neval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',   'gradientMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\neval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',      'imPadMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\neval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox', 'imResampleMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\neval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox', 'rgbConvertMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])\n\n\n%% Build BSR-related files\n% 'ucm_mean_pb'\neval(['mex ' fullfile(root_dir, 'src', 'bsr', 'ucm_mean_pb.cpp') ' -outdir ' fullfile(root_dir, 'lib')])\n\n% 'buildW'\neval(['mex ' fullfile(root_dir, 'src', 'bsr', 'buildW.cpp') ' -outdir ' fullfile(root_dir, 'lib'),...\n            ' -I' fullfile(root_dir,'src','external','BSR','buildW') ' -I' fullfile(root_dir,'src','external','BSR','buildW','util'),...\n            '   ' fullfile(root_dir,'src','external','BSR','buildW','smatrix.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','buildW','ic.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','buildW','affinity.cc'),...\n            ])\n    \n% 'mex_contour_sides'\neval(['mex ' fullfile(root_dir, 'src', 'bsr', 'mex_contour_sides.cpp') ' -outdir ' fullfile(root_dir, 'lib'),...\n            ' -I' fullfile(root_dir,'src','external','BSR','include'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','child_thread.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','runnable.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','thread.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','synchronization','synchronizables','synchronizable.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','synchronization','synchronizables','unsynchronized.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_bad_cast.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_not_found.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_not_implemented.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_index_out_of_bounds.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_invalid_argument.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_null_pointer_dereference.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','exception.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','throwable.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','lang','array.cc'),...                \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','generators','rand_gen_uniform.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source_default.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','mersenne_twister_64.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source_64.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','system_entropy.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','util','randperm.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','matrices','matrix.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','matrices','exceptions','ex_matrix_dimension_mismatch.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','libraries','lib_image.cc'),...\n            '   ' fullfile(root_dir,'src','external','BSR','src','math','libraries','lib_signal.cc'),...                     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','math.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','exact.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','point_2D.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','seg_intersect.cc'),...     \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','triangulation.cc'),...  \n            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','triangle_2D.cc'),...  \n            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','abstract','clusterer.cc'),...  \n            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','abstract','weighted_clusterer.cc'),...  \n            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','kmeans','basic_clusterer.cc'),...  \n            ]);\n\n%% Clear variables\nclear build_file file1 file2 dep1 dep2 o_file1 o_file2 ii include include_str\n\n%% Show message\ndisp('-- Successful compilation of MCG. Enjoy! --')\n\n\n", "meta": {"author": "jponttuset", "repo": "mcg", "sha": "e72031d793abf8921e39a8ef3c20de2198c8b26f", "save_path": "github-repos/MATLAB/jponttuset-mcg", "path": "github-repos/MATLAB/jponttuset-mcg/mcg-e72031d793abf8921e39a8ef3c20de2198c8b26f/full/build.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20544730334387534}}
{"text": "function y = sdpcone(varargin)\n%SDPCONE Low-level operator to define several SDP constraints in vectorized\n%form\n%\n% Input\n%    X       : Linear SDPVAR object of size n^2 x N\n%\n% Example\n%\n% The typical use is when we want to define a very large number of LMI\n% constraints with reduced overhead (no analysis or check for symmetry etc)\n%\n% This operator is very specialized and low-level, and not normally used...\n%\n% X = sdpvar(5);Y = sdpvar(5);\n% F = sdpcone([X(:) Y(:)]); % Equivalent to [X>=0, Y>=0]\n%\n% See also  @SDPVAR/CONE, @SDPVAR/RCONE\n\ny.typeflag = 57;\ny=lmi(y);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/@sdpvar/sdpcone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20544729022867356}}
{"text": "function inv_mix = spm_cfg_eeg_inv_mix\n% Configuration file for merging (using a new inversion) a number of\n% imaging source inversion reconstructions\n%__________________________________________________________________________\n% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging\n\n% Gareth Barnes\n% $Id: spm_cfg_eeg_inv_mix.m 5924 2014-03-19 14:59:12Z gareth $\n\nD = cfg_files;\nD.tag = 'D';\nD.name = 'M/EEG datasets';\nD.filter = 'mat';\nD.num = [1 Inf];\nD.help = {'Select the M/EEG mat files or .mat files containing inverses'};\n\nval = cfg_entry;\nval.tag = 'val';\nval.name = 'Inversion index';\nval.strtype = 'n';\nval.help = {'Index of the cell in D.inv (same for all files) where the forward model can be found and the results will be stored.'};\nval.val = {1};\n\nprefix = cfg_entry;\nprefix.tag = 'prefix';\nprefix.name = 'Merged file prefix';\nprefix.strtype = 's';\nprefix.val={'merged'};\nprefix.help = {'Prefix for the new filename that will contain the merged inversion results'};\n\n\n\n\n\ninv_mix = cfg_exbranch;\ninv_mix.tag = 'inv_mix';\ninv_mix.name = 'Merge source estimates from multiple inversions';\ninv_mix.val = {D, val,prefix};\ninv_mix.help = {'To merge different source level variance estimates based on the same data'};\ninv_mix.prog = @run_inv_mix;\ninv_mix.vout = @vout_inv_mix;\ninv_mix.modality = {'MEG'};\n\nfunction  out = run_inv_mix(job)\n\n\ninverse = [];\nif numel(job.D)<1,\n    error('Need to add a number of files to combine');\nend;\n\n\n%% first compile multiple inversions\ndisp('Loading inversions');\nallID=[];\nallJ=[];\nallqC=[];\nallF=[];\n\nsurfdir=[];\nfor j=1:numel(job.D), %% move through files- assume that changing directory means surface(i.e. lead field also changes)\n    [a1,b1,c1]=fileparts(job.D{j});\n    surfdir=strvcat(surfdir,a1);\nend;\n\n\ngainfiles=[];\nfor j=1:numel(job.D), %% move through files- assume that changing directory means surface(i.e. lead field also changes)\n    \n    try\n        spmfilename=job.D{j};\n        D = spm_eeg_load(spmfilename);\n        inv=D.inv{job.val};\n    catch\n        dum=load(job.D{j});\n        spmfilename=dum.spmfilename;\n        [a0,b1,c1]=fileparts(spmfilename);\n        [a1,b0,c0]=fileparts(job.D{j});\n        D=spm_eeg_load([a1 filesep b1 c1]);\n        inv=dum.inv;\n    end;\n    \n    allF(j)=inv.inverse.F;\n    allqC(j,:)=inv.inverse.qC;\n    \n    allmesh{j}.M   = inv.mesh.tess_mni;\n    allcortex{j}=inv.mesh.tess_ctx;\n    %% transform back to temporal subspace of original data\n    %% (as Us will be different for different surfaces- but just rotations)\n    check_data(j,:)=inv.inverse.U{1}'*inv.inverse.Y(:,1);\n    \n    disp('Loading SPM gain matrices from surface directories');\n    \n    \n    [L,D]=spm_eeg_lgainmat(D);\n    gainfile=[deblank(surfdir(j,:)) filesep D.inv{D.val}.gainmat];\n    gainfiles = strvcat(gainfiles,gainfile);\n    allL1(j,:)=L(1,:);\n    \n    \nend;\n\n\n%% check original data was the same\nif numel(job.D)>1,\n    if max(std(check_data))>max(std(check_data'))/1e6,\n        error('data is not the same for these files');\n    end;\nend;\n\n\n%%NB OCCAMS RAZOR AT 3\nuseind=find(allF>max(allF)-3); %%\nallqC=allqC(useind,:);\nallmesh=allmesh(useind);\nallcortex=allcortex(useind);\ngainfiles=gainfiles(useind,:);\nallL1=allL1(useind,:);\n%% only take unique lead fields out\n[dum,fileind,surfind]=unique(allL1,'rows');\nugainfiles=gainfiles(fileind,:);\n\n\n[a1,b1,c1]=fileparts(spmfilename);\noutdir=surfdir(1,1:max(strfind(surfdir(1,:),filesep))); %% go up one directory\noutfilename=[outdir filesep job.prefix b1 c1];\ndisp(sprintf('Copying and renaming original SPM file to %s',outfilename));\n\nD2=copy(D,outfilename);\n\nif ~isfield(D2.inv{D2.val},'inverse'),\n    disp('No inversion parameters in file, taking from last inversion');\n    D2.inv{D2.val}.inverse=inv.inverse;\nend;\n    \nclear dum inverse D\n\nvert=[];\nface=[];\ncmap1=[];\ncortexstr='';\nfor j=1:length(fileind),\n    offset=uint32(size(vert,1).*ones(size(allmesh{fileind(j)}.M.face)));\n    col=j*10;\n    vert=[vert ;allmesh{fileind(j)}.M.vert];\n    face=[face ;allmesh{fileind(j)}.M.face+offset];\n    cmap1=[cmap1 ;repmat(col,size(allmesh{fileind(j)}.M.face,1),1)];\n \n    cortexstr=[cortexstr sprintf('%s',allcortex{fileind(j)})];\n    if j<length(fileind),\n        cortexstr=[cortexstr ';'];\n    end;\nend;\nfigure;\nh=trisurf(face,vert(:,1),vert(:,2),vert(:,3),cmap1)\nset(h,'Linestyle','none');\nalpha(0.1);\n\n% UPDATE MNI MESH- MAY NEED TO UPDATE OTHERS TOO\n D2.inv{D2.val}.mesh.tess_mni.vert=vert;\n D2.inv{D2.val}.mesh.tess_mni.face=face;\n D2.inv{D2.val}.mesh.tess_ctx=cortexstr;\n\n%D2.save;\nclear vert face cmap1 offset\n\n\nD2=spm_eeg_invert_classic_mix(D2,D2.val,allqC,surfind,ugainfiles);\n\n\ndisp(sprintf('Improvement in model evidence over best single solution %3.2f',D2.inv{D2.val}.inverse.F-max(allF)));\n\n\n\nif ~iscell(D2)\n    D2 = {D2};\nend\n\nfor i = 1:numel(D2)\n    save(D2{i});\nend\n\nout.D = {outfilename};\n\nfunction dep = vout_inv_mix(job)\n% Output is always in field \"D\", no matter how job is structured\ndep = cfg_dep;\ndep.sname = 'M/EEG dataset(s) after imaging source reconstruction';\n% reference field \"D\" from output\ndep.src_output = substruct('.','D');\n% this can be entered into any evaluated input\ndep.tgt_spec   = cfg_findspec({{'filter','mat'}});\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_eeg_inv_mix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2053570805466392}}
{"text": "function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...\n    neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput, ...\n    connectedFromTemplates, addedFromTemplates]=gapReport(model, templateModels)\n% gapReport\n%   Performs a gap analysis and summarizes the results \n%\n%   model                       a model structure\n%   templateModels              a cell array of template models to use for\n%                               gap filling (opt)\n%\n%   noFluxRxns                  cell array with reactions that cannot carry\n%                               flux\n%   noFluxRxnsRelaxed           cell array with reactions that cannot carry\n%                               flux even if the mass balance constraint is \n%                               relaxed so that it is allowed to have \n%                               net production of all metabolites\n%   subGraphs                   structure with the metabolites in each of\n%                               the isolated sub networks\n%   notProducedMets             cell array with the metabolites that\n%                               couldn't have net production\n%   minToConnect                structure with the minimal number of\n%                               metabolites that need to be connected in \n%                               order to be able to produce all other \n%                               metabolites and which metabolites each of\n%                               them connects\n%   neededForProductionMat      matrix where n x m is true if metabolite n\n%                               allows for production of metabolite m\n%   canProduceWithoutInput      cell array with metabolites that could be\n%                               produced even when there is no input to the\n%                               model\n%   canConsumeWithoutOutput     cell array with metabolites that could be\n%                               consumed even when there is no output from\n%                               the model\n%   connectedFromTemplates      cell array with the reactions that could be\n%                               connected using the template models\n%   addedFromTemplates          structure with the reactions that were\n%                               added from the template models and which \n%                               model they were added from\n%\n%   Usage: [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...\n%    neededForProductionMat, connectedFromTemplates, addedFromTemplates]=...\n%    gapReport(model, templateModels)\n\nif nargin<2\n    templateModels=[];\n    connectedFromTemplates=[];\n    addedFromTemplates=[];\nend\n\nfprintf(['Gap analysis for ' model.id ' - ' model.name '\\n\\n']);\nif isfield(model,'unconstrained')\n    calculateINOUT=true;\n    closedModel=model;\n    model=simplifyModel(model);\nelse\n    canConsumeWithoutOutput={};\n    canProduceWithoutInput={};\n    calculateINOUT=false;\nend\n\nmodel2=model;\nmodel2.b=[model2.b inf(numel(model2.mets),1)];\nI=haveFlux(model);\nnoFluxRxns=model.rxns(~I);\nJ=haveFlux(model2);\nnoFluxRxnsRelaxed=model2.rxns(~J);\nbModel=removeReactions(model,~I,true,true);\ncModel=removeReactions(model2,~J,true,true);\nfprintf('***Overview\\n');\nfprintf([num2str(numel(model.rxns)-sum(I)) ' out of ' num2str(numel(model.rxns))...\n    ' reactions cannot carry flux (' num2str(numel(model.rxns)-sum(J)) ' if net production of all metabolites is allowed)\\n']);\nfprintf([num2str(numel(model.mets)-numel(bModel.mets)) ' out of ' num2str(numel(model.mets))...\n    ' metabolites are unreachable (' num2str(numel(model.mets)-numel(cModel.mets)) ' if net production of all metabolites is allowed)\\n']);\n\nfprintf('\\n***Isolated subnetworks\\n');\nsubGraphs=getAllSubGraphs(model);\nfprintf(['A total of ' num2str(size(subGraphs,2)) ' isolated sub-networks are present in the model\\n']);\nfor i=1:size(subGraphs,2)\n    fprintf(['\\t' num2str(i) '. ' num2str(sum(subGraphs(:,i))) ' metabolites\\n']);\nend\n\nfprintf('\\n***Metabolite connectivity\\n');\n[notProducedMets, ~, neededForProductionMat,minToConnect]=checkProduction(model,true,model.comps,false);\nfprintf(['To enable net production of all metabolites, a total of ' num2str(numel(minToConnect)) ' metabolites must be connected\\n']);\nfprintf('Top 10 metabolites to connect:\\n');\nfor i=1:min(10,numel(minToConnect))\n    fprintf(['\\t' num2str(i) '. ' minToConnect{i} '\\n']);\nend\n\nif calculateINOUT==true\n    fprintf('\\n***Mass balancing\\n');\n    produced=canProduce(closedModel);\n    canProduceWithoutInput=closedModel.mets(produced);\n    consumed=canConsume(closedModel);\n    canConsumeWithoutOutput=closedModel.mets(consumed);\n    fprintf([num2str(numel(canConsumeWithoutOutput)) ' metabolites could be consumed without any outputs\\n' num2str(numel(canProduceWithoutInput)) ' metabolites could be produced without any inputs\\n']);\nend\n\nif ~isempty(templateModels)\n    fprintf('\\n***Automated gap-filling\\n');\n    [connectedFromTemplates, ~, addedFromTemplates]=fillGaps(model,templateModels);\n    t=templateModels{1}.id;\n    for i=2:numel(templateModels)\n        t=[t ', ' templateModels{i}.id];\n    end\n    fprintf([num2str(numel(connectedFromTemplates)) ' unconnected reactions can be connected by including ' num2str(numel(addedFromTemplates)) ' reactions from\\n' t '\\n']);\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/core/gapReport.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.20527905327829218}}
{"text": "function res = vl_simplenn(net, x, dzdy, res, varargin)\n%VL_SIMPLENN  Evaluate a SimpleNN network.\n%   RES = VL_SIMPLENN(NET, X) evaluates the convnet NET on data X.\n%   RES = VL_SIMPLENN(NET, X, DZDY) evaluates the convnent NET and its\n%   derivative on data X and output derivative DZDY (foward+bacwkard pass).\n%   RES = VL_SIMPLENN(NET, X, [], RES) evaluates the NET on X reusing the\n%   structure RES.\n%   RES = VL_SIMPLENN(NET, X, DZDY, RES) evaluates the NET on X and its\n%   derivatives reusing the structure RES.\n%\n%   This function process networks using the SimpleNN wrapper\n%   format. Such networks are 'simple' in the sense that they consist\n%   of a linear sequence of computational layers. You can use the\n%   `dagnn.DagNN` wrapper for more complex topologies, or write your\n%   own wrapper around MatConvNet computational blocks for even\n%   greater flexibility.\n%\n%   The format of the network structure NET and of the result\n%   structure RES are described in some detail below. Most networks\n%   expect the input data X to be standardized, for example by\n%   rescaling the input image(s) and subtracting a mean. Doing so is\n%   left to the user, but information on how to do this is usually\n%   contained in the `net.meta` field of the NET structure (see\n%   below).\n%\n%   The NET structure needs to be updated as new features are\n%   introduced in MatConvNet; use the `VL_SIMPLENN_TIDY()` function\n%   to make an old network current, as well as to cleanup and check\n%   the structure of an existing network.\n%\n%   Networks can run either on the CPU or GPU. Use VL_SIMPLENN_MOVE()\n%   to move the network parameters between these devices.\n%\n%   To print or obtain summary of the network structure, use the\n%   VL_SIMPLENN_DISPLAY() function.\n%\n%   VL_SIMPLENN(NET, X, DZDY, RES, 'OPT', VAL, ...) takes the following\n%   options:\n%\n%   `Mode`:: `'normal'`\n%      Specifies the mode of operation. It can be either `'normal'` or\n%      `'test'`. In test mode, dropout and batch-normalization are\n%      bypassed. Note that, when a network is deployed, it may be\n%      preferable to *remove* such blocks altogether.\n%\n%   `ConserveMemory`:: `false`\n%      Aggressively delete intermediate results. This in practice has\n%      a very small performance hit and allows training much larger\n%      models. However, it can be useful to disable it for\n%      debugging. Keeps the values in `res(1)` (input) and `res(end)`\n%      (output) with the outputs of `loss` and `softmaxloss` layers.\n%      It is also possible to preserve individual layer outputs\n%      by setting `net.layers{...}.precious` to `true`.\n%      For back-propagation, keeps only the derivatives with respect to\n%      weights.\n%\n%   `CuDNN`:: `true`\n%      Use CuDNN when available.\n%\n%   `Accumulate`:: `false`\n%      Accumulate gradients in back-propagation instead of rewriting\n%      them. This is useful to break the computation in sub-batches.\n%      The gradients are accumulated to the provided RES structure\n%      (i.e. to call VL_SIMPLENN(NET, X, DZDY, RES, ...).\n%\n%   `BackPropDepth`:: `inf`\n%      Limit the back-propagation to top-N layers.\n%\n%   `SkipForward`:: `false`\n%      Reuse the output values from the provided RES structure and compute\n%      only the derivatives (backward pass).\n%\n%   ## The result format\n%\n%   SimpleNN returns the result of its calculations in the RES\n%   structure array. RES(1) contains the input to the network, while\n%   RES(2), RES(3), ... contain the output of each layer, from first\n%   to last. Each entry has the following fields:\n%\n%   - `res(i+1).x`: the output of layer `i`. Hence `res(1).x` is the\n%     network input.\n%\n%   - `res(i+1).aux`: any auxiliary output data of layer i. For example,\n%     dropout uses this field to store the dropout mask.\n%\n%   - `res(i+1).dzdx`: the derivative of the network output relative\n%     to the output of layer `i`. In particular `res(1).dzdx` is the\n%     derivative of the network output with respect to the network\n%     input.\n%\n%   - `res(i+1).dzdw`: a cell array containing the derivatives of the\n%     network output relative to the parameters of layer `i`. It can\n%     be a cell array for multiple parameters.\n%\n%   ## The network format\n%\n%   The network is represented by the NET structure, which contains\n%   two fields:\n%\n%   - `net.layers` is a cell array with the CNN layers.\n%\n%   - `net.meta` is a grab-bag of auxiliary application-dependent\n%     information, including for example details on how to normalize\n%     input data, the class names for a classifiers, or details of\n%     the learning algorithm. The content of this field is ignored by\n%     VL_SIMPLENN().\n%\n%   SimpleNN is aware of the following layers:\n%\n%   Convolution layer::\n%     The convolution layer wraps VL_NNCONV(). It has fields:\n%\n%     - `layer.type` contains the string `'conv'`.\n%     - `layer.weights` is a cell array with filters and biases.\n%     - `layer.stride` is the sampling stride (e.g. 1).\n%     - `layer.pad` is the padding (e.g. 0).\n%     - `layer.dilate` is the dilation factor (e.g. 1).\n%\n%   Convolution transpose layer::\n%     The convolution transpose layer wraps VL_NNCONVT(). It has fields:\n%\n%     - `layer.type` contains the string `'convt'`.\n%     - `layer.weights` is a cell array with filters and biases.\n%     - `layer.upsample` is the upsampling factor (e.g. 1).\n%     - `layer.crop` is the amount of output cropping (e.g. 0).\n%\n%   Max pooling layer::\n%     The max pooling layer wraps VL_NNPOOL(). It has fields:\n%\n%     - `layer.type` contains the string `'pool'`.\n%     - `layer.method` is the pooling method (either 'max' or 'avg').\n%     - `layer.pool` is the pooling size (e.g. 3).\n%     - `layer.stride` is the sampling stride (usually 1).\n%     - `layer.pad` is the padding (usually 0).\n%\n%   Normalization (LRN) layer::\n%     The normalization layer wraps VL_NNNORMALIZE(). It has fields:\n%\n%     - `layer.type` contains the string `'normalize'` or `'lrn'`.\n%     - `layer.param` contains the normalization parameters (see VL_NNNORMALIZE()).\n%\n%   Spatial normalization layer::\n%     The spatial normalization layer wraps VL_NNSPNORM(). It has fields:\n%\n%     - `layer.type` contains the string `'spnorm'`.\n%     - `layer.param` contains the normalization parameters (see VL_NNSPNORM()).\n%\n%   Batch normalization layer::\n%     This layer wraps VL_NNBNORM(). It has fields:\n%\n%     - `layer.type` contains the string `'bnorm'`.\n%     - `layer.weights` contains is a cell-array with, multiplier and\n%       biases, and moments parameters\n%\n%     Note that moments are used only in `'test'` mode to bypass batch\n%     normalization.\n%\n%   ReLU and Sigmoid layers::\n%     The ReLU layer wraps VL_NNRELU(). It has fields:\n%\n%     - `layer.type` contains the string `'relu'`.\n%     - `layer.leak` is the leak factor (e.g. 0).\n%\n%     The sigmoid layer is the same, but for the sigmoid function,\n%     with `relu` replaced by `sigmoid` and no leak factor.\n%\n%   Dropout layer::\n%     The dropout layer wraps VL_NNDROPOUT(). It has fields:\n%\n%     - `layer.type` contains the string `'dropout'`.\n%     - `layer.rate` is the dropout rate (e.g. 0.5).\n%\n%     Note that the block is bypassed in `test` mode.\n%\n%   Softmax layer::\n%     The softmax layer wraps VL_NNSOFTMAX(). It has fields\n%\n%     - `layer.type` contains the string`'softmax'`.\n%\n%   Log-loss layer and softmax-log-loss::\n%     The log-loss layer wraps VL_NNLOSS(). It has fields:\n%\n%     - `layer.type` contains `'loss'`.\n%     - `layer.class` contains the ground-truth class labels.\n%\n%     The softmax-log-loss layer wraps VL_NNSOFTMAXLOSS() instead. it\n%     has the same parameters, but `type` contains the `'softmaxloss'`\n%     string.\n%\n%   P-dist layer::\n%     The p-dist layer wraps VL_NNPDIST(). It has fields:\n%\n%     - `layer.type` contains the string  `'pdist'`.\n%     - `layer.p` is the P parameter of the P-distance (e.g. 2).\n%     - `layer.noRoot` it tells whether to raise the distance to\n%     the P-th power (e.g. `false`).\n%     - `layer.epsilon` is the regularization parameter for the derivatives.\n%\n%   Custom layer::\n%     This can be used to specify custom layers.\n%\n%     - `layer.type` contains the string `'custom'`.\n%     - `layer.forward` is  a function handle computing the block.\n%     - `layer.backward` is a function handle computing the block derivative.\n%\n%     The first function is called as\n%\n%          res(i+1) = layer.forward(layer, res(i), res(i+1))\n%\n%     where RES is the structure array specified before. The second function is\n%     called as\n%\n%          res(i) = layer.backward(layer, res(i), res(i+1))\n%\n%     Note that the `layer` structure can contain additional custom\n%     fields if needed.\n%\n%   See also: dagnn.DagNN, VL_SIMPLENN_TIDY(),\n%   VL_SIMPLENN_DISPLAY(), VL_SIMPLENN_MOVE().\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.conserveMemory = false ;\nopts.sync = false ;\nopts.mode = 'normal' ;\nopts.accumulate = false ;\nopts.cudnn = true ;\nopts.backPropDepth = +inf ;\nopts.skipForward = false ;\nopts.parameterServer = [] ;\nopts.holdOn = false ;\nopts = vl_argparse(opts, varargin);\n\nn = numel(net.layers) ;\nassert(opts.backPropDepth > 0, 'Invalid `backPropDepth` value (!>0)');\nbackPropLim = max(n - opts.backPropDepth + 1, 1);\n\nif (nargin <= 2) || isempty(dzdy)\n  doder = false ;\n  if opts.skipForward\n    error('simplenn:skipForwardNoBackwPass', ...\n      '`skipForward` valid only when backward pass is computed.');\n  end\nelse\n  doder = true ;\nend\n\nif opts.cudnn\n  cudnn = {'CuDNN'} ;\n  bnormCudnn = {'NoCuDNN'} ; % ours seems slighty faster\nelse\n  cudnn = {'NoCuDNN'} ;\n  bnormCudnn = {'NoCuDNN'} ;\nend\n\nswitch lower(opts.mode)\n  case 'normal'\n    testMode = false ;\n  case 'test'\n    testMode = true ;\n  otherwise\n    error('Unknown mode ''%s''.', opts. mode) ;\nend\n\ngpuMode = isa(x, 'gpuArray') ;\n\nif nargin <= 3 || isempty(res)\n  if opts.skipForward\n    error('simplenn:skipForwardEmptyRes', ...\n    'RES structure must be provided for `skipForward`.');\n  end\n  res = struct(...\n    'x', cell(1,n+1), ...\n    'dzdx', cell(1,n+1), ...\n    'dzdw', cell(1,n+1), ...\n    'aux', cell(1,n+1), ...\n    'stats', cell(1,n+1), ...\n    'time', num2cell(zeros(1,n+1)), ...\n    'backwardTime', num2cell(zeros(1,n+1))) ;\nend\n\nif ~opts.skipForward\n  res(1).x = x ;\nend\n\n% -------------------------------------------------------------------------\n%                                                              Forward pass\n% -------------------------------------------------------------------------\n\nfor i=1:n\n  if opts.skipForward, break; end;\n  l = net.layers{i} ;\n  res(i).time = tic ;\n  switch l.type\n    case 'conv'\n      res(i+1).x = vl_nnconv(res(i).x, l.weights{1}, l.weights{2}, ...\n        'pad', l.pad, ...\n        'stride', l.stride, ...\n        'dilate', l.dilate, ...\n        l.opts{:}, ...\n        cudnn{:}) ;\n\n    case 'convt'\n      res(i+1).x = vl_nnconvt(res(i).x, l.weights{1}, l.weights{2}, ...\n        'crop', l.crop, ...\n        'upsample', l.upsample, ...\n        'numGroups', l.numGroups, ...\n        l.opts{:}, ...\n        cudnn{:}) ;\n\n    case 'pool'\n      res(i+1).x = vl_nnpool(res(i).x, l.pool, ...\n        'pad', l.pad, 'stride', l.stride, ...\n        'method', l.method, ...\n        l.opts{:}, ...\n        cudnn{:}) ;\n\n    case {'normalize', 'lrn'}\n      res(i+1).x = vl_nnnormalize(res(i).x, l.param) ;\n\n    case 'softmax'\n      res(i+1).x = vl_nnsoftmax(res(i).x) ;\n\n    case 'loss'\n      res(i+1).x = vl_nnloss(res(i).x, l.class) ;\n\n    case 'softmaxloss'\n      res(i+1).x = vl_nnsoftmaxloss(res(i).x, l.class) ;\n\n    case 'relu'\n      if l.leak > 0, leak = {'leak', l.leak} ; else leak = {} ; end\n      res(i+1).x = vl_nnrelu(res(i).x,[],leak{:}) ;\n\n    case 'sigmoid'\n      res(i+1).x = vl_nnsigmoid(res(i).x) ;\n\n    case 'noffset'\n      res(i+1).x = vl_nnnoffset(res(i).x, l.param) ;\n\n    case 'spnorm'\n      res(i+1).x = vl_nnspnorm(res(i).x, l.param) ;\n\n    case 'dropout'\n      if testMode\n        res(i+1).x = res(i).x ;\n      else\n        [res(i+1).x, res(i+1).aux] = vl_nndropout(res(i).x, 'rate', l.rate) ;\n      end\n\n    case 'bnorm'\n      if testMode\n        res(i+1).x = vl_nnbnorm(res(i).x, l.weights{1}, l.weights{2}, ...\n                                'moments', l.weights{3}, ...\n                                'epsilon', l.epsilon, ...\n                                bnormCudnn{:}) ;\n      else\n        res(i+1).x = vl_nnbnorm(res(i).x, l.weights{1}, l.weights{2}, ...\n                                'epsilon', l.epsilon, ...\n                                bnormCudnn{:}) ;\n      end\n\n    case 'pdist'\n      res(i+1).x = vl_nnpdist(res(i).x, l.class, l.p, ...\n        'noRoot', l.noRoot, ...\n        'epsilon', l.epsilon, ...\n        'aggregate', l.aggregate, ...\n        'instanceWeights', l.instanceWeights) ;\n\n    case 'custom'\n      res(i+1) = l.forward(l, res(i), res(i+1)) ;\n\n    otherwise\n      error('Unknown layer type ''%s''.', l.type) ;\n  end\n\n  % optionally forget intermediate results\n  needsBProp = doder && i >= backPropLim;\n  forget = opts.conserveMemory && ~needsBProp ;\n  if i > 1\n    lp = net.layers{i-1} ;\n    % forget RELU input, even for BPROP\n    forget = forget && (~needsBProp || (strcmp(l.type, 'relu') && ~lp.precious)) ;\n    forget = forget && ~(strcmp(lp.type, 'loss') || strcmp(lp.type, 'softmaxloss')) ;\n    forget = forget && ~lp.precious ;\n  end\n  if forget\n    res(i).x = [] ;\n  end\n\n  if gpuMode && opts.sync\n    wait(gpuDevice) ;\n  end\n  res(i).time = toc(res(i).time) ;\nend\n\n% -------------------------------------------------------------------------\n%                                                             Backward pass\n% -------------------------------------------------------------------------\n\nif doder\n  res(n+1).dzdx = dzdy ;\n  for i=n:-1:backPropLim\n    l = net.layers{i} ;\n    res(i).backwardTime = tic ;\n    switch l.type\n\n      case 'conv'\n        [res(i).dzdx, dzdw{1}, dzdw{2}] = ...\n          vl_nnconv(res(i).x, l.weights{1}, l.weights{2}, res(i+1).dzdx, ...\n          'pad', l.pad, ...\n          'stride', l.stride, ...\n          'dilate', l.dilate, ...\n          l.opts{:}, ...\n          cudnn{:}) ;\n\n      case 'convt'\n        [res(i).dzdx, dzdw{1}, dzdw{2}] = ...\n          vl_nnconvt(res(i).x, l.weights{1}, l.weights{2}, res(i+1).dzdx, ...\n          'crop', l.crop, ...\n          'upsample', l.upsample, ...\n          'numGroups', l.numGroups, ...\n          l.opts{:}, ...\n          cudnn{:}) ;\n\n      case 'pool'\n        res(i).dzdx = vl_nnpool(res(i).x, l.pool, res(i+1).dzdx, ...\n                                'pad', l.pad, 'stride', l.stride, ...\n                                'method', l.method, ...\n                                l.opts{:}, ...\n                                cudnn{:}) ;\n\n      case {'normalize', 'lrn'}\n        res(i).dzdx = vl_nnnormalize(res(i).x, l.param, res(i+1).dzdx) ;\n\n      case 'softmax'\n        res(i).dzdx = vl_nnsoftmax(res(i).x, res(i+1).dzdx) ;\n\n      case 'loss'\n        res(i).dzdx = vl_nnloss(res(i).x, l.class, res(i+1).dzdx) ;\n\n      case 'softmaxloss'\n        res(i).dzdx = vl_nnsoftmaxloss(res(i).x, l.class, res(i+1).dzdx) ;\n\n      case 'relu'\n        if l.leak > 0, leak = {'leak', l.leak} ; else leak = {} ; end\n        if ~isempty(res(i).x)\n          res(i).dzdx = vl_nnrelu(res(i).x, res(i+1).dzdx, leak{:}) ;\n        else\n          % if res(i).x is empty, it has been optimized away, so we use this\n          % hack (which works only for ReLU):\n          res(i).dzdx = vl_nnrelu(res(i+1).x, res(i+1).dzdx, leak{:}) ;\n        end\n\n      case 'sigmoid'\n        res(i).dzdx = vl_nnsigmoid(res(i).x, res(i+1).dzdx) ;\n\n      case 'noffset'\n        res(i).dzdx = vl_nnnoffset(res(i).x, l.param, res(i+1).dzdx) ;\n\n      case 'spnorm'\n        res(i).dzdx = vl_nnspnorm(res(i).x, l.param, res(i+1).dzdx) ;\n\n      case 'dropout'\n        if testMode\n          res(i).dzdx = res(i+1).dzdx ;\n        else\n          res(i).dzdx = vl_nndropout(res(i).x, res(i+1).dzdx, ...\n                                     'mask', res(i+1).aux) ;\n        end\n\n      case 'bnorm'\n        [res(i).dzdx, dzdw{1}, dzdw{2}, dzdw{3}] = ...\n          vl_nnbnorm(res(i).x, l.weights{1}, l.weights{2}, res(i+1).dzdx, ...\n                     'epsilon', l.epsilon, ...\n                     bnormCudnn{:}) ;\n        % multiply the moments update by the number of images in the batch\n        % this is required to make the update additive for subbatches\n        % and will eventually be normalized away\n        dzdw{3} = dzdw{3} * size(res(i).x,4) ;\n\n      case 'pdist'\n        res(i).dzdx = vl_nnpdist(res(i).x, l.class, ...\n          l.p, res(i+1).dzdx, ...\n          'noRoot', l.noRoot, ...\n          'epsilon', l.epsilon, ...\n          'aggregate', l.aggregate, ...\n          'instanceWeights', l.instanceWeights) ;\n\n      case 'custom'\n        res(i) = l.backward(l, res(i), res(i+1)) ;\n\n    end % layers\n\n    switch l.type\n      case {'conv', 'convt', 'bnorm'}\n        if ~opts.accumulate\n          res(i).dzdw = dzdw ;\n        else\n          for j=1:numel(dzdw)\n            res(i).dzdw{j} = res(i).dzdw{j} + dzdw{j} ;\n          end\n        end\n        dzdw = [] ;\n        if ~isempty(opts.parameterServer) && ~opts.holdOn\n          for j = 1:numel(res(i).dzdw)\n            opts.parameterServer.push(sprintf('l%d_%d',i,j),res(i).dzdw{j}) ;\n            res(i).dzdw{j} = [] ;\n          end\n        end\n    end\n    if opts.conserveMemory && ~net.layers{i}.precious && i ~= n\n      res(i+1).dzdx = [] ;\n      res(i+1).x = [] ;\n    end\n    if gpuMode && opts.sync\n      wait(gpuDevice) ;\n    end\n    res(i).backwardTime = toc(res(i).backwardTime) ;\n  end\n  if i > 1 && i == backPropLim && opts.conserveMemory && ~net.layers{i}.precious\n    res(i).dzdx = [] ;\n    res(i).x = [] ;\n  end\nend\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/libs/matconvnet/matlab/simplenn/vl_simplenn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.20527904557263163}}
{"text": "% *************************************************************************************\n% * DESCRIPTION:                                                                      *\n% * This script computes the experiments performed in ref. [1].                       *\n% * --------------------------------------------------------------------------------- *\n% * REFERENCE:                                                                        *\n% * [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and         * \n% *     MRI texture features for the prediction of lung metastases in soft-tissue     * \n% *     sarcomas of the extremities. Physics in Medicine and Biology, 60(14),         * \n% *     5471-5496. doi:10.1088/0031-9155/60/14/5471                                   * \n% * --------------------------------------------------------------------------------- *\n% * AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>                            *\n% * --------------------------------------------------------------------------------- *\n% * HISTORY:                                                                          *\n% * - Creation: May 2015                                                              *\n% * --------------------------------------------------------------------------------- *\n% * STATEMENT:                                                                        *\n% * This file is part of <https://github.com/mvallieres/radiomics/>,                  *\n% * a package providing MATLAB programming tools for radiomics analysis.              *\n% * --> Copyright (C) 2015  Martin Vallieres                                          *\n% *                                                                                   *\n% *   This package is free software: you can redistribute it and/or modify            * \n% *   it under the terms of the GNU General Public License as published by            *\n% *   the Free Software Foundation, either version 3 of the License, or               *\n% *   (at your option) any later version.                                             *\n% *                                                                                   *\n% *   This package is distributed in the hope that it will be useful,                 *\n% *   but WITHOUT ANY WARRANTY; without even the implied warranty of                  *\n% *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                   *\n% *   GNU General Public License for more details.                                    *\n% *                                                                                   *\n% *   You should have received a copy of the GNU General Public License               *\n% *   along with this package.  If not, see <http://www.gnu.org/licenses/>.           *\n% *************************************************************************************\n\nfprintf('\\n')\nhelp masterScript_STS\nfprintf('\\n')\nwarning off\n\n% INITIALIZATION\npathWORK = pwd;\nroiNumb = load('contour_Mass'); roiNumb = struct2cell(roiNumb); roiNumb = roiNumb{1};\noutcome = load('outcome'); outcome = struct2cell(outcome); outcome = outcome{1};\nnPatient = numel(outcome);\n\n% TEXTURE EXTRACTION PARAMETERS AND DEGREES OF FREEDOM\nMRIinv_cell = {'NoInv','Inv'};\nMRIweight_mat = [1/4,1/3,1/2,2/3,3/4];\nR_mat = [1/2,2/3,1,3/2,2];\nscale_cell = {'pixelW',1,2,3,4,5};\nalgo_cell = {'Equal','Lloyd'};\nNg_mat = [8,16,32,64];\nparamSEP = {R_mat,scale_cell,algo_cell,Ng_mat};                           % NOTE: paramSEP and paramFUS must always be of the same format and size for SEPARATE \nparamFUS = {MRIinv_cell,MRIweight_mat,R_mat,scale_cell,algo_cell,Ng_mat}; % and FUSED SCANS as presented here, with the same ordering of different extraction parameters.\nbaselineSEP = [3,1,2,3]; % As defined in ref. [1]\nbaselineFUS = [1,3,3,1,2,3]; % As defined in ref. [1]\nfreedomSEP = [unique(perms([0 0 0 0]),'rows');unique(perms([0 0 0 1]),'rows');...\n              unique(perms([0 0 1 1]),'rows');unique(perms([0 1 1 1]),'rows');...\n              unique(perms([1 1 1 1]),'rows')];\nfreedomFUS = [unique(perms([0 0 0 0 0 0]),'rows');unique(perms([0 0 0 0 0 1]),'rows');...\n              unique(perms([0 0 0 0 1 1]),'rows');unique(perms([0 0 0 1 1 1]),'rows');...\n              unique(perms([0 0 1 1 1 1]),'rows');unique(perms([0 1 1 1 1 1]),'rows');...\n              unique(perms([1 1 1 1 1 1]),'rows')];\n\n% MULTIVARIABLE ANALYSIS PARAMETERS\nnBoot = 1000;\nalpha = 0.5; delta = 0.5;\nsetSize = 25;\nfSetName = {'PET','SEPARATE','FUSED'};\nmaxOrder = 10;\n          \n\n\n% ************** START COMPUTATION **************\n          \n% 1. READ DATA DOWNLOADED FROM THE TCIA WEBSITE (http://dx.doi.org/10.7937/K9/TCIA.2015.7GO2GSKS)\nfprintf('\\n\\n*********************** ORGANIZING AND PROCESSING DICOM DATA FROM TCIA WEBSITE ***********************\\n')\nreadAllDICOM_STS([pathWORK,'/Soft-tissue-Sarcoma'],nPatient)\n \n% 2. COMPUTE NON-TEXTURE FEATURES\nfprintf('\\n\\n*********************** COMPUTING NON-TEXTURE FEATURES ***********************\\n')\ncalcAllNonTextureFeatures_STS(pathWORK,nPatient,roiNumb,outcome)\n\n% 3. COMPUTE AND ORGANIZING ALL TEXTURE FEATURES\nmkdir('TEXTURES'), fprintf('\\n')\ncalcAllSeparateTextures_STS(pathWORK,nPatient,roiNumb,R_mat,scale_cell,algo_cell,Ng_mat)\norganizeSeparateTextures_STS(pathWORK,nPatient,R_mat,scale_cell,algo_cell,Ng_mat)\ncalcAllFusedTextures_STS(pathWORK,nPatient,roiNumb,MRIinv_cell,MRIweight_mat,R_mat,scale_cell,algo_cell,Ng_mat)\norganizeFusedTextures_STS(pathWORK,nPatient,MRIinv_cell,MRIweight_mat,R_mat,scale_cell,algo_cell,Ng_mat)\n\n\n\n% 5. PERFORM FEATURE SET REDUCTION\nmkdir('FSET')\nnonTextures = load('nonTextures'); nonTextures = struct2cell(nonTextures); nonTextures = nonTextures{1};\nPET  = load('textures_PET');  PET  = struct2cell(PET);  PET  = PET{1};\nT1   = load('textures_T1');   T1   = struct2cell(T1);   T1   = T1{1};\nT2FS = load('textures_T2FS'); T2FS = struct2cell(T2FS); T2FS = T2FS{1};\nPET_T1   = load('textures_PET_T1');   PET_T1   = struct2cell(PET_T1);   PET_T1   = PET_T1{1};\nPET_T2FS = load('textures_PET_T2FS'); PET_T2FS = struct2cell(PET_T2FS); PET_T2FS = PET_T2FS{1};\n\ntic\nfprintf('\\n\\nFinding the path to the ''MINE.jar'' application on the system ... ')\npathMINE = findMINE('Linux');\nfprintf('DONE\\n')\ntoc\n\n% For Feature set 1: PET\nfprintf('\\n*********************** PERFORMING FEATURE SET REDUCTION FOR ''PET'' FEATURE SET ***********************\\n')\ncalcAllFeatureSets_STS(pathWORK,pathMINE,fSetName{1},outcome,setSize,nonTextures,{PET},{'PET'},paramSEP,freedomSEP,baselineSEP,alpha,delta,nBoot)\n\n% For Feature set 2: PET, T1, T2FS\nfprintf('\\n*********************** PERFORMING FEATURE SET REDUCTION FOR ''SEPARATE'' FEATURE SET **********************\\n')\ncalcAllFeatureSets_STS(pathWORK,pathMINE,fSetName{2},outcome,setSize,nonTextures,{PET,T1,T2FS},{'PET','T1','T2FS'},paramSEP,freedomSEP,baselineSEP,alpha,delta,nBoot)\n\n% For Feature set 3: PET_T1, PET_T2FS\nfprintf('\\n*********************** PERFORMING FEATURE SET REDUCTION FOR ''FUSED'' FEATURE SET ***********************\\n')\ncalcAllFeatureSets_STS(pathWORK,pathMINE,fSetName{3},outcome,setSize,nonTextures,{PET_T1,PET_T2FS},{'PET_T1','PET_T2FS'},paramFUS,freedomFUS,baselineFUS,alpha,delta,nBoot)\n\n\n\n% 6. PERFORM FEATURE SET SELECTION\nmkdir('MODELS')\nfprintf('\\n\\nFinding the path to''fastAUC.cpp'' on the system --> COMPILATION ... ')\ntry \n    compileFastAUC('Linux')\n    fprintf('DONE\\n') \ncatch\n    fprintf('FAILED (AUC computations will be slower)\\n')\nend\n \n% For Feature set 1: PET\nfprintf('\\n*********************** PERFORMING FEATURE SELECTION FOR ''PET'' FEATURE SET ***********************\\n')\ncomputeAllModelChoice_STS(pathWORK,fSetName{1},outcome,freedomSEP,maxOrder,nBoot)\n\n% For Feature set 2: PET, T1, T2FS\nfprintf('\\n*********************** PERFORMING FEATURE SELECTION  FOR ''SEPARATE'' FEATURE SET ***********************\\n')\ncomputeAllModelChoice_STS(pathWORK,fSetName{2},outcome,freedomSEP,maxOrder,nBoot)\n\n% For Feature set 3: PET_T1, PET_T2FS\nfprintf('\\n*********************** PERFORMING FEATURE SELECTION  FOR ''FUSED'' FEATURE SET ***********************\\n')\ncomputeAllModelChoice_STS(pathWORK,fSetName{3},outcome,freedomFUS,maxOrder,nBoot)\n\n\n\n% 7. PERFORM PREDICTION PERFORMANCE ESTIMATION\nmkdir('RESULTS'), fprintf('\\n')\n\n% For Feature set 1: PET\nfprintf('\\n*********************** PERFORMING PREDICTION PERFORMANCE ESTIMATION FOR ''PET'' FEATURE SET ***********************\\n')\ncomputeAllPrediction_STS(pathWORK,fSetName{1},outcome,freedomSEP,maxOrder,nBoot)\n\n% For Feature set 2: PET, T1, T2FS\nfprintf('\\n*********************** PERFORMING PREDICTION PERFORMANCE ESTIMATION FOR ''SEPARATE'' FEATURE SET ***********************\\n')\ncomputeAllPrediction_STS(pathWORK,fSetName{2},outcome,freedomSEP,maxOrder,nBoot)\n\n% For Feature set 3: PET_T1, PET_T2FS\nfprintf('\\n*********************** PERFORMING PREDICTION PERFORMANCE ESTIMATION FOR ''FUSED'' FEATURE SET ***********************\\n')\ncomputeAllPrediction_STS(pathWORK,fSetName{3},outcome,freedomFUS,maxOrder,nBoot)\n\n% Finding the best combinations of model order and texture extraction parameter degree of freedom for all feature set types\ngroupExperiments_STS(pathWORK,fSetName{1},freedomSEP,maxOrder)\ngroupExperiments_STS(pathWORK,fSetName{2},freedomSEP,maxOrder)\ngroupExperiments_STS(pathWORK,fSetName{3},freedomFUS,maxOrder)\n\n\n\n% 8. CHOICE OF BEST PARSIMONIOUS MODEL (requires user input)\nfprintf('\\n')\nplotPredictionResults_STS([pathWORK,'/RESULTS'],fSetName,{'AUC632','Sensitivity632','Specificity632'},maxOrder)\nwhile 1\n    set = input(['\\nWhich feature set provides the best parsimonious model? \\n' ...\n                 '--> For the ',fSetName{1},' feature set, type ''1'' and press ENTER \\n' ...\n                 '--> For the ',fSetName{2},' feature set, type ''2'' and press ENTER \\n' ...\n                 '--> For the ',fSetName{3},' feature set, type ''3'' and press ENTER \\n' ...\n                 'ANSWER: ']);\n    fprintf('\\n')\n    if isnumeric(set) && (set == 1 || set == 2 || set == 3)\n        break\n    end\nend\nwhile 1\n    order = input(['Which model order of the ',fSetName{set},' feature set provides the best parsimonious model? \\n' ...\n                   '--> Type a number between 1 to ',num2str(maxOrder),' and press ENTER \\n' ...\n                   'ANSWER: ']);\n    fprintf('\\n')\n    if isnumeric(order) && order <= 10 && order >= 1\n        break\n    end\nend\ncd([pathWORK,'/RESULTS'])\nresults = load(['RESULTS_',fSetName{set},'_BEST']); results = struct2cell(results); results = results{1}; \nfinalModel = results.(['Order',num2str(order)]); \ncd(pathWORK), mkdir('FINAL_MODEL'), cd('FINAL_MODEL'), save('finalModel', 'finalModel')\n\n\n\n% 9. COMPUTING THE LOGISTIC REGRESSION COEFFICIENTS AND BOOTSTRAP CONFIDENCE INTERVALS OF THE FINAL MODEL\nfprintf('\\n\\nCOMPUTING THE LOGISTIC REGRESSION COEFFICIENTS OF THE FINAL MODEL ... ')\ntic\n[coeff,response,modelCI] = computeModelCoefficients(finalModel.Data,outcome,'IABR');\nsave('coeff','coeff'), save('response','response'), save('modelCI','modelCI')\nfprintf('DONE\\n')\ntoc\n\n\n\n% 10. DISPLAYING THE FINAL MODEL AND CORRESPONDING PREDICTION PERFORMANCE ESTIMATION\nplotSigmoidalResponse(response,outcome,modelCI,'LungMets')\nfprintf(['\\n\\n\\n --> THE FINAL MULTIVARIABLE MODEL IS:\\n\\n'...\n         '               g(x) =               \\n'])\nfor i = 1:order\n    fprintf([num2str(coeff(i)),' X ',finalModel.Name{i},'\\n'])\n    fprintf('                    +               \\n')\nend\nfprintf(['                   ',num2str(coeff(end)),'\\n'])\nfprintf('\\nWITH CORRESPONDING PREDICTION PERFORMANCE ESTIMATION:\\n')\nfprintf(['AUC = ',num2str(roundsd(finalModel.AUC632,ceil(log10(finalModel.AUC632/roundsd(finalModel.SE_AUC632,1))))),' \u00b1 ',num2str(roundsd(finalModel.SE_AUC632,1)),'\\n'])\nfprintf(['Sensitivity = ',num2str(roundsd(finalModel.Sensitivity632,ceil(log10(finalModel.Sensitivity632/roundsd(finalModel.SE_Sensitivity632,1))))),' \u00b1 ',num2str(roundsd(finalModel.SE_Sensitivity632,1)),'\\n'])\nfprintf(['Specificity = ',num2str(roundsd(finalModel.Specificity632,ceil(log10(finalModel.Specificity632/roundsd(finalModel.SE_Specificity632,1))))),' \u00b1 ',num2str(roundsd(finalModel.SE_Specificity632,1)),'\\n'])\nfprintf('\\n')\ncd(pathWORK)\n", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/STS_study/WORKSPACE/masterScript_STS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2052578137457347}}
{"text": "\nclear all; close all; clc\n\nglobal VAR; %#ok<NUSED>\nload_dir = GetOutputDataDir();\nload(fullfile(load_dir,'VAR_new.mat'),'VAR'); % stores all clustering indices\n\n%% Init load\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\n%% batch\ntotaltime = tic; %#ok<NASGU>\nisFullData = 1;\ndata_masterdir = GetCurrentDataDir();\n\nM_stimrange = GetStimRange();\n\nrange_fish = [12:15,17:18]; \n\n%% custom params here:\n% numK1 = 20; \nmasterthres = 0.7;\n\n%%\nM_regthres = {0.7,0.5};\nM_place = {1,2,3,1,4,5,6,7};\nM_stimname = {'4x4','PT','OMR','defS','Spt','DF','Lm','Dot'};\n%%\nfor i_count = 1,%%%%%%%%%\n    masterthres = M_regthres{i_count};\n%     clusParams = struct('merge',masterthres,'cap',masterthres,'reg1',masterthres,...\n%         'reg2',masterthres,'minSize',10,'k1',numK1);\n    \n    for i_stimrange = 1:7\n        if i_stimrange == 1,\n            M_stimrange = GetStimRange('5');\n        elseif i_stimrange == 2,\n            M_stimrange = GetStimRange('P');\n        elseif i_stimrange == 3,\n            M_stimrange = GetStimRange('O');\n        elseif i_stimrange == 4,\n            M_stimrange = GetStimRange('M');\n        elseif i_stimrange == 5,\n            M_stimrange = GetStimRange('S');\n        elseif i_stimrange == 6,\n            M_stimrange = GetStimRange('D');\n        elseif i_stimrange == 7,\n            M_stimrange = GetStimRange('L');\n%         elseif i_stimrange == 8,\n%             M_stimrange = GetStimRange('Y');\n        end\n\n        for i = 1:length(range_fish),\n            i_fish = range_fish(i);\n            disp(i_fish);\n            \n            % check this loop\n            stimrange = M_stimrange{i_fish};\n            if isempty(stimrange),\n                continue;\n            end\n            \n            % Load fish\n            LoadFullFish(hfig,i_fish,isFullData);\n            \n            %% 1.\n            % setup\n            absIX = getappdata(hfig,'absIX');\n\n            i_ClusGroup = 2;\n            i_Cluster = 1;\n\n            % Load cluster data\n            [cIX_load,gIX] = LoadCluster_Direct(i_fish,i_ClusGroup,i_Cluster,absIX);\n                        \n            %% partitions for CV\n            timelists = getappdata(hfig,'timelists');\n            timelists_names = getappdata(hfig,'timelists_names');\n            periods = getappdata(hfig,'periods');\n            \n            M_stim = M_stimrange{i_fish};\n            \n            timelistsCV_raw = cell(length(M_stim),2);\n            timelistsCV = cell(1,2);\n            \n            for k_stim = 1:length(M_stim), % :3\n                i_stim = M_stim(k_stim);\n                TL = timelists{i_stim};\n                seq = randperm(size(TL,2));\n                halfpoint = floor(size(TL,2)/2);\n                timelistsCV_raw{k_stim,1} = TL(seq(1:halfpoint));\n                timelistsCV_raw{k_stim,2} = TL(seq(1+halfpoint:2*halfpoint));\n%                 period = periods(i_stim);\n%                 nrep = size(TL,2)/periods(i_stim); % integer\n%                 n = floor(nrep/2);\n%                 if n>0,\n%                     timelistsCV_raw{k_stim,1} = TL(1:n*period);\n%                     timelistsCV_raw{k_stim,2} = TL(1+n*period:2*n*period);% before 12/5/16: TL(1+n*period):TL(2*n*period);\n%                 else % for spont, only one period\n%                     halfperiod = floor(period/2);\n%                     timelistsCV_raw{k_stim,1} = TL(1:halfperiod);\n%                     timelistsCV_raw{k_stim,2} = TL(1+halfperiod:2*halfperiod);\n%                 end\n            end\n            timelistsCV{1} = horzcat(timelistsCV_raw{:,1});\n            timelistsCV{2} = horzcat(timelistsCV_raw{:,2});\n            assert(length(timelistsCV{1})==length(timelistsCV{2}));\n            \n            %%\n            for k = 1:2,% CV halves\n                tIX = timelistsCV{k};\n                M = GetTimeIndexedData_Default_Direct(hfig,cIX_load,tIX);\n                M_0 = GetTimeIndexedData_Default_Direct(hfig,[],tIX,'isAllCells');\n\n                % ------custom code here---------\n                isWkmeans = true;\n                isMakeFoxels = true;\n                \n                [cIX,gIX] = AutoClustering(cIX_load,gIX,M_0,cIX_load,isWkmeans,[],...\n                    isMakeFoxels,masterthres);\n                \n                % save cluster\n                name = ['Auto_',M_stimname{i_stimrange},'_M',num2str(masterthres),'_CV',num2str(k)];\n                clusgroupID = 15+k; % 16 and 17 %13+k; % 14 and 15\n                clusIDoverride = M_place{i_stimrange};\n                SaveCluster_Direct(cIX,gIX,absIX,i_fish,name,clusgroupID,clusIDoverride);\n            end\n        end\n    end\nend\nSaveVARwithBackup();\ntotaltime = toc;\ndisp(totaltime);\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/Clustering/Batch cluster processing/Batch_crossval_by_stim_randframes_matchlength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.20516104936598703}}
{"text": "function [timeqrs,indexes,tol,messages]=qrscandidatesnew(timeqrs1,timeqrs2,timeqrs3,heasig,tol,messages)\n% [timeqrs,indexes]=qrscandidates(timeqrs1,timeqrs2,timeqrs3,heasig,tol)\n%\n% Construction QRS positions candidates vector from 3 single detections vectors\n% a QRS is admitted as candidate if:\n%   - it was found in 3 leads and the middle mark differ less than tol from the others\n%   - it was found in 2 leads and the marks differ less than tol \n%\n% marks that not fullfill the above are replaced by NaN and a QRS positions\n% candidates vector is constructed with the detections in each lead in one\n% line, one QRS in each column\n%\n% INPUT:\n% timeqrs1,timeqrs2,timeqrs3  -  line vector swith single lead detections\n%                                (in samples)\n% heasig - header information\n% tol - maximum distance to be admited as same complex (in sec)\n%       by default half of the default refractary period tol = 0.275/2 sec\n% \n% OUTPUT:\n% timeqrs - QRS positions candidates vector\n% indexes - beats corresponding to the QRS positions candidates vector\n%\n% Rute Almeida  14.APR.2005\n% Last update: 26JUL2011\n%\n% MATLAB Version R13\nif nargin<6\n    messages.status=1;\nend\nif ~isfield(messages,'warnings'), messages.warnings=[]; end\nspf=heasig.spf_ecg; %24.MAR.09\nif nargin==4\n    tol=ceil(0.275/2*heasig.freq*spf); %24.MAR.09\nelseif nargin<4\n    messages.errors=[messages.errors {'Fatal error in qrscandidatesnew: not enough inputs.'}];\n    warning(char(messages.errors(end)))\n    messages.errors_desc=[messages.errors_desc 'Mandatory inputs not defined.'];\n    messages.status=0;\n    return\nend\nindexes=[];\nindexes1=1:length(timeqrs1);\nindexes2=1:length(timeqrs2);\nindexes3=1:length(timeqrs3);\ntimeqrs=[];\nlengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\n\nfor g=1:min(lengthaux)\n    [aux auxi]=sort([timeqrs1(g) timeqrs2(g) timeqrs3(g)]);\n    if aux(1)>(aux(2)-tol-1)\n        if (aux(2)+tol+1)>aux(3)\n            timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]]; %#ok<AGROW>\n            indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]]; %#ok<AGROW>\n        else\n            if auxi(3)==1\n                timeqrs1(g+1:end+1)=timeqrs1(g:end);\n                indexes1(g+1:end+1)= indexes1(g:end);\n                indexes1(g)=NaN; \n                timeqrs1(g)=NaN;\n            else if auxi(3)==2\n                    timeqrs2(g+1:end+1)=timeqrs2(g:end);\n                    indexes2(g+1:end+1)= indexes2(g:end);\n                    timeqrs2(g)=NaN;\n                    indexes2(g)=NaN;\n                else\n                    timeqrs3(g+1:end+1)=timeqrs3(g:end);\n                    indexes3(g+1:end+1)= indexes3(g:end);\n                    timeqrs3(g)=NaN;\n                    indexes3(g)=NaN;\n                end\n            end\n            timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]]; %#ok<AGROW>\n            indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]]; %#ok<AGROW>\n        end\n    else\n        \n        if auxi(1)==1\n            g1=g+1;\n            flag=0;\n            while  g1<=length(timeqrs1) && flag==0 && timeqrs1(g1)<(aux(2)+tol+1)\n                if (timeqrs1(g1)>(aux(2)-tol-1))\n                    flag=1;\n                    timeqrs1(g:end)=[timeqrs1(g1:end) NaN*ones(1,(g1-g))];\n                    indexes1(g:end)=[indexes1(g1:end) NaN*ones(1,(g1-g))];\n                end\n                g1=g1+1;\n            end\n            if flag==0       \n                if g1>length(timeqrs1)\n                    timeqrs1(g:end)= NaN*ones(1,length(timeqrs1(g:end)));\n                    indexes1(g:end)= NaN*ones(1,length(timeqrs1(g:end)));\n                else\n                    timeqrs1(g:end)=[timeqrs1((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    indexes1(g:end)=[indexes1((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    timeqrs1(g)=NaN;\n                    indexes1(g)=NaN;\n                end\n            end\n        elseif auxi(1)==2\n            g1=g+1;\n            flag=0;\n            while  g1<=length(timeqrs2) && flag==0 && timeqrs2(g1)<(aux(2)+tol+1)\n                if (timeqrs2(g1)>(aux(2)-tol-1))\n                    flag=1;\n                    timeqrs2(g:end)=[timeqrs2(g1:end) NaN*ones(1,(g1-g))];\n                    indexes2(g:end)=[indexes2(g1:end) NaN*ones(1,(g1-g))];\n                end\n                g1=g1+1;\n            end\n            if flag==0       \n                if g1>length(timeqrs1)\n                    timeqrs2(g:end)= NaN*ones(1,length(timeqrs2(g:end)));\n                    indexes2(g:end)= NaN*ones(1,length(timeqrs2(g:end)));\n                else\n                    timeqrs2(g:end)=[timeqrs2((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    indexes2(g:end)=[indexes2((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    timeqrs2(g)=NaN;\n                    indexes2(g)=NaN;\n                end\n            end          \n        else\n            g1=g+1;\n            flag=0;\n            while  g1<=length(timeqrs3) && flag==0 && timeqrs3(g1)<(aux(2)+tol+1)\n                if (timeqrs3(g1)>(aux(2)-tol-1))\n                    flag=1;\n                    timeqrs3(g:end)=[timeqrs3(g1:end) NaN*ones(1,(g1-g))];\n                    indexes3(g:end)=[indexes3(g1:end) NaN*ones(1,(g1-g))];\n                end\n                g1=g1+1;\n            end\n            if flag==0       \n                if g1>length(timeqrs1)\n                    timeqrs3(g:end)= NaN*ones(1,length(timeqrs3(g:end)));\n                    indexes3(g:end)= NaN*ones(1,length(timeqrs3(g:end)));\n                else\n                    timeqrs3(g:end)=[timeqrs3((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    indexes3(g:end)=[indexes3((g1-1):end) NaN*ones(1,(g1-1-g))];\n                    timeqrs3(g)=NaN;\n                    indexes3(g)=NaN;\n                end\n            end\n        end\n        \n        if aux(3)-aux(2)>(tol+1)\n            if auxi(3)==1\n                timeqrs1(g+1:end+1)=timeqrs1(g:end);\n                indexes1(g+1:end+1)= indexes1(g:end);\n                indexes1(g)=NaN; \n                timeqrs1(g)=NaN;\n            else if auxi(3)==2\n                    timeqrs2(g+1:end+1)=timeqrs2(g:end);\n                    indexes2(g+1:end+1)= indexes2(g:end);\n                    timeqrs2(g)=NaN;\n                    indexes2(g)=NaN;\n                else\n                    timeqrs3(g+1:end+1)=timeqrs3(g:end);\n                    indexes3(g+1:end+1)= indexes3(g:end);\n                    timeqrs3(g)=NaN;\n                    indexes3(g)=NaN;\n                end\n            end\n        else\n            flag=1;\n        end\n        if flag==1\n            timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]]; %#ok<AGROW>\n            indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]]; %#ok<AGROW>\n        else\n            timeqrs1(g)=NaN;indexes1(g)=NaN;\n            timeqrs2(g)=NaN;indexes2(g)=NaN;\n            timeqrs3(g)=NaN;indexes3(g)=NaN;\n        end\n    end\nend\nlengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\nif isempty(g)\n    g=0;\nend\naux1=find(lengthaux-g >0);\n%remains beats in all 3 leads\nwhile length(aux1)==3\n%     intervalaux=(g+1):(min(lengthaux(aux1)));\n    for g=(g+1):(min(lengthaux(aux1)))       \n        [aux auxi]=sort([timeqrs1(g) timeqrs2(g) timeqrs3(g)]);\n        if aux(1)>(aux(2)-tol-1)\n            if (aux(2)+tol+1)>aux(3)\n                timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]];  %#ok<AGROW>\n                indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]];  %#ok<AGROW>\n            else\n                if auxi(3)==1\n                    timeqrs1(g+1:end+1)=timeqrs1(g:end);\n                    indexes1(g+1:end+1)= indexes1(g:end);\n                    indexes1(g)=NaN; \n                    timeqrs1(g)=NaN;\n                else if auxi(3)==2\n                        timeqrs2(g+1:end+1)=timeqrs2(g:end);\n                        indexes2(g+1:end+1)= indexes2(g:end);\n                        timeqrs2(g)=NaN;\n                        indexes2(g)=NaN;\n                    else\n                        timeqrs3(g+1:end+1)=timeqrs3(g:end);\n                        indexes3(g+1:end+1)= indexes3(g:end);\n                        timeqrs3(g)=NaN;\n                        indexes3(g)=NaN;\n                    end\n                end\n                timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]];  %#ok<AGROW>\n                indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]];  %#ok<AGROW>\n            end\n        else           \n            if auxi(1)==1\n                g1=g+1;\n                flag=0;\n                while  g1<=length(timeqrs1) && flag==0 && timeqrs1(g1)<(aux(2)+tol+1)\n                    if (timeqrs1(g1)>(aux(2)-tol-1))\n                        flag=1;\n                        timeqrs1(g:end)=[timeqrs1(g1:end) NaN*ones(1,(g1-g))];\n                        indexes1(g:end)=[indexes1(g1:end) NaN*ones(1,(g1-g))];\n                    end\n                    g1=g1+1;\n                end\n                if flag==0       \n                    if g1>length(timeqrs1)\n                        timeqrs1(g:end)=NaN*ones(1,length(timeqrs1(g:end)));\n                        indexes1(g:end)=NaN*ones(1,length(timeqrs1(g:end)));\n                    else\n                        timeqrs1(g:end)=[timeqrs1((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        indexes1(g:end)=[indexes1((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        timeqrs1(g)=NaN;\n                        indexes1(g)=NaN;\n                    end\n                end\n            elseif auxi(1)==2\n                g1=g+1;\n                flag=0;\n                while  g1<=length(timeqrs2) && flag==0 && timeqrs2(g1)<(aux(2)+tol+1)\n                    if (timeqrs2(g1)>(aux(2)-tol-1))\n                        flag=1;\n                        timeqrs2(g:end)=[timeqrs2(g1:end) NaN*ones(1,(g1-g))];\n                        indexes2(g:end)=[indexes2(g1:end) NaN*ones(1,(g1-g))];\n                    end\n                    g1=g1+1;\n                end\n                if flag==0       \n                    if g1>length(timeqrs1)\n                        timeqrs2(g:end)=NaN*ones(1,length(timeqrs2(g:end)));\n                        indexes2(g:end)=NaN*ones(1,length(timeqrs2(g:end)));\n                    else\n                        timeqrs2(g:end)=[timeqrs2((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        indexes2(g:end)=[indexes2((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        timeqrs2(g)=NaN;\n                        indexes2(g)=NaN;\n                    end\n                end          \n            else\n                g1=g+1;\n                flag=0;\n                while  g1<=length(timeqrs3) && flag==0 && timeqrs3(g1)<(aux(2)+tol+1)\n                    if (timeqrs3(g1)>(aux(2)-tol-1))\n                        flag=1;\n                        timeqrs3(g:end)=[timeqrs3(g1:end) NaN*ones(1,(g1-g))];\n                        indexes3(g:end)=[indexes3(g1:end) NaN*ones(1,(g1-g))];\n                    end\n                    g1=g1+1;\n                end\n                if flag==0       \n                    if g1>length(timeqrs1)\n                        timeqrs3(g:end)=NaN*ones(1,length(timeqrs3(g:end)));\n                        indexes3(g:end)=NaN*ones(1,length(timeqrs3(g:end)));\n                    else\n                        timeqrs3(g:end)=[timeqrs3((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        indexes3(g:end)=[indexes3((g1-1):end) NaN*ones(1,(g1-1-g))];\n                        timeqrs3(g)=NaN;\n                        indexes3(g)=NaN;\n                    end\n                end\n            end        \n            if aux(3)-aux(2)>(tol+1)\n                if auxi(3)==1\n                    timeqrs1(g+1:end+1)=timeqrs1(g:end);\n                    indexes1(g+1:end+1)= indexes1(g:end);\n                    indexes1(g)=NaN; \n                    timeqrs1(g)=NaN;\n                else if auxi(3)==2\n                        timeqrs2(g+1:end+1)=timeqrs2(g:end);\n                        indexes2(g+1:end+1)= indexes2(g:end);\n                        timeqrs2(g)=NaN;\n                        indexes2(g)=NaN;\n                    else\n                        timeqrs3(g+1:end+1)=timeqrs3(g:end);\n                        indexes3(g+1:end+1)= indexes3(g:end);\n                        timeqrs3(g)=NaN;\n                        indexes3(g)=NaN;\n                    end\n                end\n            else\n                flag=1;\n            end\n            if flag==1\n                timeqrs=[timeqrs [timeqrs1(g);timeqrs2(g);timeqrs3(g)]];  %#ok<AGROW>\n                indexes=[indexes [indexes1(g);indexes2(g);indexes3(g)]];  %#ok<AGROW>\n            else \n                timeqrs1(g)=NaN;indexes1(g)=NaN;\n                timeqrs2(g)=NaN;indexes2(g)=NaN;\n                timeqrs3(g)=NaN;indexes3(g)=NaN;\n            end\n        end\n    end   \n    lengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\n    aux1=find(lengthaux-g >0);\nend\n[min1i,min1]=min(find(~isnan(timeqrs1(end:-1:1)))); %#ok<NASGU,MXFND>\n[min2i,min3]=min(find(~isnan(timeqrs2(end:-1:1)))); %#ok<NASGU,MXFND>\n[min3i,min3]=min(find(~isnan(timeqrs3(end:-1:1)))); %#ok<NASGU,MXFND>\ntimeqrs1(length(timeqrs1)-min1i+2:end)=[];\ntimeqrs2(length(timeqrs2)-min2i+2:end)=[];\ntimeqrs3(length(timeqrs3)-min3i+2:end)=[];\nlengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\naux1=find(lengthaux-g >0);\n%remaining beats in 2 leads\nif length(aux1)>1\n    for intervalauxi=(g+1):(min(lengthaux(aux1)));\n        if aux1(1)==1 \n            if aux1(2)==2\n                [aux auxi]=sort([timeqrs1(intervalauxi) timeqrs2(intervalauxi)]);\n                if aux(1)>(aux(2)-tol-1)\n                    timeqrs=[timeqrs [timeqrs1(intervalauxi);timeqrs2(intervalauxi);NaN]];  %#ok<AGROW>\n                    indexes=[indexes [indexes1(intervalauxi);indexes2(intervalauxi);NaN]];  %#ok<AGROW>\n                else\n                    if auxi(2)==2\n                        timeqrs2(intervalauxi+1:end+1)=timeqrs2(intervalauxi:end);\n                        indexes2(intervalauxi+1:end+1)= indexes2(intervalauxi:end);\n                        timeqrs2(intervalauxi)=NaN;\n                        indexes2(intervalauxi)=NaN;\n                    elseif auxi(2)==1\n                        timeqrs1(intervalauxi+1:end+1)=timeqrs1(intervalauxi:end);\n                        indexes1(intervalauxi+1:end+1)= indexes1(intervalauxi:end);\n                        timeqrs1(intervalauxi)=NaN;\n                        indexes1(intervalauxi)=NaN;\n                    end\n                end\n            elseif aux1(2)==3\n                [aux auxi]=sort([timeqrs1(intervalauxi) timeqrs3(intervalauxi)]);\n                if aux(1)>(aux(2)-tol-1)\n                    timeqrs=[timeqrs [timeqrs1(intervalauxi);NaN;timeqrs3(intervalauxi)]];  %#ok<AGROW>\n                    indexes=[indexes [indexes1(intervalauxi);NaN;indexes3(intervalauxi)]];  %#ok<AGROW>\n                else\n                    if auxi(2)==2 %25SET08\n                        timeqrs3(intervalauxi+1:end+1)=timeqrs3(intervalauxi:end);\n                        indexes3(intervalauxi+1:end+1)= indexes3(intervalauxi:end);\n                        timeqrs3(intervalauxi)=NaN;\n                        indexes3(intervalauxi)=NaN;\n                    elseif auxi(2)==1\n                        timeqrs1(intervalauxi+1:end+1)=timeqrs1(intervalauxi:end);\n                        indexes1(intervalauxi+1:end+1)= indexes1(intervalauxi:end);\n                        timeqrs1(intervalauxi)=NaN;\n                        indexes1(intervalauxi)=NaN;\n                    end\n                end\n            end\n        elseif aux1(1)==2 \n            [aux auxi]=sort([timeqrs2(intervalauxi) timeqrs3(intervalauxi)]);\n            if aux(1)>(aux(2)-tol-1)\n                timeqrs=[timeqrs [NaN;timeqrs2(intervalauxi);timeqrs3(intervalauxi)]];  %#ok<AGROW>\n                indexes=[indexes [NaN;indexes2(intervalauxi);indexes3(intervalauxi)]];  %#ok<AGROW>\n            else\n                if auxi(2)==1%25SET08\n                    timeqrs2(intervalauxi+1:end+1)=timeqrs2(intervalauxi:end);\n                    indexes2(intervalauxi+1:end+1)= indexes2(intervalauxi:end);\n                    timeqrs2(intervalauxi)=NaN;\n                    indexes2(intervalauxi)=NaN;\n                elseif auxi(2)==2%25SET08\n                    timeqrs3(intervalauxi+1:end+1)=timeqrs3(intervalauxi:end);\n                    indexes3(intervalauxi+1:end+1)= indexes3(intervalauxi:end);\n                    timeqrs3(intervalauxi)=NaN;\n                    indexes3(intervalauxi)=NaN;\n                end\n            end\n        end\n    end\n    lengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\n    if isempty(intervalauxi);\n        intervalauxi=g;\n    end\n    aux1=find(lengthaux-intervalauxi >0);\n    %remains beats in 2 leads\n    while length(aux1)==2\n        intervalauxi=intervalauxi+1;\n        if aux1(1)==1 \n            if aux1(2)==2\n                [aux auxi]=sort([timeqrs1(intervalauxi) timeqrs2(intervalauxi)]);\n                if aux(1)>(aux(2)-tol-1)\n                    timeqrs=[timeqrs [timeqrs1(intervalauxi);timeqrs2(intervalauxi);NaN]];  %#ok<AGROW>\n                    indexes=[indexes [indexes1(intervalauxi);indexes2(intervalauxi);NaN]];  %#ok<AGROW>\n                else\n                    if auxi(2)==2\n                        timeqrs2(intervalauxi+1:end+1)=timeqrs2(intervalauxi:end);\n                        indexes2(intervalauxi+1:end+1)= indexes2(intervalauxi:end);\n                        timeqrs2(intervalauxi)=NaN;\n                        indexes2(intervalauxi)=NaN;\n                    elseif auxi(2)==1\n                        timeqrs1(intervalauxi+1:end+1)=timeqrs1(intervalauxi:end);\n                        indexes1(intervalauxi+1:end+1)= indexes1(intervalauxi:end);\n                        timeqrs1(intervalauxi)=NaN;\n                        indexes1(intervalauxi)=NaN;\n                    end\n                end\n            elseif aux1(2)==3\n                [aux auxi]=sort([timeqrs1(intervalauxi) timeqrs3(intervalauxi)]);\n                if aux(1)>(aux(2)-tol-1)\n                    timeqrs=[timeqrs [timeqrs1(intervalauxi);NaN;timeqrs3(intervalauxi)]];  %#ok<AGROW>\n                    indexes=[indexes [indexes1(intervalauxi);NaN;indexes3(intervalauxi)]];  %#ok<AGROW>\n                else\n                    if auxi(2)==3\n                        timeqrs3(intervalauxi+1:end+1)=timeqrs3(intervalauxi:end);\n                        indexes3(intervalauxi+1:end+1)= indexes3(intervalauxi:end);\n                        timeqrs3(intervalauxi)=NaN;\n                        indexes3(intervalauxi)=NaN;\n                    elseif auxi(2)==1\n                        timeqrs1(intervalauxi+1:end+1)=timeqrs1(intervalauxi:end);\n                        indexes1(intervalauxi+1:end+1)= indexes1(intervalauxi:end);\n                        timeqrs1(intervalauxi)=NaN;\n                        indexes1(intervalauxi)=NaN;\n                    end\n                end\n            end\n        elseif aux1(1)==2 \n            [aux auxi]=sort([timeqrs2(intervalauxi) timeqrs3(intervalauxi)]);\n            if aux(1)>(aux(2)-tol-1)\n                timeqrs=[timeqrs [NaN; timeqrs2(intervalauxi);timeqrs3(intervalauxi)]];  %#ok<AGROW>\n                indexes=[indexes [NaN; indexes2(intervalauxi);indexes3(intervalauxi)]];  %#ok<AGROW>\n            else\n                if auxi(2)==2\n                    timeqrs2(intervalauxi+1:end+1)=timeqrs2(intervalauxi:end);\n                    indexes2(intervalauxi+1:end+1)= indexes2(intervalauxi:end);\n                    timeqrs2(intervalauxi)=NaN;\n                    indexes2(intervalauxi)=NaN;\n                elseif auxi(2)==3\n                    timeqrs3(intervalauxi+1:end+1)=timeqrs3(intervalauxi:end);\n                    indexes3(intervalauxi+1:end+1)= indexes3(intervalauxi:end);\n                    timeqrs3(intervalauxi)=NaN;\n                    indexes3(intervalauxi)=NaN;\n                end\n            end\n        end\n        lengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\n        aux1=find(lengthaux-intervalauxi >0);\n    end\n    lengthaux=([length(timeqrs1) length(timeqrs2) length(timeqrs3)]);\n    g=intervalauxi;\n    aux1=find(lengthaux-g >0);   \nend\n%NOTE THAT ONLY ALIGNED ONES ARE CONSIDERED!!!!!!!!!!!!!!!!!!\nintervalaux=(g+1):(min(lengthaux(aux1)));\nif length(aux1)>1\n    timeqrs1((min(lengthaux(aux1)))+1:end)=[];\n    timeqrs2((min(lengthaux(aux1)))+1:end)=[];\n    timeqrs3((min(lengthaux(aux1)))+1:end)=[];\n    indexes1((min(lengthaux(aux1)))+1:end)=[];\n    indexes2((min(lengthaux(aux1)))+1:end)=[];\n    indexes3((min(lengthaux(aux1)))+1:end)=[];\n    if ~ismember(1,aux1)\n        timeqrs1(intervalaux)=NaN*ones(size(intervalaux));\n        indexes1(intervalaux)=NaN*ones(size(intervalaux));\n        aux=[timeqrs2(intervalaux); timeqrs3(intervalaux) ];\n    end    \n    if ~ismember(2,aux1)\n        timeqrs2(intervalaux)=NaN*ones(size(intervalaux));\n        indexes2(intervalaux)=NaN*ones(size(intervalaux));\n        aux=[timeqrs1(intervalaux); timeqrs3(intervalaux) ];\n    end\n    if ~ismember(3,aux1)\n        timeqrs3(intervalaux)=NaN*ones(size(intervalaux));\n        indexes3(intervalaux)=NaN*ones(size(intervalaux));\n        aux=[timeqrs1(intervalaux); timeqrs2(intervalaux) ];\n    end  \n    timeqrs=[timeqrs [timeqrs1(intervalaux(abs(diff(aux))<(tol+1)));timeqrs2(intervalaux(abs(diff(aux))<(tol+1)));timeqrs3(intervalaux(abs(diff(aux))<(tol+1)))]];\n    indexes=[indexes [indexes1(intervalaux(abs(diff(aux))<(tol+1)));indexes2(intervalaux(abs(diff(aux))<(tol+1)));indexes3(intervalaux(abs(diff(aux))<(tol+1)))]];\n%     indexes1(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\n%     indexes2(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\n%     indexes3(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\n%     timeqrs1(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\n%     timeqrs2(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\n%     timeqrs3(intervalaux(abs(diff(aux))>=(tol+1) | isnan(diff(aux))))=[];\nelse\n%     timeqrs1((min(lengthaux(aux1))):end)=[];\n%     timeqrs2((min(lengthaux(aux1))):end)=[];\n%     timeqrs3((min(lengthaux(aux1))):end)=[];\n%     indexes1((min(lengthaux(aux1))):end)=[];\n%     indexes2((min(lengthaux(aux1))):end)=[];\n%     indexes3((min(lengthaux(aux1))):end)=[];\nend  \nif ~isempty(indexes) %17ABRIL08\nindexes=indexes(:,~isnan(indexes(1,:))| ~isnan(indexes(2,:))|~isnan(indexes(3,:)));\nend\ntimeqrs(:,(size(indexes,2)+1):end)=[];\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/wavedet/qrscandidatesnew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.20501383988988336}}
{"text": "function [estimate] = ft_inverse_eloreta(sourcemodel, sens, headmodel, dat, C, varargin)\n\n% FT_INVERSE_ELORETA estimates the source activity using eLORETA\n%\n% Use as\n%   [estimate] = ft_inverse_eloreta(sourcemodel, sens, headmodel, dat, cov, ...)\n% where\n%   sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL\n%   sens        is the gradiometer or electrode definition, see FT_DATATYPE_SENS\n%   headmodel   is the volume conductor definition, see FT_PREPARE_HEADMODEL\n%   dat         is the data matrix with the ERP or ERF\n%   cov         is the data covariance or cross-spectral density matrix\n% and\n%   estimate    contains the estimated source parameters\n%\n% Additional input arguments should be specified as key-value pairs and can include\n%   'keepfilter'       = remember the spatial filter,    can be 'yes' or 'no'\n%   'keepleadfield'    = remember the forward computation,  can be 'yes' or 'no'\n%   'keepmom'          = remember the dipole moment,        can be 'yes' or 'no'\n%   'lambda'           = scalar, regularisation parameter (default = 0.05)\n%\n% These options influence the forward computation of the leadfield\n%   'reducerank'      = 'no' or number  (default = 3 for EEG, 2 for MEG)\n%   'backproject'     = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes')\n%   'normalize'       = 'no', 'yes' or 'column' (default = 'no')\n%   'normalizeparam'  = parameter for depth normalization (default = 0.5)\n%   'weight'          = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1)\n%\n% If the dipole definition only specifies the dipole location, a rotating dipole\n% (regional source) is assumed on each location. If a dipole moment is specified, its\n% orientation will be used and only the strength will be fitted to the data.\n%\n% This implements: \n% - R.D. Pascual-Marqui; Discrete, 3D distributed, linear imaging methods of electric\n%   neuronal activity. Part 1: exact, zero error localization. arXiv:0710.3341 \n%   2007-October-17, http://arxiv.org/pdf/0710.3341\n%\n% See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL\n\n% Copyright (C) 2013, Marlene Boenstrup, Jan-Mathijs Schoffelen and Guido Nolte\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif mod(nargin-5,2)\n  % the first 5 arguments are fixed, the other arguments should come in pairs\n  ft_error('invalid number of optional arguments');\nend\n\n% get the optional input arguments, or use defaults\nkeepfilter      = ft_getopt(varargin, 'keepfilter', 'no');\nkeepmom         = ft_getopt(varargin, 'keepmom', 'yes');\nkeepleadfield   = ft_getopt(varargin, 'keepleadfield', 'no');\nlambda          = ft_getopt(varargin, 'lambda', 0.05);\n\n% construct the low-level options for the leadfield computation as key-value pairs, these are passed to FT_COMPUTE_LEADFIELD\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     ft_getopt(varargin, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    ft_getopt(varargin, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      ft_getopt(varargin, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(varargin, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         ft_getopt(varargin, 'weight'));\n\n% convert the yes/no arguments to the corresponding logical values\nkeepfilter     = istrue(keepfilter);\nkeepmom        = istrue(keepmom);\nkeepleadfield  = istrue(keepleadfield);\n\n% flags to avoid calling isfield repeatedly in the loop over grid positions (saves a lot of time)\nhasmom        = isfield(sourcemodel, 'mom');\nhasleadfield  = isfield(sourcemodel, 'leadfield');\nhasfilter     = isfield(sourcemodel, 'filter');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% find the dipole positions that are inside/outside the brain\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(sourcemodel, 'inside')\n  if hasfilter\n    sourcemodel.inside = ~cellfun(@isempty, sourcemodel.filter);\n  elseif hasleadfield\n    sourcemodel.inside = ~cellfun(@isempty, sourcemodel.leadfield);\n  else\n    sourcemodel.inside = ft_inside_headmodel(sourcemodel.pos, headmodel);\n  end\nend\n\n% convert to logical representation\nsourcemodel = fixinside(sourcemodel);\n\n% keep the original details on inside and outside positions\noriginside = sourcemodel.inside;\norigpos    = sourcemodel.pos;\n\n% select only the dipole positions inside the brain for scanning\nsourcemodel.pos    = sourcemodel.pos(originside,:);\nsourcemodel.inside = true(size(sourcemodel.pos,1),1);\n\nif hasmom\n  sourcemodel.mom = sourcemodel.mom(:,originside);\nend\n\nif hasfilter\n  ft_info('using precomputed filters\\n');\n  sourcemodel.filter = sourcemodel.filter(originside);\nelseif hasleadfield\n  ft_info('using precomputed leadfields\\n');\n  sourcemodel.leadfield = sourcemodel.leadfield(originside);\nelse\n  ft_info('computing forward model on the fly\\n');\n  if hasmom\n    for i=size(sourcemodel.pos,1)\n      % compute the leadfield for a fixed dipole orientation\n      sourcemodel.leadfield{i} = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:}) * sourcemodel.mom(:,i);\n    end\n  else\n    for i=1:size(sourcemodel.pos,1)\n      % compute the leadfield\n      sourcemodel.leadfield{i} = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:});\n    end\n  end\nend\n\n% use existing filters, or compute them\nif ~hasfilter\n  % deal with reduced rank\n  % check the rank of the leadfields, and project onto the lower dimensional\n  % subspace if the number of columns per leadfield > rank: this to avoid\n  % numerical issues in the filter computation\n  rank_lf = zeros(1,size(sourcemodel.pos,1));\n  for i=1:size(sourcemodel.pos,1)\n    rank_lf(i) = rank(sourcemodel.leadfield{i});\n  end\n  if ~all(rank_lf==rank_lf(1))\n    ft_error('the forward solutions have a different rank for each location, which is not supported');\n  end\n  if rank_lf(1)<size(sourcemodel.leadfield{1})\n    ft_notice('the forward solutions have a rank of %d, but %d orientations\\n',rank_lf(1),size(sourcemodel.leadfield{1},2));\n    ft_notice('projecting the forward solutions on the lower dimensional subspace\\n');\n    for i=1:size(sourcemodel.pos,1)\n      [u,s,v{i}] = svd(sourcemodel.leadfield{i}, 'econ');\n      sourcemodel.leadfield{i} = sourcemodel.leadfield{i}*v{i}(:,1:rank_lf(i));\n    end\n  end\n\n  % convert the leadfield into Nchan*Ndip*Nori\n  [Nchan, Nori] = size(sourcemodel.leadfield{1});\n  Ndip          = numel(sourcemodel.leadfield);\n  leadfield     = permute(reshape(cat(2,sourcemodel.leadfield{:}),Nchan,Nori,Ndip),[1 3 2]);\n    \n  filt = mkfilt_eloreta(leadfield, lambda);\n  for i=1:size(sourcemodel.pos,1)\n    sourcemodel.filter{i,1} = squeeze(filt(:,i,:))';\n  end\nend\n\n% get the power\nsiz_C  = [size(C) 1 1]; % C can have both a freq and time dimension\nsourcemodel.pow = zeros([size(sourcemodel.pos,1),siz_C(3:4)]);\nsourcemodel.ori = cell(size(sourcemodel.pos,1),1);\nfor i=1:size(sourcemodel.pos,1)\n  sourcemodel.ori{i} = zeros([size(sourcemodel.filter{i},1) siz_C(3:4)]);\n  for j=1:siz_C(3)\n    for k=1:siz_C(4)\n      csd               = sourcemodel.filter{i}*C(:,:,j,k)*sourcemodel.filter{i}';\n      [u,s,v]           = svd(real(csd));\n      sourcemodel.pow(i,j,k)    = s(1);\n      sourcemodel.ori{i}(:,j,k) = u(:,1);\n    end\n  end\nend\n\n% get the dipole moment\nif keepmom && ~isempty(dat)\n  siz = [size(dat) 1];\n  % remove the dipole moment from the input\n  if hasmom\n    sourcemodel = rmfield(sourcemodel, 'mom');\n  end\n  for i=1:size(sourcemodel.pos,1)\n    sourcemodel.mom{i} = reshape(sourcemodel.filter{i}*dat(:,:), [size(sourcemodel.filter{i},1) siz(2:end)]);\n  end\nend\n\n% reassign the estimated values over the inside and outside grid positions\nestimate.inside  = originside;\nestimate.pos     = origpos;\nif isfield(sourcemodel, 'pow')\n  estimate.pow( originside,:,:) = sourcemodel.pow;\n  estimate.pow(~originside,:,:) = nan;\nend\nif isfield(sourcemodel, 'ori') % here ori is cell\n  estimate.ori( originside) = sourcemodel.ori;\n  estimate.ori(~originside) = {[]};\nend\nif isfield(sourcemodel, 'leadfield') && keepleadfield\n  estimate.leadfield( originside) = sourcemodel.leadfield;\n  estimate.leadfield(~originside) = {[]};\nend\nif isfield(sourcemodel, 'filter') && keepfilter\n  estimate.filter( originside) = sourcemodel.filter;\n  estimate.filter(~originside) = {[]};\nend\nif isfield(sourcemodel, 'mom') && keepmom\n  estimate.mom( originside) = sourcemodel.mom;\n  estimate.mom(~originside) = {[]};\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/inverse/ft_inverse_eloreta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.2050138390271317}}
{"text": "function q = quaternion(sym)\n\nq = quaternion(sym.properGroup.rot);\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@symmetry/quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490467}}
{"text": "classdef SetRectangularlSensorAzAngleAction < AbstractEventAction\n    %SetRectangularlSensorAzAngleAction Summary of this class goes here\n    %   Detailed explanation goes here\n    \n    properties\n        sensor RectangularSensor\n        sensorAzAngle(1,1) double {mustBeGreaterThan(sensorAzAngle, 0)} = deg2rad(10);\n    end\n    \n    properties(Constant)\n        emptyVarArr = AbstractOptimizationVariable.empty(0,1);\n    end\n    \n    methods\n        function obj = SetRectangularlSensorAngleAction(sensor, sensorAzAngle)\n            if(nargin > 0)\n                obj.sensor = sensor;\n                obj.sensorAzAngle = sensorAzAngle;\n            end\n            \n            obj.id = rand();\n        end\n        \n        function newStateLogEntry = executeAction(obj, stateLogEntry)\n            newStateLogEntry = stateLogEntry;\n            sensorState = newStateLogEntry.getSensorStateForSensor(obj.sensor);\n            sensorState.setSensorAzAngle(obj.sensorAzAngle);\n        end\n        \n        function initAction(obj, initialStateLogEntry)\n            %nothing\n        end\n        \n        function name = getName(obj)            \n            name = sprintf('Set Sensor Azimuth Half-Angle (%s => %0.3f deg)', obj.sensor.name, rad2deg(obj.sensorAzAngle));\n        end\n        \n        function tf = usesStage(obj, stage)\n            tf = false;\n        end\n        \n        function tf = usesEngine(obj, engine)\n            tf = false;\n        end\n        \n        function tf = usesTank(obj, tank)\n            tf = false;\n        end\n        \n        function tf = usesEngineToTankConn(obj, engineToTank)\n            tf = false;\n        end\n\n        function tf = usesStopwatch(obj, stopwatch)\n            tf = false;\n        end\n        \n        function tf = usesExtremum(obj, extremum)\n            tf = false;\n        end\n        \n        function tf = usesTankToTankConn(obj, tankToTank)\n            tf = false;\n        end\n        \n        function tf = usesSensor(obj, sensor)\n            tf = obj.sensor == sensor;\n        end\n        \n        function [tf, vars] = hasActiveOptimVar(obj)\n            tf = false;\n            vars = obj.emptyVarArr;\n        end\n    end\n    \n    methods(Static)\n        function addActionTf = openEditActionUI(action, lv)    \n            lvdData = lv.lvdData;\n            [~, sensors] = lvdData.sensors.getListboxStr();\n            \n            if(not(isempty(sensors)) && any([sensors.typeEnum] == SensorEnum.RectangularSensor))\n                output = AppDesignerGUIOutput({false});\n                lvd_EditActionSetRectangularSensorAzAngleGUI_App(action, lvdData, output);\n                addActionTf = output.output{1};\n            else\n                addActionTf = false;\n                warndlg('There are no rectangular sensors in this scenario.  Create one first.','Cannot Create Action','modal');\n            end\n        end\n    end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Events/actions/@SetRectangularlSensorAzAngleAction/SetRectangularlSensorAzAngleAction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490465}}
{"text": "% forcelocs() - rotate location in 3-D so specified electrodes\n%               match specified locations. \n%               CAUTION: Only for use on electrodes in\n%               and remaining in the upper spherical hemisphere,\n%               otherwise it will work improperly. Written primarily for\n%               adjusting all electrodes homogenously with Cz.\n%\n% Usage:\n%   >> chanlocs = forcelocs( chanlocs ); % pop-up window mode\n%   >> chanlocs = forcelocs( chanlocs, loc1, loc2, ... );\n% Example:\n%   >> chanlocs = forcelocs( chanlocs, { 0.78, 'x', 'A1' }, { 0.023, 'x', ...\n%   'B1','B2','Cz' } );\n%\n% Inputs:\n%   chanlocs  - EEGLAB channel structure. See help readlocs()\n%\n% Optional inputs:\n%   loc1      - cell array: { location, axis, channame1, channame2, .. } \n%               'location' is new cartesian coordinate of channame1 along 'axis'\n%               'axis' is either\n%                 'X'   New x-coordinate of mean of channame1, channame2,\n%                       etc. Used to calculate the X-Z plane angle by\n%                       which to rotate all channels.\n%                       Note that all rotations are to the corresponding positive \n%                       Z-value, since theta=atan(z/x).\n%                 'Y'   New x-coordinate of mean of channame1, channame2,\n%                       etc.\n%                 \n%               'channame#'  Name of channel(s) to be rotated, as they appear in \n%                       chanlocs.label\n%   loc2      - same as loc1\n%\n% Outputs:\n%   chanlocs  - updated EEGLAB channel structure.\n%\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 15 April 2003\n%\n% See also: readlocs()\n\n% Copyright (C) 2003 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [chanlocs,options] = forcelocs( chanlocs, varargin)\n    \n    NENTRY = 1; % number of lines in GUI\n    FIELDS = { 'X' 'Y' };\n    \n    options = [];\n    if nargin < 1\n        help forcelocs;\n        return;\n    end;\n    if nargin < 2\n        geom = { [0.4 1 1 0.3] };\n        uilist = { { 'style' 'text' 'string' 'X/Y value' 'tag' 'valstr' } ...\n                   { 'style' 'text' 'string' 'Coordinate' } ...\n                   { 'style' 'text' 'string' 'Electrode list' } ...\n                   { } };\n        for index = 1:NENTRY\n            tag = [ 'c' int2str(index) ];\n            geom = { geom{:}  [0.3 1 1 0.3] };\n            uilist = { uilist{:} { 'style' 'edit' 'string' fastif(index==1, '0','') } ...\n                       { 'style' 'listbox' 'string' 'X (rotate X-Z plane)|Y (rotate Y-Z plane)' ...\n                         'callback' [ 'if get(gco, ''value'') == 1,' ...\n                                      '     set(findobj(gcbf, ''tag'', ''valstr''), ''string'', ''Y value'');' ...\n                                      'else set(findobj(gcbf, ''tag'', ''valstr''), ''string'', ''X value'');' ...\n                                      'end;' ] } ...\n                       { 'style' 'edit' 'string'  fastif(index==1, 'Cz','') 'tag' tag } ...\n                       { 'style' 'pushbutton' 'string' 'Pick' ...\n                         'callback', [ 'tmp3 = get(gcbf, ''userdata'');' ...\n                                       '[tmp1 tmp2] = pop_chansel({tmp3.labels}, ''selectionmode'', ''single'');' ...\n                                       'if ~isempty(tmp1) set(findobj(gcbf, ''tag'', ''' tag '''), ''string'', tmp2); end;' ...\n                                       'clear tmp1 tmp2;' ] } };\n        end;\n        \n        results = inputgui( geom, uilist, 'pophelp(''forcelocs'');', 'Force electrode location -- forcelocs()', chanlocs );\n        if length(results) == 0, return; end;\n        \n        options = {};\n        for index = 1:NENTRY\n            tmpi = 3*(index-1)+1;\n            if ~isempty(results{tmpi})\n                tmpchans = parsetxt(results{tmpi+2});\n                options = { options{:} { str2num(results{tmpi}) FIELDS{results{tmpi+1}} tmpchans{:} }};\n            end;\n        end;    \n    else \n        options = varargin;\n    end;\n\n    % scan all locations\n    % ------------------\n    channelnames = lower(strvcat({chanlocs.labels}));\n    for index = 1:length(options)\n        \n        val   = options{index}{1};\n        type  = options{index}{2};\n        chans = getchans(options{index}(3:end), channelnames);\n\n        % rotate X-Z plane \n        % ----------------\n        if strcmpi(type, 'x')\n            curx   = mean([ chanlocs(chans).X ]);\n            curz   = mean([ chanlocs(chans).Z ]);\n            newx = val;\n            rotangle = solvesystem(curx, curz, newx);\n            \n            for chanind = 1:length(chanlocs)\n                [chanlocs(chanind).X chanlocs(chanind).Z]= rotation(chanlocs(chanind).X, chanlocs(chanind).Z, rotangle);\n            end;\n            chanlocs = convertlocs(chanlocs, 'cart2all');\n        end;\n        \n        % rotate Y-Z plane \n        % ----------------\n        if strcmpi(type, 'y')\n            cury   = mean([ chanlocs(chans).Y ]);\n            curz   = mean([ chanlocs(chans).Z ]);\n            newy = val;\n            rotangle = solvesystem(cury, curz, newy);\n            \n            for chanind = 1:length(chanlocs)\n                [chanlocs(chanind).Y chanlocs(chanind).Z]= rotation(chanlocs(chanind).Y, chanlocs(chanind).Z, rotangle);\n            end;\n            chanlocs = convertlocs(chanlocs, 'cart2all');\n        end;\n    \n    end;\n        \n\n% get channel indices\n% -------------------\nfunction chanlist = getchans(chanliststr, channelnames);\n    chanlist = [];\n    for index = 1:length(chanliststr)\n        i = strmatch (lower(chanliststr{index}), channelnames, 'exact');\n        chanlist  = [chanlist i];\n    end;\n\n% function rotate coordinates\n% ---------------------------\nfunction [X,Y] = rotation(x,y,rotangle)\n    X = real((x+j*y)*exp(j*rotangle));\n    Y = imag((x+j*y)*exp(j*rotangle));\n    \n% function solvesyst\n% ------------------\nfunction theta = solvesystem(x,y,nx)\n    % Original Solution\n    %eq(1,:) = [x -y]; res(1) = nx;\n    %eq(2,:) = [y x];  res(2) = sqrt(x^2+y^2-nx^2);\n    %sol = eq\\res';\n    %theta = atan2(sol(2), sol(1));\n    \n    % simplified solution\n    ny = sqrt(x^2+y^2-nx^2);\n    ang1 = angle(x+j*y);\n    ang2 = angle(nx+j*ny);\n    theta = ang2-ang1;\n    \n    % Even simpler solution     Toby 03/05/2007\n    % theta = atan(y/x);\n    \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/forcelocs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490465}}
{"text": "clc;\nclear;\n%path='C:\\Users\\Administrator\\Desktop\\mat-cvpr17_v1\\ECSSD\\';\npath='./PR_results/';\ndirpath=dir([path '*.mat']);\nmethod1 = cell(length(dirpath),3);\n\nstr=['r','r','b','b','c','c','m','m','k','k','y','y','g','g','r','r','m','m','k','k','r','r','r','r','r'];\n\nrr=[];\nFmeasure=[]; \naAUC=[];\nmethod2 = cell(length(dirpath),1);\nfor i=1:length(dirpath)\n  load([path dirpath(i).name]);\n  Fmeasure=[Fmeasure,mFmeasure];\n  aAUC=[aAUC,AUC];                     %AUC \u56fe\u50cf\u4fee\u6539\u90e8\u5206\n%  method2(i)=alg_dir{i}(1);\n  method2{i}=dirpath(i).name(1:end-4);\n  \nend\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        figure(5);\n        barMsra = [Fmeasure' aAUC'];\n        bar(barMsra );\n        set( gca, 'xtick', 1:1:length(dirpath) ),\n  \n        set( gca ,'xticklabels',  method2 , 'fontsize', 8 );\n        legend('Precision','Recall','Fmeasure','AUC');      %AUC \u56fe\u50cf\u4fee\u6539\u90e8\u5206\n        %legend('Precision','Recall','Fmeasure');\n              grid on;\n   %     saveas(  figure(5), [basedir,'SED1_bar.fig']);\n\n% xlabel('Recall');\n% ylabel('Precision');\n%legend(dirpath(1).name(5:end),dirpath(2).name(5:end),dirpath(3).name(5:end),dirpath(4).name(5:end),dirpath(5).name(5:end),dirpath(6).name(5:end),dirpath(7).name(5:end),dirpath(8).name(5:end),dirpath(9).name(5:end),dirpath(10).name(5:end),dirpath(11).name(5:end),dirpath(12).name(5:end),dirpath(13).name(5:end),dirpath(14).name(5:end),dirpath(15).name(5:end),dirpath(16).name(5:end),dirpath(17).name(5:end),dirpath(18).name(5:end),dirpath(19).name(5:end),dirpath(20).name(5:end),dirpath(21).name(5:end));\n%legend(dirpath(1).name(8:end-4),dirpath(2).name(8:end-4),dirpath(3).name(8:end-4),dirpath(4).name(8:end-4),dirpath(5).name(8:end-4),dirpath(6).name(8:end-4),dirpath(7).name(8:end-4),dirpath(8).name(8:end-4),dirpath(9).name(8:end-4),dirpath(10).name(8:end-4),dirpath(11).name(8:end-4),dirpath(12).name(8:end-4),dirpath(13).name(8:end-4),dirpath(14).name(8:end-4));\n%legend(dirpath(1).name(1:end-4),dirpath(2).name(1:end-4),dirpath(3).name(1:end-4),dirpath(4).name(1:end-4),dirpath(5).name(1:end-4),dirpath(6).name(1:end-4),dirpath(7).name(1:end-4),dirpath(8).name(1:end-4))%,dirpath(9).name(1:end-4),dirpath(10).name(1:end-4),dirpath(11).name(1:end-4));%,dirpath(12).name(1:end-4),dirpath(13).name(1:end-4));\n%legend(str(1,:),str(2,:),str(3,:),str(4,:),str(5,:),str(6,:),str(7,:),str(8,:),str(9,:),str(10,:),str(11,:),str(12,:),str(13,:),str(14,:),str(15,:),str(16,:),str(17,:));\n%legend(dirpath(1).name(2:end-4),dirpath(2).name(2:end-4),dirpath(3).name(2\n%legend(dirpath(1).name(1:end-4),dirpath(2).name(1:end-4),dirpath(3).name(1:end-4),dirpath(4).name(1:end-4),...\n%dirpath(5).name(1:end-4),dirpath(6).name(1:end-4))%,dirpath(7).name(1:end-4),dirpath(8).name(1:end-4),dirpath(9).name(1:end-4),...\n% dirpath(10).name(1:end-4),dirpath(11).name(1:end-4),dirpath(12).name(1:end-4),dirpath(13).name(1:end-4),...\n% dirpath(14).name(1:end-4),dirpath(15).name(1:end-4),dirpath(16).name(1:end-4),dirpath(17).name(1:end-4),...\n% dirpath(18).name(1:end-4),dirpath(19).name(1:end-4),dirpath(20).name(1:end-4),dirpath(21).name(1:end-4))%,...\n%dirpath(22).name(1:end-4),dirpath(23).name(1:end-4));\ngrid on;\n% save 300 AUC;\n", "meta": {"author": "jiwei0921", "repo": "Saliency-Evaluation-Toolbox", "sha": "ead7af72ed443eef7d176d1b176eb7653bc8ca48", "save_path": "github-repos/MATLAB/jiwei0921-Saliency-Evaluation-Toolbox", "path": "github-repos/MATLAB/jiwei0921-Saliency-Evaluation-Toolbox/Saliency-Evaluation-Toolbox-ead7af72ed443eef7d176d1b176eb7653bc8ca48/saliency_evaluation/0 PR/code_bar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20495296699490462}}
{"text": "function varargout = process_spike_triggered_average( varargin )\n% PROCESS_SPIKE_TRIGGERED_AVERAGE: Computes the spike triggered average.\n% Select a time window around the spikes of a specific neuron and average the LFPs of each electrode\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Konstantinos Nasiotis, 2018-2019\n%          Francois Tadel, 2022\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription()\n    % Description the process\n    sProcess.Comment     = 'Spike triggered average';\n    sProcess.FileTag     = 'STA';\n    sProcess.Category    = 'Custom';\n    sProcess.SubGroup    = 'Electrophysiology';\n    sProcess.Index       = 1230;\n    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/e-phys/functions#Spike_triggered_average';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data'};\n    sProcess.OutputTypes = {'data'};\n    sProcess.nInputs     = 1;\n    sProcess.nMinFiles   = 2;\n    % Options: Segment around spike\n    sProcess.options.timewindow.Comment  = 'Spike time window: ';\n    sProcess.options.timewindow.Type     = 'range';\n    sProcess.options.timewindow.Value    = {[-0.150, 0.150],'ms',[]};\n    % Options: Parallel Processing\n    sProcess.options.parallel.Comment = 'Parallel processing';\n    sProcess.options.parallel.Type    = 'checkbox';\n    sProcess.options.parallel.Value   = 0;\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess)\n    Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputs)\n    % Initialize returned values\n    OutputFiles = {};\n    % Get options\n    isParallel = sProcess.options.parallel.Value;\n    TimeWindow = sProcess.options.timewindow.Value{1};\n\n\n    % ===== LOAD INPUTS =====\n    % Loads all the data outside of the parfor, so it doesn't fail\n    nTrials = length(sInputs);\n    DataMats = cell(1, nTrials);\n    ChannelFlag = [];\n    for iFile = 1:length(sInputs)\n        DataMats{iFile} = in_bst_data(sInputs(iFile).FileName);\n        if isempty(ChannelFlag)\n            ChannelFlag = DataMats{iFile}.ChannelFlag;\n        else\n            ChannelFlag(DataMats{iFile}.ChannelFlag == -1) = -1;\n        end\n    end\n    % Check time window\n    if TimeWindow(1)>=0 || TimeWindow(2)<=0\n        bst_report('Error', sProcess, sInputs, 'The time-selection must be around the spikes.');\n        return;\n    elseif (TimeWindow(1) <= DataMats{1}.Time(1)) && (TimeWindow(2) >= DataMats{1}.Time(end))\n        bst_report('Error', sProcess, sInputs, 'The spike window has to be smaller than the trial window.');\n        return;\n    end\n    % Sampling frequency\n    sampling_rate = round(abs(1. / (DataMats{1}.Time(2) - DataMats{1}.Time(1))));\n    % Load channel file\n    ChannelMat = in_bst_channel(sInputs(1).ChannelFile);\n\n    \n    % === START COMPUTATION ===\n    % Input time window\n    time_segmentAroundSpikes = linspace(TimeWindow(1), TimeWindow(2), abs(TimeWindow(2))* sampling_rate + abs(TimeWindow(1))* sampling_rate + 1);    \n    % Get LPFs\n    LFP_trials = cell(1, nTrials);\n    if isParallel\n        parfor iFile = 1:nTrials\n            LFP_trials{iFile} = get_LFPs(DataMats{iFile}, ChannelMat, TimeWindow, time_segmentAroundSpikes, sampling_rate);\n        end \n    else\n        for iFile = 1:nTrials\n            LFP_trials{iFile} = get_LFPs(DataMats{iFile}, ChannelMat, TimeWindow, time_segmentAroundSpikes, sampling_rate);\n        end \n    end\n\n\n    % ===== COMPUTE SPIKE TRIGGERED AVERAGE =====\n    % The Spike Triggered Average should be a 3d matrix\n    % Number of neurons x Frequencies x Electrodes\n    % Ultimately the user will select the NEURON that wants to be displayed,\n    % and a 2D image with the other two dimensions will appear, showing the\n    % coherence of the spikes of that neuron with the LFPs on every\n    % electrode on all frequencies.\n    \n    % Create a cell that holds all of the labels and one for the unique labels\n    % This will be used to take the averages using the appropriate indices\n    all_labels = {};\n    labelsNeurons = {}; % Unique neuron labels (each trial might have different number of neurons). We need everything that appears.\n    for iFile = 1:nTrials\n        for iNeuron = 1:length(LFP_trials{iFile})\n            all_labels{iNeuron,iFile} = LFP_trials{iFile}(iNeuron).label;\n            labelsNeurons{end+1} = LFP_trials{iFile}(iNeuron).label;\n        end\n    end\n    labelsNeurons = unique(labelsNeurons,'stable');\n    \n    % Compute STA per individual neuron\n    for iNeuron = 1:length(labelsNeurons)\n        % For each TRIAL, get the index of the label that corresponds to the appropriate neuron.\n        for ii = 1:size(all_labels,1)\n            for jj = 1:size(all_labels,2)\n                logicalEvents(ii,jj) = strcmp(all_labels{ii,jj}, labelsNeurons{iNeuron});\n            end\n        end\n        \n        iEvents = zeros(size(all_labels,2),1);\n        for iFile = 1:size(all_labels,2)\n            temp = find(logicalEvents(:,iFile));\n            if ~isempty(temp)\n                iEvents(iFile) = temp;\n            else\n                iEvents(iFile) = 0; % This shows that that neuron didn't fire any spikes on that trial\n            end\n        end\n        \n        % Compute the averages of the appropriate indices\n        STA_single_neuron = zeros(length(ChannelMat.Channel), length(time_segmentAroundSpikes)); \n        std_single_neuron = zeros(length(ChannelMat.Channel), length(time_segmentAroundSpikes)); \n        divideBy = 0;\n        for iFile = 1:size(all_labels,2)\n            if iEvents(iFile)~=0\n                STA_single_neuron = STA_single_neuron + LFP_trials{iFile}(iEvents(iFile)).nSpikes * LFP_trials{iFile}(iEvents(iFile)).avgLFP; % The avgLFP are sum actually. \n                divideBy = divideBy + LFP_trials{iFile}(iEvents(iFile)).nSpikes;\n                \n                % Here I have the assumption that the LFPs on all trials\n                % have homogeneity in their variance (Cohen, 1988, p.67): \n                % http://www.utstat.toronto.edu/~brunner/oldclass/378f16/readings/CohenPower.pdf\n                % https://www.statisticshowto.datasciencecentral.com/pooled-standard-deviation/\n                std_single_neuron = std_single_neuron + (LFP_trials{iFile}(iEvents(iFile)).nSpikes-1) * LFP_trials{iFile}(iEvents(iFile)).stdLFP.^2;\n            end \n        end\n        % Divide by total number of averages\n        STA_single_neuron = (STA_single_neuron./divideBy)';\n        std_single_neuron = sqrt(std_single_neuron./(divideBy - size(all_labels,2)));\n    \n\n        % Get meaningful label from neuron name\n        better_label = panel_spikes('GetChannelOfSpikeEvent', labelsNeurons{iNeuron});\n        neuron = panel_spikes('GetNeuronOfSpikeEvent', labelsNeurons{iNeuron});\n        if ~isempty(neuron)\n            better_label = [better_label ' #' num2str(neuron)];\n        end\n\n\n        % ===== SAVE FILE =====\n        % Prepare output file structure\n        FileMat = db_template('datamat');\n        FileMat.F           = STA_single_neuron';\n        FileMat.Time        = time_segmentAroundSpikes; \n        FileMat.Std         = 2 .* std_single_neuron; % MULTIPLY BY 2 TO GET 95% CONFIDENCE (ASSUMING NORMAL DISTRIBUTION)\n        FileMat.Comment     = ['Spike Triggered Average: ' str_remove_parenth(DataMats{1}.Comment) ' (' better_label ')'];\n        FileMat.DataType    = 'recordings';\n        FileMat.ChannelFlag = ChannelFlag;\n        FileMat.Device      = DataMats{1}.Device;\n        FileMat.nAvg        = 1;\n        FileMat.History     = DataMats{1}.History;\n\n        % Add history field\n        FileMat = bst_history('add', FileMat, 'compute', ['Spike Triggered Average: [' num2str(TimeWindow(1)) ', ' num2str(TimeWindow(2)) '] ms']);\n        for iFile = 1:length(sInputs)\n            FileMat = bst_history('add', FileMat, 'average', [' - ' sInputs(iFile).FileName]);\n        end\n\n        % Get output study\n        [tmp, iTargetStudy] = bst_process('GetOutputStudy', sProcess, sInputs);\n        sTargetStudy = bst_get('Study', iTargetStudy);\n        % Output filename\n        FileName = bst_process('GetNewFilename', bst_fileparts(sTargetStudy.FileName), 'data_STA');\n        OutputFiles = {FileName};\n        % Save output file and add to database\n        bst_save(FileName, FileMat, 'v6');\n        db_add_data(iTargetStudy, FileName, FileMat);\n    end\nend\n\n\n%% ===== GET LFP =====\n% Get the events that show neurons activity\nfunction all = get_LFPs(trial, ChannelMat, TimeWindow, time_segmentAroundSpikes, sampling_rate)\n    spikeEvents = []; % The spikeEvents variable holds the indices of the events that correspond to spikes.\n    \n    allChannelEvents = cellfun(@(x) panel_spikes('GetChannelOfSpikeEvent', x), {trial.Events.label}, 'UniformOutput', 0);\n    for ielectrode = 1:length(ChannelMat.Channel)\n        iEvents = find(strcmp(allChannelEvents, ChannelMat.Channel(ielectrode).Name)); % Find the index of the spike-events that correspond to that electrode (Exact string match)\n        if ~isempty(iEvents)\n            spikeEvents(end+1:end+length(iEvents)) = iEvents;\n        end\n    end\n\n    % Get segments around each spike, FOR EACH NEURON\n    all = struct();\n    for iNeuron = 1:length(spikeEvents) % iNeuron is the iEvent\n        % Check that the entire segment around the spikes [-150,150]ms is inside the trial segment and keep only those events\n        iSel = trial.Events(spikeEvents(iNeuron)).times > trial.Time(1)   + abs(TimeWindow(1)) & ...\n               trial.Events(spikeEvents(iNeuron)).times < trial.Time(end) - abs(TimeWindow(2));\n        events_within_segment = round(trial.Events(spikeEvents(iNeuron)).times(iSel) .* sampling_rate);\n\n        % Create a matrix that holds all the segments around the spike of that neuron, for all electrodes.\n        allSpikeSegments_singleNeuron_singleTrial = zeros(length(events_within_segment),length(ChannelMat.Channel),length(time_segmentAroundSpikes));\n        for ispike = 1:length(events_within_segment)\n            allSpikeSegments_singleNeuron_singleTrial(ispike,:,:) = trial.F(:, ...\n                round(abs(trial.Time(1))*sampling_rate) + events_within_segment(ispike) - round(abs(TimeWindow(1)) * sampling_rate) + 1 : ...\n                round(abs(trial.Time(1))*sampling_rate) + events_within_segment(ispike) + round(abs(TimeWindow(2)) * sampling_rate) + 1);\n        end\n\n        all(iNeuron).label   = trial.Events(spikeEvents(iNeuron)).label;\n        all(iNeuron).nSpikes = length(events_within_segment);\n        all(iNeuron).avgLFP  = squeeze(sum(allSpikeSegments_singleNeuron_singleTrial,1));\n        all(iNeuron).stdLFP  = squeeze(std(allSpikeSegments_singleNeuron_singleTrial,[],1));\n        all(iNeuron).Used    = 0; % This indicates if this entry has already been used for computing the SFC (some spikes might not appear on every trial imported, so a new Neuron should be identified on a later trial).\n    end\n    \n    % Check if any events had no spikes in the time-region of interest and remove them!\n    %  Some spikes might be on the edges of the trial. Ultimately, the\n    %  Spikes Channel i events would be considered in the STA (I mean the event group, not the events themselves), \n    %  but there would be a zeroed avgLFP included. Get rid of those events\n    iEventsToRemove = find([all.nSpikes]==0);\n    all = all(~ismember(1:length(all),iEventsToRemove));\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_spike_triggered_average.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20495296699490462}}
{"text": "function [model, directions] = directionalityStats(model, directions, cumNormProbCutoff, printLevel)\n% Build Boolean vectors with reaction directionality statistics\n%\n% USAGE:\n%\n%    [model, directions] = directionalityStats(model, directions, cumNormProbCutoff, printLevel)\n%\n% INPUTS:\n%    model:                 a structue of boolean vectors with different directionality\n%                           assignments where some vectors contain subsets of others with field:\n%\n%                             * .directions\n%\n%    directions:            structure with field:\n%\n%                             * .forwardProbability\n%\n%                           qualitatively assigned internal reaction direactions\n%\n%                             * .forwardRecon\n%                             * .reverseRecon\n%                             * .reversibleRecon\n%                             * .equilibriumRecon\n%\n%                           quantitatively assigned internal reaction direactions\n%                           thermodynamic data is lacking\n%\n%                             * .forwardThermo\n%                             * .reverseThermo\n%                             * .reversibleThermo\n%                             * .uncertainThermo\n%                             * .equilibriumThermo\n%\n% OPTIONAL INPUT\n%    cumNormProbCutoff:     {0.2} cutoff for probablity that reaction is\n%                           reversible within this cutoff of 0.5\n%    printLevel:            -1 to print out to file,\n%                           0 to silent,\n%                           1 to print out to command window\n%\n% OUTPUT:\n%    directions:            a structue of boolean vectors with different directionality\n%                           assignments where some vectors contain subsets of others\n%\n%                           qualtiative -> quantiative changed reaction directions\n%\n%                             * .forward2Forward\n%                             * .forward2Reverse\n%                             * .forward2Reversible\n%                             * .forward2Uncertain\n%                             * .reversible2Forward\n%                             * .reversible2Reverse\n%                             * .reversible2Reversible\n%                             * .reversible2Uncertain\n%                             * .reverse2Forward\n%                             * .reverse2Reverse\n%                             * .reverse2Reversible\n%                             * .reverse2Uncertain\n%                             * .tightened\n%\n%                           subsets of qualtiatively forward  -> quantiatively reversible\n%\n%                             * .forward2Reversible_bydGt0\n%                             * .forward2Reversible_bydGt0LHS\n%                             * .forward2Reversible_bydGt0Mid\n%                             * .forward2Reversible_bydGt0RHS\n%                             * .forward2Reversible_byConc_zero_fixed_DrG0\n%                             * .forward2Reversible_byConc_negative_fixed_DrG0\n%                             * .forward2Reversible_byConc_positive_fixed_DrG0\n%                             * .forward2Reversible_byConc_negative_uncertain_DrG0\n%                             * .forward2Reversible_byConc_positive_uncertain_DrG0\n%\n% .. Author: - Ronan M.T. Fleming\n\nif ~exist('cumNormProbCutoff','var')\n    directions.cumNormProbCutoff=0.2;\nelse\n    directions.cumNormProbCutoff=cumNormProbCutoff;\nend\n%must be symmetric about 50:50 to be logically consistent\ncumNormProbFwdUpper=0.5+directions.cumNormProbCutoff;\ncumNormProbFwdLower=0.5-directions.cumNormProbCutoff;\n\nif ~exist('printLevel','var')\n    printLevel=0;\nend\nif ~exist('fileName','var')\n    fileName='directionalityStats.txt';\nend\n\nDrGtMin=model.DrGtMin;\nDrGtMax=model.DrGtMax;\nif any(DrGtMin>DrGtMax)\n    error('DrGtMin greater than DrGtMax');\nend\n\nDrGtNaNBool=(isnan(model.DrGtMax) | isnan(model.DrGtMin)) & model.SIntRxnBool;\nif any(DrGtNaNBool)\n    warning([int2str(nnz(DrGtNaNBool)) ' DrGt are NaN']);\nend\n\nnEqualDrGt=nnz(DrGtMin==DrGtMax & DrGtMin~=0);\nif any(nEqualDrGt)\n    fprintf('%s\\n',[num2str(nEqualDrGt) '/' num2str(length(DrGtMin)) ' reactions with DrGtMin=DrGtMax~=0' ]);\nend\n\nnZeroDrGt=nnz(DrGtMin==0 & DrGtMax==0);\nif any(nZeroDrGt)\n    fprintf('%s\\n',[num2str(nZeroDrGt) '/' num2str(length(DrGtMin)) ' reactions with DrGtMin=DrGtMax=0' ]);\nend\n\n[~,nRxn]=size(model.S);\n\n% qualitatively assigned directions\nforwardRecon=directions.forwardRecon;\nreverseRecon=directions.reverseRecon;\nreversibleRecon=directions.reversibleRecon;\n% quantitatively assigned directions\nforwardThermo=directions.forwardThermo;\nreverseThermo=directions.reverseThermo;\nreversibleThermo=directions.reversibleThermo;\nuncertainThermo=directions.uncertainThermo;\n\n%%%%%%CHANGES IN REACTION DIRECTIONS%%%%%%%%%%%\n%thermodynamic constraints tightened\ntightened=model.lb<model.lb_reconThermo & model.ub_reconThermo<model.ub;\n\nreversible2Forward=reversibleRecon & forwardThermo;\nreversible2Reverse=reversibleRecon & reverseThermo;\nreversible2Reversible=reversibleRecon & reversibleThermo;\nreversible2Uncertain=reversibleRecon & uncertainThermo;\n\nforward2Reverse=forwardRecon & reverseThermo;\nforward2Reversible=forwardRecon & reversibleThermo;\nforward2Forward=forwardRecon & forwardThermo;\nforward2Uncertain=forwardRecon & uncertainThermo;\n\nreverse2Reverse =  reverseRecon & reverseThermo;\nreverse2Forward   =  reverseRecon & forwardThermo;\nreverse2Reversible =  reverseRecon & reversibleThermo;\nreverse2Uncertain  =  reverseRecon & uncertainThermo;\n\n%%%%%%CAUSES TO CHANGES IN REACTION DIRECTIONS%%%%%%%%%%%\n% model.DrGtMax = model.DrGt0Max + gasConstant*T*(R'*log(model.concMax) - F'*log(model.concMin));\n% model.DrGtMin = model.DrGt0Min + gasConstant*T*(R'*log(model.concMin) - F'*log(model.concMax));\n% model.DrGtMaxMeanConc = model.DrGt0Max + gasConstant*T*(R-F)'*log((model.concMax+model.concMin)/2);\n% model.DrGtMinMeanConc = model.DrGt0Min + gasConstant*T*(R-F)'*log((model.concMax+model.concMin)/2);\n\nforward2Reversible_bydGt0=forwardRecon & reversibleThermo & model.DrGtMin<0 & model.DrGtMax>0; % dGfGCforward2ReversibleBool_bydGt0\n\nforward2Reversible_byConc_negative_fixed_DrG0 = forwardRecon & reversibleThermo & model.DrGt0Min==model.DrGt0Max & model.DrGtMax<=0; %dGfGCforward2ReversibleBool_byConc_No_dGt0ErrorLHS\nforward2Reversible_byConc_positive_fixed_DrG0 = forwardRecon & reversibleThermo & model.DrGt0Min==model.DrGt0Max & model.DrGtMin>0; %dGfGCforward2ReversibleBool_byConc_No_dGt0ErrorRHS\n\nforward2Reversible_bydGt0LHS=forward2Reversible_bydGt0 & directions.forwardProbability>cumNormProbFwdUpper; %dGfGCforward2ReversibleBool_bydGt0LHS\nforward2Reversible_bydGt0Mid=forward2Reversible_bydGt0 & directions.forwardProbability>=cumNormProbFwdLower & directions.forwardProbability<=cumNormProbFwdUpper;%dGfGCforward2ReversibleBool_bydGt0Mid\nforward2Reversible_bydGt0RHS=forward2Reversible_bydGt0 & directions.forwardProbability<cumNormProbFwdLower; %dGfGCforward2ReversibleBool_bydGt0RHS\n\nforward2Reversible_byConc_negative_uncertain_DrG0 = forwardRecon & reversibleThermo & model.DrGt0Min~=model.DrGt0Max & model.DrGt0Max<0; %dGfGCforward2ReversibleBool_byConcLHS\nforward2Reversible_byConc_positive_uncertain_DrG0 = forwardRecon & reversibleThermo & model.DrGt0Min~=model.DrGt0Max & model.DrGt0Min>0; %dGfGCforward2ReversibleBool_byConcRHS\n\nforward2Reversible_byConc_zero_fixed_DrG0 = forwardRecon & reversibleThermo & model.DrGt0Min==0 & model.DrGt0Max==0;%new to v2\n\nif printLevel<0\n    fid=fopen(fileName,'w');\nelse\n    fid=1;\nend\n\nif printLevel~=0\n    fprintf(fid,'%s\\n','Qualitative internal reaction directionality:');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(model.SIntRxnBool)),' internal reconstruction reaction directions.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(forwardRecon)), ' forward reconstruction assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(reverseRecon)), ' reverse reconstruction assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(reversibleRecon)), ' reversible reconstruction assignment.');\n    fprintf(fid,'\\n');\n\n    fprintf(fid,'%s\\n','Quantitative internal reaction directionality:');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(model.SIntRxnBool)),' internal reconstruction reaction directions.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(forwardThermo)+nnz(reverseThermo)+nnz(reversibleThermo)),  ' of which have a thermodynamic assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(uncertainThermo)),  ' of which have no thermodynamic assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(forwardThermo)), ' forward thermodynamic only assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(reverseThermo)), ' reverse thermodynamic only assignment.');\n    fprintf(fid,'%10s\\t%s\\n',int2str(nnz(reversibleThermo)), ' reversible thermodynamic only assignment.');\n    fprintf(fid,'\\n');\n\n    fprintf(fid,'%s\\n','Qualitiative vs Quantitative:');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reversible2Reversible),' Reversible -> Reversible');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reversible2Forward),' Reversible -> Forward');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reversible2Reverse),' Reversible -> Reverse');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reversible2Uncertain),' Reversible -> Uncertain');\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Forward),' Forward -> Forward');\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reverse),' Forward -> Reverse');\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible),' Forward -> Reversible');\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Uncertain),' Forward -> Uncertain');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reverse2Reversible),' Reverse -> Reverse');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reverse2Forward),' Reverse -> Forward');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reverse2Reversible),' Reverse -> Reversible');\n    fprintf(fid,'%10i\\t%s\\n',nnz(reverse2Uncertain),' Reversible -> Uncertain');\n    fprintf(fid,'\\n');\n\n    fprintf(fid,'%s\\n','Breakdown of relaxation of reaction directionality, Qualitiative vs Quantitative:');\n    %total number of qualitatively forward reactions that are\n    %quantitatively reversible\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible),' qualitatively forward reactions that are quantitatively reversible (total).');\n    %qualitatively forward reactions that are quantitatively reversible by\n    %the range of dGt0\n    fprintf(fid,'%10i\\t%s%s\\n',nnz(forward2Reversible_bydGt0LHS),' of which are quantitatively reversible by range of dGt0. ',['P(\\Delta_{r}G^{\\primeo}<0) > ' num2str(cumNormProbFwdUpper)]);\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s%s\\n',nnz(forward2Reversible_bydGt0Mid),' of which are quantitatively reversible by range of dGt0. ',[num2str(cumNormProbFwdLower) '< P(\\Delta_{r}G^{\\primeo}<0) < ' num2str(cumNormProbFwdUpper)]);\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s%s\\n',nnz(forward2Reversible_bydGt0RHS),' of which are quantitatively reversible by range of dGt0. ',['P(\\Delta_{r}G^{\\primeo}<0) < ' num2str(cumNormProbFwdLower)]);\n    %qualitatively forward reactions that are quantitatively\n    %reversible by concentration alone (no dGt0 error)\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible_byConc_zero_fixed_DrG0),' of which are quantitatively forward by fixed dGr0t, but reversible by concentration alone (zero fixed DrGt0).');\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible_byConc_negative_fixed_DrG0),' of which are quantitatively reverse by dGr0t, but reversible by concentration (negative fixed DrGt0).');\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible_byConc_positive_fixed_DrG0),' of which are quantitatively forward by dGr0t, but reversible by concentration (positve fixed DrGt0).');\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible_byConc_negative_uncertain_DrG0),' of which are quantitatively reverse by dGr0t, but reversible by concentration (uncertain negative DrGt0).');\n    %qualitatively reverse reactions that are quantitatively\n    %reversible by concentration alone (with dGt0 error)\n    fprintf(fid,'%10i\\t%s\\n',nnz(forward2Reversible_byConc_positive_uncertain_DrG0),' of which are quantitatively forward by dGr0t, but reversible by concentration (uncertain positive DrGt0).');\nend\nif printLevel<0\n    fclose(fid);\nend\n\n\n%changed directions\ndirections.forward2Forward=forward2Forward;\ndirections.forward2Reverse=forward2Reverse;\ndirections.forward2Reversible=forward2Reversible;\ndirections.forward2Uncertain=forward2Uncertain;\ndirections.reversible2Forward=reversible2Forward;\ndirections.reversible2Reverse=reversible2Reverse;\ndirections.reversible2Reversible=reversible2Reversible;\ndirections.reversible2Uncertain=reversible2Uncertain;\ndirections.reverse2Forward=reverse2Forward;\ndirections.reverse2Reverse=reverse2Reverse;\ndirections.reverse2Reversible=reverse2Reversible;\ndirections.reverse2Uncertain=reverse2Uncertain;\n\ndirections.tightened=tightened;\n\n%all forward reversible classes\ndirections.forward2Reversible_bydGt0=forward2Reversible_bydGt0;\ndirections.forward2Reversible_bydGt0LHS=forward2Reversible_bydGt0LHS;\ndirections.forward2Reversible_bydGt0Mid=forward2Reversible_bydGt0Mid;\ndirections.forward2Reversible_bydGt0RHS=forward2Reversible_bydGt0RHS;\n\ndirections.forward2Reversible_byConc_zero_fixed_DrG0=forward2Reversible_byConc_zero_fixed_DrG0;\ndirections.forward2Reversible_byConc_negative_fixed_DrG0=forward2Reversible_byConc_negative_fixed_DrG0;\ndirections.forward2Reversible_byConc_positive_fixed_DrG0=forward2Reversible_byConc_positive_fixed_DrG0;\ndirections.forward2Reversible_byConc_negative_uncertain_DrG0=forward2Reversible_byConc_negative_uncertain_DrG0;\ndirections.forward2Reversible_byConc_positive_uncertain_DrG0=forward2Reversible_byConc_positive_uncertain_DrG0;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/directionalityReport/directionalityStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814535, "lm_q1q2_score": 0.2049529669949046}}
{"text": "function out = brighterremap(x)\n% BRIGHTERREMAP Brighter set of parameters for density remap\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n    out = uint8( amplitudetodensity(x,60,40) );\nend\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Visualization/remap/remap_funcs/brighterremap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.204924706765156}}
{"text": "% -------------------------------------------------------------------------------------------------\nfunction [bboxes,fps, ground_truth] = tracker2(varargin)\n%TRACKER\n%   is the main function that performs the tracking loop\n%   Default parameters are overwritten by VARARGIN\n%\n%   Luca Bertinetto, Jack Valmadre, Joao F. Henriques, 2016\n% -------------------------------------------------------------------------------------------------\n    % These are the default hyper-params for SiamFC-3S\n    % The ones for SiamFC (5 scales) are in params-5s.txt\n    p.numScale = 3;\n    p.scaleStep = 1.0375;\n    p.scalePenalty = 0.9745;\n    p.scaleLR = 0.59; % damping factor for scale update\n    p.responseUp = 16; % upsampling the small 17x17 response helps with the accuracy\n    p.windowing = 'cosine'; % to penalize large displacements\n    p.wInfluence = 0.176; % windowing influence (in convex sum)\n    p.net = '2016-08-17.net.mat';\n    %% execution, visualization, benchmark\n    p.video = 'vot15_bag';\n    p.visualization = false;\n    p.gpus = 1;\n    p.bbox_output = false;\n    p.fout = -1;\n    %% Params from the network architecture, have to be consistent with the training\n    p.exemplarSize = 127;  % input z size\n    p.instanceSize = 255;  % input x size (search region)\n    p.scoreSize = 17;\n    p.totalStride = 8;\n    p.contextAmount = 0.5; % context amount for the exemplar\n    p.subMean = false;\n    %% SiamFC prefix and ids\n    p.prefix_z = 'a_'; % used to identify the layers of the exemplar\n    p.prefix_x = 'b_'; % used to identify the layers of the instance\n    p.prefix_join = 'xcorr';\n    p.prefix_adj = 'adjust';\n    p.id_feat_z = 'a_feat';\n    p.id_score = 'score';\n    % Get environment-specific default paths.\n    p.net_base_path = '../models/';\n    p.seq_base_path = '../demo-sequences/';\n    p.seq_vot_base_path = '/path/to/VOT/evaluation/sequences/'; % (optional)\n    p.stats_path = '/home/ethan/dxp/ours/Siam_adapt/models/ILSVRC2015.stats.mat'; % (optional)\n    % added parameters\n    p.load_video_info = @load_video_info_kcf;\n    % Overwrite default parameters with varargin\n    p = vl_argparse(p, varargin);\n% -------------------------------------------------------------------------------------------------\n\nload_video_info_fun = p.load_video_info;\n% p.video = video;\n%     % Get environment-specific default paths.\n%     p = env_paths_tracking(p);\n    % Load ImageNet Video statistics\n    if exist(p.stats_path,'file')\n        stats = load(p.stats_path);\n    else\n        warning('No stats found at %s', p.stats_path);\n        stats = [];\n    end\n    % Load two copies of the pre-trained network\n    net_z = load_pretrained([p.net_base_path p.net], p.gpus);\n    net_x = load_pretrained([p.net_base_path p.net], []);\n    [imgFiles, targetPosition, targetSize, ground_truth] = load_video_info_fun(p.seq_base_path, p.video);\n    nImgs = numel(imgFiles);\n    startFrame = 1;\n    % Divide the net in 2\n    % exemplar branch (used only once per video) computes features for the target\n    remove_layers_from_prefix(net_z, p.prefix_x);\n    remove_layers_from_prefix(net_z, p.prefix_join);\n    remove_layers_from_prefix(net_z, p.prefix_adj);\n    % instance branch computes features for search region x and cross-correlates with z features\n    remove_layers_from_prefix(net_x, p.prefix_z);\n    zFeatId = net_z.getVarIndex(p.id_feat_z);\n    scoreId = net_x.getVarIndex(p.id_score);\n    % get the first frame of the video\n    im = gpuArray(single(imgFiles{startFrame}));\n    % if grayscale repeat one channel to match filters size\n\tif(size(im, 3)==1)\n        im = repmat(im, [1 1 3]);\n    end\n    % Init visualization\n    videoPlayer = [];\n    if p.visualization && isToolboxAvailable('Computer Vision System Toolbox')\n        videoPlayer = vision.VideoPlayer('Position', [100 100 [size(im,2), size(im,1)]+30]);\n    end\n    % get avg for padding\n    avgChans = gather([mean(mean(im(:,:,1))) mean(mean(im(:,:,2))) mean(mean(im(:,:,3)))]);\n\n    wc_z = targetSize(2) + p.contextAmount*sum(targetSize);\n    hc_z = targetSize(1) + p.contextAmount*sum(targetSize);\n    s_z = sqrt(wc_z*hc_z);\n    scale_z = p.exemplarSize / s_z;\n    % initialize the exemplar\n    [z_crop, ~] = get_subwindow_tracking(im, targetPosition, [p.exemplarSize p.exemplarSize], [round(s_z) round(s_z)], avgChans);\n    if 0\n        imwrite(uint8(gather(z_crop)),'test_z.png');\n    end\n    if p.subMean\n        z_crop = bsxfun(@minus, z_crop, reshape(stats.z.rgbMean, [1 1 3]));\n    end\n    d_search = (p.instanceSize - p.exemplarSize)/2;\n    pad = d_search/scale_z;\n    s_x = s_z + 2*pad;\n    % arbitrary scale saturation\n    min_s_x = 0.2*s_x;\n    max_s_x = 5*s_x;\n\n    switch p.windowing\n        case 'cosine'\n            window = single(hann(p.scoreSize*p.responseUp) * hann(p.scoreSize*p.responseUp)');\n        case 'uniform'\n            window = single(ones(p.scoreSize*p.responseUp, p.scoreSize*p.responseUp));\n    end\n    % make the window sum 1\n    window = window / sum(window(:));\n    scales = (p.scaleStep .^ ((ceil(p.numScale/2)-p.numScale) : floor(p.numScale/2)));\n    % evaluate the offline-trained network for exemplar z features\n    net_z.eval({'exemplar', z_crop});\n    z_features = net_z.vars(zFeatId).value;\n    z_features = repmat(z_features, [1 1 1 p.numScale]);\n\n    bboxes = zeros(nImgs, 4);\n    % start tracking\ntime = 0;\n    tic;\n    for i = startFrame:nImgs\n        if i>startFrame\n            % load new frame on GPU\n            im = gpuArray(single(imgFiles{i}));\n   \t\t\t% if grayscale repeat one channel to match filters size\n    \t\tif(size(im, 3)==1)\n        \t\tim = repmat(im, [1 1 3]);\n    \t\tend\n            scaledInstance = s_x .* scales;\n            scaledTarget = [targetSize(1) .* scales; targetSize(2) .* scales];\n            % extract scaled crops for search region x at previous target position\n            x_crops = make_scale_pyramid(im, targetPosition, scaledInstance, p.instanceSize, avgChans, stats, p);\n            if 0\n                imwrite(uint8(gather(x_crops(:,:,:,2))),'test_x.png');\n            end\n            % evaluate the offline-trained network for exemplar x features\n%             tic\n            [newTargetPosition, newScale] = tracker_eval(net_x, round(s_x), scoreId, z_features, x_crops, targetPosition, window, p);\n%             toc\n            targetPosition = gather(newTargetPosition);\n            % scale damping and saturation\n            s_x = max(min_s_x, min(max_s_x, (1-p.scaleLR)*s_x + p.scaleLR*scaledInstance(newScale)));\n            targetSize = (1-p.scaleLR)*targetSize + p.scaleLR*[scaledTarget(1,newScale) scaledTarget(2,newScale)];\n        else\n            % at the first frame output position and size passed as input (ground truth)\n        end\n\n        rectPosition = [targetPosition([2,1]) - targetSize([2,1])/2, targetSize([2,1])];\n        % output bbox in the original frame coordinates\n        oTargetPosition = targetPosition; % .* frameSize ./ newFrameSize;\n        oTargetSize = targetSize; % .* frameSize ./ newFrameSize;\n        bboxes(i, :) = [oTargetPosition([2,1]) - oTargetSize([2,1])/2, oTargetSize([2,1])];\n\n        if p.visualization\n            if isempty(videoPlayer)\n                figure(1), imshow(im/255);\n                figure(1), rectangle('Position', rectPosition, 'LineWidth', 4, 'EdgeColor', 'y');\n                drawnow\n                fprintf('Frame %d\\n', startFrame+i);\n            else\n                im = gather(im)/255;\n                im = insertShape(im, 'Rectangle', rectPosition, 'LineWidth', 4, 'Color', 'yellow');\n                % Display the annotated video frame using the video player object.\n                step(videoPlayer, im);\n            end\n        end\n\n        if p.bbox_output\n            fprintf(p.fout,'%.2f,%.2f,%.2f,%.2f\\n', bboxes(i, :));\n        end\n\n    end\n\n    time = time + toc;\n    bboxes = bboxes(startFrame : i, :);\n    fps = nImgs/time;\nend\n", "meta": {"author": "shenjianbing", "repo": "TripletTracking", "sha": "b4ed538f2189b94bf3bc13fcca879b7fd12ad93a", "save_path": "github-repos/MATLAB/shenjianbing-TripletTracking", "path": "github-repos/MATLAB/shenjianbing-TripletTracking/TripletTracking-b4ed538f2189b94bf3bc13fcca879b7fd12ad93a/tracking/tracker2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2047359895443217}}
{"text": "classdef testHorizontalLaminate < TestSequentialLaminateTestedWithNumerics\n\n    methods (Access = public)\n\n        function obj = testHorizontalLaminate()\n            obj.compute();\n        end\n\n    end\n    \n    methods (Access = protected)\n\n        function loadLaminateDirection(obj)\n            d = [0 1 0];\n            dir = Vector3D;\n            dir.setValue(d);\n            dir.normalize()\n            obj.LaminateDirection = dir;\n        end\n\n        function loadFiberDirection(obj)\n            d = [1 0 0];\n            dir = Vector3D;\n            dir.setValue(d);\n            dir.normalize()\n            obj.FiberDirection = dir;\n        end\n\n    end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/tests/Source/HomogenizationTests/testHorizontalLaminate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20446893907525907}}
{"text": "function [scan3dd] = elec_load_scan_3ddasc(filename)\n\n% elec_load_scan_3ddasc - read ascii export of Neuroscan 3DD file\n% \n% Load an ascii electrode file and return \n% the electrode labels and coordinates.  This\n% function can read and return Cartesian (x,y,z) \n% and/or spherical (theta,phi,r) coordinates.\n%\n% [scan3dd] = elec_load_scan_3ddasc(filename)\n% \n% where:\n% \n% file = '<path><filename>' with row format '%s %d %f %f %f'\n% \n% The file format is that of NeuroScan 3Dspace ascii \n% export files.  Each row of the file comprises an electrode label, \n% an electrode type code (see below), and the x,y,z coordinates (cm).\n% Each field is separated by spaces.  For example,\n% \n% Fz    69  Xcm Ycm Zcm\n% \n% Example result:\n%\n% scan3dd = \n% \n%      label: {1x128 cell}\n%          x: [128x1 double]\n%          y: [128x1 double]\n%          z: [128x1 double]\n%        hsp: [1617x3 double]\n%     nasion: [-0.0333 9.0341 0]\n%        lpa: [-6.9128 0 0]\n%        rpa: [6.9128 0 0]\n%     origin: [0 0 0]\n%        ref: [0 9.9341 0]\n%\n% All coordinates are in centimeters.\n% \n% Notes:\n% \n% i) Type is defined as follows (from Neuroscan 3Dspace ascii export):\n%\n%           Electrode               Type\n%           ---------               ----\n%           Nasion                   110 (or 78)\n%           Left                     108 (or 76)\n%           Right                    114 (or 82)\n%           electrodes                69\n%           Centroid (origin)         99 (or 67; eg <0,0,0>)\n%           Ref                      120 (or 88)\n%           Scalp Points (hsp)        32\n%\n% \n\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence:  GNU GPL, no express or implied warranties\n% History:  08/1999, Darren.Weber_at_radiology.ucsf.edu\n%           08/2003, Darren.Weber_at_radiology.ucsf.edu\n%                    complete rewrite, replacing elec_load.m\n%                    new version of 3Dspace exports different type numbers ;-)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nver = '$Revision: 1.1 $';\nfprintf('\\nELEC_LOAD_SCAN3DDASC [v %s]\\n',ver(11:15));\n\ntic;\n\n[path,name,ext] = fileparts(filename);\nfile = fullfile(path,[name ext]);\n\nfprintf('...loading electrodes from:\\n\\t%s\\n', file);\n\nscan3dd = read_3dd(file);\n\nfprintf('...loaded %d electrodes\\n', size(scan3dd.x,1));\n\nt = toc; fprintf('...done (%6.2f sec).\\n\\n',t);\n\nreturn\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction scan3dd = read_3dd(file),\n\n\nscan3dd.label = [];\nscan3dd.x = [];\nscan3dd.y = [];\nscan3dd.z = [];\nscan3dd.hsp = [];\n\n\n\nfid = fopen(file);\nif fid < 0,\n  msg = sprintf('cannot open file: %s\\n',file);\n  error(msg);\nend\n\n% 3DD ascii files contain position information for \n% fiducial, sensor, and head shape fields.\n\n% First get the fiducial points by reading the whole file\n% (clumsy, but exhaustive search for field indicators).\n\n% Fiducial points are required for MRI registration. They are \n% the nasion, left and right preauricular points, eg:\n\n%      Nasion\t78\t-0.033340\t9.034104\t0.000000\n%      Left\t76\t-6.912818\t-0.000000\t0.000000\n%      Right\t82\t6.912818\t0.000000\t-0.000000\n\nfprintf('...searching for fiducials...');\n\nn = 0;\nwhile n < 5,\n  tmp = fgetl(fid);\n  if tmp < 0, break; end\n  \n  tmp = lower(tmp);\n  \n  if strfind(tmp,'nasion'),\n    tmp = sscanf(tmp,'%s %d %f %f %f');\n    scan3dd.nasion = [tmp(end-2) tmp(end-1) tmp(end)];\n    n = n + 1;\n    continue;\n  end\n  if strfind(tmp,'left'),\n    tmp = sscanf(tmp,'%s %d %f %f %f');\n    scan3dd.lpa = [tmp(end-2) tmp(end-1) tmp(end)];\n    n = n + 1;\n    continue;\n  end\n  if strfind(tmp,'right'),\n    tmp = sscanf(tmp,'%s %d %f %f %f');\n    scan3dd.rpa = [tmp(end-2) tmp(end-1) tmp(end)];\n    n = n + 1;\n    continue;\n  end\n  if strfind(tmp,'centroid'),\n    tmp = sscanf(tmp,'%s %d %f %f %f');\n    scan3dd.origin = [tmp(end-2) tmp(end-1) tmp(end)];\n    n = n + 1;\n    continue;\n  end\n  if strfind(tmp,'ref'),\n    tmp = sscanf(tmp,'%s %d %f %f %f');\n    scan3dd.ref = [tmp(end-2) tmp(end-1) tmp(end)];\n    n = n + 1;\n    continue;\n  end\nend\n\nfrewind(fid);\nfprintf('done\\n');\n\n\nfprintf('...searching for electrodes...');\n\nok = 1;\nwhile ok,\n  tmp = fgetl(fid);\n  if tmp < 0, break; end\n  \n  if strfind(lower(tmp),'nasion'),   continue; end\n  if strfind(lower(tmp),'left'),     continue; end\n  if strfind(lower(tmp),'right'),    continue; end\n  if strfind(lower(tmp),'centroid'), continue; end\n  if strfind(lower(tmp),'ref'),      continue; end\n  \n  tmp = sscanf(tmp,'%s %d %f %f %f');\n  \n  if tmp(end-3) == 69,\n    scan3dd.label{end+1} = char(tmp(1:end-4))';\n    scan3dd.x(end+1,1) = tmp(end-2);\n    scan3dd.y(end+1,1) = tmp(end-1);\n    scan3dd.z(end+1,1) = tmp(end);\n    continue;\n  end\n  if strfind(char(tmp(1:end-4))','32'),\n    break;\n    % found a head shape point\n    scan3dd.hsp(end+1,:) = [tmp(end-2),tmp(end-1),tmp(end)];\n    continue;\n  end\nend\n\n\nfrewind(fid);\nfprintf('done\\n');\n\n\n\nfprintf('...searching for head shape points...');\n\nok = 1;\nwhile ok,\n  tmp = fgetl(fid);\n  if tmp < 0, break; end\n  \n  if strfind(lower(tmp),'nasion'),   continue; end\n  if strfind(lower(tmp),'left'),     continue; end\n  if strfind(lower(tmp),'right'),    continue; end\n  if strfind(lower(tmp),'centroid'), continue; end\n  if strfind(lower(tmp),'ref'),      continue; end\n  if strfind(lower(tmp),'69'),       continue; end\n  \n  tmp = sscanf(tmp,'%d %f %f %f');\n  \n  if tmp(end-3) == 32,\n    % found a head shape point\n    scan3dd.hsp(end+1,:) = [tmp(end-2),tmp(end-1),tmp(end)];\n    continue;\n  end\nend\n\nfrewind(fid);\nfprintf('done\\n');\n\nfclose(fid);\n\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/elec_load_scan3ddasc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20446893907525907}}
{"text": "function ap = context_test(dataset, cls)\n% Rescore detections on the test dataset using the context\n% rescoring SVMs trained by context_train.m.\n%   ap = context_test(dataset, cls)\n%\n% Return value\n%   ap          AP score for context rescoring\n%\n% Arguments\n%   dataset     Dataset to context rescore\n%   cls         Object class to rescore (if not given, all are rescored)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nconf = voc_config();\ncachedir = conf.paths.model_dir;\nVOCopts  = conf.pascal.VOCopts;\nVOCyear  = conf.pascal.year;\n\nif nargin < 1\n  dataset = conf.eval.test_set;\nend\n\nif nargin < 2\n  cls = [];\nend\n\n% Get detections, filter bounding boxes, and context feature vectors\n% to be rescored\n[ds_all, bs_all, X] = context_data(dataset, VOCyear);\n\nids = textread(sprintf(VOCopts.imgsetpath, dataset), '%s');\nnumids = length(ids);\nnumcls = length(VOCopts.classes);\nap = zeros(numcls, 1);\n\nfprintf('Rescoring detections\\n');\nif ~isempty(cls)\n  cls_inds = strmatch(cls, VOCopts.classes, 'exact');\nelse\n  cls_inds = 1:numcls;\nend\n\nap = nan(numcls, 1);\n\nfor c = cls_inds\n  cls = VOCopts.classes{c};\n  fprintf('%d/%d %s ', c, numcls, cls);\n  try\n    load([cachedir cls '_boxes_' dataset '_context_' VOCyear]);\n  catch\n    load([cachedir cls '_context_classifier']);\n    pos_ind = find(model.Label == 1);\n    for i = 1:numids\n      if ~isempty(X{c,i})\n        [~, ~, s] = svmpredict(ones(size(X{c,i},1), 1), X{c,i}, model);\n        s = model.Label(1)*s;\n        ds_all{c}{i}(:,end) = s;\n        bs_all{c}{i}(:,end) = s;\n      end\n    end\n    ds = ds_all{c};\n    bs = bs_all{c};\n    save([cachedir cls '_boxes_' dataset '_context_' VOCyear], 'ds', 'bs');\n  end\n  ap(c) = pascal_eval(cls, ds, dataset, VOCyear, ['context_' VOCyear]);\n  fprintf(' %.3f\\n', ap(c));\nend\n\nfprintf('average = %f\\n', nanmean(ap));\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/context/context_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20441217641392442}}
{"text": "function test_bug2986\n\n% MEM 3gb\n% WALLTIME 00:20:00\n% DEPENDENCY ft_volumerealign ft_volumereslice\n\nload standard_mri\n\n% convert to 'cm' to show what happens\nmri = ft_convert_units(mri, 'cm');\n\n% reslice to standard (improves solutions) \nmri =  ft_volumereslice([], mri);\n\n% load headshape\nload(fullfile(dccnpath('/home/common/matlab/fieldtrip/data/test'),'bug2986.mat'));\n\n% for quick check feed in fiducial positions\nfiducial = [];\nfiducial.nas = [131 215 85];\nfiducial.lpa =  [41 108 84];\nfiducial.rpa = [213 107 80];\nfiducial.zpoint = [131 125 195];\n\n% coarse realignment based on fiducials first\ncfg          = [];\ncfg.method   = 'fiducial';\ncfg.fiducial = fiducial;\ncfg.coordsys = 'neuromag';\nmri          = ft_volumerealign(cfg,mri);\n\n% make automatic coregistration based on headshape\n% the coregistration looks fine (depending on how well you defined the\n% fiducials of course) - don't change anything in the interactive menu to\n% avoid that that's the problem\ncfg           = [];\ncfg.method    = 'headshape';\ncfg.headshape.headshape = shape;\ncfg.headshape.interactive    = 'no';\ncfg.headshape.icp = 'yes';\ncfg.coordsys  = 'neuromag';\nmri_aligned   = ft_volumerealign(cfg, mri);\n\ncfg.headshape.shape = ft_convert_units(shape, 'm');\nmri_aligned2  = ft_volumerealign(cfg, mri);\nmri_aligned3  = ft_volumerealign(cfg, ft_convert_units(mri, 'mm'));\n\n\n%% check based on fiducial + headshape alignment\n% segment the scalp to check the alignment\ncfg        = [];\ncfg.output = 'scalp';\ncfg.smooth = 2;\nseg_align  = ft_volumesegment(cfg, mri_aligned);\nseg_align2  = ft_volumesegment(cfg, mri_aligned2);\nseg_align3  = ft_volumesegment(cfg, mri_aligned3);\n\n% build headmodel\ncfg             = [];\ncfg.method      = 'singleshell';\ncfg.numvertices = 2000;\nhdm    = ft_prepare_headmodel(cfg, seg_align);\nhdm2   = ft_prepare_headmodel(cfg, seg_align2);\nhdm3   = ft_prepare_headmodel(cfg, seg_align3);\n\n% now plot\nfigure; hold on\nft_plot_headmodel(ft_convert_units(hdm, 'cm'),'edgecolor','none','facecolor','w');\nft_plot_headshape(shape);\n\nfigure; hold on\nft_plot_headmodel(ft_convert_units(hdm2, 'cm'),'edgecolor','none','facecolor','w');\nft_plot_headshape(shape);\n\nfigure; hold on\nft_plot_headmodel(ft_convert_units(hdm3, 'cm'),'edgecolor','none','facecolor','w');\nft_plot_headshape(shape);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2986.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20422063451479072}}
{"text": "function mObject3 = timeFrequencySTRAIGHTmorphingExt(mObject1,mObject2,mRate,mixMethod);\n%   Morphing based on STRAIGHT parameters\n%   mObject3 = timeFrequencySTRAIGHTmorphing(mObject1,mObject2,mRate,mixMethod);\n\n%   Designed and coded by Hideki Kawahara\n%   28/Feb./2005\n%   Copyright(c) 2005, Hideki Kawahara\n%   14/March/2005 bug fix on sampling frequency\n%   01/Oct./2005 bug fix on similarity check\n%   04/Oct./2005 partial morphing extension\n%   18/Oct./2005 direct differential manipulation and API cange\n%   29/Jan./2006 bug fix on boundary conditions\n%   24/Oct./2006 modificaton of definition\n\nswitch nargin\n    case 0\n        mObject3.morphingObject = createMobject;\n        mixRate.F0 = 0;\n        mixRate.spectrum = 0;\n        mixRate.aperiodicity = 0;\n        mixRate.timeCoordinate = 0;\n        mixRate.freqCoordinate = 0;\n        mObject3.mixRate = mixRate;\n        mObject3.mixMethods = {'linear','log','differentialLogarithm'};\n        return\nend;\nif ~isfield(mObject1,'vuv')\n    mObject1.vuv = (mObject1.F0>0);\nelseif length(mObject1.vuv) == 0\n    mObject1.vuv = (mObject1.F0>0);\nend;\nif ~isfield(mObject2,'vuv')\n    mObject2.vuv = (mObject2.F0>0);\nelseif length(mObject2.vuv) == 0\n    mObject2.vuv = (mObject2.F0>0);\nend;\nmObject3 = checkForSimilarity(mObject1,mObject2);\nmixRate = checkForMorphingConditions(mRate);\nmObject1 = checkForIntegrity(mObject1);\nmObject2 = checkForIntegrity(mObject2);\nfs = mObject1.samplingFrequency;\nif length(mObject3) ==0;return;end;\ndtFrame = mObject1.frameUpdateInterval;\nendLocation1 = (length(mObject1.F0)-1)*dtFrame; % in ms\nendLocation2 = (length(mObject2.F0)-1)*dtFrame; % in ms\ntimeAnchor1 = [0;mObject1.anchorTimeLocation;endLocation1];\ntimeAnchor2 = [0;mObject2.anchorTimeLocation;endLocation2];\nlocationOn1 = (0:length(mObject1.F0)-1)*dtFrame;\nlocationOn2 = (0:length(mObject2.F0)-1)*dtFrame;\nmapFrom1to2 = interp1(timeAnchor1,timeAnchor2,locationOn1);\n[nr1,nc1] = size(mObject1.spectrogram);\n[nr2,nc2] = size(mObject2.spectrogram);\n\n%---- initialize frequency mapping function\nfmapFrom1to2OnTime1 = generateFrequencyMap(mObject1,mObject2);\n\n%---- mixing on mObject1's time axis\nnAxis1 = length(locationOn1); \nnAxis2 = length(locationOn2);\nmorphedF0 = zeros(nAxis1,1);\nmorphedvuv = zeros(nAxis1,1);\nmorphedAp = zeros(nr1,nAxis1);\nmorphedSgram = zeros(nr1,nAxis1);\nweightSumF0 = zeros(nAxis1,1);\nfor ii=1:nAxis1\n    mappedIndexOn2 = mapFrom1to2(ii)/dtFrame+1;\n    iFloor = floor(mappedIndexOn2);\n    iFraction = mappedIndexOn2-iFloor;\n    fIndex = floor(fmapFrom1to2OnTime1(:,ii)/fs*2*(nr1-1))+1;\n    dAp = iFraction*(mObject2.aperiodicityIndex(:,min(iFloor+1,nAxis2))-mObject2.aperiodicityIndex(:,min(iFloor,nAxis2)));\n    ap2on2faxis = mObject2.aperiodicityIndex(:,min(iFloor,nAxis2))+dAp;\n    ap2on1faxis = ap2on2faxis(fIndex);\n    morphedAp(:,ii) = (1-mixRate.aperiodicity)*mObject1.aperiodicityIndex(:,ii)+mixRate.aperiodicity*ap2on1faxis; %04/Oct/2005 HK\n    switch mixMethod\n        case 'linear'\n            dSgram = iFraction*(mObject2.spectrogram(:,min(iFloor+1,nAxis2))-mObject2.spectrogram(:,min(iFloor,nAxis2)));\n            sgram2on2faxis = mObject2.spectrogram(:,min(iFloor,nAxis2))+dSgram;\n            sgram2on1faxis = sgram2on2faxis(fIndex);\n            morphedSgram(:,ii) = (1-mixRate.spectrum)*mObject1.spectrogram(:,ii)+mixRate.spectrum*sgram2on1faxis;\n        case 'log'\n            dSgram = iFraction*(log(mObject2.spectrogram(:,min(iFloor+1,nAxis2)))-log(mObject2.spectrogram(:,min(iFloor,nAxis2))));\n            sgram2on2faxis = log(mObject2.spectrogram(:,min(iFloor,nAxis2)))+dSgram;\n            sgram2on1faxis = sgram2on2faxis(fIndex);\n            tmp = (1-mixRate.spectrum)*log(mObject1.spectrogram(:,ii))+mixRate.spectrum*sgram2on1faxis;\n            morphedSgram(:,ii) = exp(tmp);\n        case 'differentialLogarithm'\n            dSgram = iFraction*(mObject2.spectrogram(:,min(iFloor+1,nAxis2))-mObject2.spectrogram(:,min(iFloor,nAxis2)));\n            sgram2on2faxis = mObject2.spectrogram(:,min(iFloor,nAxis2))+dSgram;\n            sgram2on1faxis = sgram2on2faxis(fIndex);\n            tmp = (1-mixRate.spectrum)*log(mObject1.spectrogram(:,ii))+mixRate.spectrum*sgram2on1faxis;\n            morphedSgram(:,ii) = exp(tmp);\n    end;\n    if mObject1.F0(ii)>0\n        morphedF0(ii) = (1-mixRate.F0)*log(mObject1.F0(ii));\n        weightSumF0(ii) = (1-mixRate.F0);\n    end;\n    if (mObject2.F0(iFloor)>0) & (mObject2.F0(min(iFloor+1,nAxis2))>0)\n        dF0 = iFraction*(log(mObject2.F0(min(iFloor+1,nAxis2)))-log(mObject2.F0(min(iFloor,nAxis2))));\n        morphedF0(ii) = mixRate.F0*(log(mObject2.F0(min(iFloor,nAxis2)))+dF0)+morphedF0(ii);\n        weightSumF0(ii) = weightSumF0(ii)+mixRate.F0;\n    end;\n    morphedvuv(ii) = ((mObject1.vuv(ii)*abs(1-mixRate.F0)+abs(mixRate.F0)*mObject2.vuv(min(iFloor,nAxis2)))>0);\nend;\nmorphedF0(weightSumF0>0) = exp(morphedF0(weightSumF0>0)./weightSumF0(weightSumF0>0));\n\n%----- mapping back onto morphed time axis\ntimeAnchorMorph = (1-mixRate.timeCoordinate)*timeAnchor1 + mixRate.timeCoordinate*timeAnchor2;\nlocationOnMorph = (0:(timeAnchorMorph(end)/dtFrame))*dtFrame;\nmapFormMorphTo1 = interp1(timeAnchorMorph,timeAnchor1,locationOnMorph);\nnAxisMorph = length(locationOnMorph);\nmorphedApOnMorph = zeros(nr1,nAxisMorph);\nmorphedSgramOnMorph = zeros(nr1,nAxisMorph);\nmorphedF0onMorph = zeros(nAxisMorph,1);\nmorphedVUVonMorph = zeros(nAxisMorph,1);\n%----- set place holders\nmObject3.samplingFrequency = fs;\nmObject3.F0 = morphedF0onMorph;\nmObject3.vuv = morphedVUVonMorph;\nmObject3.aperiodicityIndex = morphedApOnMorph;\nmObject3.spectrogram = morphedSgramOnMorph;\nmObject3.anchorTimeLocation = timeAnchorMorph(2:end-1);\nmObject3.anchorFrequency = (1-mixRate.freqCoordinate)*mObject1.anchorFrequency+mixRate.freqCoordinate*mObject2.anchorFrequency;\n%------ nitialize frequency mapping function\nfmapFromMorphto1OnTimeMorph = generateFrequencyMap(mObject3,mObject1);\nfor ii=1:nAxisMorph\n    mappedIndexOn1 = mapFormMorphTo1(ii)/dtFrame+1;\n    iFloor = floor(mappedIndexOn1);\n    iFraction = mappedIndexOn1-iFloor;\n    fIndex = floor(fmapFromMorphto1OnTimeMorph(:,ii)/fs*2*(nr1-1))+1;\n    morphedApOnMorph(:,ii) = morphedAp(fIndex,iFloor) ...\n        +iFraction*(morphedAp(fIndex,min(iFloor+1,nAxis1))-morphedAp(fIndex,iFloor));\n    morphedSgramOnMorph(:,ii) = morphedSgram(fIndex,iFloor) ...\n        +iFraction*(morphedSgram(fIndex,min(iFloor+1,nAxis1))-morphedSgram(fIndex,iFloor));\n    if (morphedF0(iFloor)>0) & (morphedF0(min(iFloor+1,nAxis1))>0)\n        dF0 = iFraction*(morphedF0(min(iFloor+1,nAxis1))-morphedF0(iFloor));\n        morphedF0onMorph(ii) = morphedF0(iFloor)+dF0;\n    end;\n    morphedVUVonMorph(ii) = morphedvuv(iFloor);\nend;\nmObject3.F0 = morphedF0onMorph; \nmObject3.vuv = morphedVUVonMorph;\nmObject3.aperiodicityIndex = morphedApOnMorph;\nmObject3.spectrogram = morphedSgramOnMorph;\nmObject3.anchorTimeLocation = timeAnchorMorph(2:end-1);\n%mObject3.anchorFrequency = (1-mRate)*mObject1.anchorFrequency+mRate*mObject2.anchorFrequency;\n%mObject3 = fmapFromMorphto1OnTimeMorph; % This line is a dummy.\nreturn;\n\n%%% ------ Internal function to check for object's similarity\nfunction mObject3 = checkForSimilarity(mObject1,mObject2)\nmObject3 = [];\nif mObject1.samplingFrequency ~= mObject2.samplingFrequency;mObject3 = [];return;end;\nif mObject1.frameUpdateInterval ~= mObject2.frameUpdateInterval;mObject3 = [];return;end;\nif length(mObject1.anchorTimeLocation) ~= length(mObject2.anchorTimeLocation);mObject3 = [];return;end;\nnAnchor = length(mObject1.anchorTimeLocation);\nfor ii=1:nAnchor % check for similarity of anchor structure\n    frequencyAnchor1 = mObject1.anchorFrequency(ii,:)';% 01/Oct./2005 by HK\n    frequencyAnchor2 = mObject2.anchorFrequency(ii,:)';% 01/Oct./2005 by HK\n    if (sum(frequencyAnchor1>0) ~= sum(frequencyAnchor2>0)) | ...\n            (sum(frequencyAnchor1<0) ~= sum(frequencyAnchor2<0))\n        display('Warning!! Object structures are inconsistent!'); % 01/Oct./2005 by HK\n        return;\n    end;\nend;\nmObject3 = createMobject;\nm0bject3.samplingFrequency = mObject1.samplingFrequency;\nm0bject3.frameUpdateInterval = mObject1.frameUpdateInterval;\nreturn;\n\n%%%--------\nfunction mixRate = checkForMorphingConditions(mRate);\n%   04/Oct./2005 added by HK\n\nif ~isstruct(mRate)\n    mixRate.F0 = mRate;\n    mixRate.spectrum = mRate;\n    mixRate.aperiodicity = mRate;\n    mixRate.timeCoordinate = mRate;\n    mixRate.freqCoordinate = mRate;\n    return;\nend;\nmixRate.F0 = mRate.F0;\nmixRate.spectrum = mRate.spectrum;\nmixRate.aperiodicity = mRate.aperiodicity;\nmixRate.timeCoordinate = mRate.timeCoordinate;\nmixRate.freqCoordinate = mRate.freqCoordinate;\nreturn;\n\n%%%--------\nfunction fmapFrom1to2OnTime1 = generateFrequencyMap(mObject1,mObject2);\n\ndtFrame = mObject1.frameUpdateInterval;\nendLocation1 = (length(mObject1.F0)-1)*dtFrame; % in ms\ntimeAnchor1 = [0;mObject1.anchorTimeLocation;endLocation1];\nlocationOn1 = (0:length(mObject1.F0)-1)*dtFrame;\nfs = mObject1.samplingFrequency;\n[nr1,nc1] = size(mObject1.spectrogram);\nnAnchor = length(mObject1.anchorTimeLocation);\nfmapFrom1to2 = zeros(nr1,nAnchor);\nfrequencyAxis = (0:nr1-1)'/(nr1-1)*fs/2;\nnumberOfFrequencyAnchors = zeros(nAnchor,1);\nfor ii=1:nAnchor\n    frequencyAnchor1 = mObject1.anchorFrequency(ii,:)';\n    frequencyAnchor1 = [0;frequencyAnchor1(frequencyAnchor1>0);fs/2];\n    numberOfFrequencyAnchors(ii) = length(frequencyAnchor1(frequencyAnchor1>0));\n    frequencyAnchor2 = mObject2.anchorFrequency(ii,:)';\n    frequencyAnchor2 = [0;frequencyAnchor2(frequencyAnchor2>0);fs/2];\n    fmapFrom1to2(:,ii) = interp1(frequencyAnchor1,frequencyAnchor2,frequencyAxis);\nend;\nfor ii=1:nAnchor\n    if numberOfFrequencyAnchors(ii) == 1\n        if numberOfFrequencyAnchors(min(ii+1,nAnchor)) > 1\n            fmapFrom1to2(:,ii) = fmapFrom1to2(:,min(ii+1,nAnchor));\n        elseif numberOfFrequencyAnchors(max(ii-1,1)) > 1\n            fmapFrom1to2(:,ii) = fmapFrom1to2(:,max(ii-1,1));\n        end;\n    end;\nend;\nfmapFrom1to2 = [fmapFrom1to2(:,1) fmapFrom1to2 fmapFrom1to2(:,nAnchor)];\nfmapFrom1to2OnTime1 = interp1(timeAnchor1,fmapFrom1to2',locationOn1)';\nreturn;\n\n%%%-------\nfunction cleanedUpObject = checkForIntegrity(inputObject);\n\nmaximumIndex = max([length(inputObject.F0), ...\n    size(inputObject.spectrogram,2) ...\n    size(inputObject.aperiodicityIndex,2)]);\nif length(inputObject.F0) < maximumIndex\n    inputObject.F0 = [inputObject.F0(:);inputObject.F0(end)*ones(maximumIndex - length(inputObject.F0),1)];\nend;\nif size(inputObject.spectrogram,2) < maximumIndex\n    numberOfFillIn = maximumIndex-size(inputObject.spectrogram,2);\n    inputObject.spectrogram = [inputObject.spectrogram inputObject.spectrogram(:,end)*ones(1,numberOfFillIn)];\nend;\nif size(inputObject.aperiodicityIndex,2) < maximumIndex\n    numberOfFillIn = maximumIndex-size(inputObject.aperiodicityIndex,2);\n    inputObject.aperiodicityIndex = [inputObject.aperiodicityIndex inputObject.aperiodicityIndex(:,end)*ones(1,numberOfFillIn)];\nend;\ncleanedUpObject = inputObject;\n\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/morphing_src/timeFrequencySTRAIGHTmorphingExt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2042206345147907}}
{"text": "function varargout = subsref(grains,s)\n% implements grains(1:3)\n%\n% Syntax\n%   grains(1:10)            % the 10 first grains\n%   grains('Fe')            % only Fe grains\n%   grains('id',5)          % give the grain with id 5 \n%   grains(5)               % give the 5th grain in the list\n%   grains( ~grains('fe') ) % all grains but Fe\n%   grains(cond)        \n%\n% Input\n%  grains - @grain2d\n%  cond   - logical array with same size as grains\n%\n\n\n% some special cases to speed things up\nif strcmp(s(1).type,'()') && ...\n    length(s)>1 && strcmp(s(2).type,'.') && strcmp(s(2).subs,'meanOrientation')\n  \n  if strcmp(s(1).type,'{}')\n    ind = grains.id2ind(s(1).subs{1});\n  else\n    ind = subsind(grains,s(1).subs);\n  end\n  \n  phId = unique(grains.phaseId(ind));\n\n  if length(phId) > 1\n    error('MTEX:MultiplePhases',['\\n' ...\n      '----------------------------------------------------------------\\n'...\n      'Your variable contains the phases: ' ...\n      grains.mineralList{phId(1)} ', ' grains.mineralList{phId(2)} '\\n\\n' ...\n      'However, you are executing a command that is only permitted for a single phase!\\n\\n' ...\n      'Please read the chapter ' doclink('EBSDSelect','\"select EBSD data\"')  ...\n      ' for how to restrict grains to a single phase.\\n' ...\n      '----------------------------------------------------------------\\n']);\n  end\n  if isempty(ind)\n    ori = orientation;\n  else\n    ori = orientation(grains.prop.meanRotation(ind),grains.CSList{phId});\n  end\n    \n  if numel(s)>2\n    [varargout{1:nargout}] = builtin('subsref',ori,s(3:end));\n  else\n    varargout{1} = ori;\n  end\n  return\nend\n\n\n\nif strcmp(s(1).type,'()') || strcmp(s(1).type,'{}')\n  \n  if strcmp(s(1).type,'{}')\n    ind = grains.id2ind(s(1).subs{1});\n  else\n    ind = subsind(grains,s(1).subs);\n  end\n  \n  \n  grains = subSet(grains,ind);\n \n  % is there something more to do?\n  if numel(s)>1\n    s = s(2:end);\n  else\n    varargout{1} = grains;\n    return\n  end\nend\n\n% maybe reference to a dynamic property\nif isProperty(grains,s(1).subs)\n  \n  [varargout{1:nargout}] = subsref@dynProp(grains,s);\n  \nelse\n  \n  [varargout{1:nargout}] = builtin('subsref',grains,s);\n  \nend\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@grain2d/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.20410038215969697}}
{"text": "function [varargout] = maxDose(planC, varargin)\n%Calculate a maxDose metric.\n%Stand alone metric :       maxDose(planC, structNum, doseNum, 'Percent' or 'Absolute');\n%Request m object   :       maxDose(planC, 'getnewmetric');\n%Evaluate m object  :       maxDose(planC, m, 'evaluate');\n%LM:  4 Jan 06, JOD: changed interface.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nindexS = planC{end};\noptS = planC{indexS.CERROptions};\n\nif(nargin > 1)\n    call = varargin{end};\nelse\n    warning('Incorrect Usage, try: maxDose(planC, structNum, doseNum, ''Percent'' or ''Absolute'');');\n    return;\nend\n\nswitch upper(call)\n    case 'GETNEWMETRIC'\n        m.name = 'maxDose';\n        m.valueV = [];\n        m.description = 'Returns the max dose in specified structure';\n        m.functionName = @maxDose;\n        m.note = '';\n        m.params(1).name = 'Structure';\n        m.params(1).type = 'DropDown';\n        m.params(1).list = {planC{indexS.structures}.structureName};\n        m.params(1).value = 1;\n        m.params(2).name = 'IsTarget?';\n        m.params(2).type = 'DropDown';\n        m.params(2).list ={'Target', 'Not Target'};\n        m.params(2).value = 2;\n        m.units = [];\n        m.range = [0 inf];\n        m.doseSets = [1];\n        varargout = {planC,m};\n    return;\n\n    case 'EVALUATE'\n        m = varargin{1};\n        structName = planC{indexS.structures}(m.params(1).value).structureName;\n        m.note = structName;\n        m.valueV = [];\n\n        maxD = -inf;\n\t\tfor i=1:length(m.doseSets)\n            [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, m.params(1).value, m.doseSets(i));\n            ans = calc_maxDose(doseBinsV, volsHistV, m.params(2).value);\n            m.valueV = [m.valueV ans];\n            doseArray = getDoseArray(planC{indexS.dose}(m.doseSets(i)));\n            maxD = max(maxD, max(doseArray(:)));\n        end\n        if m.params(2).value == 1\n            %Is target, high dose is best.\n            m.range = [0 max(m.valueV)];\n        elseif m.params(2).value == 2\n            m.range = [maxD min(m.valueV)];\n        end\n        m.units = getDoseUnitsStr(i,planC);\n        varargout = {planC,m};\n        return;\n\n    otherwise  %No specific call has been made, assume user just wants raw metric.\n        if(nargin > 3)\n            structNum = varargin{1};\n            doseNum = varargin{2};\n            volumeTypeString = varargin{3};\n            if(strcmp(upper(volumeTypeString), 'ABSOLUTE'))\n                volumeType = 2;\n            else\n                volumeType = 1;\n            end\n            [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, structNum, doseNum);\n            varargout = {calc_maxDose(doseBinsV, volsHistV, volumeType)};\n        else\n            error('Not enough parameters, try: maxDose(planC, structNum, doseNum, ''Percent'' or ''Absolute'');')\n            return;\n        end\n    end\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/maxDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.20399265812674997}}
{"text": "% HYBRJ  Solve a SNLE using HYBRJ\n%\n% THIS IS A LOW LEVEL FUNCTION - USE opti_hybrj() INSTEAD!\n%\n% hybrj uses the Minpack Powell Hybrid library.\n%\n%   [x,fval,exitflag,fevals] = hybrj(fun,grad,x0,opts)\n%\n%   Input arguments:\n%       fun - vector of nonlinear functions (equations to be solved)\n%       grad - gradient of nonlinear equations (optional)\n%       x0 - initial solution guess\n%       opts - solver options (see below)\n%\n%   Return arguments:\n%       x - solution vector\n%       fval - objective value at the solution\n%       exitflag - exit status (see below)\n%       fevals - number of function evaluations taken\n%\n%   Option Fields (all optional):\n%       display - solver display level [0,1,2]\n%       maxfeval - maximum function evaluations\n%       maxtime - maximum solver execution time\n%       iterfun - Iteration Callback Function, stop = iterfun(iter,fval,x)\n%\n%   Return Status:\n%       1 - optimal\n%       0 - maximum iterations exceeded\n%      -1 - infeasible / could not converge\n%      -2 - hybrj error / other\n%      -5 - user exit\n%\n%\n%   Copyright (C) 2011 Jonathan Currie (I2C2)", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/hybrj/hybrj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20398999086538425}}
{"text": "% Demo for aggregate channel features object detector on KAIST dataset.\n%\n% See also acfReadme.m\n%\n% Piotr's Computer Vision Matlab Toolbox      Version 3.40\n% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n%\n% 2015.06.02. Modified by Soonmin Hwang [smhwang-at-rcv.kaist.ac.kr]\n% 2017.10.11. Update\n\n%% extract training and testing images and ground truth\ndataDir='data/kaist-rgbt/';\naddpath( genpath( 'pdollar-toolbox' ) );\naddpath( genpath( 'libs' ) );\n\n%% set up opts for training detector (see acfTrain)\nopts=acfTrain2(); opts.modelDs=[50 20.5]; opts.modelDsPad=[64 32];\nopts.pPyramid.smooth=.5;\nopts.pPyramid.pChns.pColor.smooth=0; opts.nWeak=[32 128 256 512 1024 2048];\nopts.pBoost.pTree.maxDepth=4; \nopts.pBoost.pTree.fracFtrs=1/16; \nopts.nNeg=50000;\nopts.nAccNeg = 100000;\nopts.nPerNeg = 20;\nopts.pPyramid.pChns.pGradHist.softBin=1; opts.pJitter=struct('flip',1);\n\n% opts.trainSet = [dataDir 'imageSets/train20.txt'];\nopts.trainSet = [dataDir 'imageSets/train04.txt'];\nopts.posGtDir=[dataDir 'annotations'];\nopts.posImgDir=[dataDir 'images'];\n\npLoad={'lbls',{'person'},'ilbls',{'people','person?','cyclist'},'squarify',{3,.41}};\nopts.pLoad = [pLoad 'hRng',[45 inf], 'vType', {'none'} ];\n\n%% Set thermal features\nopts = acfSetTchFeatures(opts, [1 0 1 0]);  % T, TM, THOG, TM+TO\n\n%% train detector (see acfTrain)\ndetector = acfTrain2( opts );\n\n%% modify detector (see acfModify)\npModify=struct('cascThr',0,'cascCal',.025);\ndetector=acfModify(detector,pModify);\n\n%% run detector on a sample image (see acfDetect)\nimgDir = [dataDir 'images']; gtDir = [dataDir 'annotations'];\ntestSet = [dataDir 'imageSets/test20.txt'];\n\nimgNms =bbGt2('getSubsetFiles',{imgDir, imgDir, gtDir}, testSet);\n\nidx = 102;\nI = imreadHistEq(imgNms{1,idx}, imgNms{2,idx});\ntic, bbs=acfDetect2(I,detector); toc\nfigure(1); imshow(I(:,:,1:3)); bbApply('draw',bbs); pause(.1);\n\n%% test detector and plot roc (see acfTest)\n% Reasonable\n[~,~,gt,dt]=acfTest2('name',opts.name,'imgDir',imgDir,...\n  'gtDir',gtDir,'pLoad',[pLoad, 'hRng',[45 inf],...\n  'vType',{{'none','partial'}},'xRng',[5 635],'yRng',[5 475]],...\n  'pModify',pModify,'reapply',0,'show',2,...\n  'lims', [3.1e-3 3.1e1 .2 1], 'clr', 'g', 'subset', testSet, ...\n  'figName', 'Reasonable-all');", "meta": {"author": "SoonminHwang", "repo": "rgbt-ped-detection", "sha": "4ec3637724d009c0a64f862ae2aa0e32e61942a3", "save_path": "github-repos/MATLAB/SoonminHwang-rgbt-ped-detection", "path": "github-repos/MATLAB/SoonminHwang-rgbt-ped-detection/rgbt-ped-detection-4ec3637724d009c0a64f862ae2aa0e32e61942a3/acfDemoKAIST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.20396017862163807}}
{"text": "function y = vl_nnconcat(inputs, dim, dzdy, varargin)\n%VL_NNCONCAT CNN concatenate multiple inputs.\n%  Y = VL_NNCONCAT(INPUTS, DIM) concatenates the inputs in the cell\n%  array INPUTS along dimension DIM generating an output Y.\n%\n%  DZDINPUTS = VL_NNCONCAT(INPUTS, DIM, DZDY) computes the derivatives\n%  of the block projected onto DZDY. DZDINPUTS has one element for\n%  each element of INPUTS, each of which is an array that has the same\n%  dimensions of the corresponding array in INPUTS.\n\n% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.inputSizes = [] ;\nopts = vl_argparse(opts, varargin, 'nonrecursive') ;\n\nif nargin < 2, dim = 3; end;\nif nargin < 3, dzdy = []; end;\n\nif isempty(dzdy)\n  y = cat(dim, inputs{:});\nelse\n  if isempty(opts.inputSizes)\n    opts.inputSizes = cellfun(@size, inputs, 'UniformOutput', false) ;\n  end\n  start = 1 ;\n  y = cell(1, numel(opts.inputSizes)) ;\n  s.type = '()' ;\n  s.subs = {':', ':', ':', ':'} ;\n  for i = 1:numel(opts.inputSizes)\n    stop = start + opts.inputSizes{i}(dim) ;\n    s.subs{dim} = start:stop-1 ; ;\n    y{i} = subsref(dzdy,s) ;\n    start = stop ;\n  end\nend\n", "meta": {"author": "ybsong00", "repo": "CREST-Release", "sha": "e331e6763e6b683b1696e1d61420e902bfce4ef7", "save_path": "github-repos/MATLAB/ybsong00-CREST-Release", "path": "github-repos/MATLAB/ybsong00-CREST-Release/CREST-Release-e331e6763e6b683b1696e1d61420e902bfce4ef7/matconvnet/matlab/vl_nnconcat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.203848828071306}}
{"text": "%Voice Based Biometric System\n%By Ambavi K. Patel.\n\n\nfunction op1=cmpr(cb,cd,n,k,r,c)\nop1(1:n)=0;\nfor j=1:n      % finding euclidian distance\n\n  x(j)=sqrt(sum((cb(1,1:r)-cd((n*(k-1))+j,1:r)).^2));\n    y(j)=sqrt(sum((cb(1,r+1:r+c)-cd((n*(k-1))+j,r+1:r+c)).^2));\n    \n\n    if x(j)<0.05 && y(j)<3     % comparing with threshold values\n        op1(j)=1;\n    else op1(j)=0;\n    end;\nend;\n% display(x);\n% display(y);\n%   \n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31328-voice-based-biometric-system/MFCC_EUCLIDEAN DISTANCE/cmpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20348809120100314}}
{"text": "classdef Estimator < handle\n    %ESTIMATOR  Rotation estimator base class\n    %\n    % It takes features of all images, pairwise matches between all images\n    % and estimates rotations of all cameras.\n    %\n    % Note: The coordinate system origin is implementation-dependent, but you\n    % can always normalize the rotations in respect to the first camera, for\n    % instance.\n    %\n    % See also: cv.Stitcher, cv.BundleAdjuster\n    %\n\n    properties (SetAccess = private)\n        % Object ID\n        id\n    end\n\n    methods\n        function this = Estimator(estimatorType, varargin)\n            %ESTIMATOR  Constructor\n            %\n            %     obj = cv.Estimator(estimatorType)\n            %     obj = cv.Estimator(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __estimatorType__ Estimator type. One of:\n            %   * __HomographyBasedEstimator__ Homography based rotation\n            %     estimator.\n            %   * __AffineBasedEstimator__ Affine transformation based\n            %     estimator. This estimator uses pairwise transformations\n            %     estimated by matcher to estimate final transformation for\n            %     each camera.\n            %\n            % The following are options for the various algorithms:\n            %\n            % ### `HomographyBasedEstimator`\n            % * __IsFocalsEstimated__ default false\n            %\n            % See also: cv.Estimator.estimate\n            %\n            this.id = Estimator_(0, 'new', estimatorType, varargin{:});\n        end\n\n        function delete(this)\n            %DELETE  Destructor\n            %\n            %     obj.delete()\n            %\n            % See also: cv.Estimator\n            %\n            if isempty(this.id), return; end\n            Estimator_(this.id, 'delete');\n        end\n\n        function typename = typeid(this)\n            %TYPEID  Name of the C++ type (RTTI)\n            %\n            %     typename = obj.typeid()\n            %\n            % ## Output\n            % * __typename__ Name of C++ type\n            %\n            typename = Estimator_(this.id, 'typeid');\n        end\n    end\n\n    %% Estimator\n    methods\n        function [cameras,success] = estimate(this, features, pairwise_matches)\n            %ESTIMATE  Estimates camera parameters\n            %\n            %     cameras = obj.estimate(features, pairwise_matches)\n            %     [cameras, success] = obj.estimate(...)\n            %\n            % ## Input\n            % * __features__ Features of images. See cv.FeaturesFinder.\n            % * **pairwise_matches** Pairwise matches of images. See\n            %   cv.FeaturesMatcher.\n            %\n            % ## Output\n            % * __cameras__ Estimated camera parameters. Structure that\n            %   describes camera parameters with the following fields:\n            %   * __aspect__ Aspect ratio.\n            %   * __focal__ Focal length.\n            %   * __ppx__ Principal point X.\n            %   * __ppy__ Principal point Y.\n            %   * __R__ 3x3 camera rotation matrix.\n            %   * __t__ 3x1 camera translation vector.\n            %   * __K__ 3x3 camera intrinsic parameters.\n            % * __success__ True in case of success, false otherwise.\n            %\n            % See also: cv.Estimator.Estimator\n            %\n            [cameras,success] = Estimator_(this.id, 'estimate', features, pairwise_matches);\n        end\n    end\n\n    %% Auto-calibration methods\n    methods (Static)\n        function [K,success] = calibrateRotatingCamera(Hs)\n            %CALIBRATEROTATINGCAMERA  Calibrate rotating camera\n            %\n            %     K = cv.Estimator.calibrateRotatingCamera(Hs)\n            %     [K,success] = cv.Estimator.calibrateRotatingCamera(Hs)\n            %\n            % ## Input\n            % * __Hs__ Cell-array of 3x3 double matrices.\n            %\n            % ## Output\n            % * __K__ 3x3 double matrix.\n            % * __success__ True in case of success, false otherwise.\n            %\n            [K,success] = Estimator_(0, 'calibrateRotatingCamera', Hs);\n        end\n\n        function focals = estimateFocal(features, pairwise_matches)\n            %ESTIMATEFOCAL  Estimates focal lengths for each given camera\n            %\n            %     focals = cv.Estimator.estimateFocal(features, pairwise_matches)\n            %\n            % ## Input\n            % * __features__ Features of images.\n            % * **pairwise_matches** Matches between all image pairs.\n            %\n            % ## Output\n            % * __focals__ Estimated focal lengths for each camera, vector of\n            %   doubles.\n            %\n            focals = Estimator_(0, 'estimateFocal', features, pairwise_matches);\n        end\n\n        function [f0, f1, f0_ok, f1_ok] = focalsFromHomography(H)\n            %FOCALSFROMHOMOGRAPHY  Tries to estimate focal lengths from the given homography under the assumption that the camera undergoes rotations around its centre only\n            %\n            %     [f0, f1] = cv.Estimator.focalsFromHomography(H)\n            %     [f0, f1, f0_ok, f1_ok] = cv.Estimator.focalsFromHomography(H)\n            %\n            % ## Input\n            % * __H__ Homography, 3x3 double matrix.\n            %\n            % ## Output\n            % * __f0__ Estimated focal length along X axis.\n            % * __f1__ Estimated focal length along Y axis.\n            % * **f0_ok** True, if `f0` was estimated successfully, false\n            %   otherwise.\n            % * **f1_ok** True, if `f1` was estimated successfully, false\n            %   otherwise.\n            %\n            % ## References\n            % > Heung-Yeung Shum and Richard Szeliski. \"Construction of\n            % > of Panoramic Image Mosaics with Global and Local Alignment\".\n            %\n            [f0, f1, f0_ok, f1_ok] = Estimator_(0, 'focalsFromHomography', H);\n        end\n    end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/Estimator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20348808560940665}}
{"text": "% PLOTPROJ - plot projections of one or more ICA components along with \n%              the original data (returns the data plotted)\n%\n% Usage:\n%   >> [projdata] = plotproj(data,weights,compnums);\n%   >> [projdata] = plotproj(data,weights,compnums, ...\n%                                 title,limits,chanlist,channames,colors);\n%\n% Inputs:\n%   data        = single epoch of RUNICA input data (chans,frames) \n%   weights     = unmixing matrix (=weights*sphere)\n%   compnums    = vector of component numbers to project and plot \n%\n% Optional inputs:\n%   title       = 'fairly short plot title' {0 -> 'PLOTPROJ'}\n%   limits      = [xmin xmax ymin ymax]  (x's in msec) \n%                          {0, or both y's 0 -> data limits}\n%   chanlist    = list of data channels to plot {0 -> all}\n%   channames   = channel location file or structure (see READLOCS)\n%   colors      = file of color codes, 3 chars per line  ('.' = space)\n%                          {0 -> default color order (black/white first)}\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 05-01-96 \n%\n% See also: PLOTDATA\n\n% Without color arg, reads filename for PROJCOLORS from icadefs.m\n\n% Copyright (C) 05-01-96 from PLOTDATA Scott Makeig, SCCN/INC/UCSD,\n% scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 05-25-96 added chanlist, nargin tests, rearranged variable order -sm\n% 07-29-96 debugged, added chanlist channames option -sm\n% 10-26-96 added test for column of compnums  -sm\n% 02-18-97 improved usage message -sm\n% 02-19-97 merged versions -sm\n% 03-19-97 changed VAR to diag(COV), use datamean arg instead of frames/baseframes -sm\n% 04-24-97 tested datamean for 1-epoch; replaced COV with mean-squares -sm\n% 05-20-97 read icadefs for PROJCOLORS & MAXPLOTDATACHANS -sm\n% 06-05-97 use arbitrary chanlist as default channames -sm \n% 06-07-97 changed order of args to conform to runica -sm\n% 06-12-97 made sumdata(chanlist in line 159 below -sm\n% 07-23-97 removed datamean from args; let mean distribut4e over components -sm\n% 09-09-97 corrected write out line \" summing \" -sm\n% 10-31-97 removed errcode var -sm\n% 11-05-97 added test for channames when chanlist ~= 1:length(chanlist) -sm & ch\n% 12-19-00 adjusted new ICAPROJ args -sm\n% 01-12-01 removed sphere arg -sm\n% 01-25-02 reformated help & license, added links -ad \n\nfunction [projdata] = plotproj(data,weights,compnums,titl,limits,chanlist,channels,colors);\n\nicadefs       % read default PROJCOLORS & MAXPLOTDATACHANS variables from icadefs.m\nDEFAULT_TITLE = 'plotproj()';\n\n%\n% Substitute for missing arguments\n%\n\nif nargin < 8,\n    colors = 'white1st.col';\nelseif colors==0,\n    colors = 'white1st.col';\nend\n\nif nargin < 7,\n    channels = 0;\nend\nif nargin < 6\n    chanlist = 0;\nend\nif nargin < 5,\n    limits = 0;\nend\nif nargin < 4,\n    titl = 0;\nend\nif titl==0,\n    titl = DEFAULT_TITLE;\nend\n\nif nargin < 3,\n    fprintf('plotproj(): must have at least four arguments.\\n\\n');\n    help plotproj\n    return\nend\n%\n% Test data size\n%\n[chans,framestot] = size(data);\n\nframes = framestot; % assume one epoch\n\n[wr,wc]           = size(weights);\n\nif wc ~= chans\n    fprintf('plotproj(): sizes of weights and data incompatible.\\n\\n');\n    return\nend\n%\n% Substitute for 0 arguments\n%\nif chanlist == 0,\n    chanlist = [1:chans];\nend\nif compnums == 0,\n    compnums = [1:wr];\nend\nif size(compnums,1)>1,        % handle column of compnums !\n    compnums = compnums';\nend\nif length(compnums) > 256,\n    fprintf('plotproj(): cannot plot more than %d channels of data at once.\\n',256);\n    return\nend\n\nif channels ~= 0  % if chan name file given\n   if ~all(chanlist == [1:length(chanlist)])\n     fprintf('plotproj(): Cannot read an arbitrary chanlist of channel names.\\n');\n     return\n   end\nend\nif channels==0,\n    channels = chanlist;\nend\n\nif max(compnums)>wr,\n   fprintf(...\n '\\n    plotproj(): Component index (%d) > number of components (%d).\\n', ...\n                                 max(compnums),wr);\n   return\nend\n\nfprintf('Reconstructing (%d chan, %d frame) data summing %d components.\\n', ...\n                   chans,frames,length(compnums));\n%\n% Compute projected data for single components\n%\nprojdata = data(chanlist,:);\nfprintf('plotproj(): Projecting component(s) ');\nfor s=compnums,            % for each component \n   fprintf('%d ',s);\n   proj = icaproj(data,weights,s);   % let offsets distribute \n   projdata = [projdata proj(chanlist,:)];  % append projected data onto projdata\n   % size(projdata) = [length(chanlist)  framestot*(length(compnums)+1)]\nend\nfprintf('\\n');\n%     \n% Compute percentage of variance accounted for\n%\nsumdata = icaproj(data,weights,compnums);% let offsets distribute \nsigmssq = mean(sum(data(chanlist,:).*data(chanlist,:)));\n   data(chanlist,:) = data(chanlist,:) - sumdata(chanlist,:);\ndifmssq = mean(sum(data(chanlist,:).*data(chanlist,:)));\n\npvaf   = round(100.0*(1.0-difmssq/sigmssq)); % percent variance accounted for\n\nrtitl = ['(p.v.a.f. ' int2str(pvaf) '%)'];\n%\n% Make the plot\n%\nplotdata(projdata,length(data),limits,titl,channels,colors,rtitl);\n                                                % make the plot\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/plotproj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3775406547908327, "lm_q1q2_score": 0.20348807246810388}}
{"text": "function [fitness,convar,xtxi,models] = testlist(stimLists,GA,HRF,varargin)\n% [fitness,convar,xtxi,models] = testlist(stimLists,GA,HRF,[opt args])\n%\n% stimLists can have multiple lists (columns)\n%\n% 9/12/01 Tor Wager\n\nclockStart = cputime;\t\t\t  \t% keeps track of starting time\n\nfor i = 1:length(varargin)\n    if isstr(varargin{i})\n        switch varargin{i}\n        case 'rest', restMatrix = varargin{i+1};\n        case 'svi', svi = varargin{i+1};\n        case 'S', S = varargin{i+1};\n        end\n    end\nend\n\n% ----------------------------------------------------------------\n% * vars setup\n% ---------------------------------------------------------------- \t\n\ntrans2switch = GA.trans2switch;\ntrans2block = GA.trans2block;\nmaxOrder = GA.maxOrder;\nconditions = GA.conditions;\nfreqConditions = GA.freqConditions;\ncbalColinPowerWeights = GA.cbalColinPowerWeights;\ncontrastweights = GA.contrastweights;\nNumStimthresh = GA.NumStimthresh;\nmaxCbalDevthresh = GA.maxCbalDevthresh;\nmaxFreqDevthresh = GA.maxFreqDevthresh;\nISI = GA.ISI;\nTR = GA.TR;\nnonlinthreshold = GA.nonlinthreshold;\nscanLength = GA.scanLength;\nrestevery = GA.restevery;\nrestlength = GA.restlength;\nHPlength = GA.HPlength;\nxc = GA.xc;\ncontrasts = GA.contrasts;\n\n% ----------------------------------------------------------------\n% * contrast setup\n% ----------------------------------------------------------------\n  \n% work out whether to use contrasts.\nif isempty(contrasts)\n   nconds = sum(conditions > 0);\n   %contrasts = zeros(nconds,nconds);\n    %for i = 1:nconds\n    %    contrasts(i,i) = 1;\n    %end\n    %disp('  ...no contrasts entered; using original model')\n    docontrasts = 0;\n else \n    %disp(' ...contrasts entered')   \n    docontrasts = 1;\n    %contrasts\nend\n    \n%if ~(size(contrasts,1) == sum(conditions > 0)), \n    %disp('\t...fyi: Num contrasts does not equal num conditions')\n%end\n\n\n% ----------------------------------------------------------------\n% * setup freqConditions and rests\n% ---------------------------------------------------------------- \n\n% normalize freqConditions\nif ~sum(freqConditions) == 1,\n\tfreqConditions(1:end-1) = (1 - freqConditions(end)) / (size(freqConditions,2)-1);\n\tdisp(['\t...freqConditions does not sum to 1: normalizing to ' num2str(freqConditions)])\nend\n\n% flag for rest length.\n\tif ~isempty(restevery) &  ~isempty(restlength)\n\t\tdisp(['\t...Using rests of length ' num2str(restlength) ' and resting every ' num2str(restevery)])\n\t\tdorests = 1;\n\telse disp('\t...No rests specified.'),dorests = 0;\n\tend\n\nif ~(mod(scanLength / ISI,1) == 0),disp('Warning: Scan length in s is not an even multiple of ISI!'),end\n\n\n% ----------------------------------------------------------------\n% * initial computation of list lengths and output\n% ----------------------------------------------------------------  \n\nnumStim = ceil(scanLength / (ISI));\nif dorests,\n\tnumRestStim = (ceil(numStim/(mean(restevery)+restlength)) - 1) * restlength;\nelse\n\tnumRestStim = 0;\nend\nnumStimEachCond = ceil((numStim-numRestStim) * freqConditions);\t\t\t            % row vector of stim in each cond\nnumsamps = ceil(numStim*ISI/TR);\n\n\n% ----------------------------------------------------------------\n% * get smoothing matrix and autocorrelation matrix\n% ----------------------------------------------------------------\nif isempty(HPlength),HPlength = 'none';,end\nif ~isfield(GA,'LPsmooth'),GA.LPsmooth = 1;,end\n\ndofilter = 1;\nif strcmp(HPlength,'none') & ~GA.LPsmooth\n    dofilter = 0;\nend\n\n%disp(['\t...setting smoothing, hrf, and autocorrelation matrices, HPlength = ' num2str(HPlength) ', Smoothing = ' num2str(GA.LPsmooth)])\n\nif ~(exist('S') == 1)\n%use spm_filter\nif strcmp(HPlength,'none') & GA.LPsmooth\t\t\t\t\t\t\t\t\t% LP only\n\t%disp('\t\t...LP only')\n\t[S,KL] = use_spm_filter(TR,numsamps,'hrf','none',[]);\nelseif GA.LPsmooth\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t% HP and LP\n\t[S,KL,KH] = use_spm_filter(TR,numsamps,'hrf','specify',HPlength);\n\t%disp('\t\t...HP and LP')\nelseif strcmp(HPlength,'none') & ~GA.LPsmooth\t\t\t\t\t\t\t\t% neither\n\t%disp('\t\t...no filtering')\n\tS = eye(numsamps);\n\tdofilter = 0;\nelse [S,KL,KH] = use_spm_filter(TR,numsamps,'none','specify',HPlength);\t\t% HP only\n\t%disp('\t\tHP only')\nend\n\nend % if ~exist S\n\nif ~(exist('svi') == 1)\n    \nif isempty(xc),Vi = eye(numsamps);,disp('Using white noise autocorrelation')\nelse Vi = getv('make',xc,numsamps);\nend\n\nsvi = S * Vi * S';\n\nend % if exist svi\n\nclear KL, clear KH, clear Vi, clear myscannerV\n\n\n\n% ----------------------------------------------------------------\n% * criterion measures setup\n% ---------------------------------------------------------------- \nif ~isempty(NumStimthresh) | ~isempty(maxCbalDevthresh) | ~isempty(maxFreqDevthresh)\n\tdocriterion = 1;\n\tif isempty(NumStimthresh),NumStimthresh = 10000;,end\n \tif isempty(maxCbalDevthresh),maxCbalDevthresh = 10000;,end\n\tif isempty(maxFreqDevthresh),maxFreqDevthresh = 10000;,end\nelse\n\tdocriterion = 0;\nend\n\nmaxrestthresh = 2;\t\t\t\t\t% max number of rests in a row.\n\n% ----------------------------------------------------------------\n% * saturation setup\n% ----------------------------------------------------------------\nif isempty(nonlinthreshold) | strcmp(nonlinthreshold,'none'),dosaturation = 0;,nonlinthreshold = 'none';,else dosaturation = 1;,end\n\n\n% add intercept\n% ------------------------------\nif docontrasts, contrasts(:,end+1) = 0;, end\n\n\n\n\n\n% ----------------------------------------------------------------\n% * do it.\n% ---------------------------------------------------------------- \n\nfor z = 1:size(stimLists,2)\n\n\tstimList = stimLists(:,z);\n\n% The Switch Hack: transform list of stimuli into list of switches/no switches for each stimtype (R or L)\n      if trans2switch, stimList = transform2switches(stimList);,end\n      if trans2block,\n\t     restMatrix = varargin{1};\n\t     restlength = GA.restlength; \n\n             restList = restMatrix(:,z);\n             stimList = transform2block(stimList,restList,restlength);\n      end\n\n      \n      % ===== counterbalancing ============================================  \n      %if (cbalColinPowerWeights(1) > 0)    removed 3/30 to implement criterion rather than weights.\n   \t\t[cBal,dummy,maxDev] = getCounterBal(stimList, maxOrder,conditions,freqConditions);\n\t\t % ...if optimizing this measure, add it to fitness scores.\n         if (cbalColinPowerWeights(1) > 0),fitnessMatrix(1,z) = cBal;,end\n\t  %end\n   \n\t  \n\t  % ===== frequency discrepancy ========================================\n\t  % calculate max discrepancy between actual frequencies and requested frequencies \n\t  %if size(cbalColinPowerWeights,2) > 3                  \n      \t%if (cbalColinPowerWeights(4) > 0)    \t \n            for i = 1:size(freqConditions,2) \n         \t\tfreqMat(i) = sum(stimList == conditions(i)) / size(stimList,1);\n      \t    end\n            freqMat = freqMat ./ sum(freqMat);   % adjust for probe ''0''s\n\t\t\tmaxFreqDev = max(abs(freqConditions - freqMat));\n\t\t\t% ...if optimizing this measure, add it to fitness scores.\n      \t\tif (cbalColinPowerWeights(4) > 0), dummy = 1 - maxFreqDev;,end \n\t\t%end\n\t  %end\n\t  \n\t  \n\t  % criterion measures\n\t  % ====================================================================\n\t    go = 1;\n\t    if docriterion\n\t  \t[maxNumStim,maxrest] = getMaxInARow(stimList,dojitter); \n\t  \tif maxNumStim > NumStimthresh | maxrest > maxrestthresh | maxDev > maxCbalDevthresh | maxFreqDev > maxFreqDevthresh\n\t\t  go = 0;\n\t\t  error('Criteria not met.')\n          \tend\n\t   end\n\t\n\t \n\t\t% =====power calculation =============================================\n    if (cbalColinPowerWeights(2) > 0 | cbalColinPowerWeights(3) > 0) & go   % build predictor set of vectors and convolve with HRF\n        model = sampleInSeconds(stimList,ISI);\n        model = getPredictors(model,HRF);\n        model = resample(model,1,TR*10);\n\tif dosaturation,model = modelSaturation(model,nonlinthreshold);,end\t\t\t\t\t\t% saturation (nonlinear responses)\n        if size(model,1) > numsamps, model = model(1:numsamps,:);,end\n\n\t% add intercept\n\t% ------------------------------\n\tmodel(:,end+1) = 1;\n   \n\t\n\n        if dofilter\n\t\ttry\n            model = S * model;                                                  % temporal smoothing and HP filter\n        catch\n            whos model\n            whos S\n            error('model smoothing: wRoNg Sizes!')\n        end\n\tend\n        xtxitx = pinv(model);                                       \t\t% inv(X'S'SX)*(SX)'; pseudoinv of (S*X)\n\n\t\n\tif docontrasts,\n\t\ttry\n            con1 =  model * contrasts(1,:)';\n        catch\n            whos model\n            whos contrasts\n            error('contrast multiplication: wRoNg Sizes!')\n        end\n\tend\n\t%figure; subplot(2,1,1)\n\t%plot(model(:,1))\n\t%title(['Model ' num2str(z) ' Predictor 1'])\n\t%subplot(2,1,2)\n\t%plot(con1)\n\t%title(['Model ' num2str(z) ' Contrast 1'])\n\t%drawnow; pause(5)\n\n\txtxi{z} = inv(model'*model);\n\tmodels{z} = model;\n\n        if docontrasts\t\t\t\t\t\t\t\t\t\t\t% compute the variance of the contrasts\n           try\n              fitness(z) = 1./(contrastweights * diag(contrasts*xtxitx*svi*xtxitx'*contrasts'));\n\t      convar(z) = (contrasts(1,:)*xtxitx*svi*xtxitx'*contrasts(1,:)');\n              % it's 1/ because we want to minimize the variance, but we maximize fitnessMatrix value.\n           catch\n             disp('using contrasts: wrong sizes!!!')\n             contrasts\t\n             whos xtxitx\n             whos svi\n             diag(xtxitx*svi*xtxitx')\n             error('Exiting...')\n           end\n           \n        else\t\n           try\n               fitness(z) = 1./(contrastweights * diag(xtxitx*svi*xtxitx')); % variance of chosen regressors.\n\t\tmyconvar = diag(xtxitx*svi*xtxitx');\n\t       convar(z) = myconvar(1);\n           catch\n               disp(['no contrasts version: wrong sizes!!!'])\n               whos contrastweights\n               whos xtxitx\n               whos svi\n               diag(xtxitx*svi*xtxitx')\n               error('Exiting...')\n           end\n\tend\n    end\n\nend % loop through designs\n\n%figure;for i = 1:length(models),subplot(1,length(models),i),imagesc(models{i}),\n%\ttitle(['Model ' num2str(i) ' v = ' num2str(convar(i)) ' f = ' num2str(fitness(i))])\n%end\n\ndisp(['testlist done: ' num2str(cputime-clockStart) ' s']) \n\n\nreturn\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/other_functions/testlist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20341058314132116}}
{"text": "%% Sample execution for Baseline on CFNet-conv3\n% hyper-parameters reported in Supp.material for CVPR'17, Table 2 for arXiv version\ntracker_par.join.method = 'corrfilt';\ntracker_par.net = 'baseline-conv3-on-cfnet-conv3_e100.mat';\ntracker_par.net_gray = 'baseline-conv3-on-cfnet-conv3_gray_e70.mat';\ntracker_par.scaleStep = 1.034;\ntracker_par.scalePenalty = 0.9820;\ntracker_par.scaleLR = 0.66;\ntracker_par.wInfluence = 0.27;\ntracker_par.zLR = 0.008;\n\n[~,~,dist,overlap,~,~,~,~] = run_tracker_evaluation('all', tracker_par);", "meta": {"author": "bertinetto", "repo": "cfnet", "sha": "971e7922b7f0f9140e0d995b598e8d97dece277c", "save_path": "github-repos/MATLAB/bertinetto-cfnet", "path": "github-repos/MATLAB/bertinetto-cfnet/cfnet-971e7922b7f0f9140e0d995b598e8d97dece277c/src/tracking/run_cfnet3_evaluation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2033948967428397}}
{"text": "function varargout = segGet(seg, property, varargin);\n% Get properties of a segmentation.\n% \n% [vals] = segGet(seg, property, [optional arguments]);\n%\n% Some properties include:\n%   'classPath':    path to the .class file describing the white/gray\n%                   classification.\n%   'grayPath':     path to the .gray graph.\n%   'curMeshNum':   # of the currently-selected mesh (0=no meshes loaded).\n%   'mesh',[M]:     the M-th loaded mesh <defaults to current mesh if M\n%                   omitted.>\n%\n%   'nodes':        gray nodes. The rows of the 8xN nodes matrix represent:\n%                   (1-3) s/i, a/p, l/r coords (in I|P|R space -- see\n%                   mrFormatDescription) of each gray node.\n%                   (4)\n%                   (5)\n%                   (6) gray level/layer, counting from white matter up.\n%                   (7)\n%                   (8)\n%                   The number N of nodes will represent all the gray \n%                   nodes for this segmentation, regardless of the \n%                   current mapping.\n%   'edges':        gray edges.\n%   [nodes edges] = segGet('gray') returns both gray nodes and edges \n%                   (preventing redundant loading of the gray graph).\n%\n%   'meshCoords',[M],[mmPerPix]:   \n%                   3xN coordinates (in IPR space) of each node \n%                   represented by the M-th mesh, using the current\n%                   mapping. The current mapping is determined by\n%                   mrmPreferences. The number N of columns will\n%                   correspond to the columns of mesh{M}.initVertices,\n%                   as well as the mesh colors. \n%                   <if M omitted, uses selected mesh; if mmPerPix\n%                   omitted, tries to read from segementation's anat file,\n%                   or else assumes 1x1x1.>\n%\n%\t'nearestNode',[coord],[tolerance=5mm]:\n%\t\t\t\t\tReturn the index of the nearest gray node to a given\n%\t\t\t\t\t3D coordinate. This simply finds the node with the\n%\t\t\t\t\tsmallest euclidean distance from the input coordinate. \n%\t\t\t\t\tThe input coord should be a 1x3 or 3x1 vector, and should\n%\t\t\t\t\tbe in the same format as the gray coords. (This is in order\n%\t\t\t\t\tThe optional tolerance argument specifies how large a\n%\t\t\t\t\tdistance should be accepted for a nearest node; if no\n%\t\t\t\t\tnode is less than this amount, the nearestNode will\n%\t\t\t\t\treturn empty. By default, the tolerance is 5mm.\n%\n% ras 04/06\nif nargin<2, help(mfilename); error('Not enough input args.'); end\n\nswitch lower(property)\n    case {'classpath' 'classfile'}\n        if isstr(seg.class),    varargout{1} = seg.class;\n        else,                   varargout{1} = seg.class.filename;\n        end\n        \n    case {'classification' 'classdata' 'voxels' 'wm' 'class'}\n        if isstr(seg.class),    varargout{1} = readClassFile(seg.class);\n        else,                   varargout{1} = seg.class;\n        end\n        \n    case {'graypath' 'graygraph' 'grayfile'}\n        if isstr(seg.gray),     varargout{1} = seg.gray;\n        else,                   varargout{1} = seg.gray.path;\n        end\n        \n    case {'curmeshnum' 'curmeshn' 'meshnum' 'selectedmeshnum'}\n        varargout{1} = seg.settings.mesh;\n        \n    case {'mesh' 'curmesh' 'selectedmesh'}\n        if length(varargin)==0, M = segGet(seg, 'curMeshNum'); \n        else, M = varargin{1};\n        end\n        \n        if M==0 | isempty(seg.mesh), \n            varargout{1} = [];\n        else\n            varargout{1} = seg.mesh{M};\n        end\n        \n    case {'nodes' 'graynodes'}\n        if isempty(seg.nodes),  varargout{1} = readGrayGraph(seg.gray);\n        else,                   varargout{1} = seg.nodes;\n        end\n        \n    case {'edges' 'grayedges'}\n        if isempty(seg.edges),  [x varargout{1}] = readGrayGraph(seg.gray);\n        else,                   varargout{1} = seg.edges;\n        end\n        \n    case {'gray'}\n        if isempty(seg.nodes) | isempty(seg.edges)\n            [varargout{1} varargout{2}] = readGrayGraph(seg.gray);\n        else\n            varargout{1} = seg.nodes;\n            varargout{2} = seg.edges;\n        end\n        \n    case {'graycoords'}\n        nodes = segGet(seg, 'nodes'); \n        varargout{1} = nodes([2 1 3],:);\n        \n    case {'meshcoords' 'coords'}\n        varargin{3} = []; % fast way to init. args 1 & 2 if unspecified\n        M = varargin{1};  mmPerPix = varargin{2};\n        if isempty(M), M = segGet(seg, 'curMeshNum'); end\n        if isempty(mmPerPix)\n            try\n                anat = mrLoad(seg.anatFile);\n                mmPerPix = anat.voxelSize(1:3);\n            catch\n                disp(['Couldn''t read segmentation anatomy. Guessing ' ...\n                      'mmPerPix as [1 1 1]...'])\n                 mmPerPix = [1 1 1];\n            end\n        end\n        \n        % get mapping from mesh vertices to gray nodes\n        [nodes edges] = segGet(seg, 'gray');\n        v2g = mrmMapVerticesToGray(seg.mesh{M}.initVertices, nodes, ...\n                                   mmPerPix, edges);\n                               \n        % grab appropriate coords from nodes\n        varargout{1} = nodes(1:3,v2g);\n\t\t\n\tcase {'nearestnode'}\n        varargin{3} = []; % fast way to init. args 1 & 2 if unspecified\n\t\tpt = varargin{1}(:); tolerance = varargin{2};\n\t\tif isempty(pt), error('Need an input coordinate.'); end\n\t\tif isempty(tolerance), tolerance = 5; end\n\t\t\n\t\t% compute Euclidean distance of each node from the coord\n\t\tC = segGet(seg, 'GrayCoords');\n\t\tdist = sqrt( [C(1,:) - pt(1)] .^ 2 + ...\n\t\t\t\t\t [C(2,:) - pt(2)] .^ 2 + ...\n\t\t\t\t\t [C(3,:) - pt(3)] .^ 2 ); \n\t\tif min(dist) > tolerance\n\t\t\twarning(sprintf('[%s]: no node found within tolerance [%i mm]', ...\n\t\t\t\t\t\t\t mfilename, tolerance));\n\t\t\tvarargout{1} = [];\n\t\telse\n\t\t\tI = find(dist==min(dist));\n\t\t\tvarargout{1} = I(1);\n\t\tend\t\t\t\t\t\t\n\t\t\t \n        \n    otherwise, error('Unknown property.')\n        \nend\n\nreturn\n\n         \n            ", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Segmentation/segGet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2033598278182622}}
{"text": "function test_bug2647\n% DEPENDENCY ft_freqstatistics\n\n% WALLTIME 00:10:00\n% MEM 2gb\n\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug2647.mat'));\nstat = ft_freqstatistics(cfg,data,BL);\n%assert(all(~isfinite(stat.stat(:))));\nassert(~all(~isfinite(stat.stat(:)))); % this should now work after making ft_statfun_actvsblT more robust for NaNs\n\ncfg.design = cfg.design(:,[1:4 6:9]);\ndata.powspctrm = data.powspctrm(2:end,:,:,:);\nBL.powspctrm   = BL.powspctrm(2:end,:,:,:);\nstat = ft_freqstatistics(cfg,data,BL);\nassert(~all(~isfinite(stat.stat(:))));\n\n% conclusion: the first rpt was all NaN, causing stat.stat to be all NaN,\n% no meaningful inference possible\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2647.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20335982781826212}}
{"text": "%  Copyright (C) 2004 Yokogawa Electric Corporation, All Rights Reserved.\n% \n%  usage:\n%    calib_info = GetMeg160CalibInfoM( fid )\n% \n%  arguments:\n%    fid             : file ID\n% \n%  return values:\n%    calib_info      : (m x 3) matrix of calibration information. (m: channel_count)\n%                        detail of n: (If the sensor doesn't have following item, the item's entry will be 'Inf'.)\n%                            1   : channel number in Meg160(zero start)\n%                            2   : gain [Tesla/V]\n%                            3   : offset voltage [V]\n%  \n%  confirmation of revision:\n%   GetMeg160CalibInfoM( Inf ) will show and return revision of this function.\n%\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/yokogawa/GetMeg160CalibInfoM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20335982180501444}}
{"text": "function [estimate] = ft_inverse_music(sourcemodel, sens, headmodel, dat, varargin)\n\n% FT_INVERSE_MUSIC source localization using MUltiple SIgnal Classification.\n% This is a signal subspace method, which covers the techniques for\n% multiple source localization by using the eigen-structure of the\n% measured data matrix.\n%\n% Use as\n%   [estimate] = ft_inverse_music(sourcemodel, sens, headmodel, dat, ...)\n% where\n%   sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL\n%   sens        is the gradiometer or electrode definition, see FT_DATATYPE_SENS\n%   headmodel   is the volume conductor definition, see FT_PREPARE_HEADMODEL\n%   dat         is the data matrix with the ERP or ERF\n% and\n%   estimate    contains the estimated source parameters\n%\n% Additional input arguments should be specified as key-value pairs and can include\n%   'cov'              = data covariance matrix\n%   'numcomponent'     = integer number\n%   'feedback'         = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text')\n%\n% These options influence the forward computation of the leadfield\n%   'reducerank'      = 'no' or number  (default = 3 for EEG, 2 for MEG)\n%   'backproject'     = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes')\n%   'normalize'       = 'no', 'yes' or 'column' (default = 'no')\n%   'normalizeparam'  = parameter for depth normalization (default = 0.5)\n%   'weight'          = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1)\n%\n% This implements\n% - J.C. Mosher, P.S. Lewis and R.M. Leahy, \"Multiple dipole modeling and\n%   localization from spatiotemporal MEG data\", IEEE Trans. Biomed. Eng., \n%   pp 541-557, June, 1992.\n%\n% See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL\n\n% Copyright (C) 2004-2008, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif mod(nargin-4,2)\n  % the first 4 arguments are fixed, the other arguments should come in pairs\n  ft_error('invalid number of optional arguments');\nend\n\n% get the optional input arguments, or use defaults\ncov            = ft_getopt(varargin, 'cov');\nnumcomponent   = ft_getopt(varargin, 'numcomponent');     % this is required, see below\nfeedback       = ft_getopt(varargin, 'feedback', 'text');\n\n% construct the low-level options for the leadfield computation as key-value pairs, these are passed to FT_COMPUTE_LEADFIELD\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     ft_getopt(varargin, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    ft_getopt(varargin, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      ft_getopt(varargin, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(varargin, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         ft_getopt(varargin, 'weight'));\n\nif isempty(numcomponent)\n  ft_error('you must specify the number of signal components');\nend\n\n% flags to avoid calling isfield repeatedly in the loop over grid positions (saves a lot of time)\nhasmom        = isfield(sourcemodel, 'mom');\nhasleadfield  = isfield(sourcemodel, 'leadfield');\nhasfilter     = false; % not used here\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% find the dipole positions that are inside/outside the brain\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(sourcemodel, 'inside')\n  if hasfilter\n    sourcemodel.inside = ~cellfun(@isempty, sourcemodel.filter);\n  elseif hasleadfield\n    sourcemodel.inside = ~cellfun(@isempty, sourcemodel.leadfield);\n  else\n    sourcemodel.inside = ft_inside_headmodel(sourcemodel.pos, headmodel);\n  end\nend\n\n% convert to logical representation\nsourcemodel = fixinside(sourcemodel);\n\n% keep the original details on inside and outside positions\noriginside = sourcemodel.inside;\norigpos    = sourcemodel.pos;\n\n% select only the dipole positions inside the brain for scanning\nsourcemodel.pos    = sourcemodel.pos(originside,:);\nsourcemodel.inside = true(size(sourcemodel.pos,1),1);\n\nif hasmom\n  sourcemodel.mom = sourcemodel.mom(:,originside);\nend\n\nif hasleadfield\n  ft_info('using precomputed leadfields\\n');\n  sourcemodel.leadfield = sourcemodel.leadfield(originside);\nelse\n  ft_info('computing forward model on the fly\\n');\nend\n\nif ~isempty(cov)\n  % compute signal and noise subspace from covariance matrix\n  [u, s, v] = svd(cov);\nelse\n  % compute signal and noise subspace from average data matrix\n  [u, s, v] = svd(dat);\nend\n% select the noise subspace, c.f. equation 25\nus = u(:,(numcomponent+1):end);\nps = us * us';\n\n% allocate space to hold the result\nestimate = [];\nestimate.jr = nan(size(sourcemodel.pos,1),1);\n\nft_progress('init', feedback, 'scanning grid');\nfor i=1:size(sourcemodel.pos,1)\n  ft_progress(i/size(sourcemodel.pos,1), 'scanning grid %d/%d\\n', i, size(sourcemodel.pos,1));\n  \n  if hasleadfield && hasmom && size(sourcemodel.mom, 1)==size(sourcemodel.leadfield{i}, 2)\n    % reuse the leadfield that was previously computed and project\n    lf = sourcemodel.leadfield{i} * sourcemodel.mom(:,i);\n  elseif  hasleadfield &&  hasmom\n    % reuse the leadfield that was previously computed but don't project\n    lf = sourcemodel.leadfield{i};\n  elseif  hasleadfield && ~hasmom\n    % reuse the leadfield that was previously computed\n    lf = sourcemodel.leadfield{i};\n  elseif ~hasleadfield &&  hasmom\n    % compute the leadfield for a fixed dipole orientation\n    lf = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:}) * sourcemodel.mom(:,i);\n  else\n    % compute the leadfield\n    lf = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:});\n  end\n  \n  % compute the music metric, c.f. equation 26\n  estimate.jr(i) = (norm(ps * lf)./norm(lf)).^2;\n  % as described in the Mosher 1992 paper on page 550, \"...the general approach is to\n  % evaluare Jr(i) over a fine three-dimensional grid, plot its inverse,\n  % and look for p sharp spikes...\"\n  \nend % for each dipole position\nft_progress('close');\n\n% reassign the estimated values over the inside and outside grid positions\nestimate.inside   = originside;\nestimate.pos      = origpos;\nif isfield(estimate, 'jr')\n  estimate.jr( originside) = estimate.jr;\n  estimate.jr(~originside) = nan;\nend\nif isfield(estimate, 'leadfield')\n  estimate.leadfield( originside) = estimate.leadfield;\n  estimate.leadfield(~originside) = {[]};\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/inverse/ft_inverse_music.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.20335464308581197}}
{"text": "classdef Source < handle & matlab.mixin.Heterogeneous\n\t% Source is a superclass for all electric current sources J.\n\t\n\tproperties (SetAccess = immutable)\n\t\tlgrid  % {x_array, y_array, z_array}: locations (intercepts with normal axis) of grid planes of grid type \"this.gt\"\n\t\tlaltgrid  % {x_array, y_array, z_array}: locations (intercepts with normal axis) of grid planes of grid type \"alter(this.gt)\"\n\t\tshape  % shape of source; used to draw source\n\t\tforceprim  % true or false: flag to control the behavior of get.l()s\n\tend\n\t\n\tproperties (SetAccess = private)\n\t\tgt  % GT.prim or GT.dual: type of grid line along which dipole sources of this source are defined\n\tend\n\n\tproperties (Dependent, SetAccess = immutable)\n\t\tl\n\tend\n\n\tmethods (Abstract = true)\n\t\t[index_cell, Jw_patch] = generate_kernel(this, w_axis, grid3d)\n\tend\n\t\n\tmethods\n\t\tfunction this = Source(lgrid_cell, laltgrid_cell, shape, forceprim)\n\t\t\tchkarg(istypesizeof(lgrid_cell, 'realcell', [1 Axis.count], [1 0]), ...\n\t\t\t\t'\"lgrid_cell\" should be length-%d row cell array whose each element is row vector with real elements.', Axis.count);\n\t\t\tchkarg(istypesizeof(laltgrid_cell, 'realcell', [1 Axis.count], [1 0]), ...\n\t\t\t\t'\"laltgrid_cell\" should be length-%d row cell array whose each element is row vector with real elements.', Axis.count);\n\t\t\tchkarg(istypesizeof(shape, 'Shape'), '\"shape\" should be instance of Shape.');\n\t\t\t\n\t\t\tif nargin < 4  % no forceprim\n\t\t\t\tforceprim = false;\n\t\t\tend\n\t\t\tchkarg(istypesizeof(forceprim, 'logical'), '\"forceprim\" should be logical.');\n\t\t\t\n\t\t\tthis.lgrid = lgrid_cell;\n\t\t\tthis.laltgrid = laltgrid_cell;\n\t\t\tthis.shape = shape;\n\t\t\tthis.gt = GT.empty();\n\t\t\tthis.forceprim = forceprim;\n\t\tend\n\t\t\n\t\tfunction set_gridtype(this, gt)\n\t\t\t% If this is SRCJ and E-field grid is primary, then gt = GT.prim.\n\t\t\t% If this is SRCJ and E-field grid is dual, then gt = GT.dual.\n\t\t\t% If this is SRCM and E-field grid is primary, then gt = GT.dual.\n\t\t\t% If this is SRCM and E-field grid is dual, then gt = GT.prim.\n\t\t\tchkarg(istypesizeof(gt, 'GT'), '\"gt\" should be instance of GT.');\n\t\t\tthis.gt = gt;\n\t\tend\n\t\t\n\t\tfunction l = get.l(this)\n\t\t\tl = cell(Axis.count, GT.count);\n\t\t\tif this.forceprim\n\t\t\t\tl(:, GT.prim) = this.lgrid.';\n\t\t\t\tl(:, GT.dual) = this.laltgrid.';\n\t\t\telse\n\t\t\t\tl(:, this.gt) = this.lgrid.';\n\t\t\t\tl(:, alter(this.gt)) = this.laltgrid.';\n\t\t\tend\n\t\tend\n\t\t\n\t\tfunction [index_cell, JMw_patch] = generate(this, w_axis, grid3d)\n\t\t\tchkarg(istypesizeof(w_axis, 'Axis'), '\"w_axis\" should be instance of Axis.');\n\t\t\tchkarg(istypesizeof(grid3d, 'Grid3d'), '\"grid3d\" should be instance of Grid3d.');\n\t\t\t\n\t\t\ttry\n\t\t\t\t[index_cell, JMw_patch] = this.generate_kernel(w_axis, grid3d);  % Cw_patch: current source\n\t\t\tcatch err\n\t\t\t\texception = MException('Maxwell:srcAssign', 'Source assignment failed.');\n\t\t\t\tthrow(addCause(exception, err));\n\t\t\tend\n\t\tend\n\tend\nend\n\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/source/Source.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.203263189222306}}
{"text": "% The COBRAToolbox: testloadBiGGModel.m\n%\n% Purpose:\n%     - reads models from BiGG and the previously downloaded version in\n%       the models directory and compares them.\n%     - tests one model for equivalence wrt FBA results.\n%\n% Authors:\n%     - Thomas Pfau\n%\n\nglobal CBTDIR\nglobal CBT_MISSING_REQUIREMENTS_ERROR_ID\n\n%Check the requirements (a LP solver is necessary)\nsolverPkgs = prepareTest('needsLP',true,'requireOneSolverOf',{'gurobi','ibm_cplex','glpk','mosek','quadMinos'},'needsWebAddress','http://bigg.ucsd.edu/api/v2/models');\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testLoadBiGGModel.m'));\ncd(fileDir);\n\n% initialize the test\ncd([CBTDIR, filesep, 'test', filesep, 'models']);\n\n% Models: FileName of local file, model ID and type for BiGG, along with\n% FBA Min and Max value.\nmodelArr = {'iIT341.xml','iIT341','sbml','BiGGSBML',0,0.692812693473487;...\n    'iJO1366.mat','iJO1366','mat','BiGG',NaN,NaN};\n\n% set the tolerance\ntol = 1e-6;\n\ntested = false;\n\n%loop through the models\nfor i = 1:size(modelArr,1)\n    %reading the models takes quite a bit of time, so only do it once for\n    %all solvers.\n    % output a line before launching the test for model i\n    fprintf('   Testing %s ...\\n', modelArr{i,2});\n    \n    % load the model (actually supply the full filename of the path\n    % where the model is found)\n    model1 = getDistributedModel(modelArr{i,1});\n    try\n        model2 = loadBiGGModel(modelArr{i,2},modelArr{i,3});\n        tested = true;\n    catch ME\n        if strcmp(ME.identifier,'MATLAB:webservices:Timeout')\n            %Could not load the model, skip.\n            continue;\n        end\n    end\n        \n    model3 = readCbModel(modelArr{i,2},'fileType',modelArr{i,4});\n    \n    %Check that the direct load is the same\n    if 1\n        printLevel=1;\n        [isSame, nDiff, commonFields] = isSameCobraModel(model1, model2, printLevel);\n        assert(isSame)\n    else\n        assert(isSameCobraModel(model1,model2));\n    end\n    \n    \n    %Check that the model loaded through readCbModel is the same.\n    \n    if 1\n        printLevel=1;\n        [isSame, nDiff, commonFields] = isSameCobraModel(model1, model3, printLevel);\n        assert(isSame)\n    else\n        assert(isSameCobraModel(model1,model3));\n    end\n\n    \n    if ~isnan(modelArr{i,5})\n        for k = 1:length(solverPkgs.LP)\n            fprintf(' -- Running testLoadBiGGModel using the solver interface: %s ... ', solverPkgs.LP{k});\n            changeCobraSolver(solverPkgs.LP{k}, 'LP', 0);\n            \n            fprintf('   Testing loaded model ... \\n');\n            \n            \n            % solve the maximisation problem\n            FBA = optimizeCbModel(model2, 'max');\n            \n            % test the maximisation solution\n            assert(FBA.stat == 1);\n            assert(abs(FBA.f - modelArr{i,6}) < tol);\n            assert(norm(model2.S * FBA.x) < tol);\n            \n            % solve the minimisation problem\n            FBA = optimizeCbModel(model2, 'min');\n            \n            % test the minimisation solution\n            assert(FBA.stat == 1);\n            assert(abs(FBA.f - modelArr{i,5}) < tol);\n            assert(norm(model2.S * FBA.x) < tol);\n            \n            % print a line for success of loop i\n            fprintf(' Done.\\n');\n        end\n    end\nend\n%This should only ever happen, if the BiGG db could not be contacted.\nif ~tested\n    error(CBT_MISSING_REQUIREMENTS_ERROR_ID,'Could not connect to BiGG Database');\nend\n% change the directory\ncd(currentDir)\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/base/testIO/testLoadBiGGModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.20326317387423093}}
{"text": "function model = fgplvmExpandParam(model, params)\n\n% FGPLVMEXPANDPARAM Expand a parameter vector into a GP-LVM model.\n% FORMAT\n% DESC takes an FGPLVM structure and a vector of parameters, and\n% fills the structure with the given parameters. Also performs any\n% necessary precomputation for likelihood and gradient\n% computations, so can be computationally intensive to call.\n% ARG model : the FGPLVM structure to put the parameters in.\n% ARG params : parameter vector containing the parameters to put in\n% the FGPLVM structure.\n% \n% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2009\n%\n% MODIFICATION : Carl Henrik Ek, 2009\n% \n% SEEALSO : fgplvmCreate, fgplvmExtractParam, modelExpandParam\n\n% FGPLVM\n\n\nstartVal = 1;\nif isfield(model, 'back') & ~isempty(model.back)\n  % update modelParameters\n  endVal = model.back.numParams;\n  model.back = modelExpandParam(model.back, params(startVal:endVal));\n\n  % update latent locations\n  tmp = modelOut(model.back,model.y);\n  tmp_dim = 1;\n  for(i = 1:1:model.q)\n    if(length(find(model.back.indexOut==i))~=0)\n      model.X(:,model.back.indexOut(tmp_dim)) = tmp(:,tmp_dim);\n      tmp_dim = tmp_dim + 1;\n    else\n      startVal = endVal + 1;\n      endVal = endVal + model.N;\n      model.X(:,i) = reshape(params(startVal:endVal),model.N,1);\n    end\n  end\n  clear tmp tmp_dim;\nelse\n  endVal = model.N*model.q;\n  model.X = reshape(params(startVal:endVal), model.N, model.q);\nend\nstartVal = endVal+1;\nendVal = endVal + model.kern.nParams;\n\nswitch model.approx\n case 'ftc'\n  endVal = endVal;\n case {'dtc', 'dtcvar', 'fitc', 'pitc'}\n  if model.fixInducing\n    % account for beta attached to the end.\n    endVal = endVal + 1; \n    % X_u values are taken from X values.\n    model.X_u = model.X(model.inducingIndices, :);\n  else\n    % Parameters include inducing variables and beta.\n    endVal = endVal + model.q*model.k + 1;\n  end\n\n otherwise\n  error('Unknown approximation type.')\nend\nif model.learnScales\n  endVal = endVal + model.d;\nend\nmodel = gpExpandParam(model, params(startVal:endVal));\n\n\n% Give parameters to dynamics if they are there.\nif isfield(model, 'dynamics') & ~isempty(model.dynamics)\n  startVal = endVal + 1;\n  endVal = length(params);\n\n  % Fill the dynamics model with current latent values.\n  model.dynamics = modelSetLatentValues(model.dynamics, model.X);\n\n  % Update the dynamics model with parameters (thereby forcing recompute).\n  model.dynamics = modelExpandParam(model.dynamics, params(startVal:endVal));\nend\n\n% Constraints\nif(isfield(model,'constraints')&&~isempty(model.constraints))\n  for(i = 1:1:model.constraints.numConstraints)\n    model.constraints.comp{i} = constraintExpandParam(model.constraints.comp{i},model.X);\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/fgplvmExpandParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20302910060080626}}
{"text": "function cdf = gp_predcdf(gp, x, y, varargin) \n%GP_PREDCDF  Predictive CDF evaluated at YT\n%\n%  Description\n%    CDF = GP_PREDCDF(GP, X, Y, XT, 'yt', YT, OPTIONS)\n%    takes a GP structure together with matrix X of training\n%    inputs and vector Y of training targets, and evaluates the\n%    cdf of the predictive distribution at test inputs XT, YT. \n%\n%    CDF = GP_PREDCDF(GP, X, Y, OPTIONS) evaluates the\n%    cdf of the predictive distribution at training inputs X, Y.\n%\n%    OPTIONS is optional parameter-value pair\n%      tstind - a vector defining, which rows of X belong to which \n%               training block in *IC type sparse models. Default is [].\n%               See also GP_PRED.\n%      z      - optional observed quantity in triplet (x_i,y_i,z_i)\n%               Some likelihoods may use this. For example, in case of \n%               Poisson likelihood we have z_i=E_i, that is, expected value \n%               for ith case.\n%      zt     - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n%               Some likelihoods may use this. For example, in case of \n%               Poisson likelihood we have z_i=E_i, that is, the expected \n%               value for the ith case. \n%\n%  See also\n%    GP_PRED, GP_PAK, GP_UNPAK\n%\n% Copyright (c) 2012 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n  ip=inputParser;\n  ip.FunctionName = 'GP_PREDCDF';\n  ip.addRequired('gp',@(x) isstruct(x) || iscell(x));\n  ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n  ip.addOptional('xt', [], @(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))))\n  ip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('prct', [5 50 95], @(x) isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('nsamp', 5000, @(x) isreal(x) && all(isfinite(x(:))))\n  ip.addParamValue('predcf', [], @(x) isempty(x) || ...\n                   isvector(x) && isreal(x) && all(isfinite(x)&x>0))\n  ip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n                   (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\n  if numel(varargin)==0 || isnumeric(varargin{1})\n    % inputParser should handle this, but it doesn't\n    ip.parse(gp, x, y, varargin{:});\n  else\n    ip.parse(gp, x, y, [], varargin{:});\n  end\n  xt=ip.Results.xt;\n  yt=ip.Results.yt;\n  z = ip.Results.z;\n  zt = ip.Results.zt;\n  prct = ip.Results.prct;\n  nsamp = ip.Results.nsamp;\n  predcf=ip.Results.predcf;\n  tstind=ip.Results.tstind;\n  if isempty(xt)\n    xt=x;\n    if isempty(tstind)\n      if iscell(gp)\n        gptype=gp{1}.type;\n      else\n        gptype=gp.type;\n      end\n      switch gptype\n        case {'FULL' 'VAR' 'DTC' 'SOR'}\n          tstind = [];\n        case {'FIC' 'CS+FIC'}\n          tstind = 1:size(x,1);\n        case 'PIC'\n          if iscell(gp)\n            tstind = gp{1}.tr_index;\n          else\n            tstind = gp.tr_index;\n          end\n      end\n    end\n    if isempty(yt)\n      yt=y;\n    end\n    if isempty(zt)\n      zt=z;\n    end\n  end\n\n  % pass these forward\n  options=struct();\n  if ~isempty(z);options.z=z;end\n  if ~isempty(yt);options.yt=yt;end\n  if ~isempty(zt);options.zt=zt;end\n  if ~isempty(predcf);options.predcf=predcf;end\n  if ~isempty(tstind);options.tstind=tstind;end\n\n  [tn, nin] = size(x);\n  \n  if iscell(gp) || numel(gp.jitterSigma2)>1 || isfield(gp,'latent_method')\n    % gp_array\n    if iscell(gp)\n      nGP = numel(gp);\n      for i1=1:nGP\n        Gp=gp{i1};\n        P_TH(:,i1)=Gp.ia_weight;\n        [Ef,Varf]=gp_pred(Gp,x,y,xt,options);\n        cdfs(:,i1)=Gp.lik.fh.predcdf(Gp.lik, Ef, Varf, yt);\n      end\n      cdf=sum(bsxfun(@times,cdfs,P_TH),2);\n    elseif numel(gp.jitterSigma2)>1\n      % MCMC samples\n      [Efs,Varfs]=gpmc_preds(gp,x,y,xt,options);\n      nmc=size(gp.jitterSigma2,1);\n      for i1=1:nmc\n        Gp = take_nth(gp,i1);\n        cdfs(:,i1)=Gp.lik.fh.predcdf(Gp.lik, Ef, Varf, yt);\n      end\n      cdf=mean(cdfs, 2);\n    else\n      [Ef,Varf]=gp_pred(gp,x,y,xt,options);\n      cdf=gp.lik.fh.predcdf(gp.lik, Ef, Varf, yt);\n    end\n    \n  end\n\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gp_predcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.2029634642232427}}
{"text": "function model = changeCOBRAConstraints(model, constraintID, varargin)\n% Modify an existing COBRA constraint by providing new settings for the\n% constraint to update existing settings.\n% USAGE:\n%    model = changeCOBRAConstraints(model, constraintID, varargin)\n%\n% INPUTS:\n%    model:             model structure\n%    constraintID:      The ID of the constraint (or the index in the\n%                       ctrs field) \n% \n% OPTIONAL INPUTS:\n%    varargin:      all elements (name, d, dsense and c can be modified as indicated below.  \n%                   * idList:           cell array of ids either from either the rxns, or the evars vectors. Can also be a a double vector of indices (in which case indices in evars have to be set off by numel(rxns).\n%                   * c:                the elements of the C matrix. If idList is empty, this has to be a vector of length #rxns + #evars\n%                   * dsense:           the constraint sense ('L': <= ,'G': >=, 'E': =), or a vector for multiple constraints\n%                   * d:                The right hand side of the C*v <= d constraint (or a vector, for multiple simultaneous addition)\n%                   * name:             The new, descriptive name of the constraint.\n%                   \n% OUTPUT:\n%    model:         constrained model\n%\n% EXAMPLE:\n%    Modify the constraint 'A_and_B_Lower_10' to read A + B + C <= 10\n%    model = addCOBRAConstraints(model, 'A_and_B_Lower_10', 'idList', {'A','B','C'}, 'c', [1,1,1]);\n%\n% NOTE:\n%    If c is provided, the whole constraint coefficients will be reset and\n%    existing coefficients will be removed!\n%\n% Author: Thomas Pfau, Oct 2018\n\n\nparser = inputParser();\nparser.addRequired('model',@isstruct);\nparser.addRequired('constraintID',@(x) ischar(x) && any(ismember(model.ctrs,x)));\nparser.addParameter('d',[],@isnumeric);\nparser.addParameter('c',[],@(x) isnumeric(x));\nparser.addParameter('dsense','', @ischar );\nparser.addParameter('idList',{},@(x) iscell(x) );\nparser.addParameter('name',[],@(x) ischar(x) );\nparser.parse(model,constraintID,varargin{:});\n\ncoefs = columnVector(parser.Results.c)';\nd = parser.Results.d;\ndsense = parser.Results.dsense;\nidList = parser.Results.idList;\nname = parser.Results.name;\nc = parser.Results.c;\n\n% get some model properties\n[~,nRxns] = size(model.S);\nif isfield(model,'evars')\n    [nCtrs,nVars] = size(model.D);\nelse\n    nVars = 0;\nend\n\nif ischar(constraintID)\n    constraintID = find(ismember(model.ctrs,constraintID));\nend\n\n% check idList to determine new C/D values.\nif ~isempty(c)\n    if isempty(idList)\n        if size(coefs,2) ~= nVars + nRxns\n            error('If no idList is provided, the c vector has to contain one element for each reaction and each variable in the model');\n        end\n        newC = c(1:nRxns);\n        newD = c((nRxns+1):end);\n    else\n        if size(c,2) ~= numel(idList)\n            error('If idList is provided, the c vector has to contain one element for each element in idList');\n        end\n        % get the positions of the provided ids in rxns/evars\n        [pos,pres] = getIDPositions(model,idList,'rxns');\n        if any(~pres)\n            missingreactions = idList(~pres);\n            error('The following ids were not found in the model:\\n%s\\nNo Constraint was added',strjoin(missingreactions,', '));\n        end\n        % create the respective rows.\n        newC = sparse(1,nRxns);\n        newD = sparse(1,nVars);\n        % get the positions of the variables\n        vars = pos > nRxns;\n        varPos = pos(vars) - nRxns;\n        varCoefs = c(vars);\n        rxns = pos <= nRxns;\n        rxnPos = pos(rxns);\n        rxnCoefs = c(rxns);\n        newC(rxnPos) = rxnCoefs;\n        newD(varPos) =varCoefs;        \n    end\n    \n    % set the rows if applicable\n    model.C(constraintID,:) = newC;\n    if isfield(model, 'D')\n        model.D(constraintID,:) = newD;\n    end\nend\n\n% update d\nif ~isempty(d)\n    model.d(constraintID) = d;\nend\n\n% update dsense\nif ~isempty(dsense)\n    model.dsense(constraintID) = dsense;\nend\n\n% update name:\nif ~isempty(name)\n    if ~isfield(model,'ctrNames')\n        model = createEmptyFields(model,'ctrNames');\n    end\n    model.ctrNames{constraintID} = name;\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/refinement/changeCOBRAConstraints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.20296346043595379}}
{"text": "dbcnn.name = 'dbcnn' ;\ndbcnn.opts = {...\n  'type', 'bcnn', ...\n  'modela', 'D:\\dbcnn\\data\\models\\imagenet-vgg-verydeep-16.mat', ...\n  'layera', 30,...\n  'modelb', 'D:\\dbcnn\\data\\models\\scnn.mat', ...\n  'layerb', 18,...\n  'shareWeight', false,...\n  };\n\n\nopts.setupNameList = {'dbcnn'};\nopts.encoderList = {{dbcnn}}; \nopts.datasetList = {{'live', 1}};  \n%opts.learningRate = 1e-6;\nopts.momentum = 0.9;\nopts.batchSize = 8;\nopts.numEpoch = 30;\nopts.dataset = opts.datasetList{1,1}{1};\n\n\nsrcc = zeros(1,10);\nplcc = zeros(1,10);\n\nswitch opts.dataset\n    case 'live'\n        subdirec = 'data\\checkgpu\\live-seed-01';\n        modelpath = 'models\\LIVE_models';\n        datapath = 'data\\checkgpu\\live-seed-01';\n        opts.learningRate = 1e-6;\n    case 'csiq'\n        subdirec = 'data\\checkgpu\\csiq-seed-01';\n        modelpath = 'models\\CSIQ_models';\n        datapath = 'data\\checkgpu\\csiq-seed-01';\n        opts.learningRate = 1e-6;\n    case 'tid'\n        subdirec = 'data\\checkgpu\\tid-seed-01';\n        modelpath = 'models\\TID_models';\n        datapath = 'data\\checkgpu\\tid-seed-01';\n        opts.learningRate = 1e-5;\n    case 'mlive'\n        subdirec = 'data\\checkgpu\\mlive-seed-01';\n        modelpath = 'models\\MLIVE_models';\n        datapath = 'data\\checkgpu\\mlive-seed-01';\n        opts.learningRate = 1e-5;\n    case 'clive'\n        subdirec = 'data\\checkgpu\\clive-seed-01';\n        modelpath = 'models\\Challen_models';\n        datapath = 'data\\checkgpu\\clive-seed-01';\n        opts.learningRate = 1e-5;\nend\n\n\n\nfor split = 1:10\n    mkdir(subdirec);\n    rmdir(subdirec,'s');\n    imdbpath = fullfile(subdirec,'imdb');\n    mkdir(imdbpath);\n    copyfile(fullfile(modelpath,num2str(split),'imdb-seed-1.mat'),...\n        fullfile(imdbpath,'imdb-seed-1.mat'));\n    [options, imdb] = run_experiments_bcnn_train(opts);\n    deploy_each_dagnet(opts.numEpoch, datapath);\n    options.ftpath = fullfile(subdirec,'fine-tuned-model');\n    [srcc(1,split),plcc(1,split),index] = find_bestmodel(opts.numEpoch, imdb, options);\nend\n", "meta": {"author": "zwx8981", "repo": "DBCNN", "sha": "64f6e3e86f1a055b387fc170c93aa2dd994a5256", "save_path": "github-repos/MATLAB/zwx8981-DBCNN", "path": "github-repos/MATLAB/zwx8981-DBCNN/DBCNN-64f6e3e86f1a055b387fc170c93aa2dd994a5256/dbcnn/run_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2029634566486649}}
{"text": "function [ output_args ] = Makeparadigm_MI( varargin )\n% Makeparadigm_MI (Experimental paradigm):\n% \n% Description:\n%   Basic motor imagery experiment paradigm using psychtoolbox.\n%   It shows a cross, an arrow, and blank screen alternately.\n% \n% Example:\n%   Makeparadigm_MI({'time_cross',1.5;'time_sti',60;'time_blank',5;'num_trial',1;'num_class',3});\n% \n% Input: (Nx2 size, cell-type)\n%   time_cross  - time for concentration, showing a cross [s]\n%   time_sti    - time for a stimulus, showing an arrow (right, left, or down) [s]\n%   time_blank  - time for rest, showing nothing but gray screen [s]\n%   num_trial   - number of trials per class\n%   num_class   - number of class you want, 1 to 3, (right, left, and foot)\n%   num_screen  - number of screen to show \n%   screen_size - size of window showing experimental stimulus\n%                 'full' or matrix (e.g.[0 0 300 300])\n% \n\nopt=opt_cellToStruct(varargin{:});\n\n\n%% default setting\nif ~isfield(opt,'time_sti'),    time_sti=4;      else time_sti=opt.time_sti;      end\nif ~isfield(opt,'time_cross'),  time_cross=3;    else time_cross=opt.time_cross;  end\nif ~isfield(opt,'time_blank'),  time_blank=3;    else time_blank=opt.time_blank;  end\nif ~isfield(opt,'num_trial'),   num_trial=50;    else num_trial=opt.num_trial;    end\n% if ~isfield(opt,'time_jitter'), time_jitter=0.1; else time_jitter=opt.time_jitter;end\nif ~isfield(opt,'num_class'),   num_class=3;     else num_class=opt.num_class;    end\n% screenNumber=2;\n\n%% screen setting\nscreens=Screen('Screens');\nif ~isfield(opt,'num_screen'),screenNumber=max(screens); else screenNumber=opt.num_screen; end\nif ~isfield(opt,'screen_size'),screen_size='full'; else screen_size=opt.screen_size; end\n% if ~isfield(opt,'screen_type'),screen_type='window'; else screen_type=opt.screen_type; end\n\n%% beep setting\nbeep='on';\nfreq=22000;\nbeepLengthSecs=0.5;\n\n%% trigger setting\nglobal IO_ADDR IO_LIB;\nIO_ADDR=hex2dec('D010');\nIO_LIB=which('inpoutx64.dll');\n\n%% jittering\na=-1;b=1;\n% association with + time jittering\njitter = a + (b-a).*rand(num_trial*num_class,1);\njitter=jitter*0.5;\n\n%% image load\ncurrentFile = mfilename( 'fullpath' );\n[pathstr,~,~] = fileparts( currentFile );\nimg_right=imread(fullfile(pathstr, \"..\", '\\Stimulus\\right.jpg'));\nimg_left=imread(fullfile(pathstr, \"..\",'\\Stimulus\\\\left.jpg'));\nimg_down=imread(fullfile(pathstr, \"..\",'\\Stimulus\\down.jpg'));\n% img_cross=imread('\\Stimulus\\cross.jpg');\n\n%% beep sound\nif strcmp(beep,'on')\n    [beep,samplingRate] = MakeBeep(500,beepLengthSecs,freq);\n    Snd('Open');\n    sound=1;\nelse\n    sound=0;\nend\n% Screen('Preference', 'SkipSyncTests', 1);\n\n%% psychtoolbox setting\ngray=GrayIndex(screenNumber);\n% screenRes = [0 0 300 300];\nif strcmp(screen_size,'full')\n    [w, wRect]=Screen('OpenWindow',screenNumber, gray);\nelse\n    [w, wRect]=Screen('OpenWindow',screenNumber, gray, screen_size);\nend\n\n%% order of stimulus (random)\nfor i=1:num_class\n    a1(i,1:num_trial)=i;\nend\n% a1=Shuffle(a1);\n% [t s]=size(a1);\n% sti_stack=reshape(a1,1,t*s);\nsti_stack=Shuffle(a1(:)'); % smkim\n\n\n% click to start:\nScreen('TextSize',w, 50);\nDrawFormattedText(w,'Mouse click to start MI experiment \\n\\n (Press s to pause, esc to stop)','center','center',[0 0 0]);\nScreen('Flip', w);\nGetClicks(w);\nppTrigger(111); % START\n\nescapeKey = KbName('esc');\nwaitKey=KbName('s');\np_close=0;\n\n%% Eyes open/closed\n% run(fullfile(pathstr,\"..\", '\\Artifact\\eyesOpenClosed')) % script\nrun('Paradigm\\Artifact\\eyesOpenClosed') % script\n\n%% fixation cross\n[X,Y] = RectCenter(wRect);\nFixationSize = 20;\nFixCross = [X-1,Y-FixationSize,X+1,Y+FixationSize;X-FixationSize,Y-1,X+FixationSize,Y+1];\n\n%% paradigm start\n    Screen('FillRect', w, [0 0 0], FixCross');\n    Screen('Flip', w);\n    WaitSecs(2.5)\n\nfor num_stimulus=1:length(sti_stack)\n    \n    if num_stimulus==length(sti_stack)/2\n        Screen('TextSize',w, 50);\n        DrawFormattedText(w,'Rest\\n\\n(Pause the brain vision)','center','center',[0 0 0]);\n        Screen('Flip', w);\n        GetClicks(w);\n        DrawFormattedText(w,'(Resume recording)','center','center',[0 0 0]);\n        Screen('Flip', w);\n        GetClicks(w);\n        DrawFormattedText(w,'Click to continue the experiment','center','center',[0 0 0]);\n        Screen('Flip', w);\n        GetClicks(w);\n    end\n    \n    start=GetSecs;\n    while GetSecs < start+time_blank+jitter(num_stimulus)-2\n        [ keyIsDown, seconds, keyCode ] = KbCheck;\n        if keyIsDown\n            if keyCode(escapeKey)\n%                 ShowCursor;\n%                 p_close=1;\n                Screen('CloseAll');\n                fclose('all');\n                return\n            elseif keyCode(waitKey)\n                warning('stop')\n                GetClicks(w);\n                Screen('Close',tex1);\n                \n            end\n        end\n        pause(0.1);\n    end\n    \n%     if p_close\n%         break;\n%     end\n    \n    Screen('FillRect', w, [0 0 0], FixCross');\n    Screen('Flip', w);\n    if sound\n        Snd('Play',beep);\n    end\n    \n    WaitSecs(1)\n    ppTrigger(5);\n    WaitSecs(time_cross)\n\n    switch sti_stack(num_stimulus)\n        case 1 % right class\n            ppTrigger(1);\n            image=img_right;\n            tex1=Screen('MakeTexture', w, image );\n            Screen('DrawTexture', w, tex1);\n            Screen('FillRect', w, [0 0 0], FixCross');\n            Screen('Flip', w);\n            \n            WaitSecs(time_sti);\n            Screen('Close',tex1);\n%             ppTrigger(11);\n            \n        case 2 % left class\n            ppTrigger(2);\n            image=img_left;\n            tex1=Screen('MakeTexture', w, image );\n            Screen('DrawTexture', w, tex1);\n            Screen('FillRect', w, [0 0 0], FixCross');\n            Screen('Flip', w);\n\n            WaitSecs(time_sti);\n            Screen('Close',tex1);\n%             ppTrigger(22);\n            \n        case 3 % foot class\n            ppTrigger(3);\n            image=img_down;\n            tex1=Screen('MakeTexture', w, image );\n            Screen('DrawTexture', w, tex1);\n            Screen('FillRect', w, [0 0 0], FixCross');\n            Screen('Flip', w);\n            \n            WaitSecs(time_sti);\n            Screen('Close',tex1);\n%             ppTrigger(33);\n    end\n    num_stimulus\n    \n    Screen('Flip', w);\n    WaitSecs(time_blank)\n\nend\n\nppTrigger(222);\nScreen('TextSize',w, 50);\nDrawFormattedText(w, 'Thank you', 'center', 'center', [0 0 0]);\nScreen('Flip', w);\nWaitSecs(2);\nScreen('CloseAll');\nShowCursor;\nfclose('all');\nPriority(0);\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/Paradigm/MI/Makeparadigm_MI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.2029099544470006}}
{"text": "function invert = spm_cfg_eeg_inv_invert\n% Configuration file for configuring imaging source inversion\n% reconstruction\n%__________________________________________________________________________\n% Copyright (C) 2010-2016 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: spm_cfg_eeg_inv_invert.m 7076 2017-05-19 12:47:36Z vladimir $\n\nD = cfg_files;\nD.tag = 'D';\nD.name = 'M/EEG datasets';\nD.filter = 'mat';\nD.num = [1 Inf];\nD.help = {'Select the M/EEG mat files.'};\n\nval = cfg_entry;\nval.tag = 'val';\nval.name = 'Inversion index';\nval.strtype = 'n';\nval.help = {'Index of the cell in D.inv where the forward model can be found and the results will be stored.'};\nval.val = {1};\n\nall = cfg_const;\nall.tag = 'all';\nall.name = 'All';\nall.val  = {1};\nall.help = {''};\n\ncondlabel = cfg_entry;\ncondlabel.tag = 'condlabel';\ncondlabel.name = 'Condition label';\ncondlabel.strtype = 's';\ncondlabel.val = {''};\ncondlabel.help = {''};\n\nconditions = cfg_repeat;\nconditions.tag = 'conditions';\nconditions.name = 'Conditions';\nconditions.help = {'Specify the labels of the conditions to be included in the inversion'};\nconditions.num  = [1 Inf];\nconditions.values  = {condlabel};\nconditions.val = {condlabel};\n\nwhatconditions = cfg_choice;\nwhatconditions.tag = 'whatconditions';\nwhatconditions.name = 'What conditions to include?';\nwhatconditions.values = {all, conditions};\nwhatconditions.val = {all};\nwhatconditions.help = {'What conditions to include?'};\n\nstandard = cfg_const;\nstandard.tag = 'standard';\nstandard.name = 'Standard';\nstandard.help = {'Use default settings for the inversion'};\nstandard.val  = {1};\n\ninvtype = cfg_menu;\ninvtype.tag = 'invtype';\ninvtype.name = 'Inversion type';\ninvtype.help = {'Select the desired inversion type'};\ninvtype.labels = {'MSP (GS)',  'COH', 'IID', 'EBB'};\ninvtype.values = {'GS',        'LOR', 'IID', 'EBB'};\ninvtype.val = {'GS'};\n\nwoi = cfg_entry;\nwoi.tag = 'woi';\nwoi.name = 'Time window of interest';\nwoi.strtype = 'r';\nwoi.num = [1 2];\nwoi.val = {[-Inf Inf]};\nwoi.help = {'Time window to include in the inversion (ms)'};\n\nfoi = cfg_entry;\nfoi.tag = 'foi';\nfoi.name = 'Frequency window of interest';\nfoi.strtype = 'r';\nfoi.num = [1 2];\nfoi.val = {[0 256]};\nfoi.help = {'Frequency window (the same as high-pass and low-pass in the GUI)'};\n\nhanning = cfg_menu;\nhanning.tag = 'hanning';\nhanning.name = 'PST Hanning window';\nhanning.help = {'Multiply the time series by a Hanning taper to emphasize the central part of the response.'};\nhanning.labels = {'yes', 'no'};\nhanning.values = {1, 0};\nhanning.val = {1};\n\npriorsmask  = cfg_files;\npriorsmask.tag = 'priorsmask';\npriorsmask.name = 'Priors file';\npriorsmask.filter = '(.*\\.gii$)|(.*\\.mat$)|(.*\\.nii(,\\d+)?$)|(.*\\.img(,\\d+)?$)';\npriorsmask.num = [0 1];\npriorsmask.help = {'Select a mask or a mat file with priors.'};\npriorsmask.val = {{''}};\n\nspace = cfg_menu;\nspace.tag = 'space';\nspace.name = 'Prior image space';\nspace.help = {'Space of the mask image.'};\nspace.labels = {'MNI', 'Native'};\nspace.values = {1, 0};\nspace.val = {1};\n\npriors = cfg_branch;\npriors.tag = 'priors';\npriors.name = 'Source priors';\npriors.help = {'Restrict solutions to pre-specified VOIs'};\npriors.val  = {priorsmask, space};\n\nlocs  = cfg_entry;\nlocs.tag = 'locs';\nlocs.name = 'Source locations';\nlocs.strtype = 'r';\nlocs.num = [Inf 3];\nlocs.help = {'Input source locations as n x 3 matrix'};\nlocs.val = {zeros(0, 3)};\n\nradius = cfg_entry;\nradius.tag = 'radius';\nradius.name = 'Radius of VOI (mm)';\nradius.strtype = 'r';\nradius.num = [1 1];\nradius.val = {32};\nradius.help = {''};\n\nmask  = cfg_files;\nmask.tag = 'mask';\nmask.name = 'Mask image';\nmask.filter = '(.*\\.nii(,\\d+)?$)|(.*\\.img(,\\d+)?$)';\nmask.num = [0 1];\nmask.help = {'Select a mask image'};\nmask.val = {{''}};\n\nrestrict = cfg_branch;\nrestrict.tag = 'restrict';\nrestrict.name = 'Restrict solutions';\nrestrict.help = {'Restrict solutions to pre-specified VOIs'};\nrestrict.val  = {locs, radius, mask};\n\ncustom = cfg_branch;\ncustom.tag = 'custom';\ncustom.name = 'Custom';\ncustom.help = {'Define custom settings for the inversion'};\ncustom.val  = {invtype, woi, foi, hanning, priors, restrict};\n\nisstandard = cfg_choice;\nisstandard.tag = 'isstandard';\nisstandard.name = 'Inversion parameters';\nisstandard.help = {'Choose whether to use standard or custom inversion parameters.'};\nisstandard.values = {standard, custom};\nisstandard.val = {standard};\n\nmodality = cfg_menu;\nmodality.tag = 'modality';\nmodality.name = 'Select modalities';\nmodality.help = {'Select modalities for the inversion (only relevant for multimodal datasets).'};\nmodality.labels = {'All', 'EEG', 'MEG', 'MEGPLANAR', 'EEG+MEG', 'MEG+MEGPLANAR', 'EEG+MEGPLANAR', 'EEG+MEG+MEGPLANAR'};\nmodality.values = {\n    {'All'}\n    {'EEG'}\n    {'MEG'}\n    {'MEGPLANAR'}\n    {'EEG', 'MEG'}\n    {'MEG', 'MEGPLANAR'}\n    {'EEG', 'MEGPLANAR'}\n    {'EEG', 'MEG', 'MEGPLANAR'}\n    }';\nmodality.val = {{'All'}};\n\ninvert = cfg_exbranch;\ninvert.tag = 'invert';\ninvert.name = 'Source inversion';\ninvert.val = {D, val, whatconditions, isstandard, modality};\ninvert.help = {'Run imaging source reconstruction'};\ninvert.prog = @run_inversion;\ninvert.vout = @vout_inversion;\ninvert.modality = {'EEG'};\n\nfunction  out = run_inversion(job)\n\nD = spm_eeg_load(job.D{1});\n\ninverse = [];\nif isfield(job.whatconditions, 'condlabel')\n    inverse.trials = job.whatconditions.condlabel;\nend\n\nif isfield(job.isstandard, 'custom')\n    inverse.type = job.isstandard.custom.invtype;\n    inverse.woi  = fix([max(min(job.isstandard.custom.woi), 1000*D.time(1)) min(max(job.isstandard.custom.woi), 1000*D.time(end))]);\n    inverse.Han  = job.isstandard.custom.hanning;\n    inverse.lpf  =  fix(min(job.isstandard.custom.foi));\n    inverse.hpf  =  fix(max(job.isstandard.custom.foi));\n    \n    P = char(job.isstandard.custom.priors.priorsmask);\n    if ~isempty(P)        \n        [p,f,e] = fileparts(P);\n        switch lower(e)\n            case '.gii'\n                g = gifti(P);\n                inverse.pQ = cell(1,size(g.cdata,2));\n                for i=1:size(g.cdata,2)\n                    inverse.pQ{i} = double(g.cdata(:,i));\n                end\n            case '.mat'\n                load(P);\n                inverse.pQ = pQ;\n            case {'.img', '.nii'}\n                S.D = D;\n                S.fmri = P;\n                S.space = job.isstandard.custom.priors.space;\n                D = spm_eeg_inv_fmripriors(S);\n                inverse.fmri = D.inv{D.val}.inverse.fmri;\n                load(inverse.fmri.priors);\n                inverse.pQ = pQ;\n            otherwise\n                error('Unknown file type.');\n        end\n    end\n    \n    if ~isempty(job.isstandard.custom.restrict.locs)\n        inverse.xyz = job.isstandard.custom.restrict.locs;\n        inverse.rad = job.isstandard.custom.restrict.radius;\n    end\n    \n    P = char(job.isstandard.custom.restrict.mask);\n    if ~isempty(P)\n        inverse.mask = P;\n    end\nend\n\n[mod, list] = modality(D, 1, 1);\nif strcmp(job.modality{1}, 'All')\n    inverse.modality  = list;\nelse\n    inverse.modality  = intersect(list, job.modality);\nend\n\nif numel(inverse.modality) == 1\n    inverse.modality = inverse.modality{1};\nend\n\nD = {};\n\nfor i = 1:numel(job.D)\n    D{i} = spm_eeg_load(job.D{i});\n    \n    D{i}.val = job.val;\n    \n    D{i}.con = 1;\n    \n    if ~isfield(D{i}, 'inv')\n        error('Forward model is missing for subject %d.', i);\n    elseif  numel(D{i}.inv)<D{i}.val || ~isfield(D{i}.inv{D{i}.val}, 'forward')\n        if D{i}.val>1 && isfield(D{i}.inv{D{i}.val-1}, 'forward')\n            D{i}.inv{D{i}.val} = D{i}.inv{D{i}.val-1};\n            warning('Duplicating the last forward model for subject %d.', i);\n        else\n            error('Forward model is missing for subject %d.', i);\n        end\n    end\n    \n    D{i}.inv{D{i}.val}.inverse = inverse;\nend\n\nD = spm_eeg_invert(D);\n\nif ~iscell(D)\n    D = {D};\nend\n\nfor i = 1:numel(D)\n    save(D{i});\nend\n\nout.D = job.D;\n\nfunction dep = vout_inversion(job)\n% Output is always in field \"D\", no matter how job is structured\ndep = cfg_dep;\ndep.sname = 'M/EEG dataset(s) after imaging source reconstruction';\n% reference field \"D\" from output\ndep.src_output = substruct('.','D');\n% this can be entered into any evaluated input\ndep.tgt_spec   = cfg_findspec({{'filter','mat'}});\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_eeg_inv_invert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.20273926506981726}}
{"text": "function engine = jtree_2TBN_inf_engine(bnet, varargin)\n% JTREE_ONLINE_INF_ENGINE Online Junction tree inference algorithm for DBNs.\n% engine = jtree_online_inf_engine(bnet, ...)\n%\n% The following optional arguments can be specified in the form of name/value pairs:\n% [default value in brackets]\n%\n% clusters - specifies variables that must be grouped in the 1.5 slice DBN\n% maximize - 1 means do max-product, 0 means sum-product [0]\n%\n% The same nodes must be observed in every slice.\n\nss = length(bnet.intra);\nclusters = {};\nengine.maximize = 0;\n\nargs = varargin;\nnargs = length(args);\nfor i=1:2:length(args)\n  switch args{i},\n   case 'clusters', clusters = args{i+1};\n   case 'maximize', engine.maximize = args{i+1};\n   otherwise, error(['unrecognized argument ' args{i}])\n  end\nend\n\nengine.evidence = [];\nengine.node_sizes = [];\n\n%int = compute_interface_nodes(bnet.intra, bnet.inter);\nint = [];\n\nif 1\n% include nodes with any outgoing arcs\nfor u=1:ss\n  if any(bnet.inter(u,:))\n    int = [int u];\n  end\nend\nend\n\nif 0\n% include nodes with any incoming  arcs\nincoming = [];\nfor u=1:ss\n  if any(bnet.inter(:,u))\n    int = [int u];\n    incoming = [incoming u];\n  end\nend\n% include nodes which are parents of nodes with incoming\nfor u=1:ss\n  cs = children(bnet.intra, u);\n  if ~isempty(cs) & mysubset(cs, incoming)\n    int = [int u];\n  end\nend\nint = unique(int);\nend % if\n\nint\nengine.interface = int;\nengine.nonint = mysetdiff(1:ss, int);\n\nonodes = bnet.observed;\n\n% Create a \"1.5 slice\" jtree, containing the interface nodes of slice 1\n% and all the nodes of slice 2\n% To keep the node numbering the same, we simply disconnect the non-interface nodes\n% from slice 1, and set their size to 1.\n% We do this to speed things up, and so that the likelihood is computed correctly - we do not need to do\n% this if we just want to compute marginals (i.e., we can include nodes whose potentials will\n% be left as all 1s).\nintra15 = bnet.intra;\nfor i=engine.nonint(:)'\n  intra15(:,i) = 0;\n  intra15(i,:) = 0;\nend\ndag15 = [intra15      bnet.inter;\n\t zeros(ss)    bnet.intra];\nns = bnet.node_sizes(:);\n%ns(engine.nonint) = 1; % disconnected nodes get size 1\nobs_nodes = [onodes(:) onodes(:)+ss];\nbnet15 = mk_bnet(dag15, ns, 'discrete', bnet.dnodes, 'equiv_class', bnet.equiv_class(:), ...\n\t\t 'observed', obs_nodes(:));\n\n% use unconstrained elimination,\n% but force there to be a clique containing both interfaces\nclusters(end+1:end+2) = {int, int+ss};\nengine.jtree_engine = jtree_inf_engine(bnet15, 'clusters', clusters, 'root', int+ss);\njtree_engine = struct(engine.jtree_engine); % violate object privacy\n\nengine.in_clq = clq_containing_nodes(engine.jtree_engine, int);\nengine.out_clq = clq_containing_nodes(engine.jtree_engine, int+ss);\nengine.clq_ass_to_node = jtree_engine.clq_ass_to_node;\nengine.root = jtree_engine.root_clq;\n\n% Also create an engine just for slice 1\nbnet1 = mk_bnet(bnet.intra1, bnet.node_sizes_slice, 'discrete', myintersect(bnet.dnodes,1:ss), ...\n\t\t'equiv_class', bnet.equiv_class(:,1), 'observed', onodes);\nfor i=1:max(bnet1.equiv_class)\n  bnet1.CPD{i} = bnet.CPD{i};\nend\nengine.jtree_engine1 = jtree_inf_engine(bnet1, 'clusters', {int}, 'root', int);\njtree_engine1 = struct(engine.jtree_engine1); % violate object privacy\nengine.int_clq1 = clq_containing_nodes(engine.jtree_engine1, int);\nengine.clq_ass_to_node1 = jtree_engine1.clq_ass_to_node;\nengine.root1 = jtree_engine1.root_clq;\n\nengine.observed = [onodes onodes+ss];\nengine.observed1 = onodes;\nengine.pot_type = determine_pot_type(bnet, onodes);\nengine.slice_size = bnet.nnodes_per_slice;\n\nengine = class(engine, 'jtree_2TBN_inf_engine', inf_engine(bnet));\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/online/@jtree_2TBN_inf_engine/Old/jtree_2TBN_inf_engine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20267465727715742}}
{"text": "function test_ft_appendsens\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY\n\n\n% regular\nelec1.elecpos = [1 1 1; 2 2 2; 3 3 3];\nelec1.chanpos = elec1.elecpos;\nelec1.label = {'1';'2';'3'};\nelec1.unit  = 'mm';\nelec1.coordsys  = 'acpc';\n\nelec2.elecpos = [4 4 4; 5 5 5];\nelec2.chanpos = elec2.elecpos;\nelec2.label = {'4';'5'};\nelec2.unit  = 'mm';\nelec2.coordsys  = 'acpc';\n\nelec = ft_appendsens([], elec1, elec2);\n\n% duplicate chanpos, elecpos, and channel\nelec1.elecpos = [1 1 1; 2 2 2; 3 3 3];\nelec1.chanpos = elec1.elecpos;\nelec1.label = {'1';'2';'3'};\nelec1.unit  = 'mm';\nelec1.coordsys  = 'acpc';\nelec1.tra  = [1 0 0; 0 1 0; 0 0 1];\nelec2.elecpos = [2 2 2; 0 0 0]; % 2 2 2 is a duplicate\nelec2.chanpos = elec2.elecpos;\nelec2.label = {'2';'7'}; % 2 is a duplicate\nelec2.unit  = 'mm';\nelec2.coordsys  = 'acpc';\nelec2.tra  = [1 0; 0 1];\nelec = ft_appendsens([], elec1, elec2);\n\n% duplicate elecpos (eg same elec used for two bipolar derivations)\nelec1.elecpos = [1 1 1; 2 2 2];\nelec1.chanpos = [1.5 1.5 1.5];\nelec1.label = {'1-2'};\nelec1.unit  = 'mm';\nelec1.coordsys  = 'acpc';\nelec1.tra  = [1 -1];\nelec2.elecpos = [2 2 2; 3 3 3]; % 2 2 2 is a duplicate\nelec2.chanpos = [2.5 2.5 2.5];\nelec2.label = {'2-3'}; % 2 is a duplicate\nelec2.unit  = 'mm';\nelec2.coordsys  = 'acpc';\nelec2.tra  = [1 -1];\n\nelec = ft_appendsens([], elec1, elec2);\n\n% duplicate chanpos and elecpos, but no duplicate label (eg two electrodes\n% localized to the same location)\nelec1.elecpos = [1 1 1; 2 2 2; 3 3 3];\nelec1.chanpos = elec1.elecpos;\nelec1.label = {'1';'2';'3'};\nelec1.unit  = 'mm';\nelec1.coordsys  = 'acpc';\nelec1.tra  = [1 0 0; 0 1 0; 0 0 1];\nelec2.elecpos = [2 2 2; 0 0 0]; % 2 2 2 is a duplicate\nelec2.chanpos = elec2.elecpos;\nelec2.label = {'8';'7'}; % no duplicate label\nelec2.unit  = 'mm';\nelec2.coordsys  = 'acpc';\nelec2.tra  = [1 0; 0 1];\n\ntry\n  elec = ft_appendsens([], elec1, elec2);\n  % this SHOULD throw an error because two labels for the same chanpos are not allowed\n  error('an error was expected but not thrown')\ncatch\n  fprintf('ft_appendsens threw an error as expected\\n')\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_appendsens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20250740690874458}}
{"text": "function eddyscan_compiled_script(file_name, file_path, save_path, varargin)%#codegen\nif ~strcmp(file_path(end), '/')\n    file_path = strcat(file_path, '/');\nend\nif ~strcmp(save_path(end), '/')\n    save_path = strcat(save_path, '/');\nend\nvars = load('area_map.mat');\narea_map = vars.area_map;\n[dir, rem] = strtok(file_name, '/');\nfilename = strtok(rem, '/');\neddy_dir = [save_path, dir];\nindices = regexp(filename, '[0-9]');\nnums = filename(indices);\ndate = nums(1:8);\neddy_file = ['anticyc_', date, '.mat'];\nif exist(eddy_dir, 'dir')\n    cd(eddy_dir);\n    if exist(eddy_file, 'file')\n        disp('Eddy file detected, quitting.');\n        %quit;\n    end\nend\ncd([file_path, dir]);\nif exist([file_path, dir, '/', filename], 'file') && ~exist([save_path, dir, '/', eddy_file], 'file')\n    ssh = ncread(filename, 'sla')';\n    lat = double(ncread(filename, 'lat'));\n    lon = double(ncread(filename, 'lon'));\n    cd(save_path);\n    ant_eddies = scan_single(ssh, lat, lon, date, 'anticyc', 'v2', area_map, varargin{:});%#ok\n    cyc_eddies = scan_single(ssh, lat, lon, date, 'cyclonic', 'v2', area_map, varargin{:});%#ok\n    if ~exist([save_path, dir], 'dir')\n        mkdir([save_path, dir]);\n    end\n    cd([save_path, dir]);\n    save(['anticyc_', date, '.mat'], 'ant_eddies');\n    save(['cyclonic_', date, '.mat'], 'cyc_eddies');\nelse\n    \nend\n%quit;\nend\n\nfunction [ eddies ] = scan_single( ssh, lat, lon, date, cyc, scan_type, areamap, varargin )\n%SCAN_SINGLE Wrapper function to do scanning\n% ssh: ssh slice with nans for land, size should be [length(lat) length(lon)]\n% lat: 1D array of the latitudes of ssh grid\n% lon: 1D array of the longitudes of ssh grid\n% cyc: 'anticyc' or 'cyclonic'\n% scan_type: 'v1', 'v2', 'hybrid'\n%         v1: Will run top-down scanning (only works with full data of 0.25 x 0.25 ssh grid)\n%         v2: Will run bottom-up scanning from the minima of the field\n%     hybrid: Will run v2 and v1 scanning and will take the union of the\n%             two sets where, for common features, v2 bodies will be used\n% areamap: A 2D array that refer to the area of each pixel in SSH data (should have same size as ssh), or 1D array \n%   that refer to area of each pixel for a specific lat in a regular grid (pixeld have same area for the same \n%   latitude)\n% Optional parameters (only applicable for v2 eddyscan):\n%   'minimumArea': minimum number of pixels for an eddy, used for validating eddies, default value is 9\n%   'thresholdStep': the minimum step for thresholding, the unit is SSH's unit, default value is 0.05\n%   'isPadding': whether or not to pad SSH data, should be true when scanning SSH data with the longitudes expanding the \n%   whole world dmap. Set to false if only partial SSH data is used. Default value is true\n    if ~any(isnan(ssh(:)))\n        error('Invalid ssh data, must contain NaNs for land values');\n    end\n\n    if ~all(size(ssh) == [length(lat) length(lon)])\n        error('Invalid ssh data size, should be [length(lat) length(lon]');\n    end\n    \n    if ~all(size(areamap) == size(ssh))\n        % Not a 2d array with same size as ssh\n        if ~any(size(areamap) == [1 1]) || length(areamap) ~= length(lat)\n            disp('Invalid areamap, using NaN for eddy surface area');\n        end\n    end\n    \n    stype = get_stype(scan_type);\n    ctype = get_ctype(cyc);\n    disp('About to start scanning eddies');\n    \n    %oldpath = addpath('lib');\n    switch stype\n        case 1\n            eddies = top_down_single(ssh, lat, lon, areamap, ctype, varargin{:});\n        case 2\n            eddies = bottom_up_single(ssh, lat, lon, areamap, ctype, varargin{:});\n%        case 0\n%            scanners = {@top_down_single, @bottom_up_single};\n%            eddies_out = {[], []};\n%            parfor i = 1:2\n%                eddies_out{i} = scanners{i}(ssh, lat, lon, areamap, ctype, varargin{:});\n%            end\n%            eddies = get_combined_eddy_frames(eddies_out{2}, eddies_out{1}, ssh);\n    end\n    [eddies.Date] = deal(date);\n    \n    %path(oldpath);\n   \nend\n%end\n\nfunction cyc_t = get_ctype(cyc)\n    switch cyc\n        case 'anticyc'\n            cyc_t = 1;\n        case 'cyclonic'\n            cyc_t = -1;\n        otherwise\n            error('cyc must be anticyc or cyclonic');\n    end\nend\n\nfunction scan_t = get_stype(scan_type)\n    switch scan_type\n        case 'v1'\n            scan_t = 1;\n        case 'v2'\n            scan_t = 2;\n        case 'hybrid'\n            scan_t = 0;\n        otherwise\n            error('scan_type must be v1, v2, or hybrid');\n    end\nend\n\nfunction [ eddies ] = bottom_up_single(ssh_data, lat, lon, areamap, cyc, varargin)\n%BOTTOM_UP_SINGLE Finds eddies using the Bottom Up method\n%   Will return an array of struct's that contain the eddy data.\n%   ssh_data: A 2D array of double's that contain the sea surface heights (latsxlons)\n%   lat: A 1D array of double's that gives the latitude for a given index (dimension should match\n%         that of ssh_data)\n%   lon: A 1D array of double's that gives the longitude for a given index (dimension should match\n%         that of ssh_data)\n%   areamap: A 2D array that refer to the area of each pixel in SSH data (should have same size as ssh), or 1D array \n%   that refer to area of each pixel for a specific lat in a regular grid (pixeld have same area for the same \n%   latitude)\n%   cyc: Pass 1 to output anticyclonic eddies or -1 to output cyclonic eddies\n%   Optional parameters:\n%   'minimumArea': minimum number of pixels for an eddy, used for validating eddies\n%   'thresholdStep': the minimum step for thresholding, the unit is SSH's unit\n%   'isPadding': whether or not to pad SSH data, should be true when scanning SSH data of the whole map. Set to false if\n%   only partial SSH data is used.\n%   'sshUnits': The units the SSH data is in. bottom_up_single is built to work natively on centimeter SSH data.\n%   Valid parameters are 'meters' and 'centimeters'. If the paramater passed in is 'meters', the SSH data will\n%   be multiplied by 100. No changes will be made if the paramater passed in is 'centimeters'.\n%   The default value of 'sshUnits' is centimeters.\n    p = inputParser;\n    defaultMinPixelSize = 9;\n    defaultThresholdStep = 0.05;\n    defaultSSHUnits = 'centimeters';\n    defaultPaddingFlag = true;\n    addRequired(p, 'ssh_data');\n    addRequired(p, 'lat');\n    addRequired(p, 'lon');\n    addRequired(p, 'areamap');\n    addRequired(p, 'cyc');\n    addParameter(p, 'minimumArea', defaultMinPixelSize);%, @isnumeric);\n    addParameter(p, 'thresholdStep', defaultThresholdStep);%, @isnumeric);\n    addParameter(p, 'isPadding', defaultPaddingFlag);\n    addParameter(p, 'sshUnits', defaultSSHUnits);\n    parse(p, ssh_data, lat, lon, areamap, cyc, varargin{:});\n    minimumArea = p.Results.minimumArea;\n    thresholdStep = p.Results.thresholdStep;\n    isPadding = p.Results.isPadding;\n    SSH_Units = p.Results.sshUnits;\n    disp(minimumArea);\n    if isa(minimumArea, 'char')\n        disp('Minimum area was a string, converting to double.');\n        minimumArea = str2double(minimumArea);\n        disp(minimumArea);\n    end\n    if isa(thresholdStep, 'char')\n        disp('Threshold step was a string, converting to double.');\n        thresholdStep = str2double(thresholdStep);\n        disp(thresholdStep);\n    end\n    if strcmp(SSH_Units, 'meters')\n        ssh_data = ssh_data * 100;\n    elseif strcmp(SSH_Units, 'centimeters')\n        max_val = max(ssh_data(:));\n        min_val = max(ssh_data(:));\n        if max_val < 1 && min_val > -1\n            ssh_data = ssh_data * 100;\n        elseif max_val < 100 && min_val > -100\n        \n        else\n            error('Could not figure out what units the SSH data provided is in. Please specify it as an additional parameter: sshUnits');\n        end\n    end\n\n    %Check if the grid is regular (differences between lats and lons are equal)\n    lat_diffs = lat(2:end) - lat(1:end-1);\n    lat_diffs2 = lat_diffs(2:end) - lat_diffs(1:end-1);\n    lon_diffs = lon(2:end) - lon(1:end-1);\n    lon_diffs(lon_diffs <= -180) = lon_diffs(lon_diffs <= -180) + 360;\n    lon_diffs(lon_diffs >= 180) = lon_diffs(lon_diffs >= 180) - 360;\n    lon_diffs = abs(lon_diffs);\n    lon_diffs2 = lon_diffs(2:end) - lon_diffs(1:end-1);\n    if all(lat_diffs2 == 0) && all(lon_diffs2 == 0)\n        % Regular grid, create a georasterref object to get eddy's centroid\n        geo_raster_lat_limit = [lat(1) lat(end)];\n        if lon(1) > lon(end)\n            geo_raster_lon_limit = [lon(1) (360 + lon(end))];\n        else\n            geo_raster_lon_limit = [lon(1) lon(end)];\n        end\n\n        R = georasterref('LatLim', geo_raster_lat_limit, 'LonLim', geo_raster_lon_limit, 'RasterSize', ...\n         size(ssh_data), 'ColumnsStartFrom', 'south', 'RowsStartFrom', 'west');\n    else\n        % Use normal indexing to get eddy's centroid\n        R = [];\n    end\n    disp('About to get extrema');\n    \n    extrema = get_extrema(ssh_data, cyc);\n    disp('Got extrema');\n    if isPadding\n        origExtrema = extrema;\n        extrema = [zeros(size(extrema, 1), 200), extrema, zeros(size(extrema, 1), 200)];\n        sshExtended = [ssh_data(:, end-199:end), ssh_data(:, :), ssh_data(:, 1:200)];\n        [extrema_lat_indexes, extrema_lon_indexes] = ind2sub(size(extrema), find(extrema == 1));\n\n        extrema(:, 1:200) = origExtrema(:, end-199:end);\n        extrema(:, end-199:end) = origExtrema(:, 1:200);\n    else\n        [extrema_lat_indexes, extrema_lon_indexes] = ind2sub(size(extrema), find(extrema == 1));\n        sshExtended = ssh_data;\n    end\n        \n    disp('Scanning');\n    eddies = new_eddy();\n    eddies(length(extrema_lat_indexes)).Date = NaN;\n    cyc_sshExtended = sshExtended * cyc;\n    parfor i = 1:length(extrema_lat_indexes) % Normally a parfor. Modified to a for loop solely for itasca testing\n        curr_lat_index = extrema_lat_indexes(i); curr_lon_index = extrema_lon_indexes(i);\n        e = thresholdBU(cyc, curr_lat_index-5, curr_lat_index+5, curr_lon_index-5, curr_lon_index+5, ...\n            sshExtended, extrema, curr_lat_index, curr_lon_index, sshExtended(curr_lat_index, curr_lon_index), ...\n            thresholdStep, NaN, ...\n            zeros(size(sshExtended)), lat, lon, R, areamap, minimumArea, isPadding, cyc_sshExtended);\n        %disp(e);\n        if ~isempty(e.Stats)\n            %disp(['Adding eddy at index: ', num2str(i)]);\n            %disp(e);\n            eddies(i) = e;\n        end\n    end\n    %lat_array = [eddies.Lat];\n    %disp(lat_array);\n    mask = false(1, length(eddies));\n    for i = 1:length(eddies)\n        if isempty(eddies(i).Lat)\n    %        disp(['Empty lat array index at ', num2str(i)]);\n            mask(i) = true;\n        end\n    end\n    disp('Scanned');\n    %mask = cellfun('isempty', {eddies.Lat});\n    eddies = eddies(~mask);\n    %lat_array = [eddies.Lat];\n    %disp(lat_array);\nend\n\nfunction [eddy] = thresholdBU(cyc, block_bottom_index, block_top_index, block_left_index, block_right_index, ...\n        ssh, extrema, extrema_lat_index, extrema_lon_index, thresh, threshold_step, last_step, previous, ...\n        lat, lon, R, areamap, min_pixel_size, is_padding, cyc_ssh)\n% THRESHOLDBU Get an eddy by bottom up method\n%   cyc: 1 for anticyclonic and -1 for cyclonic\n%   block_bottom(top/left/right)_index: index of the bottom/top/left/right of the block that will be used for\n%   thresholding\n%   ssh: ssh data(extended if is_padding is true)\n%   extrema: logical index of ssh extrema\n%   extrema_lat/lon_index: lat/lon index of the extremum that is being used to find an eddy\n%   thresh: current threshold that is being used to find an eddy\n%   threshold_step: the step to increase/decrease threshold value, based on eddy type\n%   last_step: the last step was used for thresholding\n%   previous: 2d logical array of the connected component that contains the extremum in the last thresholdBU call\n%   lat: 1d array of latitudes of the ssh grid\n%   lon: 1d array of longitudes of the ssh grid\n%   R: the georasterref object for SSH grid\n%   areamap: 1D or 2D array of reference to area of each pixel in SSH grid\n%   min_pixel_size: minimum number of pixels for an eddy\n%   is_padding: whether or not the SSH data is padded\n    \n    switch cyc\n        case 1\n            intensity = 'MaxIntensity';\n        case -1\n            intensity = 'MinIntensity';\n        otherwise\n            error('Invalid cyc');\n    end\n\n    if block_bottom_index < 1 || block_top_index > size(ssh, 1) || ...\n            block_left_index < 1 || block_right_index > size(ssh, 2)\n        edgeOfWorld = true;\n        \n        while block_bottom_index < 1 || block_top_index > size(ssh, 1) || ...\n            block_left_index < 1 || block_right_index > size(ssh, 2)\n            % Make sure that the block is inside the grid\n        \n            block_bottom_index = block_bottom_index + 1;\n            block_top_index = block_top_index - 1;\n            block_left_index = block_left_index + 1;\n            block_right_index = block_right_index - 1;\n            if block_top_index <= block_bottom_index + 2 || block_right_index <= block_left_index + 2\n                % If the block is too small, just return an empty eddy\n                eddy = new_eddy();\n                return;\n            end\n        end\n        \n        block = ssh(block_bottom_index:block_top_index, block_left_index:block_right_index);\n        \n        extremaBlock = extrema(block_bottom_index:block_top_index, block_left_index:block_right_index);\n\n    else\n        edgeOfWorld = false;\n        block = ssh(block_bottom_index:block_top_index, block_left_index:block_right_index);\n        extremaBlock = extrema(block_bottom_index:block_top_index, block_left_index:block_right_index);\n    end\n    \n    if isnan(last_step)\n        step = threshold_step;\n    else\n        step = last_step;\n    end\n    \n    iter = 1;\n    while true\n        iter = iter+1;\n        if iter > 5000\n\n            perim = imdilate(logical(current), ones(3)) & ~logical(current);\n            if all(isnan(block(perim)))\n                eddy = new_eddy();\n                return;\n            end\n            disp('potential infinite loop')\n        end\n\n        bw = cyc .* block >= cyc .* thresh;\n        labels = bwlabel(bw);\n\n        extrema_label = labels(extrema_lat_index - block_bottom_index + 1, extrema_lon_index - block_left_index + 1);\n        current = labels == extrema_label;\n        currentExtrema = extremaBlock(current);\n        \n        existing_pixel_at_box_edge = outterRing(labels, extrema_label);\n\n        if sum(currentExtrema) > 1 || ( edgeOfWorld && existing_pixel_at_box_edge)\n            \n            if step ~= threshold_step\n                % Go back to last threshold\n                thresh = thresh + cyc*step;\n                step = threshold_step;\n                thresh = thresh - cyc*step;\n                continue;\n            end\n\n            if size(block, 1) ~= size(previous(block_bottom_index:block_top_index, block_left_index:block_right_index), 1)\n                prevBlock = block(2:end-1, 2:end-1);\n            else\n                prevBlock = block;\n            end\n\n            perim = imdilate(logical(previous(block_bottom_index:block_top_index, block_left_index:block_right_index)), ones(3)) ...\n                & ~logical(previous(block_bottom_index:block_top_index, block_left_index:block_right_index));\n            nan = isnan(prevBlock(perim));\n            if sum(nan) / length(nan) > .3\n                %if more than half of your perimeter is land, then throw it out.\n                eddy = new_eddy();\n                return;\n            end\n\n            if sum(previous(:)) < min_pixel_size\n                    eddy = new_eddy();\n                    return;\n            end\n\n            perim = bwperim(previous);\n            meanPerim = mean(ssh(logical(perim)));\n            amp = cyc * (ssh(extrema_lat_index, extrema_lon_index)-meanPerim);\n            \n            stats = regionprops(previous, ssh, 'Area', 'Extrema',...\n                'PixelIdxList', intensity, 'ConvexImage', 'PixelList', ...\n                'Solidity', 'Extent', 'Orientation', 'MajorAxisLength', ...\n                'MinorAxisLength');\n            \n            stats.Intensity = stats.(intensity);\n            stats = rmfield(stats, intensity);\n            \n            if is_padding\n                [idx, r, c] = extidx2original(stats.PixelIdxList, [length(lat) length(lon)], size(ssh));\n                stats.PixelIdxList = idx; \n            else\n                [r, c] = ind2sub(size(ssh), stats.PixelIdxList);\n            end\n            \n            stats.PixelList = [r, c];\n\n            % Getting geodesic speed\n            if is_padding\n                geoSpeed = mean_geo_speed(ssh(:, 201:end-200), stats.PixelIdxList, lat, lon);\n                if ~isempty(R)\n                    [elat, elon] = weighted_centroid(cyc_ssh(:, 201:end-200), stats.PixelList, stats.PixelIdxList, R);\n                else\n                    [elat, elon] = weighted_centroid_irregular_grid(cyc_ssh(:, 201:end-200), stats.PixelList, stats.PixelIdxList, lat, lon);\n                end\n            else\n                geoSpeed = mean_geo_speed(ssh, stats.PixelIdxList, lat, lon);\n                if ~isempty(R)\n                    [elat, elon] = weighted_centroid(cyc_ssh, stats.PixelList, stats.PixelIdxList, R);\n                else\n                    [elat, elon] = weighted_centroid_irregular_grid(cyc_ssh, stats.PixelList, stats.PixelIdxList, lat, lon);\n                end\n            end\n            \n            % weighted_centroid returns lon from 0-360, fix this\n            % TODO: should we also fix lat lon -270 to 80?\n            elon = (elon > 180).*(elon - 360) + (elon <= 180).*elon;\n            \n            % Getting surface area of the eddy\n            if all(size(areamap) == [length(lat) length(lon)]) \n                % area is 2D array for areas of pixels at [lat, lon]\n                sarea = sum(areamap(stats.PixelIdxList));\n            elseif any(size(areamap) == [1 1]) && length(areamap) == length(lat) \n                % Area is 1D array for areas of pixels at a specific latitude\n                sarea = sum(areamap(stats.PixelList(:, 1)));\n            else\n                % Invalid areamap\n                sarea = NaN;\n            end\n            \n            eddy = new_eddy(rmfield(stats, 'PixelList'), amp, elat, elon, thresh, sarea, cyc, geoSpeed, 'ESv2');\n\n            return\n        end\n\n        if existing_pixel_at_box_edge\n            %disp('expanding size');\n            eddy = thresholdBU(cyc, block_bottom_index-1, block_top_index+1, block_left_index-1,...\n                block_right_index+1, ssh, extrema, extrema_lat_index, extrema_lon_index, thresh, threshold_step, ...\n                step, previous, lat, lon, R, areamap, min_pixel_size, ...\n                is_padding, cyc_ssh);\n            return\n        end\n\n        previous(block_bottom_index:block_top_index, block_left_index:block_right_index) = current;\n        \n        step = step * 2; % double the step for less number of iterations\n        thresh = thresh - cyc*step;\n    end\n\nend\n\nfunction [ extrema ] = get_extrema( ssh, cyc )\n%GET_EXTREMA Returns a matrix containing all of the minima or maxima\n%(depending on the value of cyc) in a 5x5 matrix within the 2D ssh field.\n% ssh: ssh slice containing NaNs for land\n% cyc: 1 for anticyclonic, -1 for cyclonic\n\n    padded = [ssh(:,end-1:end) ssh(:,:) ssh(:,1:2)];\n    padded(isnan(padded)) = cyc*-Inf;\n    padded = padarray(padded, [1, 1], cyc*-Inf);\n    n = ones(5); n(3, 3) = 0;\n    padded = cyc .* padded; % Want to find right extrema for cyclonic and anticyc eddies\n\n    extrema = padded > imdilate(padded, n);\n    extrema = extrema(2:end-1, 4:end-3);\nend\n\nfunction [res] = outterRing(box, val)\n    ring = [box(1, 1:end)'; box(end, 1:end)'; box(1:end, 1); box(1:end, end)];\n    res = any(ring == val);\nend\n\nfunction [idx, row, col] = extidx2original(idx, original_size, extended_size)\n%EXTIDX2ORIGINAL Convert from extended indexes to original indexes\n    [row, col] = ind2sub(extended_size,idx);\n    \n    offright = col > (extended_size(2) + original_size(2)) / 2;\n    offleft = col < (extended_size(2) - original_size(2)) / 2 + 1;\n    notoff = ~(offleft | offright);\n    col(offright)=col(offright) - (extended_size(2) + original_size(2)) / 2;\n    col(offleft) = col(offleft) + original_size(2) - (extended_size(2) - original_size(2)) / 2;\n    col(notoff)=col(notoff) - (extended_size(2) - original_size(2)) / 2;\n    \n    idx = sub2ind(original_size,row,col);\nend\n\nfunction mean_speed = mean_geo_speed(ssh, pixels, lat, lon)\n%MEAN_GEO_SPEED Returns the mean geostrophic speed for pixels.\n% lat and lon should yield the correct values for indices of ssh.\n\n    g = 980.665; % cm/s\n    omega = 7.2921e-5;\n    [x, y] = ind2sub(size(ssh), pixels);\n    lats = lat(x);\n    f = 2*omega*sin(lats);\n    f(f == 0) = 2*omega*sin(0.25); % f is coriolis frequency\n    \n    dSSH_y = ssh(sub2ind(size(ssh), x, mod(y, size(ssh, 2))+1)) - ...\n        ssh(sub2ind(size(ssh), x, mod(y-2, size(ssh, 2))+1));\n    dSSH_x = ssh(sub2ind(size(ssh), min(x+1, zeros(size(x)) + size(ssh, 1)), y))...\n        - ssh(sub2ind(size(ssh), max(x-1, ones(size(x))), y));\n\n    dy = deg2km(distance(lat(x), lon(mod(y, size(ssh, 1))+1), lat(x), lon(mod(y-2, size(ssh, 1))+1))) * 100000;\n    dx = (min(x+1, size(ssh, 1)) - max(1, x-1)) .* 111.12 .* 100000 .* 180 ./ (length(lats) - 1);\n    \n    vs = -g .* (dSSH_y) ./ (2.*f .* dy);\n    us = g .* (dSSH_x) ./ (2 .* f .* dx );\n    speeds = sqrt(us .^2 + vs .^2);\n    mean_speed = nanmean(speeds);\nend\n\nfunction [lat, lon] = weighted_centroid(cyc_ssh, pixellist, pixelidxlist, R)\n%WEIGHTED_CENTROID Returns the location of the weighted centroid for the\n%pixels provided\n    %ssh = cyc * ssh;\n    shift = min(cyc_ssh(pixelidxlist));\n    \n    x = pixellist(:, 1);\n    y = pixellist(:, 2);\n    \n    if min(y) == 1 && max(y) == size(cyc_ssh,2)\n        y(y > size(cyc_ssh,2)/2) = y(y > size(cyc_ssh,2)/2) - size(cyc_ssh,2);\n    end\n    \n    mask = ~isnan(cyc_ssh(pixelidxlist));\n    intensities = cyc_ssh(pixelidxlist)+shift;\n    intensities = intensities - min(intensities); % should start from 0\n    \n    xbar = sum(x(mask) .* intensities(mask).^2) / sum(intensities(mask).^2);\n    ybar = sum(y(mask) .* intensities(mask).^2) / sum(intensities(mask).^2);\n    \n    if ybar <= 0\n        ybar = ybar + size(cyc_ssh,2);\n    end\n    \n    [lat, lon] = pix2latlon(R, xbar, ybar);\n\nend\n\nfunction [lat, lon] = weighted_centroid_irregular_grid(cyc_ssh, pixellist, pixelidxlist, lats, lons)\n%WEIGHTED_CENTROID_IRREGULAR_GRID Returns the location of the weighted centroid for the\n%pixels provided\n    %ssh = cyc * ssh;\n    shift = min(cyc_ssh(pixelidxlist));\n    \n    x = pixellist(:, 1);\n    y = pixellist(:, 2);\n    \n    if min(y) == 1 && max(y) == size(cyc_ssh,2)\n        y(y > size(cyc_ssh,2)/2) = y(y > size(cyc_ssh,2)/2) - size(cyc_ssh,2);\n    end\n    \n    mask = ~isnan(cyc_ssh(pixelidxlist));\n    intensities = cyc_ssh(pixelidxlist)+shift;\n    intensities = intensities - min(intensities); % should start from 0\n    xbar = sum(x(mask) .* intensities(mask).^2) / sum(intensities(mask).^2);\n    ybar = sum(y(mask) .* intensities(mask).^2) / sum(intensities(mask).^2);\n    \n    if ybar <= 0\n        ybar = ybar + size(cyc_ssh,2);\n    end\n\n    x_lower = floor(xbar);\n    x_upper = ceil(xbar);\n    if x_lower == 0\n        lat = lats(1);\n    elseif x_upper == length(lats) + 1\n        lat = lats(end);\n    else\n        lat_lower = lats(x_lower);\n        lat_upper = lats(x_upper);\n        lat = lat_lower + (lat_upper - lat_lower) * (xbar - x_lower) / (x_upper - x_lower);\n        if isnan(lat)\n            lat = 90;\n        end\n    end\n    y_lower = floor(ybar);\n    y_upper = ceil(ybar);\n    if y_lower == 0\n        lon = lons(1);\n    elseif y_upper == length(lons) + 1\n        lon = lons(end);\n    else\n        lon_lower = lons(y_lower);\n        lon_upper = lons(y_upper);\n        if lon_upper - lon_lower > 180\n            lon_upper = lon_upper - 360;\n        elseif lon_lower - lon_upper > 180\n            lon_lower = lon_lower - 360;\n        end\n        lon = lon_lower + (lon_upper - lon_lower) * (ybar - y_lower) / (y_upper - y_lower);\n    end\n\nend\n\n\nfunction eddy = new_eddy(STATS, amplitude, lat, lon, thresh, sa, cyc, geospeed, detect)\n%NEW_EDDY Initializes new eddy objects, run with no arguments to create an\n%empty matrix\n    if nargin\n        eddy = struct('Stats', STATS, ...\n            'Lat', lat, ...\n            'Lon', lon, ...\n            'Amplitude', amplitude, ...\n            'ThreshFound', thresh, ...\n            'SurfaceArea', sa, ...\n            'Date', NaN, ...\n            'Cyc', cyc, ...\n            'MeanGeoSpeed', geospeed, ...\n            'DetectedBy', detect);\n    else\n        eddy = struct('Stats', [], ...\n            'Lat', [], ...\n            'Lon', [], ...\n            'Amplitude', [], ...\n            'ThreshFound', [], ...\n            'SurfaceArea', [], ...\n            'Date', [], ...\n            'Cyc', [], ...\n            'MeanGeoSpeed', [], ...\n            'DetectedBy', []);\n    end\nend\n", "meta": {"author": "jfaghm", "repo": "OceanEddies", "sha": "a5e33155f9cc534093c88b1a514b0c8281591755", "save_path": "github-repos/MATLAB/jfaghm-OceanEddies", "path": "github-repos/MATLAB/jfaghm-OceanEddies/OceanEddies-a5e33155f9cc534093c88b1a514b0c8281591755/compiled_code/eddyscan_compiled_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.20241635076459014}}
{"text": "function edgesEvalPlot( algs, nms, cols )\n% Plot edge precision/recall results for directory of edge images.\n%\n% Enhanced replacement for plot_eval() from BSDS500 code:\n%  http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/\n% Uses same format and is fully compatible with plot_eval. Use this\n% function to plot the edge results created using edgesEvalDir.\n%\n% USAGE\n%  edgesEvalPlot( algs, [nms], [cols] )\n%\n% INPUTS\n%  algs       - {nx1} algorithm result directories\n%  nms        - [{nx1}] algorithm names (for legend)\n%  cols       - [{nx1}] algorithm colors\n%\n% OUTPUTS\n%\n% EXAMPLE\n%\n% See also edgesEvalDir\n%\n% Structured Edge Detection Toolbox      Version 3.0\n% Copyright 2014 Piotr Dollar.  [pdollar-at-microsoft.com]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the MSR-LA Full Rights License [see license.txt]\n\n% parse inputs\nif(nargin<2||isempty(nms)), nms={}; end; if(~iscell(nms)), nms={nms}; end\nif(nargin<3||isempty(cols)), cols=repmat({'r','g','b','k','m'},1,100); end\nif(~iscell(algs)), algs={algs}; end; if(~iscell(cols)), cols={cols}; end\n\n% setup basic plot (isometric contour lines and human performance)\nclf; box on; grid on; hold on;\nline([0 1],[.5 .5],'LineWidth',2,'Color',.7*[1 1 1]);\nfor f=0.1:0.1:0.9, r=f:0.01:1; p=f.*r./(2.*r-f); %f=2./(1./p+1./r)\n  plot(r,p,'Color',[0 1 0]); plot(p,r,'Color',[0 1 0]); end\nif(1), h=plot(0.7235,0.9014,'o','MarkerSize',8,'Color',[0 .5 0],...\n    'MarkerFaceColor',[0 .5 0],'MarkerEdgeColor',[0 .5 0]); end\nset(gca,'XTick',0:0.1:1,'YTick',0:0.1:1);\ngrid on; xlabel('Recall'); ylabel('Precision');\naxis equal; axis([0 1 0 1]);\n\n% load results for every algorithm (pr=[T,R,P,F])\nn=length(algs); hs=zeros(1,n); res=zeros(n,9); prs=cell(1,n);\nfor i=1:n, a=[algs{i} '-eval'];\n  pr=dlmread(fullfile(a,'eval_bdry_thr.txt')); pr=pr(pr(:,2)>=1e-3,:);\n  [~,o]=unique(pr(:,3)); R50=interp1(pr(o,3),pr(o,2),max(pr(o(1),3),.5));\n  res(i,1:8)=dlmread(fullfile(a,'eval_bdry.txt')); res(i,9)=R50; prs{i}=pr;\nend;\n\n% sort algorithms by ODS score\n[~,o]=sort(res(:,4),'descend'); res=res(o,:); prs=prs(o);\ncols=cols(o); if(~isempty(nms)), nms=nms(o); end\n\n% plot results for every algorithm (plot best last)\nfor i=n:-1:1\n  hs(i)=plot(prs{i}(:,2),prs{i}(:,3),'-','LineWidth',3,'Color',cols{i});\n  fprintf('ODS=%.3f OIS=%.3f AP=%.3f R50=%.3f',res(i,[4 7:9]));\n  if(~isempty(nms)), fprintf(' - %s',nms{i}); end; fprintf('\\n');\nend\n\n% show legend if nms provided (report best first)\nhold off; if(isempty(nms)), return; end\nfor i=1:n, nms{i}=sprintf('[F=.%i] %s',round(res(i,4)*100),nms{i}); end\nif(1), hs=[h hs]; nms=['[F=.80] Human'; nms(:)]; end\nlegend(hs,nms,'Location','sw');\n\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/edgeBoxes/releaseV3/edgesEvalPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2024163469654892}}
{"text": "function computeAssociations_Textures_Old(pathUnivariate,pathFeatures,cohorts,outcomes,timeToEvent,featType,textType,textName,nPatient,scale_mat,algo_cell,Ng_mat)\n\n% THIS FUNCTION WAS MODIFIED ON SEPTEMBER 29 TO COMPUTE FUSED TEXTURE\n% RESULTS. PREVIOUS VERSION (WITHOUT FUSED) IS WITH COMMENTED LINES.\n\n\nstartpath = pwd;\ncd(pathUnivariate)\nfid = fopen('Texture_SignificanceProportion.txt','w');\n\nnameOutcomes = fieldnames(outcomes.(cohorts{1})); nOutcomes = numel(nameOutcomes); nCohort = numel(cohorts);\nnFeatType = numel(featType); nTextType = numel(textType);\nnText = 0;\nfor t = 1:nTextType\n    nText = nText + numel(textName{t});\nend\n\n% featureNames = {'Best PET texture - GTVp'; 'Best PET texture - GTVtot'; 'Best CT texture - GTVp'; 'Best CT texture - GTVtot'}; nFeature = numel(featureNames); \nfeatureNames = {'Best PET texture - GTVp'; 'Best PET texture - GTVtot'; 'Best CT texture - GTVp'; 'Best CT texture - GTVtot'; 'Best PET/CT texture - GTVp'; 'Best PET/CT texture - GTVtot'}; nFeature = numel(featureNames); \nrsMat_Binary = zeros(nFeature,nOutcomes); pMat_Binary = zeros(nFeature,nOutcomes); pCell_Binary = cell(nFeature,nOutcomes); stringCell_Binary = cell(nFeature,nOutcomes); nameTextCell_Binary = cell(nFeature,nOutcomes);\nrsMat_Time = zeros(nFeature,nOutcomes); pMat_Time = zeros(nFeature,nOutcomes); pCell_Time = cell(nFeature,nOutcomes); stringCell_Time = cell(nFeature,nOutcomes); nameTextCell_Time = cell(nFeature,nOutcomes);\n% scans = {'PT','CT'}; nScans = numel(scans); nParams = [numel(scale_mat)*numel(algo_cell)*numel(Ng_mat),numel(scale_mat)*numel(algo_cell)*numel(Ng_mat)]; paramSizes = {[numel(scale_mat),numel(algo_cell),numel(Ng_mat)],[numel(scale_mat),numel(algo_cell),numel(Ng_mat)]};\nscans = {'PT','CT','PTCT'}; nScans = numel(scans); nParams = [numel(scale_mat)*numel(algo_cell)*numel(Ng_mat),numel(scale_mat)*numel(algo_cell)*numel(Ng_mat),numel(CTweight_mat)*numel(scale_mat)*numel(algo_cell)*numel(Ng_mat)]; paramSizes = {[numel(scale_mat),numel(algo_cell),numel(Ng_mat)],[numel(scale_mat),numel(algo_cell),numel(Ng_mat)],[numel(CTweight_mat),numel(scale_mat),numel(algo_cell),numel(Ng_mat)]};\nnPat = 0;\nfor c = 1:nCohort\n    nPat = nPat + nPatient.(cohorts{c});\nend\ni = 0;\nfor scan = 1:nScans\n    nParam = nParams(scan);\n    paramSize = paramSizes{scan};\n    textParamName = cell(1,nText*nParam); count = 0;\n    for t = 1:numel(textType)\n        for tStr = 1:numel(textName{t})\n            for p = 1:nParam\n                count = count + 1;\n                if numel(paramSize) == 3\n                    [aa,bb,cc] = ind2sub(paramSize,p);\n                    textParamName{count} = [textType{t},'/',textName{t}{tStr},' -- ','Scale=',num2str(scale_mat(aa)),',Quant.algo=',algo_cell{bb},',Ng=',num2str(Ng_mat(cc))];\n                elseif numel(paramSize) == 4 % Remove this if fused is not used.\n                    [aa,bb,cc,dd] = ind2sub(paramSize,p);\n                    textParamName{count} = [textType{t},'/',textName{t}{tStr},' -- ','CTweight=',num2str(CTweight_mat(aa),'%.2f'),',Scale=',num2str(scale_mat(bb)),',Quant.algo=',algo_cell{cc},',Ng=',num2str(Ng_mat(dd))];\n                end\n            end\n        end\n    end\n    for type = 1:nFeatType\n        i = i + 1; textMat = zeros(nPat,nText*nParam); countPat = 0;\n        outcomeMat = zeros(nPat,nOutcomes);\n        timeMat = zeros(nPat,nOutcomes);\n        cd(pathFeatures)\n        for c = 1:nCohort\n            cohort = cohorts{c};\n            text = load(['text_',cohort,'_',scans{scan},'_',featType{type}]); text = struct2cell(text); text = text{1};\n            patientVect = (countPat+1):(countPat+nPatient.(cohort)); countPat = countPat + nPatient.(cohort);\n            count = 0;\n            for t = 1:numel(textType)\n                for tStr = 1:numel(textName{t})\n                    for p = 1:nParam\n                        count = count + 1;\n                        if numel(paramSize) == 3\n                            [aa,bb,cc] = ind2sub(paramSize,p);\n                            textMat(patientVect,count) = text{aa,bb,cc}.(textType{t}).(textName{t}{tStr}).Data;\n                        elseif numel(paramSize) == 4 % Remove this if fused is not used.\n                            [aa,bb,cc,dd] = ind2sub(paramSize,p);\n                            textMat(patientVect,count) = text{aa,bb,cc,dd}.(textType{t}).(textName{t}{tStr}).Data;\n                        end\n                    end\n                end\n            end\n            for j = 1:nOutcomes\n                outcomeMat(patientVect,j) = outcomes.(cohort).(nameOutcomes{j});\n                timeMat(patientVect,j) = timeToEvent.(cohort).(nameOutcomes{j});\n            end\n        end\n        cd(pathUnivariate)\n        for j = 1:nOutcomes\n            outcome = outcomeMat(:,j);\n            time = timeMat(:,j);\n            [rsTemp,pTemp] = corr(textMat,outcome,'type','Spearman','rows','pairwise'); temp = abs(rsTemp);\n            [significance] = benjamini_hochberg(pTemp,0.10); proportion = sum(significance)/numel(significance);\n            if proportion > 0\n                starB = '*';\n            else\n                starB = '';\n            end\n            fprintf(fid,['Proportion of significant textures: ',scans{scan},', ',featType{type},', ',nameOutcomes{j},', Binary: ',num2str(proportion),'\\n']);\n            [~,indMax] = max(temp);\n            rsMat_Binary(i,j) = rsTemp(indMax); pMat_Binary(i,j) = pTemp(indMax); nameTextCell_Binary{i,j} = textParamName{indMax};\n            pCell_Binary{i,j} = pTemp; \n            [rsTemp,pTemp] = corr(textMat,time,'type','Spearman','rows','pairwise'); temp = abs(rsTemp);\n            [significance] = benjamini_hochberg(pTemp,0.10); proportion = sum(significance)/numel(significance);\n            if proportion > 0\n                starT = '*';\n            else\n                starT = '';\n            end\n            fprintf(fid,['Proportion of significant textures: ',scans{scan},', ',featType{type},', ',nameOutcomes{j},', Time: ',num2str(proportion),'\\n']);\n            [~,indMax] = max(temp);\n            rsMat_Time(i,j) = rsTemp(indMax); pMat_Time(i,j) = pTemp(indMax); nameTextCell_Time{i,j} = textParamName{indMax};\n            pCell_Time{i,j} = pTemp; \n            if pMat_Binary(i,j) < 0.01\n                stringCell_Binary{i,j} = [starB,'rs = ',num2str(rsMat_Binary(i,j),'%.2f'),', p = ',num2str(pMat_Binary(i,j),'%.2i'),starB];\n            else\n                stringCell_Binary{i,j} = [starB,'rs = ',num2str(rsMat_Binary(i,j),'%.2f'),', p = ',num2str(pMat_Binary(i,j),'%.2f'),starB];\n            end\n            if pMat_Time(i,j) < 0.01\n                stringCell_Time{i,j} = [starT,'rs = ',num2str(rsMat_Time(i,j),'%.2f'),', p = ',num2str(pMat_Time(i,j),'%.2i'),starT];\n            else\n                stringCell_Time{i,j} = [starT,'rs = ',num2str(rsMat_Time(i,j),'%.2f'),', p = ',num2str(pMat_Time(i,j),'%.2f'),starT];\n            end\n        end\n    end\nend\ncd(pathUnivariate), fclose(fid);\nLocoregional = stringCell_Binary(:,1); Distant = stringCell_Binary(:,2); Death = stringCell_Binary(:,3);\nresults.tableCorr = table(Locoregional,Distant,Death,'RowNames',featureNames);\nLocoregional = nameTextCell_Binary(:,1); Distant = nameTextCell_Binary(:,2); Death = nameTextCell_Binary(:,3);\nresults.tableTextName = table(Locoregional,Distant,Death,'RowNames',featureNames);\nresults.rsMat = rsMat_Binary; results.pMat = pMat_Binary; results.pCell = pCell_Binary;\nsave('texturesBest_UniV_Binary','results'), clear results\nLocoregional = stringCell_Time(:,1); Distant = stringCell_Time(:,2); Death = stringCell_Time(:,3);\nresults.tableCorr = table(Locoregional,Distant,Death,'RowNames',featureNames);\nLocoregional = nameTextCell_Time(:,1); Distant = nameTextCell_Time(:,2); Death = nameTextCell_Time(:,3);\nresults.tableTextName = table(Locoregional,Distant,Death,'RowNames',featureNames);\nresults.rsMat = rsMat_Time; results.pMat = pMat_Time; results.pCell = pCell_Time;\nsave('texturesBest_UniV_Time','results'), clear results\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/computeAssociations_Textures_Old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.20237229797937564}}
{"text": "% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).\n% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)\n% Copyright: ETH Zurich, 2014\n% Author: Romano Cicchetti\n\nfunction [result] = weiss(evaluation_and_training_days, setup, fid)\n\n    % load parameters of algorithm\n    dataset = setup.dataset;\n    household = setup.household;\n    granularity = setup.granularity;\n    filteringMethod = setup.filtering;\n    filtLength = setup.filtLength;\n    plevelMinLength = setup.plevelMinLength;\n    maxEventDuration = setup.maxEventDuration;\n    eventPowerStepThreshold = setup.eventThreshold;\n    r = setup.r;\n    osc = setup.osc;\n    evaluation_days = evaluation_and_training_days{1};\n    training_days = evaluation_and_training_days{2};\n    appliance = setup.appliance;\n    \n    % set variables\n    edgeThreshold = 2;\n    num_measurements = size(evaluation_days,1)*86400;\n\n    % build signature database \n    global caching;\n    if caching == 1\n        if exist('cache_sigdat.mat') == 2\n            load('cache_sigdat');\n        else\n            signature_database = buildSignatureDatabase(setup, training_days);\n            save('cache_sigdat', 'signature_database');\n        end\n    else\n        signature_database = buildSignatureDatabase(setup, training_days);        \n    end\n    \n    signatures = signature_database.signatures;\n    names_of_signatures = signature_database.names;\n    phases_of_signatures = signature_database.phases;\n    % calculate length (2-norm) of each signature\n    numOfSignatures = size(signatures,1);\n    signatureLength = zeros(numOfSignatures,1);\n    for j = 1:numOfSignatures\n        signatureLength(j,1) = norm(signatures(j,:)); \n    end\n    signature_database.signatureLength = signatureLength;\n    \n    % write signatures to text file\n    fprintf(fid,'%20s %13s %16s %9s\\n', 'appliance:', 'true power:', 'reactive power:', 'phase:');\n    for i = 1:size(signatures,1)\n        fprintf(fid,'%20s %13.2f %16.2f %9s\\n', cell2mat(names_of_signatures(i)), signatures(i,1),...\n             signatures(i,2), num2str(phases_of_signatures(i,1)));\n    end\n    fprintf(fid, '\\n\\n'); \n\n    result = struct;\n    result.events = [];  \n    result.appliance_names = {};\n    \n    input_params = struct;\n    input_params.dataset = dataset;\n    input_params.household = household;\n    input_params.evaluation_days = evaluation_days;\n    input_params.granularity = granularity;\n    input_params.filtering_method = filteringMethod;\n    input_params.filtLength = filtLength;\n    input_params.edgeThreshold = filtLength;\n    input_params.plevelMinLength = plevelMinLength;\n    input_params.eventPowerStepThreshold = eventPowerStepThreshold;\n    input_params.maxEventDuration = maxEventDuration;\n    \n    % Disaggregate all appliances or individual appliance?\n    if strcmp(appliance, 'Stove') == 1\n        [events, times] = get_events_of_multi_phase_appliance(input_params);\n        matching_ids = find(strcmp(signature_database.names, 'Stove'));\n        stove_sig = signatures(matching_ids,:);\n        result = infer_events_stove(result, events, times, min(stove_sig(stove_sig > 0))-200);\n        [result.usage, result.usage_times_start] = infer_usage(appliance, result.events(:,3), result.events(:,1), num_measurements, setup.usage_duration);\n        result.consumption = infer_consumption_stove(result.events(:,3), result.events(:,1), num_measurements, setup.usage_duration);\n\n    elseif strcmp(appliance, 'Dishwasher') == 1\n        applianceID = getApplianceID(appliance);\n        phase = getPhase(household, applianceID, dataset);\n        [events, times] = get_events_of_single_phase_appliance(phase, input_params);\n        result = infer_events(result, events, times, signature_database, phase, setup, appliance);\n        [result.usage, result.usage_times_start] = infer_usage(appliance, result.events(:,3), result.events(:,1), num_measurements, setup.usage_duration);\n        result.consumption = infer_consumption(result, evaluation_and_training_days, setup.usage_duration, appliance, setup);\n\n    elseif strcmp(appliance, 'Water kettle') == 1 || strcmp(appliance, 'TV') == 1 || strcmp(appliance, 'Stereo') == 1\n            applianceID = getApplianceID(appliance);\n            phase = getPhase(household, applianceID, dataset);\n            [events, times] = get_events_of_single_phase_appliance(phase, input_params);\n            result = infer_events(result, events, times, signature_database, phase, setup, appliance);\n            [result.usage, result.usage_times_start] = infer_usage(appliance, result.events(:,3), result.events(:,1), num_measurements, setup.usage_duration);\n            result.consumption = infer_consumption(result, evaluation_and_training_days, setup.usage_duration, appliance, setup);\n    elseif strcmp(appliance, 'Fridge') == 1 || strcmp(appliance, 'Freezer') == 1\n            applianceID = getApplianceID(appliance);\n            phase = getPhase(household, applianceID, dataset);\n            [events, times] = get_events_of_single_phase_appliance(phase, input_params);\n            result = infer_events(result, events, times, signature_database, phase, setup, appliance);\n            result.consumption = infer_consumption(result, evaluation_and_training_days, setup.usage_duration, appliance, setup);\n    elseif strcmp(appliance, 'Laptop') == 1\n            applianceID = getApplianceID(appliance);\n            phase = getPhase(household, applianceID, dataset);\n            [events, times] = get_events_of_single_phase_appliance(phase, input_params);\n            result = infer_events(result, events, times, signature_database, phase, setup, appliance);\n%             result.consumption = infer_consumption(result, evaluation_and_traini            \n    elseif strcmp(appliance, 'All')\n\n        %% \"Old\": all appliances\n        signatures_in_previous_phases = 0;\n        for phase = 1:3\n            if caching == 1\n                error('Does not work with caching - run without caching');\n            end\n           [event_vecs, timeOfEvents] = get_events_of_single_phase_appliance(phase, input_params);\n            % assign each event to its best match in the signature database\n            [signatureIDs, dist] = knnsearch(signatures(phases_of_signatures == phase, 1:2), event_vecs(:,1:2));        \n            if ~isempty(signatureIDs)\n                dist_threshold = r*signatureLength(signatureIDs,1) + event_vecs(:,4);\n                matching_valid = dist < dist_threshold;\n                %% should te next line not be earlier???\n                signatureIDs = signatureIDs + signatures_in_previous_phases;\n                result.events = [result.events; timeOfEvents(matching_valid), signatureIDs(matching_valid), event_vecs(matching_valid, 1:3)];\n                signatures_in_previous_phases = signatures_in_previous_phases + nnz(phases_of_signatures == phase);\n            end\n        end\n        \n    else\n        error('Appliance not supported');\n    end\n    \n    % store labeled events\n    for i = 1:length(names_of_signatures)\n        if ismember(cell2mat(names_of_signatures(i)), result.appliance_names)\n            result.events(result.events(:,2) == i,2) = find(ismember(result.appliance_names, names_of_signatures{i}));\n        else\n            % do nothing if signature is not in signature database\n            % result.appliance_names{end+1} = cell2mat(names_of_signatures(i));\n            % result.events(result.events(:,2) == i,2) = length(result.appliance_names);\n        end\n    end        \nend\n\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/algorithms/weiss_alg/weiss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.20231924992543907}}
{"text": "function model = yalmip2nonlinearsolver(model)\n\nglobal newmodel\n\nnewmodel = 1;\n\nmodel.dense = 0;\nif ~model.equalitypresolved\n    model = propagate_bounds_from_equalities(model);\nend\n\nK = model.K;\nlb = model.lb;\nub = model.ub;\nx0 = model.x0;\nc = model.c;\n\n% Pick out the positive conditions from cones ||Ax+b|| <= c'*x+d which will\n% be treated as (Ax+b)'*(ax+b) <= (c'*x+d)^2,  c'*x+d >= 0\nif any(K.q)\n    aux = [];\n    top = 1 + K.f + K.l;\n    for i = 1:length(K.q)\n        row = model.F_struc(top,:);\n        if any(row(2:end))\n            aux = [aux;row];\n        end\n        top = top + model.K.q(i);\n    end\n    model.F_struc = [model.F_struc(1:K.f+K.l,:);aux;model.F_struc(K.f+K.l+1:end,:)];\n    model.K.l = model.K.l + size(aux,1);\nend\n\nif isempty(model.evaluation_scheme)\n    model = build_recursive_scheme(model);\nend\nmodel = compress_evaluation_scheme(model);\n\n% Do some pre-calc to be used in calls from fmincon\nnonlinearindicies = union(find(model.variabletype~=0),model.evalVariables);\nlinearindicies    = setdiff(find(model.variabletype==0),nonlinearindicies);\nmodel.nonlinearindicies = nonlinearindicies;\nmodel.linearindicies    = linearindicies;\n\nmodel.Anonlinineq = [];\nmodel.bnonlinineq = [];\nmodel.Anonlineq = [];\nmodel.bnonlineq = [];\n\n% Extract linear and nonlinear equality constraints\nif K.f>0\n    Aeq = -model.F_struc(1:1:K.f,2:end);\n    beq = model.F_struc(1:1:model.K.f,1);\n    \n    nonlinear_equalities_indicies = find(any(Aeq(:,nonlinearindicies),2));\n    model.Anonlineq = Aeq(nonlinear_equalities_indicies,:);\n    model.bnonlineq = beq(nonlinear_equalities_indicies);\n    \n    Aeq(nonlinear_equalities_indicies,:) = [];\n    beq(nonlinear_equalities_indicies,:) = [];\n    Aeq(:,nonlinearindicies) = [];\n    model.F_struc(1:model.K.f,:) = [];\n    model.K.f = 0;\nelse\n    Aeq = [];\n    beq = [];\nend\n\n% Find nonlinear eualities implied by lower and upper bounds\nif ~isempty(ub) && ~isempty(lb)\n    nonlinearequality = find(lb(nonlinearindicies) == ub(nonlinearindicies));\n    if ~isempty(nonlinearequality)\n        for i = 1:length(nonlinearequality)\n          %  model.Anonlineq = [model.Anonlineq;eyev(length(c),nonlinearindicies(nonlinearequality(i)))'];\n            model.Anonlineq = [model.Anonlineq;sparse(1,nonlinearindicies(nonlinearequality(i)),1,1,length(c))];\n            model.bnonlineq = [model.bnonlineq;lb(nonlinearindicies(nonlinearequality(i)))];\n        end\n    end\nend\n\n% Extract linear and nonlinear inequality constraints\nif model.K.l>0\n    A = -model.F_struc(1:model.K.l,2:end);\n    b = model.F_struc(1:model.K.l,1);\n    \n    nonlinear_inequalities_indicies = find(any(A(:,nonlinearindicies),2));\n    \n    model.Anonlinineq = A(nonlinear_inequalities_indicies,:);\n    model.bnonlinineq = b(nonlinear_inequalities_indicies);\n    \n    A(nonlinear_inequalities_indicies,:) = [];\n    b(nonlinear_inequalities_indicies,:) = [];\n    A(:,nonlinearindicies) = [];\n    \n    model.F_struc(1:model.K.l,:) = [];\n    model.K.l = 0;\nelse\n    A = [];\n    b = [];\nend\n\n% This helps with robustness in bnb in some cases\nx0candidate = zeros(length(c),1);\nif ~isempty(lb) && ~isempty(ub)\n    bounded = find(~isinf(lb) & ~isinf(ub));\n    x0candidate(bounded) = (lb(bounded) + ub(bounded))/2;\n    bounded_below = find(~isinf(lb) & isinf(ub));\n    x0candidate(bounded_below) = lb(bounded_below) + 0.5;\n    bounded_above = find(~isinf(lb) & isinf(ub));\n    x0candidate(bounded_above) = lb(bounded_above) + 0.5;\nend\n\nif isempty(x0)\n    x0 = x0candidate(linearindicies);\nelse\n    if ~isempty(lb) && ~isempty(ub)\n        x0((x0 < lb) | (x0 > ub)) = x0candidate((x0 < lb) | (x0 > ub));\n    end\n    x0 = x0(linearindicies);\nend\n\nif ~isempty(lb)\n    lb = lb(linearindicies);\nend\nif ~isempty(ub)\n    ub = ub(linearindicies);\nend\n\nlb_old = lb;\nub_old = ub;\n[lb,ub,A,b] = remove_bounds_from_Ab(A,b,lb,ub);\n[lb,ub,Aeq,beq] = remove_bounds_from_Aeqbeq(Aeq,beq,lb,ub);\n\nif any(model.variabletype == 4)\n    problematic = find(any(model.monomtable(:,linearindicies) < 0 ,1));\n    if ~isempty(problematic)\n        problematic = problematic(find(x0(problematic)==0));\n        Oneisfeas = problematic(find(ub(problematic) > 1));\n        x0(Oneisfeas) = 1;\n    end\n    \n    problematic = find(any(model.monomtable(:,linearindicies)~=fix(model.monomtable(:,linearindicies)) ,1));\n    lb(problematic) = max(lb(problematic),0);\nend\nx0(find(lb==ub)) = lb(find(lb==ub));\n    \nif size(A,1) == 0\n    A = [];\nend\n\nif size(b,1) == 0\n    b = [];\nend\n\nif size(Aeq,1) == 0\n    Aeq = [];\nend\n\nif size(beq,1) == 0\n    beq = [];\nend\n\nif model.presolveequalities\n    if ~isempty(beq) &  (~model.equalitypresolved | ~(isequal(lb,lb_old) & isequal(ub,ub_old)))\n        % This helps when there are artificial variables introduced to model\n        % nonlinear operators such as log(2*x+1)\n        p.F_struc = [beq -Aeq];\n        p.K.f = size(beq,1);\n        p.lb = lb;\n        p.ub = ub;\n        p.variabletype = zeros(1,length(lb));\n        p.binary_variables = [];\n        p.integer_variables = [];\n        p = propagate_bounds_from_equalities(p);\n        lb = p.lb;\n        ub = p.ub;\n    end\nend\n\nmodel.A = A;\nmodel.b = b;\nmodel.Aeq = Aeq;\nmodel.beq = beq;\nmodel.lb = lb;\nmodel.ub = ub;\nmodel.x0 = x0;\n\nmodel = setup_fmincon_params(model);\n\n% Check if all derivatives are available\nmodel.derivative_available = 1;\nfor i = 1:length(model.evalMap)\n    if isempty(model.evalMap{i}.properties.derivative)\n        model.derivative_available = 0;\n        break\n    end\nend\n\n% Some precomputation of computational scheme for Jacobian\nallA = [model.Anonlineq;model.Anonlinineq];\nif any(model.K.q)\n    allA = [allA;model.F_struc(1+model.K.f + model.K.f:end,2:end)];\nend\nrequested = any(allA',2);\n[i,j] = find((model.deppattern(find(requested),:)));\nrequested(j) = 1;\nif ~isempty(model.evalMap)\n    % Recursive stuff is only possible if we have evaluation-based\n    % operators\n    model.Crecursivederivativeprecompute = precomputeDerivative(model,requested);\nend\n\n% Some precomputation of computational scheme for gradient\nrequested = model.c | any(model.Q,2);\n[i,j,k] = find((model.deppattern(find(requested),:)));\nrequested(j) = 1;\nmodel.frecursivederivativeprecompute = precomputeDerivative(model,requested);\n\n% Precomputed list of bilinear expressions, used in\n% apply_recursive_differentiation\nmodel = compile_bilinearslist(model);\nmodel = compile_quadraticslist(model);\n\nmodel.binary_variables  = find(ismember(linearindicies,model.binary_variables));\nmodel.integer_variables  = find(ismember(linearindicies,model.integer_variables));\nmodel.semicont_variables  = find(ismember(linearindicies,model.semicont_variables));\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/yalmip2nonlinearsolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.20231254501800727}}
{"text": "%% housekeeping\nclc\n\n%% rise the model\n\nm=rise('pdk','rise_flags',{'Sektors',{'C','I'}},...\n    'steady_state_file','sstate_model',...\n    'saveas',true);\n\n%% get the parameters\n\n[p,priors]=create_parameters(~true);\n\nm=set(m,'parameters',p);\n\n%% get the data\n\ndata=create_data();\n\n%% estimate model\nclc\n\nms=estimate(m,'data',data,'estim_priors',priors,'optimizer','fminunc');\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/PeterIreland/productivity_RED2008/master.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.20202608538426223}}
{"text": "\n% Author: Guosheng Lin (guosheng.lin@gmail.com)\n\n% this is a simpler demo file for testing on your own images.\n\nfunction demo_test_simple_voc()\n\nrng('shuffle');\naddpath('./my_utils');\ndir_matConvNet='../libs/matconvnet/matlab';\nrun(fullfile(dir_matConvNet, 'vl_setupnn.m'));\n\n\nrun_config=[];\n\nrun_config.use_gpu=true;\n% run_config.use_gpu=false;\nrun_config.gpu_idx=1;\n\n\n% result dir:\nresult_name=['runner_result_dir' datestr(now, 'YYYYmmDDHHMMSS')];\nresult_dir=fullfile('../cache_data', 'test_examples_city', result_name);\nmkdir_notexist(result_dir);\n\n\n% the folder that contains testing images:\nimg_data_dir='../datasets/example_imgs_cityscapes';\n\n\n% using a trained model which is trained on VOC 2012\nrun_config.trained_model_path='../model_trained/refinenet_res101_cityscapes.mat';\nrun_config.class_info=gen_class_info_cityscapes();\n\n\n% for trained model, control the size of input images\nrun_config.input_img_short_edge_min=600;\nrun_config.input_img_short_edge_max=1100;\n\nrunner_info=prepare_runner_test_simple(run_config);\n\nimg_filenames=my_list_file(img_data_dir);\nimg_num=length(img_filenames);\nfor img_idx=1:img_num\n    task_info=[];\n    task_info.img_dir=img_data_dir;\n    task_info.img_filename=img_filenames{img_idx};\n    task_result=runner_info.run_task_fn(runner_info, task_info);\n    \n    [~, img_name]=fileparts(task_info.img_filename);\n    one_cache_file=fullfile(result_dir, [img_name '.png']);\n    fprintf('save prediction mask:%s\\n', one_cache_file);\n    imwrite(task_result.mask_data, run_config.class_info.mask_cmap, one_cache_file);\nend\n\n\nend\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/demo_test_simple_city.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.20202608294205807}}
{"text": "function pcc=pro(pc);\n\ntest(1:100)=0;\nl=round(100*pc);\ntest(1:l)=1;\nn=round(rand*99)+1;\npcc=test(n);   ", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/HeuristicAlgorithm\uff08\u8865\u5206\u542f\u53d1\u5f0f\u7b97\u6cd5\uff0c\u5305\u62ec\u795e\u7ecf\u7f51\u7edc\u3001\u6a21\u62df\u9000\u706b\u3001\u9057\u4f20\u7b97\u6cd5\uff09/\u9057\u4f20\u7b97\u6cd5/\u9057\u4f20\u7b97\u6cd5\u6c42\u89e3\u51fd\u6570\u4f18\u5316\u95ee\u9898/pro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.20192150523452673}}
{"text": "% ----------------------------------------------------------------------------\n% function hfssAddMaterial(fid, Name, Er, bSigma, tanDelta)\n%\n% Description :\n% -------------\n% Creates VB Script necessary to add a new material to the HFSS Materials\n% Manager.\n%\n% Parameters :\n% ------------\n% fid      - file identifier of the HFSS script file.\n% Name     - name of the material to be added.\n% Er       - dielectric constant of the material to be added.\n% bSigma   - bulk conductivity of the material to be added (Siemens)\n% tanDelta - loss tangent of the material.\n% \n% Note :\n% ------\n% If a material with the given name already exists in HFSS, this code will\n% have no effect and the script will continue running. A warning message will\n% appear in the HFSS message log.\n%\n% Example :\n% ---------\n% fid = fopen('Dipole.vbs', 'wt');\n% ...\n% hfssAddMaterial(fid, 'CoaxDielectric', 2.07, 0, 0);\n% ----------------------------------------------------------------------------\n\n% ----------------------------------------------------------------------------\n% This file is part of HFSS-MATLAB-API.\n%\n% HFSS-MATLAB-API is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the Free \n% Software Foundation; either version 2 of the License, or (at your option) \n% any later version.\n%\n% HFSS-MATLAB-API is distributed in the hope that it will be useful, but \n% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \n% or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License \n% for more details.\n%\n% You should have received a copy of the GNU General Public License along with\n% Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple \n% Place, Suite 330, Boston, MA  02111-1307  USA\n%\n% Copyright 2004, Vijay Ramasami (rvc@ku.edu)\n% ----------------------------------------------------------------------------\nfunction hfssAddMaterial(fid, Name, Er, bSigma, tanDelta)\n\n% Preamble.\nfprintf(fid, '\\n');\nfprintf(fid, 'oProject.AddMaterial _\\n');\n\n% Name.\nfprintf(fid, 'Array(\"NAME:%s\", _\\n', Name);\n\n% Dielectric Properties.\nfprintf(fid, '\"permittivity:=\", \"%f\", _\\n', Er);\nfprintf(fid, '\"conductivity:=\", \"%f\", _\\n', bSigma); \nfprintf(fid, '\"dielectric_loss_tangent:=\", \"%f\")\\n', tanDelta);", "meta": {"author": "yuip", "repo": "hfss-api", "sha": "93ac0700830f473f1438f335a7fa964383b07abb", "save_path": "github-repos/MATLAB/yuip-hfss-api", "path": "github-repos/MATLAB/yuip-hfss-api/hfss-api-93ac0700830f473f1438f335a7fa964383b07abb/general/hfssAddMaterial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20189535675066908}}
{"text": "function [bbox3M, planC] = crop_for_constrictor(planC,paramS,varargin)\n% Custom crop function for segmentation model\n% AI 10/04/19\n\n%% Limits of bounding box using chewing structures\nindexS = planC{end};\nstrC = {planC{indexS.structures}.structureName};\nbboxIdx = [];\n\n%% Return bounding box if it exists\nif isfield(paramS,'saveStrToPlanCFlag') && paramS.saveStrToPlanCFlag\n    if isfield(paramS,'outStrName')\n        outStrName = paramS.outStrName;\n    else\n        outStrName = 'crop_for_constrictor';\n    end\n    bboxIdx = getMatchingIndex(outStrName,strC,'EXACT');\nend\nif ~isempty(bboxIdx)\n    bbox3M = getStrMask(bboxIdx,planC);\nelse\n    bboxName = paramS.structureName.cropStructure;\n    idx1 = getMatchingIndex(bboxName,strC,'EXACT');\n    scanNum = getStructureAssociatedScan(idx1,planC);\n    [mask3M, planC]  = getStrMask(idx1,planC);\n    if sum(mask3M(:))>0\n        [minr,~,minc,maxc,mins,~] = compute_boundingbox(mask3M);\n    else\n        minr = 1;\n        minc = 1;\n        maxc = size(mask3M,2);\n        mins = 1;\n    end\n    %% Limits of bbox around larynx\n    larynxStrName = paramS.structureName.larynx;\n    idx2 = getMatchingIndex(larynxStrName,strC,'EXACT');\n    [mask3M, planC]  = getStrMask(idx2,planC);\n    if sum(mask3M(:))>0\n        [~,maxr,~,~,~,maxs] = compute_boundingbox(mask3M);\n    else\n        maxr = size(mask3M,1);\n        maxs = size(mask3M,3);\n    end\n\n    %% Get bounding box for constrictors\n    tol_r = 30;\n    tol_s = 15;\n    maxr = min(maxr+tol_r,size(mask3M,1));\n    maxs = min(maxs+tol_s,size(mask3M,3));\n\n    bbox3M = false(size(getScanArray(scanNum,planC)));\n    bbox3M(minr:maxr,minc:maxc,mins:maxs) = true;\nend\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/customProcessing/crop_for_constrictor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2018953509686364}}
{"text": "classdef clusteringGUI < handle\n    \n    properties\n        currentCluster = 1\n        page = 1\n        thumbnail_size = [200 200]\n        clustAssign\n        clusters\n        rejected\n        ClusteringData\n        minfreq\n        maxfreq\n        fig\n        image_axes = gobjects()\n        handle_image = gobjects()\n        ColorData\n        totalCount\n        count\n        clusterName\n        pagenumber\n        finished\n        call_id_text      \n        txtbox\n    end\n    \n    methods\n        function [obj, NewclusterName, NewRejected, NewFinished, NewClustAssign] = clusteringGUI(clustAssign, ClusteringData)\n            \n            \n            \n            obj.clustAssign = clustAssign;\n            %Image, Lower freq, delta time, Time points, Freq points, File path, Call ID in file, power, RelBox\n            obj.ClusteringData = ClusteringData;\n            obj.rejected = zeros(1,length(obj.clustAssign));\n            \n            obj.minfreq = prctile(ClusteringData.MinFreq, 5);\n            obj.maxfreq = prctile(ClusteringData.MinFreq + ClusteringData.Bandwidth, 95);\n            obj.ColorData = jet(256); % Color by mean frequency\n            % obj.ColorData = HSLuv_to_RGB(256, 'H',  [270 0], 'S', 100, 'L', 75, 'type', 'HSL'); % Make a color map for each category\n            obj.ColorData = reshape(obj.ColorData,size(obj.ColorData,1),1,size(obj.ColorData,2));\n            \n            if iscategorical(obj.clustAssign)\n                obj.clusterName =unique(obj.clustAssign);\n                obj.clusters = unique(obj.clustAssign);\n            else\n                obj.clusterName = categorical(unique(obj.clustAssign(~isnan(obj.clustAssign))));\n                obj.clusters = (unique(obj.clustAssign(~isnan(obj.clustAssign))));\n            end\n            \n            obj.fig = dialog('Visible','off','Position',[360,500,600,600],'WindowStyle','Normal','resize', 'on','WindowState','maximized' );\n            obj.fig.CloseRequestFcn = @(src,event) finished_Callback(obj, src, event);\n            set(obj.fig,'color',[.1, .1, .1]);\n            \n            movegui(obj.fig,'center');\n            %             set(obj.fig,'WindowButtonMotionFcn', @(hObject, eventdata) mouse_over_Callback(obj, hObject, eventdata));\n            \n            txt = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.1 .1 .1],...\n                'ForegroundColor','w',...\n                'Style','text',...\n                'Position',[120 565 80 30],...\n                'String','Name:');\n            \n            obj.txtbox = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Style','edit',...\n                'String','',...\n                'Position',[120 550 80 30],...\n                'Callback',@(src,event) txtbox_Callback(obj,src,event));\n            \n            \n            obj.totalCount = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.1 .1 .1],...\n                'ForegroundColor','w',...\n                'Style','text',...\n                'String','',...\n                'Position',[330 542.5 200 30],...\n                'HorizontalAlignment','left');\n            \n            \n            back = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Position',[20 550 80 30],...\n                'String','Back',...\n                'Callback',@(src,event) back_Callback(obj, src, event));\n            \n            next = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Position',[220 550 80 30],...\n                'String','Next',...\n                'Callback',@(src,event) next_Callback(obj, src, event));\n            \n            apply = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Position',[440 550 60 30],...\n                'String','Save',...\n                'Callback',@(src,event)  finished_Callback(obj, src, event));\n            \n            if nargin == 2\n                redo = uicontrol('Parent',obj.fig,...\n                    'BackgroundColor',[.149 .251 .251],...\n                    'ForegroundColor','w',...\n                    'Position',[510 550 60 30],...\n                    'String','Redo',...\n                    'Callback',@(src,event) finished_Callback(obj, src, event));\n            else\n                redo = uicontrol('Parent',obj.fig,...\n                    'BackgroundColor',[.149 .251 .251],...\n                    'ForegroundColor','w',...\n                    'Position',[510 550 60 30],...\n                    'String','Cancel',...\n                    'Callback',@(src,event) finished_Callback(obj, src, event));\n            end\n            %% Paging\n            nextpage = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Position',[220 517 80 30],...\n                'String','Next Page',...\n                'Callback',@(src,event) nextpage_Callback(obj, src, event));\n            \n            backpage = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.149 .251 .251],...\n                'ForegroundColor','w',...\n                'Position',[20 517 80 30],...\n                'String','Previous Page',...\n                'Callback',@(src,event, h) backpage_Callback(obj, src, event));\n            \n            obj.pagenumber = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.1 .1 .1],...\n                'ForegroundColor','w',...\n                'Style','text',...\n                'String','',...\n                'Position',[118 509 80 30],...\n                'HorizontalAlignment','center');\n            \n            \n            obj.call_id_text = uicontrol('Parent',obj.fig,...\n                'BackgroundColor',[.1 .1 .1],...\n                'ForegroundColor','w',...\n                'Style','text',...\n                'String','',...\n                'FontSize',12,...\n                'Position',[100 470 400 30],...\n                'HorizontalAlignment','center');\n            \n            \n            obj.render_GUI();\n            \n            % Wait for d to close before running to completion\n            set( findall(obj.fig, '-property', 'Units' ), 'Units', 'Normalized');\n            obj.fig.Visible = 'on';\n            \n            % Enable pointer management for the figure for mouse hover over\n            iptPointerManager(obj.fig, 'enable');\n                    \n            uiwait(obj.fig);\n            NewclusterName = obj.clusterName;\n            NewRejected = obj.rejected;\n            NewFinished = obj.finished;\n            NewClustAssign = obj.clustAssign;\n            \n        end\n        \n        function render_GUI(obj)\n            \n            %% Colormap\n            xdata = obj.minfreq:obj.maxfreq;\n            caxis = axes(obj.fig,'Units','Normalized','Position',[.88 .05 .04 .8]);\n            image(1,xdata,obj.ColorData,'parent',caxis)\n            caxis.YDir = 'normal';\n            set(caxis,'YColor','w','box','off','YAxisLocation','right');\n            ylabel(caxis, 'Frequency (kHz)')\n            \n            %% Make the axes\n            aspectRatio = median(cellfun(@(im) size(im,1) ./ size(im,2), obj.ClusteringData.Spectrogram));\n            \n            % Choose a number of rows and columns to fill the space with\n            % the average call aspect ratio\n            % nFrames = 10;\n            % figureAspectRatio = 1;\n            % x_grids = sqrt(aspectRatio * figureAspectRatio * nFrames);\n            % x_grids = ceil(x_grids);\n            % y_grids = ceil(nFrames / x_grids);\n        \n            obj.thumbnail_size = round(sqrt(20000 .* [aspectRatio, 1/aspectRatio]));\n\n            axes_spacing = .70; % Relative width of each image\n            y_range = [.05, .75]; % [Start, End] of the grid\n            x_range = [.05, .85];\n            x_grids = 9; % Number of x grids\n            y_grids = 3; % Number of y grids\n\n            ypos = linspace(y_range(1), y_range(2) - axes_spacing * range(y_range) / y_grids, y_grids );\n            xpos = linspace(x_range(1), x_range(2) - axes_spacing * range(x_range) / x_grids, x_grids );\n            xpos = fliplr(xpos);\n\n            pos = [];\n            for i = 1:length(ypos)\n                for j = 1:length(xpos)\n                    pos(end+1,:) = [xpos(j), ypos(i), (xpos(1)-xpos(2)) * axes_spacing, (ypos(2)-ypos(1)) * axes_spacing];\n                end\n            end\n            pos = flipud(pos);\n            for i = 1 : length(ypos) * length(xpos)\n                    im = zeros([obj.thumbnail_size, 3]);\n                    obj.image_axes(i) = axes(obj.fig,'Units','Normalized','Position',pos(i,:));\n                    obj.handle_image(i) = image(im,'parent',obj.image_axes(i));\n                    set(obj.image_axes(i),'Visible','off')\n                    set(get(obj.image_axes(i),'children'),'Visible','off');\n            end\n            plotimages(obj);\n        end\n        \n        function [colorIM, rel_x, rel_y] = create_thumbnail(obj, ClusteringData,clustIndex,callID)\n            % Resize the image while maintaining the aspect ratio by\n            % padding with zeros\n            im_size = size(ClusteringData.Spectrogram{clustIndex(callID)}) ;\n            new_size = floor(im_size .* min(obj.thumbnail_size ./ im_size));\n            im = double(imresize(ClusteringData.Spectrogram{clustIndex(callID)}, new_size));\n            pad = (obj.thumbnail_size - size(im)) / 2;\n            im = padarray(im, floor(pad), 'pre');\n            im = padarray(im, ceil(pad), 'post');\n            \n            % Relative offsets for setting the tick values\n            rel_size = pad ./ obj.thumbnail_size;\n            rel_x = [rel_size(2), 1-rel_size(2)];\n            rel_y = [rel_size(1), 1-rel_size(1)];\n            \n            % Apply color to the greyscale images\n            freqRange = [ClusteringData.MinFreq(clustIndex(callID)),...\n                ClusteringData.MinFreq(clustIndex(callID)) + ClusteringData.Bandwidth(clustIndex(callID))];\n            % Account for any padding on the y axis\n            freqRange = freqRange + range(freqRange) .* rel_y(1) .* [-1, 1];\n\n            freqdata = linspace(freqRange(2) ,freqRange(1), obj.thumbnail_size(1));\n            colorMask = interp1(linspace(obj.minfreq, obj.maxfreq, size(obj.ColorData,1)), obj.ColorData, freqdata, 'nearest', 'extrap');\n            colorIM = im .* colorMask ./ 255;\n        end\n        \n        function obj = config_axis(obj, axis_handles,i, rel_x, rel_y)\n            set(axis_handles,'xcolor','w');\n            set(axis_handles,'ycolor','w');\n            \n            x_lim = xlim(axis_handles);\n            x_span = x_lim(2) - x_lim(1);\n            xtick_positions = linspace(x_span*rel_x(1)+x_lim(1), x_span*rel_x(2)+x_lim(1),4);\n            x_ticks = linspace(0,obj.ClusteringData.Duration(i),4);\n            x_ticks = arrayfun(@(x) sprintf('%.3f',x),x_ticks(2:end),'UniformOutput',false);\n            \n            y_lim = ylim(axis_handles);\n            y_span = y_lim(2) - y_lim(1);\n            ytick_positions = linspace(y_span*rel_y(1)+y_lim(1), y_span*rel_y(2)+y_lim(1),3);            \n            \n            y_ticks = linspace(obj.ClusteringData.MinFreq(i),obj.ClusteringData.MinFreq(i)+obj.ClusteringData.Bandwidth(i),3);\n            y_ticks = arrayfun(@(x) sprintf('%.1f',x),y_ticks(1:end),'UniformOutput',false);\n            y_ticks = flip(y_ticks);\n            \n            yticks(axis_handles,ytick_positions);\n            xticks(axis_handles,xtick_positions(2:end));\n            xticklabels(axis_handles,x_ticks);\n            yticklabels(axis_handles,y_ticks);\n            xlabel(axis_handles,'Time (s)');\n            ylabel(axis_handles,'Frequency (kHz)');\n        end\n        \n        function obj = plotimages(obj)\n            % Number of calls in each cluster\n            for cl = 1:length(obj.clusterName)\n                obj.count(cl) = sum(obj.clustAssign==obj.clusters(cl));\n            end\n            \n            clustIndex = find(obj.clustAssign==obj.clusters(obj.currentCluster));\n            \n            for i=1:length(obj.image_axes)\n                if i <= length(clustIndex) - (obj.page - 1)*length(obj.image_axes)\n                    % set(image_axes(i),'Visible','off')\n                    \n                    set(get(obj.image_axes(i),'children'),'Visible','on');\n                    \n                    callID = i + (obj.page - 1)*length(obj.image_axes);\n                    [colorIM, rel_x, rel_y] = obj.create_thumbnail(obj.ClusteringData,clustIndex,callID);\n                    set(obj.handle_image(i), 'ButtonDownFcn',@(src,event) clicked(obj,src,event,clustIndex(callID),i,callID));\n                    obj.add_cluster_context_menu(obj.handle_image(i),clustIndex(callID));\n                    \n                    \n                    % Display the file ID and call number on mouse hover\n                    [~,call_file,~] = fileparts(obj.ClusteringData.Filename(clustIndex(callID)));\n                    call_id = sprintf('Call: %u', obj.ClusteringData.callID(clustIndex(callID)));                   \n                    pointerBehavior.enterFcn = @(~,~) set(obj.call_id_text, 'string', {call_id, call_file});\n                    pointerBehavior.traverseFcn = [];\n                    pointerBehavior.exitFcn = @(~,~) set(obj.call_id_text, 'string', '');\n                    iptSetPointerBehavior(obj.handle_image(i), pointerBehavior);\n\n\n\n                    % Make the image red if the call is rejected\n                    if obj.rejected(clustIndex(callID))\n                        colorIM(:,:,1) = colorIM(:,:,1) + .5;\n                    end\n                    \n                    set(obj.handle_image(i),'CData',colorIM, 'XData', []);\n                    \n                    obj.config_axis(obj.image_axes(i),clustIndex(callID), rel_x, rel_y);\n                    \n                    set(obj.image_axes(i),'Visible','on')\n                    \n                else\n                    set(obj.image_axes(i),'Visible','off')\n                    set(get(obj.image_axes(i),'children'),'Visible','off');\n                end\n                \n            end\n            \n            % Update text\n            obj.pagenumber.String = sprintf('Page %u of %u', obj.page, ceil(obj.count(obj.currentCluster) / length(obj.image_axes)));\n            obj.txtbox.String = string(obj.clusterName(obj.currentCluster));\n            obj.totalCount.String = sprintf('total count: %u', obj.count(obj.currentCluster));\n            obj.fig.Name = sprintf('Cluster %u of %u', obj.currentCluster, length(obj.count));\n            \n        end\n        \n        function obj = add_cluster_context_menu(obj, hObject, i)\n            unique_clusters = unique(obj.clusterName);\n            \n            c = uicontextmenu(obj.fig);\n            for ci=1:length(unique_clusters)\n                uimenu(c,'text',string(obj.clusterName(ci)),'Callback',@(src,event) assign_cluster(obj, src, event,i,unique_clusters(ci)));\n            end\n            \n            set(hObject, 'UIContextMenu',c);\n        end\n        \n        function obj = assign_cluster(obj, hObject,eventdata,i, clusterLabel)\n            obj.clustAssign(i) = clusterLabel;\n            obj.plotimages();\n        end\n        \n        function obj = clicked(obj, hObject,eventdata,i,plotI,callID)\n            if( eventdata.Button ~= 1 ) % Return if not left clicked\n                return\n            end\n            \n            clustIndex = find(obj.clustAssign == obj.clusters(obj.currentCluster));\n            \n            obj.rejected(i) = ~obj.rejected(i);\n            \n            [colorIM, ~, ~] = obj.create_thumbnail(obj.ClusteringData,clustIndex,callID);\n           \n            if obj.rejected(i)\n                colorIM(:,:,1) = colorIM(:,:,1) + .5;\n            end            \n            set(obj.handle_image(plotI),'CData',colorIM);\n        end\n        \n        function obj = next_Callback(obj, hObject, eventdata)\n            obj.clusterName(obj.currentCluster) = get(obj.txtbox,'String');\n            if obj.currentCluster < length(obj.clusterName)\n                obj.currentCluster = obj.currentCluster + 1;\n                obj.page = 1;\n                obj.plotimages();\n            end\n        end\n        \n        function obj = back_Callback(obj, hObject, eventdata)\n            obj.clusterName(obj.currentCluster) = get(obj.txtbox,'String');\n            if obj.currentCluster > 1\n                obj.currentCluster = obj.currentCluster-1;\n                obj.page = 1;\n                obj.plotimages();\n            end\n        end\n        \n        function obj = nextpage_Callback(obj, hObject, eventdata)\n            if obj.page < ceil(obj.count(obj.currentCluster) / length(obj.image_axes))\n                obj.page = obj.page + 1;\n                obj.plotimages();\n            end\n        end\n        \n        function obj = backpage_Callback(obj, hObject, eventdata)\n            if obj.page > 1\n                obj.page = obj.page - 1;\n                obj.plotimages();\n            end\n        end\n        \n        function obj = txtbox_Callback(obj, hObject, eventdata)\n            obj.clusterName(obj.currentCluster) = get(hObject,'String');\n        end\n\n        function obj = finished_Callback(obj, hObject, eventdata)\n            % If window is closed, finished = 2\n            % If clicked apply, finished = 1\n            % If clicked redo, finished = 0\n            switch eventdata.EventName\n                case 'Close'\n                    obj.finished = 2;\n                otherwise\n                    switch hObject.String\n                        case 'Save'\n                            obj.finished = 1;\n                        case 'Redo'\n                            obj.finished = 0;\n                    end\n            end\n            set(obj.fig,  'closerequestfcn', '');\n            delete(obj.fig);\n            obj.fig = [];\n        end\n        \n    end\nend\n", "meta": {"author": "DrCoffey", "repo": "DeepSqueak", "sha": "c62f2c7bb86a9d77ae177248abe7d234857edf53", "save_path": "github-repos/MATLAB/DrCoffey-DeepSqueak", "path": "github-repos/MATLAB/DrCoffey-DeepSqueak/DeepSqueak-c62f2c7bb86a9d77ae177248abe7d234857edf53/Functions/Call Classification/clusteringGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2018953509686364}}
{"text": "function rcnn_cache_pool5_features(imdb, varargin)\n% rcnn_cache_pool5_features(imdb, varargin)\n%   Computes pool5 features and saves them to disk. We compute\n%   pool5 features because we can easily compute fc6 and fc7\n%   features from them on-the-fly and they tend to compress better\n%   than fc6 or fc7 features due to greater sparsity.\n%\n%   Keys that can be passed in:\n%\n%   start             Index of the first image in imdb to process\n%   end               Index of the last image in imdb to process\n%   crop_mode         Crop mode (either 'warp' or 'square')\n%   crop_padding      Amount of padding in crop\n%   net_file          Path to the Caffe CNN to use\n%   cache_name        Path to the precomputed feature cache\n\n% AUTORIGHTS\n% ---------------------------------------------------------\n% Copyright (c) 2014, Ross Girshick\n% \n% This file is part of the R-CNN code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% ---------------------------------------------------------\n\nip = inputParser;\nip.addRequired('imdb', @isstruct);\nip.addOptional('start', 1, @isscalar);\nip.addOptional('end', 0, @isscalar);\nip.addOptional('crop_mode', 'warp', @isstr);\nip.addOptional('crop_padding', 16, @isscalar);\nip.addOptional('net_file', ...\n    './data/caffe_nets/finetune_voc_2007_trainval_iter_70k', ...\n    @isstr);\nip.addOptional('cache_name', ...\n    'v1_finetune_voc_2007_trainval_iter_70000', @isstr);\n\nip.parse(imdb, varargin{:});\nopts = ip.Results;\nopts.net_def_file = './model-defs/rcnn_batch_256_output_pool5.prototxt';\n\nimage_ids = imdb.image_ids;\nif opts.end == 0\n  opts.end = length(image_ids);\nend\n\n% Where to save feature cache\nopts.output_dir = ['./feat_cache/' opts.cache_name '/' imdb.name '/'];\nmkdir_if_missing(opts.output_dir);\n\n% Log feature extraction\ntimestamp = datestr(datevec(now()), 'dd.mmm.yyyy:HH.MM.SS');\ndiary_file = [opts.output_dir 'rcnn_cache_pool5_features_' timestamp '.txt'];\ndiary(diary_file);\nfprintf('Logging output in %s\\n', diary_file);\n\nfprintf('\\n\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n');\nfprintf('Feature caching options:\\n');\ndisp(opts);\nfprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\\n');\n\n% load the region of interest database\nroidb = imdb.roidb_func(imdb);\n\nrcnn_model = rcnn_create_model(opts.net_def_file, opts.net_file);\nrcnn_model = rcnn_load_model(rcnn_model);\nrcnn_model.detectors.crop_mode = opts.crop_mode;\nrcnn_model.detectors.crop_padding = opts.crop_padding;\n\ntotal_time = 0;\ncount = 0;\nfor i = opts.start:opts.end\n  fprintf('%s: cache features: %d/%d\\n', procid(), i, opts.end);\n\n  save_file = [opts.output_dir image_ids{i} '.mat'];\n  if exist(save_file, 'file') ~= 0\n    fprintf(' [already exists]\\n');\n    continue;\n  end\n  count = count + 1;\n\n  tot_th = tic;\n\n  d = roidb.rois(i);\n  im = imread(imdb.image_at(i));\n\n  th = tic;\n  d.feat = rcnn_features(im, d.boxes, rcnn_model);\n  fprintf(' [features: %.3fs]\\n', toc(th));\n\n  th = tic;\n  save(save_file, '-struct', 'd');\n  fprintf(' [saving:   %.3fs]\\n', toc(th));\n\n  total_time = total_time + toc(tot_th);\n  fprintf(' [avg time: %.3fs (total: %.3fs)]\\n', ...\n      total_time/count, total_time);\nend\n", "meta": {"author": "rbgirshick", "repo": "rcnn", "sha": "43b0334e96e9e910bc45c94902a093b5a6f35d0a", "save_path": "github-repos/MATLAB/rbgirshick-rcnn", "path": "github-repos/MATLAB/rbgirshick-rcnn/rcnn-43b0334e96e9e910bc45c94902a093b5a6f35d0a/rcnn_cache_pool5_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20189535096863637}}
{"text": "% TEST_CNNIMAGERETRIEVAL  Code to evaluate (not train) the methods presented in the papers:\n% F. Radenovic, G. Tolias, O. Chum, Fine-tuning CNN Image Retrieval with No Human Annotation, TPAMI 2018\n% F. Radenovic, G. Tolias, O. Chum, CNN Image Retrieval Learns from BoW: Unsupervised Fine-Tuning with Hard Examples, ECCV 2016\n%\n% Authors: F. Radenovic, G. Tolias, O. Chum. 2017. \n\nclear;\n\n%---------------------------------------------------------------------\n% Set data folder and testing parameters\n%---------------------------------------------------------------------\n\n% Set data folder, change if you have downloaded the data somewhere else\ndata_root = fullfile(get_root_cnnimageretrieval(), 'data');\n% Check, and, if necessary, download train data (for whiten)\ndownload_train(data_root);\n% Check, and, if necessary, download test data (Oxf5k and Par6k), and fine-tuned networks\ndownload_test(data_root); \n\n% Set test options\ntest_datasets = {'oxford5k', 'paris6k', 'roxford5k', 'rparis6k'};  % list of datasets to evaluate on\ntest_imdim = 1024;  % choose test image dimensionality\nuse_ms = 1; % use multi-scale representation, otherwise use single-scale\nuse_rvec = 0;  % use regional representation (R-MAC, R-GeM), otherwise use global (MAC, GeM)\nuse_gpu = [1];  % use GPUs (array of GPUIDs), if empty use CPU\n\n% Choose ECCV16 fine-tuned CNN network\n% network_file = fullfile(data_root, 'networks', 'retrieval-SfM-30k', 'retrievalSfM30k-siamac-alex.mat');\n% network_file = fullfile(data_root, 'networks', 'retrieval-SfM-30k', 'retrievalSfM30k-siamac-vgg.mat');\n\n% Choose TPAMI18 fine-tuned CNN network\n% network_file = fullfile(data_root, 'networks', 'retrieval-SfM-30k', 'retrievalSfM30k-gem-alex.mat');\n% network_file = fullfile(data_root, 'networks', 'retrieval-SfM-120k', 'retrievalSfM120k-gem-vgg.mat');\nnetwork_file = fullfile(data_root, 'networks', 'retrieval-SfM-120k', 'retrievalSfM120k-gem-resnet101.mat');\n\n% After running the training script train_cnnimageretrieval.m you can evaluate fine-tuned network\n% network_file = fullfile(data_root, 'networks', 'exp', 'resnet101_gem_test', 'net-epoch-30');\n\n%---------------------------------------------------------------------\n% Set dependent variables\n%---------------------------------------------------------------------\n\n% Choose training data for whitening and set up data folder\n% train_whiten_file = fullfile(data_root, 'train', 'dbs', 'retrieval-SfM-30k-whiten.mat'); % less images, faster\ntrain_whiten_file = fullfile(data_root, 'train', 'dbs', 'retrieval-SfM-120k-whiten.mat'); % more images, better results but slower\n\n% Set folder where original training images are stored, whitening learned on them\nims_whiten_dir = fullfile(data_root, 'train', 'ims');\n\n% Prepare function for desc extraction\nif ~use_rvec \n\tif ~use_ms\n\t\tdescfun = @(x, y) cnn_vecms (x, y, 1);\n\telse\n\t\tdescfun = @(x, y) cnn_vecms (x, y, [1, 1/sqrt(2), 1/2]);\n\tend  \nelse \n\tif ~use_ms\n\t\tdescfun = @(x, y) cnn_vecrms (x, y, 3, 1);\n\telse\n\t\tdescfun = @(x, y) cnn_vecrms (x, y, 3, [1, 1/sqrt(2), 1/2]);\n\tend  \nend\n\n%---------------------------------------------------------------------\n% Testing\n%---------------------------------------------------------------------\n[~, network_name, ~] = fileparts(network_file);\nfprintf('>> %s: Evaluating CNN image retrieval...\\n', network_name);\n\n% Load pre-trained CNN network\nload(network_file);\nnet = dagnn.DagNN.loadobj(net);\n\n% prepare GPUs if necessary\nnumGpus = numel(use_gpu);\nif numGpus, fprintf('>> Preparing GPU(s)...\\n'); end\nif numGpus > 1\n\t% check parallel pool integrity as it could have timed out\n\tpool = gcp('nocreate');\n\tif ~isempty(pool) && pool.NumWorkers ~= numGpus\n\t\tdelete(pool);\n\tend\n\tpool = gcp('nocreate');\n\tif isempty(pool)\n\t\tparpool('local', numGpus);\n\tend\nend\nif numGpus >= 1\n\tif numGpus == 1\n\t\tgpuinfo = gpuDevice(use_gpu);\n\t\tnet.move('gpu');\n\t\tfprintf('>>>> Running on GPU %s with Index %d\\n', gpuinfo.Name, gpuinfo.Index);  \n\telse\n\t\tspmd\n\t\t\tgpuinfo = gpuDevice(use_gpu(labindex));\n\t\t\tfprintf('>>>> Running on GPU %s with Index %d\\n', gpuinfo.Name, gpuinfo.Index);  \n\t\tend\n\tend\nend\n\n% Load training data filenames and pairs for whitening\ntrain_whiten = load(train_whiten_file);\nif isfield(train_whiten, 'train') && isfield(train_whiten, 'val')\n\tcids  = [train_whiten.train.cids train_whiten.val.cids]; \n\tqidxs = [train_whiten.train.qidxs train_whiten.val.qidxs+numel(train_whiten.train.cids)]; % query indexes \n\tpidxs = [train_whiten.train.pidxs train_whiten.val.pidxs+numel(train_whiten.train.cids)]; % positive indexes\nelse\n\tcids  = train_whiten.cids; \n\tqidxs = train_whiten.qidxs; % query indexes \n\tpidxs = train_whiten.pidxs; % positive indexes\nend\n\n% learn whitening\nfprintf('>> whitening: Extracting CNN descriptors for training images...\\n');\nvecs_whiten = cell(1, numel(cids));\nif numGpus <= 1\n\tprogressbar(0);\n\tfor i=1:numel(cids)\n\t\tvecs_whiten{i} = descfun(imresizemaxd(imread(cid2filename(cids{i}, ims_whiten_dir)), test_imdim, 0), net);\n\t\tprogressbar(i/numel(cids));\n\tend\nelse\n\ttime = tic;\n\tparfor i=1:numel(cids)\n\t\tif strcmp(net.device, 'cpu'), net.move('gpu'); end\n\t\tvecs_whiten{i} = descfun(imresizemaxd(imread(cid2filename(cids{i}, ims_whiten_dir)), test_imdim, 0), net);\n\tend\n\tfprintf('>>>> done in %s\\n', htime(toc(time)));\nend\nvecs_whiten = cell2mat(vecs_whiten);\nfprintf('>> whitening: Learning...\\n');\nLw = whitenlearn(vecs_whiten, qidxs, pidxs);\n\n% extract and evaluate\nfor d = 1:numel(test_datasets)\n\tfprintf('>> %s: Processing test dataset...\\n', test_datasets{d});\t\t\n\tcfg = configdataset (test_datasets{d}, fullfile(data_root, 'test/')); % config file for the dataset\n\n\tfprintf('>> %s: Extracting CNN descriptors for db images...\\n', test_datasets{d}); \n\tvecs = cell(1, cfg.n);\n\tif numGpus <= 1\n\t\tprogressbar(0);\n\t\tfor i = 1:cfg.n\n\t\t\tvecs{i} = descfun(imresizemaxd(imread(cfg.im_fname(cfg, i)), test_imdim, 0), net);\n\t\t\tprogressbar(i/cfg.n);\n\t\tend\n\telse\n\t\ttime = tic;\n\t\tparfor i = 1:cfg.n\n\t\t\tif strcmp(net.device, 'cpu'), net.move('gpu'); end\n\t\t\tvecs{i} = descfun(imresizemaxd(imread(cfg.im_fname(cfg, i)), test_imdim, 0), net);\n\t\tend\n\t\tfprintf('>>>> done in %s\\n', htime(toc(time)));\n\tend\n\tvecs = cell2mat(vecs);\n\n\tfprintf('>> %s: Extracting CNN descriptors for query images...\\n', test_datasets{d}); \n\tqvecs = cell(1, cfg.nq);\n\tif numGpus <= 1\n\t\tprogressbar(0);\n\t\tfor i = 1:cfg.nq\n\t\t\tqvecs{i} = descfun(crop_qim(imread(cfg.qim_fname(cfg, i)), cfg.gnd(i).bbx, test_imdim), net);\n\t\t\tprogressbar(i/cfg.nq);\n\t\tend\n\telse\n\t\ttime = tic;\n\t\tparfor i = 1:cfg.nq\n\t\t\tif strcmp(net.device, 'cpu'), net.move('gpu'); end\n\t\t\tqvecs{i} = descfun(crop_qim(imread(cfg.qim_fname(cfg, i)), cfg.gnd(i).bbx, test_imdim), net);\n\t\tend\n\t\tfprintf('>>>> done in %s\\n', htime(toc(time)));\n\tend\n\tqvecs = cell2mat(qvecs);\n\n\tvecsLw = whitenapply(vecs, Lw.m, Lw.P); % apply whitening on database descriptors\n\tqvecsLw = whitenapply(qvecs, Lw.m, Lw.P); % apply whitening on query descriptors\n\n\tfprintf('>> %s: Retrieval...\\n', test_datasets{d});\n\tif strcmp(test_datasets{d}, 'oxford5k') || strcmp(test_datasets{d}, 'paris6k') \n\t\t% % raw descriptors\n\t\t% sim = vecs'*qvecs;\n\t\t% [sim, ranks] = sort(sim, 'descend');\n\t\t% map = compute_map (ranks, cfg.gnd);\t\n\t\t% fprintf('>> %s: mAP = %.4f, without whiten\\n', test_datasets{d}, map);\n\t\t% with learned whitening\n\t\tsim = vecsLw'*qvecsLw;\n\t\t[sim, ranks] = sort(sim, 'descend');\n\t\tmap = compute_map (ranks, cfg.gnd);\t\n\t\tfprintf('>> %s: mAP = %.4f\\n', test_datasets{d}, map);\n\telseif strcmp(test_datasets{d}, 'roxford5k') || strcmp(test_datasets{d}, 'rparis6k') \n\t\tsim = vecsLw'*qvecsLw;\n\t\t[sim, ranks] = sort(sim, 'descend');\n\t\t% evaluate ranks\n\t\tks = [1, 5, 10];\n\t\t% search for easy (E setup)\n\t\tfor i = 1:numel(cfg.gnd), gnd(i).ok = [cfg.gnd(i).easy]; gnd(i).junk = [cfg.gnd(i).junk, cfg.gnd(i).hard]; end\n\t\t[mapE, apsE, mprE, prsE] = compute_map (ranks, gnd, ks);\n\t\t% search for easy & hard (M setup)\n\t\tfor i = 1:numel(cfg.gnd), gnd(i).ok = [cfg.gnd(i).easy, cfg.gnd(i).hard]; gnd(i).junk = cfg.gnd(i).junk; end\n\t\t[mapM, apsM, mprM, prsM] = compute_map (ranks, gnd, ks);\n\t\t% search for hard (H setup)\n\t\tfor i = 1:numel(cfg.gnd), gnd(i).ok = [cfg.gnd(i).hard]; gnd(i).junk = [cfg.gnd(i).junk, cfg.gnd(i).easy]; end\n\t\t[mapH, apsH, mprH, prsH] = compute_map (ranks, gnd, ks);\n\t\tfprintf('>> %s: mAP E: %.2f, M: %.2f, H: %.2f\\n', test_datasets{d}, 100*mapE, 100*mapM, 100*mapH);\n\t\tfprintf('>> %s: mP@k[%d %d %d] E: [%.2f %.2f %.2f], M: [%.2f %.2f %.2f], H: [%.2f %.2f %.2f]\\n', test_datasets{d}, ks(1), ks(2), ks(3), 100*mprE, 100*mprM, 100*mprH);\n\tend\nend\n", "meta": {"author": "filipradenovic", "repo": "cnnimageretrieval", "sha": "93a7391a2f8b13ff189d0c6131b95e0363542659", "save_path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval", "path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval/cnnimageretrieval-93a7391a2f8b13ff189d0c6131b95e0363542659/examples/test_cnnimageretrieval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.20184700894860283}}
{"text": "function [data] = ft_megrealign(cfg, data)\n\n% FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations by\n% projecting the individual timelocked data towards a coarse source reconstructed\n% representation and computing the magnetic field on the standard gradiometer\n% locations.\n%\n% Use as\n%   [interp] = ft_megrealign(cfg, data)\n% where the input data corresponds to the output from FT_PREPROCESSING.\n%\n% Required configuration options are\n%   cfg.template\n%   cfg.inwardshift\n%\n% The new gradiometer definition is obtained from a template dataset,\n% or can be constructed by averaging the gradiometer positions over\n% multiple datasets.\n%   cfg.template       = single dataset that serves as template\n%   cfg.template(1..N) = datasets that are averaged into the standard\n%\n% The realignment is done by computing a minumum norm estimate using a\n% large number of dipoles that are placed in the upper layer of the brain\n% surface, followed by a forward computation towards the template\n% gradiometer array. This requires the specification of a volume conduction\n% model of the head and of a source model.\n%\n% A volume conduction model of the head should be specified with\n%   cfg.headmodel   = structure, see FT_PREPARE_HEADMODEL\n%\n% A source model (i.e. a superficial layer with distributed sources) can be\n% constructed from a headshape file, or from inner surface of the volume conduction\n% model using FT_PREPARE_SOURCEMODEL using the following options\n%   cfg.spheremesh  = number of dipoles in the source layer (default = 642)\n%   cfg.inwardshift = depth of the source layer relative to the headshape\n%                     surface or volume conduction model (no default\n%                     supplied, see below)\n%   cfg.headshape   = a filename containing headshape, a structure containing a\n%                     single triangulated boundary, or a Nx3 matrix with surface\n%                     points\n%\n% If you specify a headshape and it describes the skin surface, you should specify an\n% inward shift of 2.5 cm.\n%\n% For a single-sphere or a local-spheres volume conduction model based on the skin\n% surface, an inward shift of 2.5 cm is reasonable.\n%\n% For a single-sphere or a local-spheres volume conduction model based on the brain\n% surface, you should probably use an inward shift of about 1 cm.\n%\n% For a realistic single-shell volume conduction model based on the brain surface, you\n% should probably use an inward shift of about 1 cm.\n%\n% Other configuration options are\n%   cfg.tolerance  = tolerance ratio for leadfield matrix inverse based on a truncated svd,\n%                    reflects the relative magnitude of the largest singular value\n%                    to retain (default =s 1e-3)\n%   cfg.verify     = 'yes' or 'no', show the percentage difference (default = 'yes')\n%   cfg.feedback   = 'yes' or 'no' (default = 'no')\n%   cfg.channel    =  Nx1 cell-array with selection of channels (default = 'MEG'),\n%                     see FT_CHANNELSELECTION for details\n%   cfg.trials     = 'all' or a selection given as a 1xN vector (default = 'all')\n%\n% This implements the method described by T.R. Knosche, Transformation\n% of whole-head MEG recordings between different sensor positions.\n% Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and\n% related methods, see Stolk et al., Online and offline tools for head\n% movement compensation in MEG. NeuroImage, 2012.\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n%   cfg.outputfile  =  ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL\n\n% Copyright (C) 2004-2014, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin   = nargin;\nft_nargout  = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar data\nft_preamble provenance data\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n  return\nend\n\n% store the original datatype\ndtype = ft_datatype(data);\n\n% check if the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes');\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden',  {'channels', 'trial'}); % prevent accidental typos, see issue 1729\ncfg = ft_checkconfig(cfg, 'renamed',    {'plot3d',      'feedback'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'headshape',   'headmodel', []});\ncfg = ft_checkconfig(cfg, 'required',   {'inwardshift', 'template'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'hdmfile',     'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'vol',         'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'grid',        'sourcemodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'pruneratio',  'tolerance'});\n\n% set the default configuration\ncfg.headshape  = ft_getopt(cfg, 'headshape',  []);\ncfg.pruneratio = ft_getopt(cfg, 'tolerance',  1e-3);\ncfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642);\ncfg.verify     = ft_getopt(cfg, 'verify',     'yes');\ncfg.feedback   = ft_getopt(cfg, 'feedback',   'yes');\ncfg.trials     = ft_getopt(cfg, 'trials',     'all', 1);\ncfg.channel    = ft_getopt(cfg, 'channel',    'MEG');\ncfg.topoparam  = ft_getopt(cfg, 'topoparam',  'rms');\n\n% do realignment per trial\npertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label));\n\n% put the low-level options pertaining to the dipole grid in their own field\ncfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\nif isstruct(cfg.template)\n  % this should be a cell-array\n  cfg.template = {cfg.template};\nend\n\n% retain only the MEG channels and temporarily store the rest of the channels\n% elsewhere, these will be added back to the transformed data later.\n\n% select trials and channels of interest, first of the non-MEG channels, then of the MEG channels\ntmpcfg = keepfields(cfg, {'trials', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'}); % don't keep tolerance, it is used differently here\ntmpcfg.channel = setdiff(data.label, ft_channelselection(cfg.channel, data.label), 'stable');\nrest = ft_selectdata(tmpcfg, data);\ntmpcfg.channel = ft_channelselection(cfg.channel, data.label);\ndata = ft_selectdata(tmpcfg, data);\n\n% restore the provenance information\n[cfg, data] = rollback_provenance(cfg, data);\n\nNtrials = length(data.trial);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% construct the average template gradiometer array\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntemplate = struct([]); % initialize as 0x0 empty struct array with no fields\nfor i=1:length(cfg.template)\n  if ischar(cfg.template{i})\n    ft_info('reading template sensor position from %s\\n', cfg.template{i});\n    tmp = ft_read_sens(cfg.template{i}, 'senstype', 'meg');\n  elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'coilpos') && isfield(cfg.template{i}, 'coilori') && isfield(cfg.template{i}, 'tra')\n    tmp = cfg.template{i};\n  elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra')\n    % it seems to be a pre-2011v1 type gradiometer structure, update it\n    tmp = ft_datatype_sens(cfg.template{i});\n  else\n    ft_error('unrecognized template input');\n  end\n  % prevent \"Subscripted assignment between dissimilar structures\" error\n  template = appendstruct(template, tmp); clear tmp\nend\n\ngrad = ft_average_sens(template);\n\n% construct the final template gradiometer definition\ntemplate = [];\ntemplate.grad = grad;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PREPARE_HEADMODEL will match the data labels, the gradiometer labels and the\n% volume model labels (in case of a localspheres model) and result in a gradiometer\n% definition that only contains the gradiometers that are present in the data.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvolcfg = [];\nvolcfg.headmodel = cfg.headmodel;\nvolcfg.grad      = data.grad;\nvolcfg.channel   = data.label; % this might be a subset of the MEG channels\n\n% FIXME As of yet the next steps might not entirely correct, because it does not keep\n% track of the balancing of the gradiometer array. This may require some thought\n% because the leadfields are computed with low level functions and do not easily\n% accommodate for matching the correct channels with each other (in order to compute\n% the projection matrix).\n\n% PREPARE_HEADMODEL will match the data labels, the gradiometer labels and the\n% volume model labels (in case of a localspheres model) and result in a gradiometer\n% definition that only contains the gradiometers that are present in the data.\n[volold, data.grad] = prepare_headmodel(volcfg, []);\n\n% Note that it is necessary to keep the two volume conduction models separate, since\n% the single-shell Nolte model contains gradiometer specific precomputed parameters.\n% Also note that this is not guaranteed to result in a good projection for local\n% sphere models.\nvolcfg.grad    = template.grad;\nvolcfg.channel = 'MEG'; % include all MEG channels\n[volnew, template.grad] = prepare_headmodel(volcfg, []);\n\n% construct the low-level options for the leadfield computation as key-value pairs, these are passed to FT_COMPUTE_LEADFIELD\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     ft_getopt(cfg, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    ft_getopt(cfg, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      ft_getopt(cfg, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(cfg, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         ft_getopt(cfg, 'weight'));\n\nif strcmp(ft_senstype(data.grad), ft_senstype(template.grad))\n  [id, it] = match_str(data.grad.label, template.grad.label);\n  ft_info('mean distance towards template gradiometers is %.2f %s\\n', mean(sum((data.grad.chanpos(id,:)-template.grad.chanpos(it,:)).^2, 2).^0.5), template.grad.unit);\nelse\n  % the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult\n  cfg.feedback = 'no';\n  cfg.verify = 'no';\nend\n\n% copy all options that are potentially used in ft_prepare_sourcemodel\ntmpcfg           = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ntmpcfg.headmodel = volold;\ntmpcfg.grad      = data.grad;\n% create the source positions on which the data will be projected\nsourcemodel = ft_prepare_sourcemodel(tmpcfg);\n\n% compute the forward model for the new gradiometer positions\nft_info('computing forward model for %d dipoles\\n', size(sourcemodel.pos,1));\nlfnew = ft_compute_leadfield(sourcemodel.pos, template.grad, volnew, leadfieldopt{:});\nif ~pertrial\n  % this needs to be done only once\n  lfold = ft_compute_leadfield(sourcemodel.pos, data.grad, volold, leadfieldopt{:});\n  [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);\nend\n\n% interpolate the data towards the template gradiometers\nfor i=1:Ntrials\n  ft_info('realigning trial %d\\n', i);\n  if pertrial\n    %warp the gradiometer array according to the motiontracking data\n    sel   = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'});\n    hmdat = rest.trial{i}(sel,:);\n    if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)]))\n      ft_error('only one position per trial is at present allowed');\n    else\n      M    = ft_headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1));\n      grad = ft_transform_geometry(M, data.grad);\n    end\n    \n    volcfg.grad = grad;\n    % compute volume conductor\n    [volold, grad] = prepare_headmodel(volcfg, []);\n    % compute forward model\n    lfold = ft_compute_leadfield(sourcemodel.pos, grad, volold, leadfieldopt{:});\n    % compute projection matrix\n    [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);\n  end\n  data.realign{i} = realign * data.trial{i};\n  if strcmp(cfg.verify, 'yes')\n    % also compute the residual variance when interpolating\n    [id,it]   = match_str(data.grad.label, template.grad.label);\n    rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:));\n    ft_info('original -> template             RV %.2f %%\\n', 100 * mean(rvrealign));\n    datnoalign = noalign * data.trial{i};\n    datbkalign = bkalign * data.trial{i};\n    rvnoalign = rv(data.trial{i}, datnoalign);\n    rvbkalign = rv(data.trial{i}, datbkalign);\n    ft_info('original             -> original RV %.2f %%\\n', 100 * mean(rvnoalign));\n    ft_info('original -> template -> original RV %.2f %%\\n', 100 * mean(rvbkalign));\n  end\nend\n\n% plot the topography before and after the realignment\nif strcmp(cfg.feedback, 'yes')\n  \n  ft_warning('showing MEG topography (RMS value over time) in the first trial only');\n  Nchan = length(data.grad.label);\n  [id,it]   = match_str(data.grad.label, template.grad.label);\n  pos1 = data.grad.chanpos(id,:);\n  pos2 = template.grad.chanpos(it,:);\n  prj1 = elproj(pos1); tri1 = delaunay(prj1(:,1), prj1(:,2));\n  prj2 = elproj(pos2); tri2 = delaunay(prj2(:,1), prj2(:,2));\n  \n  switch cfg.topoparam\n    case 'rms'\n      p1 = sqrt(mean(data.trial{1}(id,:).^2, 2));\n      p2 = sqrt(mean(data.realign{1}(it,:).^2, 2));\n    case 'svd'\n      [u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1);\n      [u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1);\n    otherwise\n      ft_error('unsupported cfg.topoparam');\n  end\n  \n  X = [pos1(:,1) pos2(:,1)]';\n  Y = [pos1(:,2) pos2(:,2)]';\n  Z = [pos1(:,3) pos2(:,3)]';\n  \n  % show figure with old an new helmets, volume model and source positions\n  figure\n  hold on\n  ft_plot_headmodel(volold);\n  plot3(sourcemodel.pos(:,1),sourcemodel.pos(:,2),sourcemodel.pos(:,3),'b.');\n  plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n  plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n  line(X,Y,Z, 'color', 'black');\n  view(-90, 90);\n  \n  % show figure with data on old helmet location\n  figure\n  hold on\n  plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n  plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n  line(X,Y,Z, 'color', 'black');\n  axis equal; axis vis3d\n  bnd1 = [];\n  bnd1.pos = pos1;\n  bnd1.tri = tri1;\n  ft_plot_mesh(bnd1,'vertexcolor',p1,'edgecolor','none')\n  title('RMS, before realignment')\n  view(-90, 90)\n  \n  % show figure with data on new helmet location\n  figure\n  hold on\n  plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n  plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n  line(X,Y,Z, 'color', 'black');\n  axis equal; axis vis3d\n  bnd2 = [];\n  bnd2.pos = pos2;\n  bnd2.tri = tri2;\n  ft_plot_mesh(bnd2,'vertexcolor',p2,'edgecolor','none')\n  title('RMS, after realignment')\n  view(-90, 90)\nend\n\n% store the realigned data in a new structure\ninterp.label   = template.grad.label;\ninterp.grad    = template.grad;   % replace with the template gradiometer array\ninterp.trial   = data.realign;    % remember the processed data\ninterp.fsample = data.fsample;\ninterp.time    = data.time;\n\n% add the rest channels back to the data, these were not interpolated\nif ~isempty(rest.label)\n  ft_info('adding %d non-MEG channels back to the data (', length(rest.label));\n  ft_info('%s, ', rest.label{1:end-1});\n  ft_info('%s)\\n', rest.label{end});\n  for trial=1:length(rest.trial)\n    interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}];\n  end\n  interp.label = [interp.label; rest.label];\nend\n\n% copy the trial specific information into the output\nif isfield(data, 'trialinfo')\n  interp.trialinfo = data.trialinfo;\nend\n\n% copy the sampleinfo field as well\nif isfield(data, 'sampleinfo')\n  interp.sampleinfo = data.sampleinfo;\nend\n\n% convert back to input type if necessary\nswitch dtype\n  case 'timelock'\n    interp = ft_checkdata(interp, 'datatype', 'timelock');\n  otherwise\n    % keep the output as it is\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous data\n\n% rename the output variable to accomodate the savevar postamble\ndata = interp;\n\nft_postamble provenance data\nft_postamble history    data\nft_postamble savevar    data\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunction that computes the projection matrix(ces)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [realign, noalign, bkalign] = computeprojection(lfold, lfnew, tolerance, verify)\n\n% compute this inverse only once, although it is used twice\ntmp = ft_inv(lfold, 'method', 'tsvd', 'tolerance', tolerance);\n% compute the three interpolation matrices\nft_info('computing interpolation matrix #1\\n');\nrealign = lfnew * tmp;\nif strcmp(verify, 'yes')\n  ft_info('computing interpolation matrix #2\\n');\n  noalign = lfold * tmp;\n  ft_info('computing interpolation matrix #3\\n');\n  bkalign = (lfold * ft_inv(lfnew, 'method', 'tsvd', 'tolerance', tolerance)) * realign;\nelse\n  noalign = [];\n  bkalign = [];\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_megrealign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.2018233577308342}}
{"text": "function [output,cost,psave,timing] = solvelower(p,options,lowersolver,xmin,upper,timing)\n\npsave = p;\nremoveThese = find(p.InequalityConstraintState==inf);\np.F_struc(p.K.f + removeThese,:) = [];\np.K.l = p.K.l - length(removeThese);\n\nremoveThese = find(p.EqualityConstraintState==inf);\np.F_struc(removeThese,:) = [];\np.K.f = p.K.f - length(removeThese);\n\nif p.options.bmibnb.cut.bilinear\n    p_cut = addBilinearVariableCuts(p);\nend\nif p.options.bmibnb.cut.evalvariable\n    p_cut = addEvalVariableCuts(p_cut);\n    psave.evalMap = p_cut.evalMap;\nend\nif p.options.bmibnb.cut.monomial\n    p_cut = addMonomialCuts(p_cut);\nend\nif p.options.bmibnb.cut.multipliedequality\n    p_cut = addMultipliedEqualityCuts(p_cut);\nend\nif p.options.bmibnb.cut.convexity\n    p_cut = addConvexityCuts(p_cut);\nend\nif p.options.bmibnb.cut.complementarity\n    p_cut = addComplementarityCuts(p_cut);\nend\n% **************************************\n% SOLVE NODE PROBLEM\n% **************************************\nif any(p_cut.ub+1e-8<p_cut.lb)\n    output.problem=1;\n    cost = inf;\nelse\n    % We are solving relaxed problem (penbmi might be local solver)\n    p_cut.monomtable = eye(length(p_cut.c));\n    \n    if p.solver.lowersolver.objective.quadratic.convex\n        % Setup quadratic\n        [p_cut.Q,p_cut.c] = compileQuadratic(p.c,p);\n        \n        if nonconvexQuadratic(p_cut.Q);\n            p_cut.Q = p.Q;\n            p_cut.c = p.c;\n        end\n    end\n    \n    fixed = p_cut.lb >= p_cut.ub;\n    if nnz(fixed) == length(p.c)\n        % All variables are fixed to a bound\n        output.Primal = p.lb;\n        res = constraint_residuals(p,output.Primal);\n        eq_ok = all(res(1:p.K.f)>=-p.options.bmibnb.eqtol);\n        iq_ok = all(res(1+p.K.f:end)>=p.options.bmibnb.pdtol);\n        feasible = eq_ok & iq_ok;\n        if feasible\n            output.problem = 0;\n        else\n            output.problem = 1;\n        end\n        cost = output.Primal'*p.Q*output.Primal + p.c'*output.Primal + p.f;\n    else\n        \n        if nnz(fixed)==0\n            \n            if ~isempty(p_cut.bilinears) & 0\n                top = size(p_cut.F_struc,1);\n                if length(p_cut.K.s)==1 & p_cut.K.s(1)==0\n                    p_cut.K.s = [];\n                end\n                usedterms = zeros(size(p_cut.bilinears,1),1);\n                for i = 1:size(p_cut.bilinears,1)\n                    if ~usedterms(i)\n                        windex = p_cut.bilinears(i,1);\n                        xindex = p_cut.bilinears(i,2);\n                        yindex = p_cut.bilinears(i,3);\n                        if xindex ~=yindex\n                            % OK, we have a bilinear term\n                            xsquaredindex = find(p_cut.bilinears(:,2)==xindex & p_cut.bilinears(:,3)==xindex);\n                            ysquaredindex = find(p_cut.bilinears(:,2)==yindex & p_cut.bilinears(:,3)==yindex);\n                            if ~isempty(xsquaredindex) & ~isempty(ysquaredindex)\n                                usedterms(i) = 1;\n                                usedterms(xsquaredindex) = 1;\n                                usedterms(ysquaredindex) = 1;\n                                xsquaredindex =  p_cut.bilinears(xsquaredindex,1);\n                                ysquaredindex =  p_cut.bilinears(ysquaredindex,1);\n                                if 0\n                                    Z = zeros(9,size(p_cut.F_struc,2));\n                                    Z(1,xsquaredindex+1) = 1;\n                                    Z(2,windex+1) = 1;\n                                    Z(4,windex+1) = 1;\n                                    Z(5,ysquaredindex+1) = 1;\n                                    Z(3,xindex+1) = 1;\n                                    Z(7,xindex+1) = 1;\n                                    Z(6,yindex+1) = 1;\n                                    Z(8,yindex+1) = 1;\n                                    Z(9,1)=1;\n                                else\n                                    xL = p.lb(xindex);\n                                    yL = p.lb(yindex);\n                                    \n                                    Z = zeros(9,size(p_cut.F_struc,2));\n                                    Z(1,xsquaredindex+1) = 1;\n                                    Z(2,windex+1) = 1;\n                                    Z(4,windex+1) = 1;\n                                    Z(5,ysquaredindex+1) = 1;\n                                    Z(3,xindex+1) = 1;\n                                    Z(7,xindex+1) = 1;\n                                    Z(6,yindex+1) = 1;\n                                    Z(8,yindex+1) = 1;\n                                    Z(9,1)=1;\n                                    Z(3,1) = -xL;\n                                    Z(7,1) = -xL;\n                                    Z(6,1) = -yL;\n                                    Z(8,1) = -yL;\n                                    \n                                    Z(1,xindex+1) = -2*xL;\n                                    Z(5,yindex+1) = -2*yL;\n                                    \n                                    Z(1,1) = xL^2;\n                                    Z(5,1) = yL^2;\n                                    \n                                    Z(4,xindex+1) = -yL;\n                                    Z(4,yindex+1) = -xL;\n                                    Z(4,1) = xL*yL;\n                                    \n                                    Z(2,xindex+1) = -yL;\n                                    Z(2,yindex+1) = -xL;\n                                    Z(2,1) = xL*yL;\n                                    \n                                    \n                                end\n                                p_cut.F_struc = [p_cut.F_struc;Z];\n                                p_cut.K.s = [p_cut.K.s 3];\n                            end\n                        end\n                    end\n                end\n            end\n            \n            p_cut.linearindicies = 1:length(p.c);\n            p_cut.nonlinearindicies = [];\n            p_cut.variabletype = zeros(1,length(p.c));\n            p_cut.deppattern = eye(length(p.c));\n            p_cut.linears = 1:length(p.c);\n            p_cut.bilinears = [];\n            p_cut.nonlinears = [];\n            p_cut.monomials = [];\n            p_cut.evaluation_scheme = [];\n            \n            tstart = tic;                                             \n            output = feval(lowersolver,removenonlinearity(p_cut));\n            psave.counter.lowersolved = psave.counter.lowersolved + 1;\n            timing.lowersolve = timing.lowersolve + toc(tstart);\n            cost = output.Primal'*p_cut.Q*output.Primal + p_cut.c'*output.Primal + p.f;\n            % Minor clean-up\n            pp=p;\n            output.Primal(output.Primal<p.lb) = p.lb(output.Primal<p.lb);\n            output.Primal(output.Primal>p.ub) = p.ub(output.Primal>p.ub);\n            x=output.Primal;\n            return\n        else\n            pp = p_cut;\n            removethese = fixed;\n            if ~isempty(p_cut.F_struc)\n                p_cut.F_struc(:,1)=p_cut.F_struc(:,1)+p_cut.F_struc(:,1+find(fixed))*p_cut.lb(fixed);\n                p_cut.F_struc(:,1+find(fixed))=[];\n                \n                rf = find(~any(p_cut.F_struc,2));\n                rf = rf(rf<=(p_cut.K.f + p_cut.K.l));\n                p_cut.F_struc(rf,:) = [];\n                p_cut.K.l = p_cut.K.l - nnz(rf>p_cut.K.f);\n                p_cut.K.f = p_cut.K.f - nnz(rf<=p_cut.K.f);\n            end\n            p_cut.c(removethese)=[];\n            if nnz(p_cut.Q)>0\n                p_cut.c = p_cut.c + 2*p_cut.Q(find(~removethese),find(removethese))*p_cut.lb(removethese);\n                p_cut.Q(:,find(removethese))=[];\n                p_cut.Q(find(removethese),:)=[];\n            else\n                p_cut.Q = spalloc(length(p_cut.c),length(p_cut.c),0);\n            end\n            \n            if ~isempty(p_cut.binary_variables)\n                new_bin = [];\n                new_var = find(~fixed);\n                for i = 1:length(p_cut.binary_variables)\n                    temp = find(p_cut.binary_variables(i) == new_var);\n                    new_bin =  [new_bin temp(:)'];\n                end\n                p_cut.binary_variables = new_bin;\n            end\n            if ~isempty(p_cut.integer_variables)\n                new_bin = [];\n                new_var = find(~fixed);\n                for i = 1:length(p_cut.integer_variables)\n                    temp = find(p_cut.integer_variables(i) == new_var);\n                    new_bin =  [new_bin temp(:)'];\n                end\n                p_cut.integer_variables = new_bin;\n            end\n            \n            p_cut.lb(removethese)=[];\n            p_cut.ub(removethese)=[];\n            p_cut.x0(removethese)=[];\n            p_cut.monomtable(:,find(removethese))=[];\n            p_cut.monomtable(find(removethese),:)=[];\n            \n            % The model can become absolutely trivial in some case\n            % For instance in ex9_2_2 everything is presolved\n            if nnz(p_cut.c)==0 & nnz(p_cut.Q)==0 & size(p_cut.F_struc,1)==0\n                % No objective and no constraints\n                if all(p_cut.lb <= p_cut.ub)\n                    output.Primal = (p_cut.lb + p_cut.ub)/2;\n                    output.Primal(isinf(p_cut.lb) & isinf(p_cut.ub))=0;\n                    output.problem = 0;\n                else\n                    output.Primal = zeros(length(p_cut.lb),1);\n                    output.problem = 1;\n                end\n            else\n                try\n                    tstart = tic;\n                    output = feval(lowersolver,removenonlinearity(p_cut));\n                    psave.counter.lowersolved = psave.counter.lowersolved + 1;\n                    timing.lowersolve = timing.lowersolve + toc(tstart);\n                catch\n                    1\n                end\n            end\n            x=full(p.c*0);\n            x(removethese)=p.lb(removethese);\n            x(~removethese)=output.Primal;\n            output.Primal = x;\n            cost = output.Primal'*pp.Q*output.Primal + pp.c'*output.Primal + p.f;\n        end\n    end\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/modules/global/solvelower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.20182335366624216}}
{"text": "%kigeowarp 'Perform Direct Bilinear Geometric Warping'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros igeowarp.pane file\n%\n% Parameters: \n% InputFile: i 'Input ', required: 'Input data object'\n% Toggle: planes 'Process by planes', default: 0: 'Process data by full planes instead of small prisms'\n% OutputFile: o 'Output', required: 'Output data object'\n% InputFile: wcoeffs 'W warp coeffs object', optional: 'W warp function coeffs object'\n% InputFile: hcoeffs 'H warp coeffs object', optional: 'H warp function coeffs object'\n%\n% Example: o = kigeowarp({i, wcoeffs, hcoeffs}, {'i','';'planes',0;'o','';'wcoeffs','';'hcoeffs',''})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% igeowarp - Perform Direct Bilinear Geometric Warping\n%\n%  DESCRIPTION\n% .I igeowarp\n% is used to apply a direct bilinear warping to an image. In this mode, the\n% bilinear mapping equations give the mapping of output data coordinates to\n% input data coordinates. A given output data coordinate is operated on by the\n% mapping functions to give the input data coordinate. The value of the input\n% data coordinate is interpolated using bilinear interpolation, and the resulting\n% value is assigned to the output data coordinate.\n% \n% All warping is assumed to occur only in the WxH plane.\n% If warping in a different plane is desired, it is necessary to use the kaxis\n% program to reorient the data such that the desired plane is the WxH plane before\n% applying igeowarp. This limitation is due to computational complexity and\n% performance issues, particularly when dealing with large data sets.\n% \n% The mapping functions used by igeowarp are:\n% \n% \n%             f(w,h) = output image\n% \n%             g(w',h') = input image coordinate\n% \n%             w' = a00 + a01*w + a10*h +a11*w*h\n%             h' = b00 + b01*w + b10*h +b11*w*h\n% \n% \n% Note that in general, w' and h' are not integers for a given integer pair\n% w and h. The\n% data value at g(w',h') is obtained by bilinear interpolation of the four\n% nearest neighbors to coordinate (w',h').\n% \n% The mapping is called direct because it directly gives the location in the\n% input data that corresponds to a given location in the output data. The \n% opposite case gives the location in the output data that corresponds to a\n% given input data location; this requires much trickier and computationally\n% expensive interpolation methods to obtain good results.\n% \n% The input parameters a00, a01, a10, a11, b00, b01, b10, b11 are exactly as\n% specified in the mapping functions above. These parameters can also be supplied\n% in the form of object value data where the data is assumed to be organized with\n% the parameters a00, a01, a10, and a11 present in that storage order for the\n% W coefficients and likewise for the H coefficients.\n% \n% If the input object has a mask, a new mask will be computed for the output\n% object indicating which data points contain reliable data. \n% \n% If the input object has a map, the data is pulled through the map prior to\n% rotation, and the output object will have no map.\n% \n% The -planes flag is used to change the way the data is accessed for processing.\n% If the data set is small enough that individual planes of data (including the\n% E data) parallel to the WxH plane will fit in memory, then use of the -planes \n% flag will permit processing to happen in a plane-by-plane basis; this can\n% occur with efficiency and speed. Otherwise,\n% processing will occur in prisms down the D axis, which is much slower but will\n% work on data sets of any size. If you have lots of memory, you may be able to\n% get away with using -planes even for quite large data sets, say around 2Kx2K\n% or more points per plane.\n%\n%  \n%\n%  EXAMPLES\n%\n%  \"SEE ALSO\"\n% irotate(1)\n%\n%  RESTRICTIONS \n% \n% For this initial release, the E dimension data is \"not\\fR handled\n% correctly. Data in WxHxD \"is\\fR handled correctly. This deficiency\n% will be corrected in the next version of\n% .I igeowarp.\n%\n%  REFERENCES \n%\n%  COPYRIGHT\n% Copyright (C) 1993 - 1997, Khoral Research, Inc. (\"KRI\")  All rights reserved.\n% \n\n\nfunction varargout = kigeowarp(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kigeowarp(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i', '__input';'planes', 0;'o', '__output';'wcoeffs', '__input';'hcoeffs', '__input'};\nmaxval={0,0,0,1,1};\nminval={0,0,0,1,1};\nistoggle=[0,1,0,1,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','Toggle','OutputFile','InputFile','InputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'igeowarp\"  '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kigeowarp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.2016404076872351}}
{"text": "%{\nnohup matlab -nodesktop -nodisplay < main002_instSeg_v1_ftAbsEucMM_epoch83.m 1>main002_instSeg_v1_ftAbsEucMM_epoch83.log &\n%}\nclear\n% close all\nclc;\n\naddpath './fun4MeanShift';\naddpath('./local_functions_demo1');\naddpath '../libs/exportFig/';\naddpath '../libs/layerExt/';\naddpath '../libs/myFunctions/';\n\npath_to_matconvnet = '../libs/matconvnet-1.0-beta23_modifiedDagnn';\n\nrun(fullfile(path_to_matconvnet, 'matlab', 'vl_setupnn'));\naddpath(genpath(fullfile('dependencies', 'matconvnet','examples')));\n%% read matconvnet model\nload('imdb_toydata_v3_from_mnist.mat');\nimdb.path = './toydata_v3';\nimdb.path_to_dataset = './toydata_v3';\n% set GPU\ngpuId = 1; \ngpuDevice(gpuId);\nflagSaveFig = true; % {true false} whether to store the result\n\nsaveFolder = 'main007_instSeg_v1_absEucMM';\nmodelName = 'softmax_net-epoch-83.mat';\n\n\n\nnetbasemodel = load( fullfile('./exp', saveFolder, modelName) );\nnetbasemodel = netbasemodel.net;\n\nnetbasemodel.layers(136).block = rmfield(netbasemodel.layers(136).block, 'ignoreAverage');\nnetbasemodel.layers(135).block = rmfield(netbasemodel.layers(135).block, 'ignoreAverage');\n\nnetbasemodel = dagnn.DagNN.loadobj(netbasemodel);\n%% 1st mean-shift grouping loop\nkeepLayerName = sprintf('obj_instSeg_reg');\nnetbasemodel.layers(netbasemodel.getLayerIndex(keepLayerName)).block.lastLayerName = 'res7_cosSim';\nkeepLayerName = sprintf('obj_instSeg_MM');\nnetbasemodel.layers(netbasemodel.getLayerIndex(keepLayerName)).block.lastLayerName = 'res7_cosSim';\n\nweight_for_losses = {'obj_instSeg_reg', 1, 'obj_instSeg_MM', 1};\nsName_l2norm = 'res7_l2norm';\ngt_name =  sprintf('gt_ins');\nGaussianBandwidth = 0.1;\nrandSampleRatio = 0.2;\nfor loopIdx = 1:5\n    [netbasemodel, sName, sName_l2norm] = addOneLoop_forMeanShiftGrouping(...\n        netbasemodel, sName_l2norm, loopIdx,...\n        GaussianBandwidth, randSampleRatio);\n    \n    % add regression loss\n    obj_name = sprintf('loop%d_instSeg_reg', loopIdx);\n    netbasemodel.addLayer(obj_name, ...\n        InstanceSegRegLoss_randSample('loss', 'cosinesimilarityabsregloss', 'lastLayerName', sName), ... softmaxlog logistic\n        {sName, gt_name}, obj_name);\n    weight_for_losses{end+1} = obj_name;\n    weight_for_losses{end+1} = 1;\n    \n    % add max-margin loss\n    obj_name = sprintf('loop%d_instSeg_MM', loopIdx);    \n    netbasemodel.addLayer(obj_name, ...\n        InstanceSegMMLoss_randSample('loss', 'cosinesimilaritymmloss', 'marginAlpha_', 0.07, 'adaptiveMM', false, 'lastLayerName', sName), ...\n        {sName, gt_name}, obj_name)\n    weight_for_losses{end+1} = obj_name;\n    weight_for_losses{end+1} = 1; \nend\n%% show learning rates for all layers\nfor ii = 1:numel(netbasemodel.layers)    \n    curLayerName = netbasemodel.layers(ii).name;\n    if strfind(curLayerName, 'bn')\n        fprintf('%03d, %s\\n', ii, curLayerName);\n        netbasemodel.params(netbasemodel.layers(ii).paramIndexes(3)).learningRate = 0.1;\n    end\nend\nnetbasemodel.params(netbasemodel.getParamIndex('res6_conv_f')).learningRate = 1;\nnetbasemodel.params(netbasemodel.getParamIndex('res6_conv_b')).learningRate = 1;\n\nfor i = 1:numel(netbasemodel.params)\n    fprintf('%d\\t%25s, \\t%.2f',i, netbasemodel.params(i).name, netbasemodel.params(i).learningRate);\n    fprintf('\\tsize: %dx%dx%dx%d\\n', size(netbasemodel.params(i).value,1), size(netbasemodel.params(i).value,2), size(netbasemodel.params(i).value,3), size(netbasemodel.params(i).value,4));\nend\n%% configure training environment\nbatchSize = 1;\ntotalEpoch = 100;\nlearningRate = 1:totalEpoch;\nlearningRate = (1.0e-4) * (1-learningRate/totalEpoch).^0.9;\n\nweightDecay=0.0005; % weightDecay: usually use the default value\n\nopts.batchSize = batchSize;\nopts.learningRate = learningRate;\nopts.weightDecay = weightDecay;\nopts.momentum = 0.9 ;\n\nopts.expDir = fullfile('./exp', 'main002_instSeg_v1_ftAbsEucMM_epoch83');\nif ~isdir(opts.expDir)\n    mkdir(opts.expDir);\nend\n\nopts.withSemanticSeg = false ;\nopts.withInstanceSeg = true ;\nopts.withWeights = false ;\n\nopts.numSubBatches = 1 ;\nopts.continue = true ;\nopts.gpus = gpuId ;\n%gpuDevice(opts.train.gpus); % don't want clear the memory\nopts.prefetch = false ;\nopts.sync = false ; % for speed\nopts.cudnn = true ; % for speed\nopts.numEpochs = numel(opts.learningRate) ;\nopts.learningRate = learningRate;\n\nfor i = 1:2\n    curSetName = imdb.sets.name{i};\n    idxList = find(imdb.set==i);\n    curList = imdb.imgList(idxList);\n    opts.(curSetName) = curList;    \nend\n\nopts.checkpointFn = [];\nmopts.classifyType = 'softmax';\n\nrng(777);\nbopts = netbasemodel.meta.normalization;\nbopts.numThreads = 12;\nbopts.imdb = imdb;\n%% train\nfn = getBatchWrapper4toyDigitV2(bopts);\n\nopts.backPropDepth = inf; % could limit the backprop\nprefixStr = [mopts.classifyType, '_'];\nopts.backPropAboveLayerName = 'conv1_conv'; \n\ntrainfn = @cnnTrain;\n[netbasemodel, info] = trainfn(netbasemodel, prefixStr, imdb, fn, 'derOutputs', ...\n    weight_for_losses, ...\n    opts);\n\n%% leaving blank\n%{\n%}\n\n\n\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/demo1_tutorial_instance_segmentation/step004_instSeg_v1_multiMShiftLoops_finetuneStep003.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.20164040594198895}}
{"text": "%% t_mrdViewFibers\n%\n% Load and view a set of fibers stored in a PDB (v3) file using mrMesh.\n% \n% (c) Stanford VISTA Team\n\n%% Make sure that vistadata is on your path\n% vistaDataPath;\n\n\n%% dtiStart for scripts\n\ndataDir = fullfile(mrvDataRootPath,'diffusion','sampleData');\ndt6Name = fullfile(dataDir,'dti40','dt6.mat');\n% Initialize mrDiffusion\n[dtiFig, dtiH]= mrDiffusion('on',dt6Name);\n% At this point you can use dtiSet/Get on dtiH\n\nif isunix, disp('Start mrMeshSrv.exe')\nelse       mrmStart\nend\n\n%% Load fiber group structure\ndifDir = fullfile(mrvDataRootPath,'diffusion','sampleData','dti40');\nchdir(difDir)\n\nfgName = fullfile(mrvDataRootPath,'diffusion','sampleData','fibers','leftArcuate.pdb');\n% The mtr<> function name is old from metrotrac days.  It will probably change some\n% day.\nfg = mtrImportFibers(fgName);\n\n%% Show fibers in mrMesh\n\n% Attach the fiber group to the handles\ndtiH = dtiSet(dtiH,'add fiber group',fg);\n\nset(dtiH.cbUseMrMesh, 'Value',1);     % Use mrMesh for update\nset(dtiH.cbShowFibers,'Value',1);     % Show loaded fibers\nset(dtiH.cbShowMatlab3d,'Value',0);   % No 3d Matlab window\nset(dtiH.popupBackground,'Value',2);  % Mean diffusivity\n\nguidata(dtiFig,dtiH);  % Refresh the Matlab window handles.\n\nmrmCloseWindow(dtiH.mrMesh.id,dtiH.mrMesh.host);\n\nshowMeshWindow = 1;\ndtiH = dtiRefreshFigure(dtiH,showMeshWindow);\n\n%% The code below pulls out key routines from dtiRefreshFigure \n\n% Closing the window and then running this is much faster than removing the\n% previous actors.\nmrmCloseWindow(dtiH.mrMesh.id,dtiH.mrMesh.host);\n\n% This code, which is not normally used, permits a faster reload of the\n% mrMesh window. The code below here could be placed in a routine like\n%\n%   id = dtiMeshView(dtiH,varargin);\n%\nset(dtiH.popupBackground,'Value',1);  % Choose type of background (1-4)\nset(dtiH.rbSagittal,'Value',1);       % Choose which planes\nset(dtiH.rbCoronal, 'Value',0);\nset(dtiH.rbAxial,   'Value',1);\n\n% With mrMesh - This started with the code from dtiRefreshFogure/dtiFiberUI\n% Needs anat, anatXform\n[xSliceRgb,ySliceRgb,zSliceRgb,anat,anatXform, ...\n    mmPerVoxel,xform,xSliceAxes,ySliceAxes,zSliceAxes] = ...\n    dtiGetCurSlices(dtiH);\n\ncurPosition = dtiGet(dtiH,'curpos');\n\n% Should be:\n% anatXform = dtiGet(dtiH,'anatXform');\n\n[zIm] = dtiGetSlice(anatXform, anat, 3, curPosition(3), [], dtiH.interpType);\n[yIm] = dtiGetSlice(anatXform, anat, 2, curPosition(2), [], dtiH.interpType);\n[xIm] = dtiGetSlice(anatXform, anat, 1, curPosition(1), [], dtiH.interpType);\n% figure; imagesc(zIm); axis image; colormap(gray)\n\n% This is a little slow.\n[xIm,yIm,zIm] = dtiMrMeshSelectImages(dtiH,xIm,yIm,zIm);\norigin = dtiMrMeshOrigin(dtiH);\ndtiH = dtiMrMesh3AxisImage(dtiH, origin, xIm, yIm, zIm);\n\n%%  Manipulating the mesh view\n\n% Need to permute the rotation matrix, I think, for various cases.\n% I haven't worked that out.\n\nmsh = dtiGet(dtiH,'mesh'); % If you have a mrDiffusion guidata in dtiH\nmrmRotateCamera(msh.id,'front',1); pause(1)\nmrmRotateCamera(msh.id,'back',1);  pause(1)\nmrmRotateCamera(msh.id,'top',1);   pause(1)\nmrmRotateCamera(msh.id,'bottom',1);pause(1)\nmrmRotateCamera(msh.id,'right',1); pause(1)\nmrmRotateCamera(msh.id,'left',1);\n\n\n%% End after here\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/tutorials/diffusion/t_mrdViewFibers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2014675528181386}}
{"text": "function Projector = in_projector_fif( SspFiles, ChannelNames )\n% IN_PROJECTOR_FIF: Read a FIF file, and return a brainstorm Channel structure.\n%\n% USAGE:  Projector = in_projector_fif( SspFile, ChannelNames );\n%         Projector = in_projector_fif( projs, ChannelNames );\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2010-2012\n\nglobal FIFF;\n\n%% ===== PARSE INPUTS =====\nif ischar(SspFiles)\n    SspFiles = {SspFiles};\nend\n% Remove spaces in all the channel names\ntmp = ChannelNames;\nChannelNames = cellfun(@(c)upper(c(c~=' ')), ChannelNames, 'UniformOutput', 0);\n\n\n%% ===== READ PROJECTORS =====\nprojs = [];\n% Read files\nif iscell(SspFiles)\n    % Loop on all files\n    for i = 1:length(SspFiles)\n        % Open SSP file\n        [ fid, tree ]  = fiff_open(SspFiles{i});\n        if (fid < 0)\n            error(['Cannot open FIFF file : \"' SspFiles{i} '\"']);\n        end\n        % Read projectors\n        node = fiff_dir_tree_find(tree, FIFF.FIFFB_PROJ);\n        newProjs = fiff_read_proj(fid, node);\n        % Add projectors to list of all projectors to combine\n        if isempty(projs)\n            projs = newProjs;\n        else\n            projs = [projs, newProjs];\n        end\n        % Close SSP file\n        fclose(fid);\n    end\n% Projectors already loaded\nelseif isstruct(SspFiles)\n    projs = SspFiles;\nelse\n    error('Invalid input.');\nend\n\n\n%% ====== BUILD PROJECTION MATRIX =====\nProjector = repmat(db_template('projector'), 0);\nnChannels = length(ChannelNames);\n% Collect all the projections from the FIF file\nfor i = 1:length(projs)\n    % Check type of the projector\n    if (projs(i).kind ~= FIFF.FIFFV_PROJ_ITEM_FIELD)\n        fprintf(1, 'SSP> Unsupported type of projector #%d: \"%s\". Skipping...\\n', projs(i).kind, projs(i).desc);\n        continue;\n    end\n    % Copy basic information\n    iNew = length(Projector) + 1;\n    Projector(iNew).Comment = projs(i).desc;\n    if projs(i).active\n        Projector(iNew).Status = 2;  % Recordings in the file saved this way\n    else\n        Projector(iNew).Status = 1;  % Projector is selected and applied dynamically to the recordings\n    end\n    % Get the projectors values\n    data = projs(i).data;\n    % Remove the spaces in the channel names\n    data.col_names = cellfun(@(c)upper(c(c~=' ')), data.col_names, 'UniformOutput', 0);\n    % Copy the information of each channel\n    U = zeros(nChannels, data.nrow);\n    for iCol = 1:data.ncol\n        iChan = find(strcmpi(data.col_names{iCol}, ChannelNames));\n        if isempty(iChan)\n            % Channel not found\n            continue;\n        elseif (length(iChan) > 1)\n            disp('IN> Warning: Several channels have the same name, the result might be random...');\n            iChan = iChan(1);\n        end\n        U(iChan,:) = data.data(:,iCol)';\n    end\n    % Finish filling the entry\n    Projector(iNew).Components = U;\n    Projector(iNew).CompMask   = ones(1,data.nrow);\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_projector_fif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.34864512179822554, "lm_q1q2_score": 0.20134094193311805}}
{"text": "function display_obj(obj,texture)\n%\n% function display_obj(obj,texture)\n%\n% displays an obj structure with texture\n%\n% INPUTS:  obj:     object data\n%                   - obj.v:    vertices\n%                   - obj.vt:   texture coordinates\n%                   - obj.f.v:  face definition vertices\n%                   - obj.f.vt: face definition texture\n%\n%       : texture -  texture image full path\n%\n% Author: Bernard Abayowa\n% University of Dayton\n% 6/16/08\n\ntexture = imread(texture);\ntexture_img = flipdim(texture,1);\n[sy sx sz] = size(texture_img);\ntexture_img =  reshape(texture_img,sy*sx,sz);\n\n% make image 3D if grayscale\nif sz == 1\n    texture_img = repmat(texture_img,1,3);\nend\n\n% select what texture correspond to each vertex according to face\n% definition\n[vertex_idx fv_idx] = unique(obj.f.v);\ntexture_idx = obj.f.vt(fv_idx);\n\nx = abs(round(obj.vt(:,1)*(sx-1)))+1;\ny = abs(round(obj.vt(:,2)*(sy-1)))+1;\nxy = sub2ind([sy sx],y,x);\ntexture_pts = xy(texture_idx);\ntval = double(texture_img(texture_pts,:))/255;\n\n\n\n% display object\nfigure; patch('vertices',obj.v,'faces',obj.f.v,'FaceVertexCData', tval);\nshading interp\ncolormap gray(256);\nlighting phong;\ncamproj('perspective');\naxis square; \naxis off;\naxis equal\naxis tight;\ncameramenu", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20307-displayobj/display_obj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2012557041507788}}
{"text": "function output = ...\n  SynthesizeByEventBasedMethod(event_index, event_time, ...\n                               harmonics_level_at_event, ...\n                               harmonics_deviation_at_event, fs, f0i, ...\n                               unvoiced_mask)\n% Synthesize speech from event based information made from lean\n% representation\n% output = ...\n%  SynthesizeByEventBasedMethod(event_index, event_time, ...\n%                               harmonics_level_at_event, ...\n%                               harmonics_deviation_at_event, fs, f0i, ...\n%                               unvoiced_mask)\n%\n% output = ...\n%  SynthesizeByEventBasedMethod(event_index, event_time, ...\n%                               harmonics_level_at_event, ...\n%                               harmonics_deviation_at_event, fs, f0i, ...\n%                               unvoiced_mask, interp_method)\n%\n% Input argument\n%\n% event_index: event location in sample index\n% event_time: actual event location (s)\n% harmonics_level_at_event: power information (dB)\n% harmonics_deviation_at_event: rondom relative power information (dB)\n% fs: sampling frequency (Hz)\n% f0i: fundamental frequency in sample time (Hz)\n% unvoiced_mask: silent indicator (for each event)\n%\n% Return value\n%\n% output: synthesized signal\n\n% Copyright 2016 Google Inc. All Rights Reserved\n% Author: hidekik@google.com (Hideki Kawahara)\n\n%% convert to FFT-based array\nnarginchk(7, 7);\n[response_for_periodic_trim, response_for_random_trim, ola_fftl] = ...\n  GenerateResponses(f0i, fs, harmonics_level_at_event, ...\n                    harmonics_deviation_at_event, event_time, event_index);\n%%\nout_buffer = f0i*0;\nnoise_out_buffer = out_buffer;\nsynth_out_buffer = out_buffer;\nsynth_noise_buffer = out_buffer;\nnData = length(out_buffer);\nhalf_width_of_BLIT = 2 * fs / (0.55 * fs);\nblit_base = -ceil(half_width_of_BLIT):ceil(half_width_of_BLIT);\ninitial_index = 1;\nnoise_spread = max(1,min(1,unvoiced_mask(:))); % 0.2 to 1\nbase_noise = randn(length(out_buffer),1);\nperiodic_working_buffer = zeros(ola_fftl, 1);\nzero_vector = periodic_working_buffer;\nola_zero = round(fs / min(f0i)) + 1;\nola_base = (1:ola_fftl)' - ola_zero;\nsample_index = (1:nData)';\nfor ii = 1:length(event_time)\n  base_index = event_index(ii) - blit_base; % minus (-) is the proper sign\n  [synth_out_buffer, out_buffer] = ...\n    UpdatePeriodicComponent(response_for_periodic_trim, synth_out_buffer, ...\n                            base_index, ii, zero_vector, event_time, ...\n                            event_index, fs, ola_zero, ola_base, ola_fftl, ...\n                            sample_index, unvoiced_mask, out_buffer);\n  [synth_noise_buffer, noise_out_buffer, initial_index] = ...\n    UpdateRandomComponent(response_for_random_trim, synth_noise_buffer, ...\n                          initial_index, ii, noise_spread, event_time, ...\n                          event_index, ola_zero, ola_base, ola_fftl, ...\n                          sample_index, base_noise, noise_out_buffer);\nend;\nraw_blit = GenerateBlitImpulse(blit_base, half_width_of_BLIT);\nblit_equalizer_response = DesignBlitEqualizer(raw_blit);\nhalf_width_of_EQBLIT = round((length(blit_equalizer_response) - 1) / 2);\ntmp_period = fftfilt(blit_equalizer_response, ...\n                     [synth_out_buffer; zeros(2 * half_width_of_EQBLIT, 1)]);\nsynth_noise_out = synth_noise_buffer ./ sqrt(f0i);\nsynth_periodic_out = ...\n  tmp_period(half_width_of_EQBLIT + (1:nData)) ./ sqrt(f0i);\noutput = synth_periodic_out + synth_noise_out;\nend\n\nfunction [response_for_periodic_trim, response_for_random_trim, ola_fftl] ...\n  = GenerateResponses(f0i, fs, harmonics_level_at_event, ...\n                      harmonics_deviation_at_event, event_time, event_index)\nkResidualToSNR = 11; % calibration constant from residual to SNR (dB)\nspectrum_out.used_f0 = f0i(event_index);\nspectrum_out.sampling_frequency = fs;\nspectrum_out.temporal_positions = event_time;\nspectrum_out.harmonic_power_dB = harmonics_level_at_event;\nspectral_envelope = CalculateSpectrumEnvelope(spectrum_out);\nnoise_out = spectrum_out;\nnoise_out.refined_f0 = f0i(event_index);\nnoise_out.frame_time = event_time;\nnoise_out.aperiodicity_matrix = harmonics_deviation_at_event;\naperiodicity_dB = ...\n  CalculateAperiodicitySgram(noise_out) + kResidualToSNR;\naperiodicity_ratio = ConvertDecibelToPower(min(0, aperiodicity_dB));\nmaximum_response_length = 0.03; % default 30 ms\nresponse_lengh = round(maximum_response_length * fs); % samples\nmaximum_noise_length = 2 / min(f0i);\nnoise_length = round(maximum_noise_length * fs); % samples\nola_fftl = 2 ^ ceil(log2(noise_length + response_lengh + 1));\nfftl = (size(spectral_envelope ,1) - 1) * 2;\n\ndata_frequency_axis = (0:fftl - 1) / fftl * fs;\ndata_frequency_axis(data_frequency_axis > fs / 2) = ...\n  data_frequency_axis(data_frequency_axis > fs / 2) - fs;\n% TODO(hidekik) need check: originally 50 maybe 150 better? (hz)\n% 1000 is the corner frequenccy (Hz)\nlow_noise_masker = ...\n  GetSigmoidNoiseShaper(data_frequency_axis, 1000, 150);\nspectral_envelope_DFTBIN = ...\n  [spectral_envelope;spectral_envelope(end-1:-1:2,:)];\nrandom_envelope_DFTBIN = ...\n  [aperiodicity_ratio;aperiodicity_ratio(end-1:-1:2,:)];\nrandom_envelope_SHAPED = ...\n  diag(low_noise_masker) * random_envelope_DFTBIN;\nperiodic_part = max(0.0001, (1 - random_envelope_SHAPED));\nperiodic_spectrum = sqrt(periodic_part .* spectral_envelope_DFTBIN);\nrandom_spectrum = ...\n  sqrt(random_envelope_SHAPED .* spectral_envelope_DFTBIN);\n%%\ntime_axis = (0:fftl -1)' / fs;\ntime_shaper = time_axis * 0 + 1;\ntime_shaper(time_axis > maximum_response_length) = 0;\ntime_segment = ...\n  (time_axis(time_axis > 0.8 * maximum_response_length & ...\n  time_axis <= maximum_response_length) ...\n  -0.8 * maximum_response_length) / (0.2 * maximum_response_length);\ntime_shaper(time_axis > 0.8 * maximum_response_length & ...\n  time_axis <= maximum_response_length) ...\n  = 0.5 + 0.5 * cos(pi * time_segment);\ncepstrum_for_periodic = ifft(log(periodic_spectrum));\ncomplex_cepstrum_for_periodic = cepstrum_for_periodic;\ncomplex_cepstrum_for_periodic(fftl / 2 + 1:end,:) = 0;\ncomplex_cepstrum_for_periodic(2:fftl / 2,:) = ...\n  complex_cepstrum_for_periodic(2:fftl / 2,:) * 2;\nresponse_for_periodic = diag(time_shaper) * ...\n  real(ifft(exp(fft(complex_cepstrum_for_periodic))));\nresponse_for_periodic_trim = response_for_periodic(1:response_lengh, :);\ncepstrum_for_random = ifft(log(random_spectrum));\ncomplex_cepstrum_for_random = cepstrum_for_random;\ncomplex_cepstrum_for_random(fftl / 2 + 1:end,:) = 0;\ncomplex_cepstrum_for_random(2:fftl / 2,:) = ...\n  complex_cepstrum_for_random(2:fftl / 2,:) * 2;\nresponse_for_random = diag(time_shaper) * ...\n  real(ifft(exp(fft(complex_cepstrum_for_random))));\nresponse_for_random_trim = response_for_random(1:response_lengh, :);\nend\n\nfunction [synth_out_buffer, out_buffer] = ...\n  UpdatePeriodicComponent(response_for_periodic_trim, synth_out_buffer, ...\n                          base_index, ii, zero_vector, event_time, ...\n                          event_index, fs, ola_zero, ola_base, ola_fftl, ...\n                          sample_index, unvoiced_mask, out_buffer)\n%\nnData = length(out_buffer);\nhalf_width_of_BLIT = 2 * fs / (0.55 * fs);\nblit_base = -ceil(half_width_of_BLIT):ceil(half_width_of_BLIT);\nperiodic_working_buffer = zero_vector;\nfractional_index = event_time(ii) * fs - event_index(ii) + 1 + blit_base;\ntmp_blit = GenerateBlitImpulse(fractional_index, half_width_of_BLIT);\nperiodic_working_buffer(ola_zero - blit_base) = tmp_blit / sum(tmp_blit);\nperiodic_working_out_buffer = ...\n  real(ifft(fft(periodic_working_buffer) .* ...\n            fft(response_for_periodic_trim(:, ii), ola_fftl)));\nout_buffer(max(1,min(nData,base_index))) = tmp_blit / sum(tmp_blit);\npast_index_condition = event_index(ii) + ola_base > 0 & ...\n  event_index(ii) + ola_base < nData;\nsynth_out_buffer(sample_index(event_index(ii) + ...\n  ola_base(past_index_condition))) = ...\n  periodic_working_out_buffer(past_index_condition) * ...\n  (1 - unvoiced_mask(ii)) + ...\n  synth_out_buffer(sample_index(event_index(ii) + ...\n  ola_base(past_index_condition)));\nend\n\nfunction [synth_noise_buffer, noise_out_buffer, initial_index] = ...\n  UpdateRandomComponent(response_for_random_trim, synth_noise_buffer, ...\n                        initial_index, ii, noise_spread, event_time, ...\n                        event_index, ola_zero, ola_base, ola_fftl, ...\n                        sample_index, base_noise, noise_out_buffer)\n%----\nnData = length(noise_out_buffer);\nprev_index = initial_index:event_index(ii);\nif ii == length(event_time)\n  post_index = event_index(ii):nData;\nelse\n  post_index = event_index(ii):event_index(ii + 1);\nend;\nprev_time = (prev_index(:) - event_index(ii)) / length(prev_index);\npost_time = (post_index(:) - event_index(ii)) / length(post_index);\nnoise_shape = 0.5 * [(1 + cos(pi*prev_time / noise_spread(ii))) .* ...\n  (abs(prev_time / noise_spread(ii)) <= 1); ...\n  (1 + cos(pi * post_time(2:end) / noise_spread(ii))) .* ...\n  (abs(post_time(2:end) / noise_spread(ii)) <= 1)];\nnoise_out_buffer(prev_index(1):post_index(end)) = ...\n  noise_out_buffer(prev_index(1):post_index(end)) + noise_shape .* ...\n  base_noise(prev_index(1):post_index(end)) / sqrt(sum(noise_shape .^ 2));\ninitial_index = event_index(ii);\nnoise_base_index = (prev_index(1):post_index(end))' - event_index(ii);\nnoise_working_buffer(max(1,ola_zero + noise_base_index)) = ...\n  noise_shape .* base_noise(prev_index(1):post_index(end)) / ...\n  sqrt(sum(noise_shape .^ 2));\nnoise_working_out_buffer = ...\n  real(ifft(fft(noise_working_buffer(:), ola_fftl) .* ...\n            fft(response_for_random_trim(:, ii), ola_fftl)));\npast_index_condition = event_index(ii) + ola_base > 0 & ...\n  event_index(ii) + ola_base < nData;\nsynth_noise_buffer(sample_index(event_index(ii) + ...\n  ola_base(past_index_condition))) = ...\n  noise_working_out_buffer(past_index_condition) + ...\n  synth_noise_buffer(sample_index(event_index(ii) + ...\n  ola_base(past_index_condition)));\nend\n", "meta": {"author": "google", "repo": "yang_vocoder", "sha": "45787d4bbbb5b36617424b95c19430ced277db23", "save_path": "github-repos/MATLAB/google-yang_vocoder", "path": "github-repos/MATLAB/google-yang_vocoder/yang_vocoder-45787d4bbbb5b36617424b95c19430ced277db23/SynthesizeByEventBasedMethod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.2012092785990805}}
{"text": "% This function dynamically generates distorted speech signals. It is\n% usually used for speech enhancement or robust ASR tasks. \n%\n% Authors: Xiong Xiao, NTU, Singapore\n% Last Modified: 28 Feb 2017\n%\nfunction [data, paraDD, data_log] = GenDynamicDistortion(base_data, paraDD)\n\nclean_data = base_data(1).data;\nrir_data = base_data(2).data;\nnoise_data = base_data(3).data;\n\n% get settings\nuseSoftMask = ReturnFieldWithDefaultValue(paraDD, 'useSoftMask', 0);\nrandomizeFileOrder = ReturnFieldWithDefaultValue(paraDD, 'randomizeFileOrder', 1);\ngainNorm = ReturnFieldWithDefaultValue(paraDD, 'gainNorm', 1);\nvadStream = ReturnFieldWithDefaultValue(paraDD, 'vadStream', []);\nif ~isempty(vadStream)\n    vadData = base_data(vadStream);\nend\n\n[clean_data_loaded, clean_idx] = LoadOriginalWave(clean_data, paraDD, randomizeFileOrder,1);\nif ~isempty(rir_data)\n    [rir_data_loaded, rir_idx] = LoadOriginalWave(rir_data, paraDD, randomizeFileOrder,2);\nend\nif ~isempty(noise_data)\n    [noise_data_loaded, noise_idx] = LoadOriginalWave(noise_data, paraDD, randomizeFileOrder,3);\nend\n\nif length(base_data)>3  % sometimes, we have other data, such as frame phone label. We just copy that to the output data. \n    hasExtraData = 0; extraData = [];\n    for i=4:length(base_data)\n        if ~isempty(vadStream) && i == vadStream; continue; end\n        extraData(end+1).data = base_data(i).data(clean_idx);  % note that the extra data streams are binded with the clean data. \n        hasExtraData = 1;\n    end\nend\n\nswitch lower(paraDD.SNR_PDF)\n    case 'uniform'\n        SNR = rand(1,paraDD.nUtt4Iteration) * (paraDD.SNR_para(2) - paraDD.SNR_para(1)) + paraDD.SNR_para(1);\n    case 'normal'\n        SNR = randn(1,paraDD.nUtt4Iteration) * paraDD.SNR_para(2) + paraDD.SNR_para(1);\n        SNR = max(-50, min(50, SNR));   % do not allow too low or high SNRs\nend\n\nif isfield(paraDD, 'seglen') && paraDD.seglen>0\n    doSegmentation = 1;\n    seglen = paraDD.seglen;\n    segshift = paraDD.segshift;\n    frame_len = paraDD.frame_len;\n    frame_shift = paraDD.frame_shift;\nelse\n    doSegmentation = 0;\nend\nif isfield(paraDD, 'outputDataIdxMask') && ~isempty(paraDD.outputDataIdxMask) && paraDD.outputDataIdxMask>0\n    genMask = 1;\nelse\n    genMask = 0;\nend\n\nif ~isfield(paraDD, 'outputDataIdxClean')   % by default, the clean speech should be in stream 2\n    cleanStreamIdx = 2;\nelseif ~isempty(paraDD.outputDataIdxClean) && paraDD.outputDataIdxClean>0   % otherwise, put it in the defined index\n    cleanStreamIdx = paraDD.outputDataIdxClean;\nelse\n    cleanStreamIdx = -1;\nend\n\ndistorted = {}; clean_data_aligned = {}; mask = {};\nfor j=1:length(extraData)\n    extraDataSeg(j).data = {};\nend\nfor i=1:length(clean_idx)\n    data_log{i} = [clean_data{clean_idx(i)}];\n    if paraDD.singlePrecision\n        curr_clean_wav = single(clean_data_loaded{clean_idx(i)})';\n        if ~isempty(rir_data); curr_rir = single(rir_data_loaded{rir_idx(i)})'; else; curr_rir = []; end\n        if ~isempty(noise_data); curr_noise = single(noise_data_loaded{noise_idx(i)})'; else; curr_noise = [];  end\n    else\n        curr_clean_wav = double(clean_data_loaded{clean_idx(i)})';\n        if ~isempty(rir_data); curr_rir = double(rir_data_loaded{rir_idx(i)})'; else; curr_rir = []; end\n        if ~isempty(noise_data); curr_noise = double(noise_data_loaded{noise_idx(i)})'; else; curr_noise = [];  end\n    end\n    if ~isempty(curr_rir)   % we want the direct sound to have the gain of 1\n        curr_rir = curr_rir/max(curr_rir(:));\n        data_log{i} = sprintf('%s\\t%s', data_log{i}, rir_data{rir_idx(i)});\n    else\n        data_log{i} = sprintf('%s\\tNULL', data_log{i});\n    end\n    if ~isempty(noise_data)\n        data_log{i} = sprintf('%s\\t%s', data_log{i}, noise_data{noise_idx(i)});\n    else\n        data_log{i} = sprintf('%s\\tNULL', data_log{i});\n    end\n    data_log{i} = sprintf('%s\\t%fdB', data_log{i}, SNR(i));\n    \n    [curr_distorted, curr_reverb, curr_direct] = ApplyConstRirNoise(curr_clean_wav, paraDD.fs, curr_rir, curr_noise, SNR(i), paraDD.useGPU);\n    curr_distorted = gather(curr_distorted)';\n    curr_distorted(:, length(curr_clean_wav)+1:end) = [];\n    curr_direct = gather(curr_direct)';\n    curr_direct(:, length(curr_clean_wav)+1:end) = [];\n    %curr_reverb = gather(curr_reverb)';\n    %curr_reverb(:, length(curr_clean_wav)+1:end) = [];\n    \n    if genMask\n        if 0    \n            [curr_mask, curr_SNR] = genMaskFromParallelData(curr_clean_wav, curr_distorted', paraDD.fs, 0);\n        else    % it's better to use curr_direct, which contains the early reflection up to 50ms after the direct sound, as the clean reference. \n            if isempty(vadStream)\n                [curr_mask] = genMaskFromParallelData(curr_clean_wav, curr_direct', curr_distorted', [], paraDD.fs, useSoftMask, 0);\n            else\n                [curr_mask] = genMaskFromParallelData(curr_clean_wav, curr_direct', curr_distorted', vadData.data{clean_idx(i)}, paraDD.fs, useSoftMask, 0);\n            end\n        end    \n    end\n    if gainNorm\n        curr_distorted = curr_distorted / max(abs(curr_distorted(:))); \n    end\n    switch class(gather(clean_data_loaded{clean_idx(i)}(1)))\n        case 'int16'\n            curr_distorted = StoreWavInt16(curr_distorted);\n        case {'single', 'float'}\n            curr_distorted = single(curr_distorted);\n        otherwise\n            curr_distorted = double(curr_distorted);            \n    end\n    \n    if doSegmentation\n        curr_distorted_seg = DivideSent2Segments(curr_distorted, (seglen-1)*frame_shift+frame_len, segshift*frame_shift, 1);\n        distorted = [distorted curr_distorted_seg'];\n        curr_clean_wav_seg = DivideSent2Segments(clean_data_loaded{clean_idx(i)}, (seglen-1)*frame_shift+frame_len, segshift*frame_shift, 1);\n        if cleanStreamIdx>0\n            clean_data_aligned = [clean_data_aligned curr_clean_wav_seg'];\n        end\n        if genMask\n            curr_mask_seg = DivideSent2Segments(curr_mask, seglen, segshift, 1);\n            mask = [mask curr_mask_seg'];\n        end\n        for j=1:length(extraData)\n            tmpDataSeg = DivideSent2Segments(extraData(j).data{i}, seglen, segshift, 1);    % we assume that the extra data are having 100Hz frame rate\n            extraDataSeg(j).data = [extraDataSeg(j).data tmpDataSeg'];\n        end\n    else\n        distorted{i} = curr_distorted;\n        if cleanStreamIdx>0; clean_data_aligned{i} = clean_data_loaded{clean_idx(i)}; end\n        if genMask; mask{i} = curr_mask; end\n    end\n    \n    PrintProgress(i, length(clean_idx), max(10, round(length(clean_idx)/10)), ...\n            'GenDynamicDistortion->Mixing clean speech with RIR and noise');\nend\n\nnOutputStream = 3;\nif ~isfield(paraDD, 'outputDataIdxDistorted')   % by default, the distorted speech should be in stream 1\n    data(1).data = distorted;\nelseif ~isempty(paraDD.outputDataIdxDistorted) && paraDD.outputDataIdxDistorted>0   % otherwise, put it in the defined index\n    data(paraDD.outputDataIdxDistorted).data = distorted;\nelse\n    nOutputStream = nOutputStream -1;\n    % do not output distorted speech\nend\nif cleanStreamIdx>0\n    data(cleanStreamIdx).data = clean_data_aligned;\nelse\n    nOutputStream = nOutputStream -1;\n    % do not output clean speech\nend\nif genMask\n    data(paraDD.outputDataIdxMask).data = mask;\nelse\n    nOutputStream = nOutputStream -1;\nend\n\nif hasExtraData\n    if doSegmentation\n        data = [data extraDataSeg];\n    else\n        data = [data extraData];\n    end\nend\n\nend\n\n\nfunction [data, idx] = LoadOriginalWave(wavlist, paraDD, randomizeFileOrder, streamIdx)\nif isempty(wavlist)\n    return;\nend\nif randomizeFileOrder\n    idx = randperm(length(wavlist));\nelse\n    idx = 1:length(wavlist);\nend\nnRepeat = ceil(paraDD.nUtt4Iteration/length(idx));\nidx = repmat(idx, 1, nRepeat);\nidx(paraDD.nUtt4Iteration+1:end) = [];\n\nif paraDD.inputFeature(streamIdx)\n    data = wavlist;\nelse\n    need2load = unique(idx);\n    for i=1:length(need2load)\n        PrintProgress(i, length(need2load), max(100, round(length(need2load)/10)), ...\n            sprintf('GenDynamicDistortion->LoadOriginalWav->Stream %d', streamIdx));\n        % data{need2load(i)} = InputReader(wavlist{need2load(i)}, paraDD.fileReader(streamIdx));\n        data{need2load(i)} = paraDD.fileReader{streamIdx}.read(wavlist{need2load(i)});\n    end\nend\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/utils/GenDynamicDistortion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.2012092745881376}}
{"text": "function studyreg = readLeksellStudyregFile(filename)\n%\"readLeksellStudyregFile\"\n%   Reads a Leksell studyreg file using decodeLeksellData and places the\n%   fields into a datastructure with meaningful names.  This structure\n%   shows the meaning of the transformation matrices in the Leksell Study\n%   files so that it is clear which modality the matrices are going to and\n%   from.  However, this information is not used when importing to CERR\n%   because the target modality is always LGP (the Leksell coordinate\n%   system).\n%\n%JRA 6/13/05\n%\n%LM: KRK, 05/29/07, added additional documentation\n%\n%Usage:\n%   studyreg = readLeksellStudyregFile(filename)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nfid = fopen(filename, 'r', 'b');\n\ndata = decodeLeksellData(fid);\n\nfclose(fid);\n\n%If data does not have at least two elements it is effectively empty.\nif length(data) < 2\n    studyreg = [];\n    return;\nend\n\nfor i=1:length(data) - 1\n    rawStudyreg = data{i};\n\n\tstudyreg(i).original_modality       = rawStudyreg{1}; %MR/CT/etc\n\tstudyreg(i).target_modality         = rawStudyreg{2}; %Leksell   \n  \tstudyreg(i).registration_value      = rawStudyreg{3}; %original modalities reg. value\n\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/Leksell_Gamma/readLeksellStudyregFile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20112811389726704}}
{"text": "function [vM, vM_]=cluster200x(fTaumin, fTaumax, fXk, fXmeff, fP1, fRfact, fMerr, fZerr,mCat)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Example: [vMain, vClus]=cluster200x(2880,14400,0.5,3.0,0.99,10,0,0,a)\n% Author: van Stiphout, Thomas\n% Email: vanstiphout@sed.ethz.ch\n% Created: 14. Feb. 2007\n% Changed: -\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Variables:\n% mCat              Catalog to be declustered\n% iYr1                Starting year (read from mCat)\n% iYr2                Ending year (read from mCat)\n% fXmeff            Magnitude cutoff\n% fRfact             rfact\n% fTau0              Tau0 (is equal fTaumin)\n% fTaumin          Taumin\n% fTaumax         Taumax\n% fP1                  P1\n% fXk                  xk\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% prevent year 2000 problem / transition\nfYrStart_=floor(min(mCat(:,3)));\nmCatTime_=mCat(:,3);\nmCat(:,3)=mCat(:,3)-fYrStart_;\n% prepare variables\nfTaumin=fTaumin*24*60;\nfTau0=fTaumin;\nfTaumax=fTaumax*24*60;\nsYr1=num2str(floor(min(mCat(:,3))));\nsYr2=num2str(ceil(max(mCat(:,3))));\n% sYr1=sYr1(3:4);\n% sYr2=sYr2(3:4);\n\n% does catalog contain 12 columns?\nif (size(mCat,2)<12)\n    mTmp=nan(size(mCat,1),(12-size(mCat,2)));\n    mCat=[mCat mTmp];\nend\n!rm tmp cluster.* input.cmn tmp v.dat CA.hypo71\n% export to readalbe format for tmp\nexport2hypo71(mCat,'tmp');\n% remove NaN from exported catalog\nunix(['sed ''s/NaN/   /'' tmp > CA.hypo71']);\n% write input file (input.cmn)\ninfile=fopen('input.cmn','w');\nfprintf(infile,'CA.hypo71\\n4\\n%2s\\n%2s\\n%3.1f\\n%06.3f\\n%08.3f\\n%010.2f\\n%010.2f\\n%05.2f\\n%05.2f',...\n    sYr1,sYr2,fXmeff,fRfact,fTau0,fTaumin,fTaumax,fP1,fXk);\nfclose(infile);\n% run declustering algorithm of f reasenberg cluster200x\nunix('~/zmap/src/thomas/decluster/reasen/cluster200x > tmp');\n% extract vector with 1 and 0's of events in declustered catalog\nunix(['awk -f ~/zmap/src/thomas/decluster/reasen/clu2list.awk cluster.ano > v.dat ' ]);\n% import vector\nvM_=load('v.dat');\nvSelN0=(vM_==0);\nvSelNc=zeros(size(vSelN0));\n\nfor i=1:max(vM_)\n    vPos1=find(vM_==i);\n    if ~isempty(vPos1)\n        vPos2=find(mCat(vPos1,6)==max(mCat(vPos1,6)));\n        if (vPos2==1)\n            vPos3=vPos1(vPos2);\n        else\n            vPos3=vPos1(1);\n        end\n        vSelNc(vPos3)=1;\n    end\n    clear vPos1 vPos2 vPos3\nend\n\nvM=(logical(vSelN0) | logical(vSelNc));\n% % clean up\n% !rm cluster.*\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/thomas/decluster/reasen/cluster200x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.2008166837891869}}
{"text": "function [ bad_idx ] = prepLBPconf( config, options, type, annotation_struct, images_fname, gt_fname )\n%PREPLBPCONF Prepares configuration for LBP features function call. \n%   Detailed explanation goes here\n% \n% INPUT:\n%   config       ...     structure config (see experiment02.m)\n%   options      ...     structure options (bw, bw_margin, components, M, order, ...)\n%   type         ...     string with one of ['TRN', 'TST', 'VAL'] value\n%   datapath     ...     path to dataset (TRN, VAL, TST)\n%   images_fname ...     full path filename where matrix with images will be stored\n%   gt_fname     ...     full path filename where GT will be stored\n% \n% 09-08-10 Michal Uricar\n% 12-07-11 Michal Uricar, corners dataset modification\n\n    bad_idx = [];\n\n    if (~strcmp(type, 'TRN') && ~strcmp(type, 'VAL') && ~strcmp(type, 'TST'))\n        error('??? Invalid type of dataset. Must be one of [''TRN'', ''VAL'', ''TST'']');\n    end;\n    \n    fprintf(['Prepare ' type ' images...\\n']);\n\n%     load(datapath);\n    switch (config.nImages)\n        case 'all'\n            nImages = annotation_struct.N;\n        case 'half'\n            nImages = round(annotation_struct.N/2);\n        otherwise\n            nImages = str2num(config.nImages);\n    end;\n    \n    gt = cell(nImages, 1);\n    \n    fprintf([type ': Creating array of images...\\n']);\n    imSize = [options.bw(2), options.bw(1)];\n    Images = uint8(zeros(options.bw(1)*options.bw(2), nImages));\n    for i = 1 : nImages\n        [I, Annotation] = getImageFrame(options, i, annotation_struct);\n        \n        if (isempty(Annotation))\n            bad_idx = [bad_idx i];\n            continue;\n        end;\n        \n        Points = prepareS0gt(Annotation.P, options);    % transform nose to the center of face\n        Points = Points(:, options.comselect);          % extract relevant points only (name list in options.compnames)\n        Points(:, options.M) = Annotation.P(:, 10);     % copy back original nose position\n\n        fprintf([type ': %.2f%% Processing image %s.\\n'], i*100/nImages, Annotation.image.filename);\n        \n        Images(:, i) = I(:);\n        gt{i} = Points;\n        %gt{i} = TestPoints;\n    end;\n    \n    %% Save array of Images\n    fprintf([ type ': Saving array of images to file %s...\\n'], images_fname);\n    save(images_fname, 'Images', 'imSize');\n    fprintf([ type ': Saving ground truth points to file %s...\\n'], gt_fname);\n    save(gt_fname, 'gt');\nend\n", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/Functions/prepLBPconf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20076527063350744}}
{"text": "function D = spm_eeg_combineplanar(S)\n% Combine data from MEGPLANAR sensors\n% FORMAT D = spm_eeg_combineplanar(S)\n%\n% S        - optional input struct\n%  fields of S:\n%   D        - MEEG object or filename\n%   mode     -\n%              'append'     - add combined channels to the origal channels\n%              'replace'    - replace MEGPLANAR with combined [default]\n%              'replacemeg' - replace all MEG channels with combined but\n%                             keep non-MEG\n%              'keep'       - only write out the combined channels\n%\n%   prefix   - prefix for the output file [default: 'P']\n%\n% Output:\n% D        - MEEG object (also written on disk)\n%\n%__________________________________________________________________________\n% Copyright (C) 2008-2017 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: spm_eeg_combineplanar.m 7132 2017-07-10 16:22:58Z guillaume $\n\nSVNrev = '$Rev: 7132 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('FnBanner', mfilename, SVNrev);\nspm('FigName','MEG Combine planar'); spm('Pointer','Watch');\n\nif ~isfield(S, 'prefix'),       S.prefix   = 'P';           end\nif ~isfield(S, 'mode'),         S.mode     = 'replace';     end\n\nD = spm_eeg_load(S.D);\n\nisTF = strncmpi(D.transformtype,'TF',2);\n\nchanset = spm_eeg_planarchannelset(D.chanlabels);\n\nchanind = [];\nlabelnew = {};\nfor i = 1:size(chanset, 1)\n    cind = D.indchannel(chanset(i, 1:2));\n    if length(cind) == 2\n        chanind  = [chanind cind];\n        labelnew = [labelnew; chanset(i, end)];\n    end\nend\n\nmegind    = D.indchantype('MEG');\nplanarind = D.indchantype('MEGPLANAR');\n\n% add a row of zeros;\nchanind(3, end) = 0;\ncopyind = [];\nswitch S.mode\n    case 'append'\n        copyind = 1:D.nchannels;\n        copyind = [copyind; copyind];\n        chanind(3, :) = (D.nchannels+1):(D.nchannels+size(chanind, 2));\n    case {'replace', 'replacemeg'}\n        ind = 1;\n        for i = 1:D.nchannels\n            if any(i == planarind)\n                k = find((chanind(1, :) == i) | (chanind(2, :) == i));\n                if ~isempty(k) && (chanind(3, k) == 0)\n                    chanind(3, k) = ind;\n                    ind = ind + 1;\n                end\n            elseif isequal(S.mode, 'replace') || ~any(i == megind)\n                copyind = [copyind [i ind]'];\n                ind = ind + 1;\n            end\n        end\n    case 'keep'\n        copyind       = [];\n        chanind(3, :) = 1:size(chanind, 2);\nend\n\nif isempty(copyind)\n    Nchannels = max(chanind(3, :));\nelse\n    Nchannels = max([chanind(3, :), copyind(2, :)]);\nend\n\n%-Generate new MEEG object with new files\n%--------------------------------------------------------------------------\nif isTF\n    Dnew = clone(D, [S.prefix fname(D)], [Nchannels D.nfrequencies D.nsamples D.ntrials], 1);\nelse\n    Dnew = clone(D, [S.prefix fname(D)], [Nchannels D.nsamples D.ntrials], 1);\nend\n\nif strcmp(D.type, 'continuous')\n    %-Continuous data\n    %----------------------------------------------------------------------\n    blksz  = D.fsample;\n    blknum = floor(D.nsamples/blksz);\n    \n    spm_progress_bar('Init', blknum, 'Data blocks processed');\n    if blknum > 100, Ibar = floor(linspace(1, blknum,100));\n    else Ibar = 1:blknum; end\n    \n    if isTF\n        i = 1;\n        while 1\n            if i<=blknum\n                Iblock  = ((i-1)*blksz + 1):(i*blksz);\n            elseif (i == (blknum + 1)) && blknum*blksz < D.nsamples\n                Iblock  = (blknum*blksz + 1):D.nsamples;\n            else\n                break;\n            end\n            \n            \n            planar1 = D(chanind(1, :), :, Iblock);\n            planar2 = D(chanind(2, :), :, Iblock);\n                       \n            Dnew(chanind(3, :), :, Iblock) = planar1 + planar2;\n            \n            \n            if ~isempty(copyind)\n                Dnew(copyind(2, :), :, Iblock) =  D(copyind(1, :), :, Iblock);\n            end\n            \n            if any(Ibar == i), spm_progress_bar('Set', i); end\n            \n            i = i+1;\n        end\n    else\n        i = 1;\n        while 1\n            if i<=blknum\n                Iblock  = ((i-1)*blksz + 1):(i*blksz);\n            elseif (i == (blknum + 1)) && blknum*blksz < D.nsamples\n                Iblock  = (blknum*blksz + 1):D.nsamples;               \n            else\n                break;\n            end\n            \n            planar1 = D(chanind(1, :),  Iblock);\n            planar2 = D(chanind(2, :),  Iblock);\n            \n            Dnew(chanind(3, :), Iblock) = sqrt(planar1.^2 + planar2.^2);\n            \n            if ~isempty(copyind)\n                Dnew(copyind(2, :), Iblock) =  D(copyind(1, :), Iblock);\n            end\n            \n            if any(Ibar == i), spm_progress_bar('Set', i); end\n            \n            i = i+1;\n        end\n    end\nelse\n    %-Epoched data\n    %----------------------------------------------------------------------\n    spm_progress_bar('Init', D.ntrials, 'Trials processed');\n    if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials, 100));\n    else Ibar = 1:D.ntrials; end\n    \n    if isTF\n        for i=1:D.ntrials\n            planar1 = D(chanind(1, :), :, :, i);\n            planar2 = D(chanind(2, :), :, :, i);\n            \n            Dnew(chanind(3, :),:, :, i) = planar1 + planar2;\n            \n            if ~isempty(copyind)\n                Dnew(copyind(2, :), :, :, i) =  D(copyind(1, :), :, :, i);\n            end\n            \n            if any(Ibar == i), spm_progress_bar('Set', i); end\n        end\n    else\n        for i=1:D.ntrials\n            planar1 = D(chanind(1, :), :, i);\n            planar2 = D(chanind(2, :), :, i);\n            \n            Dnew(chanind(3, :), :, i) = sqrt(planar1.^2 + planar2.^2);\n            \n            if ~isempty(copyind)\n                Dnew(copyind(2, :), :, i) =  D(copyind(1, :), :, i);\n            end\n            \n            if any(Ibar == i), spm_progress_bar('Set', i); end\n        end\n    end\nend\n\nspm_progress_bar('Clear');\n\nDnew = chanlabels(Dnew, chanind(3, :), labelnew);\nDnew = badchannels(Dnew, chanind(3, :), badchannels(D, chanind(1, :)) | badchannels(D, chanind(2, :)));\nDnew = chantype(Dnew, chanind(3, :), 'MEGCOMB');\nDnew = units(Dnew, chanind(3, :), units(D, chanind(1, :)));\nDnew = coor2D(Dnew, chanind(3, :), 0.5*(coor2D(D, chanind(1,:))+coor2D(D, chanind(1,:))));\n\nif ~isempty(copyind)\n    Dnew = chanlabels(Dnew, copyind(2, :), D.chanlabels(copyind(1, :)));\n    Dnew = badchannels(Dnew, copyind(2, :), badchannels(D, copyind(1, :)));\n    Dnew = chantype(Dnew, copyind(2, :), D.chantype(copyind(1, :)));\n    Dnew = units(Dnew, copyind(2, :), D.units(copyind(1, :)));\n    Dnew = coor2D(Dnew, copyind(2, :),coor2D(D, copyind(1, :)));\nend\n\n%-Save the new M/EEG dataset\n%--------------------------------------------------------------------------\nDnew = Dnew.history(mfilename, S);\nsave(Dnew);\n\nD = Dnew;\n\n%-Cleanup\n%--------------------------------------------------------------------------\nfprintf('%-40s: %30s\\n','Completed',spm('time'));                       %-#\nspm('FigName','MEG Combine planar: done'); spm('Pointer','Arrow');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_combineplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.20070311158327583}}
{"text": "2     % problem\n5     % outflow boundary\n7     % grid parameter\n3     % discretisation\n0.02  % viscosity parameter\n1     % Picard/Newton/hybrid linearization\n9     % number of Picard iterations\n1.d-5 % nonlinear tolerance\n\n%% Data file for backward facing step\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/batchfiles/NS_bfs_R100_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2005531420953717}}
{"text": "function model = edgesTrainDL(dlPara, varargin )\n% Train structured edge detector with deep contour features.\n% The code is modified from Structured Edge Detection Toolbox\n\n\n% get default parameters\ndfs={'imWidth',32, 'gtWidth',16, 'nPos',5e5, 'nNeg',5e5, 'nImgs',inf, ...\n  'nTrees',10, 'fracFtrs',0.25, 'minCount',1, 'minChild',8, ...\n  'maxDepth',64, 'discretize','pca', 'nSamples',256, 'nClasses',2, ...\n  'split','gini', 'nOrients',4, 'grdSmooth',0, 'chnSmooth',2, ...\n  'simSmooth',8, 'normRad',4, 'shrink',2, 'nCells',5, 'rgbd',0, ...\n  'stride',2, 'multiscale',0, 'sharpen',2, 'nTreesEval',4, ...\n  'nThreads',4, 'nms',0, 'seed',1, 'useParfor',0, 'modelDir','models/', ...\n  'modelFnm','model', 'bsdsDir','BSR/BSDS500/data/'};\nopts = getPrmDflt(varargin,dfs,1);\nif(nargin==0), model=opts; return; end\n% opts.nBatch = dlPara.nBatch;\n% opts.nOutputNum = dlPara.nOutputNum;\nopts.patch_mean = dlPara.patch_mean;\nopts.modelDir = dlPara.modelDir;\nopts.selected_dims = dlPara.selected_dims;\n% if forest exists load it and return\ncd(fileparts(mfilename('fullpath')));\nforestDir = [opts.modelDir '/forest/'];\nforestFn = [forestDir opts.modelFnm];\nif(exist([forestFn '.mat'], 'file'))\n  load([forestFn '.mat']); return; end\nif(~exist(forestDir,'dir')), mkdir(forestDir); end\n% compute constants and store in opts\nnTrees=opts.nTrees; nCells=opts.nCells; shrink=opts.shrink;\nopts.nPos=round(opts.nPos); opts.nNeg=round(opts.nNeg);\nopts.nTreesEval=min(opts.nTreesEval,nTrees);\nopts.stride=max(opts.stride,shrink);\nimWidth=opts.imWidth; gtWidth=opts.gtWidth;\n% imWidth=round(max(gtWidth,imWidth)/shrink/2)*shrink*2;\n% opts.imWidth=imWidth; opts.gtWidth=gtWidth;\n% nChnsGrad=(opts.nOrients+1)*2; nChnsColor=3;\n% if(opts.rgbd==1), nChnsColor=1; end\n% if(opts.rgbd==2), nChnsGrad=nChnsGrad*2; nChnsColor=nChnsColor+1; end\n% nChns = nChnsGrad+nChnsColor; \n\n% opts.nChnFtrs = imWidth*imWidth*nChns/shrink/shrink;\n% opts.nSimFtrs = (nCells*nCells)*(nCells*nCells-1)/2*nChns;\nnChns = length(opts.selected_dims);\nif(nChns == 0)\n    I = zeros([1 1 3], 'single');\n    deepFeat = edgesChnsDL2(I, opts);\n    nChns = size(deepFeat, 3);\n    opts.selected_dims = [1:nChns]';\nend\nopts.nChns = nChns;\n% opts.nTotFtrs = imWidth*imWidth*nChns/shrink/shrink; disp(opts);\nopts.nTotFtrs = round(imWidth/shrink)*round(imWidth/shrink)*nChns; disp(opts);\n% generate stream for reproducibility of model\nstream=RandStream('mrg32k3a','Seed',opts.seed);\n\n% train nTrees random trees (can be trained with parfor if enough memory)\nif(opts.useParfor), \n    parfor i=1:nTrees, \n        trainTree(opts,stream,i); \n    end\nelse\n    for i=1:nTrees, \n        trainTree(opts,stream,i); \n    end; \nend\n\n% merge trees and save model\nmodel = mergeTrees( opts );\nif(~exist(forestDir,'dir')), mkdir(forestDir); end\nsave([forestFn '.mat'], 'model', '-v7.3');\n\nend\n\nfunction model = mergeTrees( opts )\n% accumulate trees and merge into final model\nnTrees=opts.nTrees; gtWidth=opts.gtWidth;\ntreeFn = [opts.modelDir '/tree/' opts.modelFnm '_tree'];\nfor i=1:nTrees\n  t=load([treeFn int2str2(i,3) '.mat'],'tree'); t=t.tree;\n  if(i==1), trees=t(ones(1,nTrees)); else trees(i)=t; end\nend\nnNodes=0; for i=1:nTrees, nNodes=max(nNodes,size(trees(i).fids,1)); end\n% merge all fields of all trees\nmodel.opts=opts; Z=zeros(nNodes,nTrees,'uint32');\nmodel.thrs=zeros(nNodes,nTrees,'single');\nmodel.fids=Z; model.child=Z; model.count=Z; model.depth=Z;\nmodel.segs=zeros(gtWidth,gtWidth,nNodes,nTrees,'uint8');\nfor i=1:nTrees, tree=trees(i); nNodes1=size(tree.fids,1);\n  model.fids(1:nNodes1,i) = tree.fids;\n  model.thrs(1:nNodes1,i) = tree.thrs;\n  model.child(1:nNodes1,i) = tree.child;\n  model.count(1:nNodes1,i) = tree.count;\n  model.depth(1:nNodes1,i) = tree.depth;\n  model.segs(:,:,1:nNodes1,i) = tree.hs-1;\nend\n% remove very small segments (<=5 pixels)\nsegs=model.segs; nSegs=squeeze(max(max(segs)))+1;\nparfor i=1:nTrees*nNodes, m=nSegs(i);\n  if(m==1), continue; end; S=segs(:,:,i); del=0;\n  for j=1:m, Sj=(S==j-1); if(nnz(Sj)>5), continue; end\n    S(Sj)=median(single(S(convTri(single(Sj),1)>0))); del=1; end\n  if(del), [~,~,S]=unique(S); S=reshape(S-1,gtWidth,gtWidth);\n    segs(:,:,i)=S; nSegs(i)=max(S(:))+1; end\nend\nmodel.segs=segs; model.nSegs=nSegs;\n% store compact representations of sparse binary edge patches\nnBnds=opts.sharpen+1; eBins=cell(nTrees*nNodes,nBnds);\neBnds=zeros(nNodes*nTrees,nBnds);\nparfor i=1:nTrees*nNodes\n  if(model.child(i) || model.nSegs(i)==1), continue; end %#ok<PFBNS>\n  E=gradientMag(single(model.segs(:,:,i)))>.01; E0=0;\n  for j=1:nBnds, eBins{i,j}=uint16(find(E & ~E0)'-1); E0=E;\n    eBnds(i,j)=length(eBins{i,j}); E=convTri(single(E),1)>.01; end\nend\neBins=eBins'; model.eBins=[eBins{:}]';\neBnds=eBnds'; model.eBnds=uint32([0; cumsum(eBnds(:))]);\nend\n\nfunction trainTree( opts, stream, treeInd )\n% Train a single tree in forest model.\n\n% location of ground truth\ntrnImgDir = [opts.bsdsDir '/images/train/'];\ntrnDepDir = [opts.bsdsDir '/depth/train/'];\ntrnGtDir = [opts.bsdsDir '/groundTruth/train/'];\ntrnFeatFir = [opts.modelDir '/feat/'];\nif(~exist(trnFeatFir,'dir')), mkdir(trnFeatFir); end\nimgIds=dir(trnImgDir); imgIds=imgIds([imgIds.bytes]>0);\nimgIds={imgIds.name}; ext=imgIds{1}(end-2:end);\nnImgs=length(imgIds); for i=1:nImgs, imgIds{i}=imgIds{i}(1:end-4); end\n\n% extract commonly used options\nimWidth=opts.imWidth; imRadius=floor(imWidth/2);\ngtWidth=opts.gtWidth; gtRadius=gtWidth/2;\nnChns=opts.nChns; \nnTotFtrs=opts.nTotFtrs;\nselected_dims = opts.selected_dims;\nrgbd=opts.rgbd;\nnPos=opts.nPos; nNeg=opts.nNeg; shrink=opts.shrink;\n\n% finalize setup\ntreeDir = [opts.modelDir '/tree/'];\ntreeFn = [treeDir opts.modelFnm '_tree'];\nif(exist([treeFn int2str2(treeInd,3) '.mat'],'file'))\n  fprintf('Reusing tree %d of %d\\n',treeInd,opts.nTrees); return; end\nfprintf('\\n-------------------------------------------\\n');\nfprintf('Training tree %d of %d\\n',treeInd,opts.nTrees); tStart=clock;\n\n% set global stream to stream with given substream (will undo at end)\nstreamOrig = RandStream.getGlobalStream();\nset(stream,'Substream',treeInd);\nRandStream.setGlobalStream( stream );\n\n% collect positive and negative patches and compute features\nfids=sort(randperm(nTotFtrs,round(nTotFtrs*opts.fracFtrs)));\nk = nPos+nNeg; nImgs=min(nImgs,opts.nImgs);\nftrs = zeros(k,length(fids),'single');\nlabels = zeros(gtWidth,gtWidth,k,'uint8'); k = 0;\ntid = ticStatus('Collecting data',30,1);\nfor i = 1:nImgs\n  % get image and compute channels\n  gt=load([trnGtDir imgIds{i} '.mat']); gt=gt.groundTruth;\n  I=imread([trnImgDir imgIds{i} '.' ext]); siz=size(I);\n  if(rgbd), D=single(imread([trnDepDir imgIds{i} '.png']))/1e4; end\n  if(rgbd==1), I=D; elseif(rgbd==2), I=cat(3,single(I)/255,D); end\n  p=zeros(1,4); p([2 4])=mod(4-mod(siz(1:2),4),4);\n  if(any(p)), I=imPad(I,p,'symmetric'); end\n%   [chnsReg,chnsSim] = edgesChns(I,opts);\n%   deepFeat = chnsReg(:, :, 4);\n  tic;\nif exist([trnFeatFir imgIds{i} '_deepFeat.mat'], 'file');\n    load([trnFeatFir imgIds{i} '_deepFeat.mat']);\nelse\n  deepFeat = edgesChnsDL2(I, opts);\n  save([trnFeatFir imgIds{i} '_deepFeat.mat'], 'deepFeat');\nend\n  deepFeat = deepFeat(:, :, selected_dims);\n  toc;\n  % sample positive and negative locations\n  nGt=length(gt); xy=[]; k1=0; B=false(siz(1),siz(2));\n  B(shrink:shrink:end,shrink:shrink:end)=1;\n  B([1:imRadius end-imRadius:end],:)=0;\n  B(:,[1:imRadius end-imRadius:end])=0;\n  for j=1:nGt\n    M=gt{j}.Boundaries; M(bwdist(M)<gtRadius)=1;\n    [y,x]=find(M.*B); k2=min(length(y),ceil(nPos/nImgs/nGt));\n    rp=randperm(length(y),k2); y=y(rp); x=x(rp);\n    xy=[xy; x y ones(k2,1)*j]; k1=k1+k2; %#ok<AGROW>\n    [y,x]=find(~M.*B); k2=min(length(y),ceil(nNeg/nImgs/nGt));\n    rp=randperm(length(y),k2); y=y(rp); x=x(rp);\n    xy=[xy; x y ones(k2,1)*j]; k1=k1+k2; %#ok<AGROW>\n  end\n  if(k1>size(ftrs,1)-k), k1=size(ftrs,1)-k; xy=xy(1:k1,:); end\n  % crop patches and ground truth labels\n  psReg=zeros(round(imWidth/shrink),round(imWidth/shrink),nChns,k1,'single');\n  lbls=zeros(gtWidth,gtWidth,k1,'uint8');\n%   psSim=psReg; \n    ri=round(imRadius/shrink); \n    rg=gtRadius;\n%     ftrs1 = zeros(k1, nTotFtrs);\n  for j=1:k1, xy1=xy(j,:); xy2=xy1/shrink;\n    psReg(:,:,:,j)=deepFeat(round(xy2(2))-ri+1:round(xy2(2))+ri,round(xy2(1))-ri+1:round(xy2(1))+ri,:);\n%     psSim(:,:,:,j)=chnsSim(xy2(2)-ri+1:xy2(2)+ri,xy2(1)-ri+1:xy2(1)+ri,:);\n%     ftrs1(j, :) = deepFeat(round(xy2(2)), round(xy2(1)), :);\n    t=gt{xy1(3)}.Segmentation(xy1(2)-rg+1:xy1(2)+rg,xy1(1)-rg+1:xy1(1)+rg);\n    if(all(t(:)==t(1))), lbls(:,:,j)=1; else [~,~,t]=unique(t);\n      lbls(:,:,j)=reshape(t,gtWidth,gtWidth); end\n  end\n%   if(0), figure(1); montage2(squeeze(psReg(:,:,1,:))); drawnow; end\n%   if(0), figure(2); montage2(lbls(:,:,:)); drawnow; end\n  % compute features and store\n    ftrs1=reshape(psReg,[],k1)';\n%   ftrs1=[reshape(psReg,[],k1)' stComputeSimFtrs(psSim,opts)];\n%   ftrs1=reshape(ftrs1,[],k1)';\n\n  ftrs(k+1:k+k1,:)=ftrs1(:,fids); \n  labels(:,:,k+1:k+k1)=lbls;\n  k=k+k1; \n  if(k==size(ftrs,1)), tocStatus(tid,1); break; end\n  tocStatus(tid,i/nImgs);\nend\nif(k<size(ftrs,1)), ftrs=ftrs(1:k,:); labels=labels(:,:,1:k); end\n\n% train structured edge classifier (random decision tree)\npTree=struct('minCount',opts.minCount, 'minChild',opts.minChild, ...\n  'maxDepth',opts.maxDepth, 'H',opts.nClasses, 'split',opts.split);\nt=labels; labels=cell(k,1); for i=1:k, labels{i}=t(:,:,i); end\npTree.discretize=@(hs,H) discretize(hs,H,opts.nSamples,opts.discretize);\ntree=forestTrain(ftrs,labels,pTree); tree.hs=cell2array(tree.hs);\ntree.fids(tree.child>0) = fids(tree.fids(tree.child>0)+1)-1;\nif(~exist(treeDir,'dir')), mkdir(treeDir); end\nsave([treeFn int2str2(treeInd,3) '.mat'],'tree'); e=etime(clock,tStart);\nfprintf('Training of tree %d complete (time=%.1fs).\\n',treeInd,e);\nRandStream.setGlobalStream( streamOrig );\n\nend\n\nfunction ftrs = stComputeSimFtrs( chns, opts )\n% Compute self-similarity features (order must be compatible w mex file).\nw=opts.imWidth/opts.shrink; n=opts.nCells; if(n==0), ftrs=[]; return; end\nnSimFtrs=opts.nSimFtrs; nChns=opts.nChns; m=size(chns,4);\ninds=round(w/n/2); inds=round((1:n)*(w+2*inds-1)/(n+1)-inds+1);\nchns=reshape(chns(inds,inds,:,:),n*n,nChns,m);\nftrs=zeros(nSimFtrs/nChns,nChns,m,'single');\nk=0; for i=1:n*n-1, k1=n*n-i; i1=ones(1,k1)*i;\n  ftrs(k+1:k+k1,:,:)=chns(i1,:,:)-chns((1:k1)+i,:,:); k=k+k1; end\nftrs = reshape(ftrs,nSimFtrs,m)';\nend\n\nfunction [hs,segs] = discretize( segs, nClasses, nSamples, type )\n% Convert a set of segmentations into a set of labels in [1,nClasses].\npersistent cache; w=size(segs{1},1); assert(size(segs{1},2)==w);\nif(~isempty(cache) && cache{1}==w), [~,is1,is2]=deal(cache{:}); else\n  % compute all possible lookup inds for w x w patches\n  is=1:w^4; is1=floor((is-1)/w/w); is2=is-is1*w*w; is1=is1+1;\n  kp=is2>is1; is1=is1(kp); is2=is2(kp); cache={w,is1,is2};\nend\n% compute n binary codes zs of length nSamples\nnSamples=min(nSamples,length(is1)); kp=randperm(length(is1),nSamples);\nn=length(segs); is1=is1(kp); is2=is2(kp); zs=false(n,nSamples);\nfor i=1:n, zs(i,:)=segs{i}(is1)==segs{i}(is2); end\nzs=bsxfun(@minus,zs,sum(zs,1)/n); zs=zs(:,any(zs,1));\nif(isempty(zs)), hs=ones(n,1,'uint32'); segs=segs{1}; return; end\n% find most representative segs (closest to mean)\n[~,ind]=min(sum(zs.*zs,2)); segs=segs{ind};\n% apply PCA to reduce dimensionality of zs\nU=pca(zs'); d=min(5,size(U,2)); zs=zs*U(:,1:d);\n% discretize zs by clustering or discretizing pca dimensions\nd=min(d,floor(log2(nClasses))); hs=zeros(n,1);\nfor i=1:d, hs=hs+(zs(:,i)<0)*2^(i-1); end\n[~,~,hs]=unique(hs); hs=uint32(hs);\nif(strcmpi(type,'kmeans'))\n  nClasses1=max(hs); C=zs(1:nClasses1,:);\n  for i=1:nClasses1, C(i,:)=mean(zs(hs==i,:),1); end\n  hs=uint32(kmeans2(zs,nClasses,'C0',C,'nIter',1));\nend\n% optionally display different types of hs\nfor i=1:0, figure(i); montage2(cell2array(segs(hs==i))); end\nend\n", "meta": {"author": "shenwei1231", "repo": "DeepContour", "sha": "17b989464bdcf8be7d14f4d37aeae7b803f11966", "save_path": "github-repos/MATLAB/shenwei1231-DeepContour", "path": "github-repos/MATLAB/shenwei1231-DeepContour/DeepContour-17b989464bdcf8be7d14f4d37aeae7b803f11966/edgesTrainDL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.2005531402119038}}
{"text": "function varargout = process_aec2( varargin )\n% PROCESS_AEC2: Compute amplitude envelope correlation between one signal in one file, and all the signals in another file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012-2014\n%          Peter Donhauser, 2017\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'Amplitude Envelope Correlation AxB';\n    sProcess.Category    = 'Custom';\n    sProcess.SubGroup    = 'Connectivity';\n    sProcess.Index       = 657;\n    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Connectivity';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data', 'results', 'matrix'};\n    sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq'};\n    sProcess.nInputs     = 2;\n    sProcess.nMinFiles   = 1;\n    sProcess.isPaired    = 1;\n    \n    % === CONNECT INPUT\n    sProcess = process_corr2('DefineConnectOptions', sProcess);\n    % === FREQ BANDS\n    sProcess.options.freqbands.Comment = 'Frequency bands for the Hilbert transform:';\n    sProcess.options.freqbands.Type    = 'groupbands';\n    sProcess.options.freqbands.Value   = bst_get('DefaultFreqBands');\n    % === Orthogonalize pairs of signals\n    sProcess.options.isorth.Comment = 'Orthogonalize signal pairs before envelope computation';\n    sProcess.options.isorth.Type    = 'checkbox';\n    sProcess.options.isorth.Value   = 0;\n    % === OUTPUT MODE\n    sProcess.options.outputmode.Comment = {'Save individual results (one file per input file)', 'Concatenate input files before processing (one file)', 'Save average connectivity matrix (one file)'};\n    sProcess.options.outputmode.Type    = 'radio';\n    sProcess.options.outputmode.Value   = 1;\n    sProcess.options.outputmode.Group   = 'output';\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n    Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputA, sInputB) %#ok<DEFNU>\n    % Input options\n    OPTIONS = process_corr2('GetConnectOptions', sProcess, sInputA, sInputB);\n    if isempty(OPTIONS)\n        OutputFiles = {};\n        return\n    end\n    \n    OPTIONS.Method = 'aec';\n    % Hilbert and frequency bands options\n    OPTIONS.Freqs = sProcess.options.freqbands.Value;\n    OPTIONS.isOrth = sProcess.options.isorth.Value; \n    \n    % Compute metric\n    OutputFiles = bst_connectivity({sInputA.FileName}, {sInputB.FileName}, OPTIONS);\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/deprecated/process_aec2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.20042860254032463}}
{"text": "function varargout = process_ft_channelrepair( varargin )\n% PROCESS_FT_CHANNELREPAIR: Call FieldTrip function ft_channelrepair.\n% Replace bad channels with interpolations of neighboring values.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Roey Schurr, Francois Tadel, 2015\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok<DEFNU>\n    % Description the process\n    sProcess.Comment     = 'FieldTrip: ft_channelrepair';\n    sProcess.Category    = 'File';\n    sProcess.SubGroup    = 'Standardize';\n    sProcess.Index       = 309;\n    sProcess.Description = 'http://www.fieldtriptoolbox.org/reference/ft_channelrepair';\n    % Definition of the input accepted by this process\n    sProcess.InputTypes  = {'data'};\n    sProcess.OutputTypes = {'data'};\n    sProcess.nInputs     = 1;\n    sProcess.nMinFiles   = 1;\n    \n    % Definition of the options\n    % === INTEPROLATION METHOD\n    sProcess.options.warning.Comment = ['Note that you cannot indicate the bad channels here, <BR>' ...\n                                        'you need to mark them from the interface before.<BR><BR>' ...\n                                        'Interpolation method:'];\n    sProcess.options.warning.Type    = 'label';\n    sProcess.options.method.Comment = {'Nearest: Neighbours weighted by distance', 'Average: Mean of all neighbours', 'Spline: Spherical spline', 'Slap: Surface Laplacian'};\n    sProcess.options.method.Type    = 'radio';\n    sProcess.options.method.Value   = 1;\n    % === MAXIMAL DISTANCE BETWEEN NEIGHBOURS\n    sProcess.options.maxdist.Comment = 'Maximal distance between neighbours: ';\n    sProcess.options.maxdist.Type    = 'value';\n    sProcess.options.maxdist.Value   = {4, 'cm', 1};\n    % === SENSOR TYPES\n    sProcess.options.sensortypes.Comment = 'Sensor types (empty=all): ';\n    sProcess.options.sensortypes.Type    = 'text';\n    sProcess.options.sensortypes.Value   = 'EEG';\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok<DEFNU>\n     Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInput) %#ok<DEFNU>\n    % Initialize returned list of files\n    OutputFiles = {};\n    % Initialize FieldTrip\n    [isInstalled, errMsg] = bst_plugin('Install', 'fieldtrip');\n    if ~isInstalled\n        bst_report('Error', sProcess, [], errMsg);\n        return;\n    end\n    bst_plugin('SetProgressLogo', 'fieldtrip');\n    % Get option values\n    MaxDist = sProcess.options.maxdist.Value{1} / 100;   % Convert from centimeters to meters\n    SensorTypes = sProcess.options.sensortypes.Value;\n    switch (sProcess.options.method.Value)\n        case 1,    Method  = 'nearest';   % replacs the electrode with the average of its neighbours weighted by distance\n        case 2,    Method  = 'average';\n        case 3,    Method  = 'spline';\n        case 4,    Method  = 'slap';\n        otherwise, error('Invalid method');\n    end\n\n    % ===== LOAD DATA =====\n    % Convert to FieldTrip structures\n    [ftData, DataMat, ChannelMat] = out_fieldtrip_data(sInput.FileName, sInput.ChannelFile, SensorTypes, 0);\n\n    % ===== FIND NEIGHBORS =====\n    % Prepare structure of neighbouring electrodes\n    neicfg = struct();\n    neicfg.method        = 'distance';\n    neicfg.neighbourdist = MaxDist;\n    if isfield(ftData, 'elec')\n        neicfg.elec = ftData.elec;\n    end\n    if isfield(ftData, 'grad')\n        neicfg.grad = ftData.grad;\n    end\n    neighbours = ft_prepare_neighbours(neicfg);\n    \n    % ===== INTERPOLATE CHANNELS =====\n    % Find bad channels\n    iBadChan = find(DataMat.ChannelFlag == -1);\n    badchannel = {ChannelMat.Channel(iBadChan).Name};\n    % Preprare structure\n    intcfg = struct();\n    intcfg.neighbours = neighbours;\n    intcfg.method     = Method;   \n    intcfg.badchannel = badchannel';\n    intcfg.trials     = 1;\n    interpolatedData = ft_channelrepair(intcfg, ftData);\n    \n    % ===== GET RESULTS =====\n    % Get indices of the channels that were updated\n    [tmp,I,J] = intersect({ChannelMat.Channel(iBadChan).Name}, ftData.label);\n    % Replace interpolated channels\n    DataMat.F(iBadChan(I),:) = interpolatedData.trial{1}(J,:);\n    % Set those channels as good\n    DataMat.ChannelFlag(iBadChan(I),:) = 1;\n    % Add history comment\n    DataMat = bst_history('add', DataMat, 'interpbad', ['Replaced bad channels with method \"' Method '\" (' num2str(MaxDist*100) 'cm): ' sprintf('%s ', intcfg.badchannel{:})]);\n    if isfield(interpolatedData, 'cfg') && isfield(interpolatedData.cfg, 'version')\n        DataMat = bst_history('add', DataMat, 'fieldtrip', interpolatedData.cfg.version.name);\n        DataMat = bst_history('add', DataMat, 'fieldtrip', interpolatedData.cfg.version.id);\n    end\n    % Add comment tag\n    DataMat.Comment = [DataMat.Comment ' | interpbad'];\n    \n    % ===== SAVE THE RESULTS =====\n    % Create output filename\n    [fPath, fBase, fExt] = bst_fileparts(file_fullpath(sInput.FileName));\n    OutputFiles{1} = file_unique(bst_fullfile(fPath, [fBase '_interpbad', fExt]));\n    % Save on disk\n    bst_save(OutputFiles{1}, DataMat, 'v6');\n    % Register in database\n    db_add_data(sInput.iStudy, OutputFiles{1}, DataMat);\n    % Remove logo\n    bst_plugin('SetProgressLogo', []);\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_ft_channelrepair.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20037919996372283}}
{"text": "function [A_zV, a_zV, B_zV, b_zV] = GetPBConsts(DepthsV, EnergyC, PBDataS, flag);\n\n%       - constantsAaBb(1) - depth\n%       - constantsAaBb(2) - A\n%       - constantsAaBb(3) - a\n%       - constantsAaBb(4) - B\n%       - constantsAaBb(5) - b\n%\n%     Example\n%     using Ahnesjoe's notation\n%     0.075  2.0958E-02  22.777100  1.8582E-05  0.058308\n%     0.225  2.4948E-02  12.957500  2.1138E-05  0.067823\n%\n%LM:  JOD, 3 Nov 03, allow nearest neighbor indexing.\n%JOD, 17 Nov 03, added scale factor, default at 100.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nscale = 100;\n%For convenience, scale up A and B coefficients, so dose values are closer to unity.\n\nif nargin == 4 & strcmp(flag,'nearest')\n\n  Aahn6=PBDataS.aahn6b;\n  Aahn18=flipud(PBDataS.aahn18b);\n\n  MaxDepth=50;\n\n  if EnergyC==6\n   ParamMat=Aahn6;\n\n  else\n   if EnergyC==18\n    ParamMat=Aahn18;\n   end\n  end\n\n  DepthTableV=ParamMat(:,1);\n\n  %our own linear interpolation (faster than Matlab).\n  %compute two interpolation indices:\n  if any([DepthsV>MaxDepth])\n       disp('Warning!  Some depths exceed 50 cm, which is dosimetry limit!')\n  end\n\n  DepthsV=DepthsV.*[DepthsV<=MaxDepth]+MaxDepth.*[DepthsV>MaxDepth];\n\n  IndexLow=floor((DepthsV+0.075)/0.15)+1;\n  IndexHigh=ceil((DepthsV+0.075)/0.15)+1;\n\n  DepthLow=DepthTableV(IndexLow);\n  DepthHigh=DepthTableV(IndexHigh);\n\n  indexV = round((DepthsV+0.075)/0.15)+1;\n\n\n  A_zV= ParamMat(indexV,2);\n  a_zV= ParamMat(indexV,3);\n  B_zV= ParamMat(indexV,4);\n  b_zV= ParamMat(indexV,5);\n\n\n  A_zV = A_zV * scale;\n  B_zV = B_zV * scale;\n\n  return\n\nend\n\n\n%-----------code below not currently used (terrible!)---------------------%\n\n\n\nAahn6=PBDataS.aahn6b;\nAahn18=flipud(PBDataS.aahn18b);\nAahn8MCF=flipud(PBDataS.aahn8MMM);\n\nMaxDepth=50;\n\nif EnergyC==6\n ParamMat=Aahn6;\nelse\n if EnergyC==18\n  ParamMat=Aahn18;\n end\nend\n\nif EnergyC==8\n   ParamMat=Aahn8MCF;\n   MaxDepth=20;\nend\n\nDepthTableV=ParamMat(:,1);\n\n%our own linear interpolation (faster than Matlab).\n%compute two interpolation indices:\nif any([DepthsV>MaxDepth])\n     warning('Some depths exceed 50 cm, which is dosimetry limit!')\n end\n\nDepthsV=DepthsV.*[DepthsV<=MaxDepth]+MaxDepth.*[DepthsV>MaxDepth];\n\nIndexLow=floor((DepthsV+0.075)/0.15)+1;\nIndexHigh=ceil((DepthsV+0.075)/0.15)+1;\n\nif EnergyC==8\n    IndexLow=floor((DepthsV)/0.253) + 1;\n    IndexHigh=ceil((DepthsV)/0.253) + 1;\n    IndexLow(IndexLow > length(ParamMat(:,1))) = length(ParamMat(:,1));\n    IndexHigh(IndexHigh > length(ParamMat(:,1))) = length(ParamMat(:,1));\nend\n\n\nDepthLow=DepthTableV(IndexLow);\nDepthHigh=DepthTableV(IndexHigh);\n\nA_zV=((ParamMat(IndexLow,2).*(DepthHigh-DepthsV)+...\n    ParamMat(IndexHigh,2).*(DepthsV-DepthLow))./(DepthHigh-DepthLow+10*eps)).*...\n      [DepthHigh~=DepthLow]+ParamMat(IndexLow,2).*[DepthHigh==DepthLow];\na_zV=((ParamMat(IndexLow,3).*(DepthHigh-DepthsV)+...\n    ParamMat(IndexHigh,3).*(DepthsV-DepthLow))./(DepthHigh-DepthLow+10*eps)).*...\n      [DepthHigh~=DepthLow]+ParamMat(IndexLow,3).*[DepthHigh==DepthLow];\nB_zV=((ParamMat(IndexLow,4).*(DepthHigh-DepthsV)+...\n   ParamMat(IndexHigh,4).*(DepthsV-DepthLow))./(DepthHigh-DepthLow+10*eps)).*...\n      [DepthHigh~=DepthLow]+ParamMat(IndexLow,4).*[DepthHigh==DepthLow];\nb_zV=((ParamMat(IndexLow,5).*(DepthHigh-DepthsV)+...\n     ParamMat(IndexHigh,5).*(DepthsV-DepthLow))./(DepthHigh-DepthLow+10*eps)).*...\n       [DepthHigh~=DepthLow]+ParamMat(IndexLow,5).*[DepthHigh==DepthLow];\n\n%clear IndexLow IndexHigh DepthLow DepthHigh\n\n\n%Scale final answers for convenience:\n\nA_zV = A_zV * scale;\nB_zV = B_zV * scale;\n\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/GetPBConsts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.20006036153349901}}
