{"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 violinplot for a\n % boxplot-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 - scatter plot of the data points\n % ScatterPlot2 - scatter second plot of the data points\n % ViolinPlot - fill plot of the kernel density estimate\n % ViolinPlot2 - fill second 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 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(hquartiles(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 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 [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\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 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 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\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 = 'Sensors/sources to be investigated :';\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 = 'Processing options [expert only]:';\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 = 'Output options:';\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\n Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputsA) %#ok\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(skip2 & N2\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 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 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 [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) 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 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)/lambda0;\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": "% 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(znorminv(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": "% 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": "%% 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 [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 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": "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": "%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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))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)) 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)))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 minsgmax(surr_pix) || ...\n mono_image(i,j) 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)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)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)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": "%% 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% \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": "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": "% 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 . \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 [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 [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": "%%*************************************************************************\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 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 .\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 [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 [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 .\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 nchans0.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": "% 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 .\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": "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 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 [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": "% 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 .\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": "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 [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": "%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 [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 .\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": "% 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 [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": "%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 [ 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": "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": "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() 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() 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() 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() 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 [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 [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": "% 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 .\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=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=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 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": "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 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": "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 [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 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": "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 [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": "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": "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\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 [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": "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     |\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 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 iumbraldetT*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 %%% 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 %%% 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 %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": "%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 .\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": "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)=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) 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) 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": "% 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 [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 .\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 reducerank0\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": "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": "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 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": "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": "% 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)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,:)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,:)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 [ 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 (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\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\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 [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),